1 /*
   2  * Copyright (c) 1995, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.module.ModuleDescriptor;
  29 import java.lang.module.ModuleDescriptor.Exports;
  30 import java.lang.module.ModuleDescriptor.Opens;
  31 import java.lang.reflect.Member;
  32 import java.io.FileDescriptor;
  33 import java.io.File;
  34 import java.io.FilePermission;
  35 import java.net.InetAddress;
  36 import java.net.SocketPermission;
  37 import java.security.AccessControlContext;
  38 import java.security.AccessController;
  39 import java.security.Permission;
  40 import java.security.PrivilegedAction;
  41 import java.security.Security;
  42 import java.security.SecurityPermission;
  43 import java.util.HashSet;
  44 import java.util.Map;
  45 import java.util.Objects;
  46 import java.util.PropertyPermission;
  47 import java.util.Set;
  48 import java.util.concurrent.ConcurrentHashMap;
  49 
  50 import jdk.internal.module.ModuleLoaderMap;
  51 import jdk.internal.reflect.CallerSensitive;
  52 import sun.security.util.SecurityConstants;
  53 
  54 /**
  55  * The security manager is a class that allows
  56  * applications to implement a security policy. It allows an
  57  * application to determine, before performing a possibly unsafe or
  58  * sensitive operation, what the operation is and whether
  59  * it is being attempted in a security context that allows the
  60  * operation to be performed. The
  61  * application can allow or disallow the operation.
  62  * <p>
  63  * The <code>SecurityManager</code> class contains many methods with
  64  * names that begin with the word <code>check</code>. These methods
  65  * are called by various methods in the Java libraries before those
  66  * methods perform certain potentially sensitive operations. The
  67  * invocation of such a <code>check</code> method typically looks like this:
  68  * <blockquote><pre>
  69  *     SecurityManager security = System.getSecurityManager();
  70  *     if (security != null) {
  71  *         security.check<i>XXX</i>(argument, &nbsp;.&nbsp;.&nbsp;.&nbsp;);
  72  *     }
  73  * </pre></blockquote>
  74  * <p>
  75  * The security manager is thereby given an opportunity to prevent
  76  * completion of the operation by throwing an exception. A security
  77  * manager routine simply returns if the operation is permitted, but
  78  * throws a <code>SecurityException</code> if the operation is not
  79  * permitted.
  80  * <p>
  81  * Environments using a security manager will typically set the security
  82  * manager at startup. In the JDK implementation, this is done by setting
  83  * the system property {@code java.security.manager} on the command line to
  84  * the class name of the security manager. It can also be set to the empty
  85  * String ("") or the special token "{@code default}" to use the
  86  * default {@code java.lang.SecurityManager}. If a class name is specified,
  87  * it must be {@code java.lang.SecurityManager} or a public subclass and have
  88  * a public no-arg constructor. The class is loaded by the
  89  * {@linkplain ClassLoader#getSystemClassLoader() built-in system class loader}
  90  * if it is not {@code java.lang.SecurityManager}. If the
  91  * {@code java.security.manager} system property is not set, the default value
  92  * is {@code null}, which means a security manager will not be set at startup.
  93  * <p>
  94  * The Java run-time may also allow, but is not required to allow, the security
  95  * manager to be set dynamically by invoking the
  96  * {@link System#setSecurityManager(SecurityManager) setSecurityManager} method.
  97  * In the JDK implementation, if the Java virtual machine is started with
  98  * the {@code java.security.manager} system property set to the special token
  99  * "{@code disallow}" then a security manager will not be set at startup and
 100  * cannot be set dynamically (the
 101  * {@link System#setSecurityManager(SecurityManager) setSecurityManager}
 102  * method will throw an {@code UnsupportedOperationException}). If the
 103  * {@code java.security.manager} system property is not set or is set to the
 104  * special token "{@code allow}", then a security manager will not be set at
 105  * startup but can be set dynamically. Finally, if the
 106  * {@code java.security.manager} system property is set to the class name of
 107  * the security manager, or to the empty String ("") or the special token
 108  * "{@code default}", then a security manager is set at startup (as described
 109  * previously) and can also be subsequently replaced (or disabled) dynamically
 110  * (subject to the policy of the currently installed security manager). The
 111  * following table illustrates the behavior of the JDK implementation for the
 112  * different settings of the {@code java.security.manager} system property:
 113  * <table class="striped">
 114  * <caption style="display:none">property value,
 115  *  the SecurityManager set at startup,
 116  *  can dynamically set a SecurityManager
 117  * </caption>
 118  * <thead>
 119  * <tr>
 120  * <th scope="col">Property Value</th>
 121  * <th scope="col">The SecurityManager set at startup</th>
 122  * <th scope="col">System.setSecurityManager run-time behavior</th>
 123  * </tr>
 124  * </thead>
 125  * <tbody>
 126  *
 127  * <tr>
 128  *   <th scope="row">null</th>
 129  *   <td>None</td>
 130  *   <td>Success or throws {@code SecurityException} if not permitted by
 131  * the currently installed security manager</td>
 132  * </tr>
 133  *
 134  * <tr>
 135  *   <th scope="row">empty String ("")</th>
 136  *   <td>{@code java.lang.SecurityManager}</td>
 137  *   <td>Success or throws {@code SecurityException} if not permitted by
 138  * the currently installed security manager</td>
 139  * </tr>
 140  *
 141  * <tr>
 142  *   <th scope="row">"default"</th>
 143  *   <td>{@code java.lang.SecurityManager}</td>
 144  *   <td>Success or throws {@code SecurityException} if not permitted by
 145  * the currently installed security manager</td>
 146  * </tr>
 147  *
 148  * <tr>
 149  *   <th scope="row">"disallow"</th>
 150  *   <td>None</td>
 151  *   <td>Always throws {@code UnsupportedOperationException}</td>
 152  * </tr>
 153  *
 154  * <tr>
 155  *   <th scope="row">"allow"</th>
 156  *   <td>None</td>
 157  *   <td>Success or throws {@code SecurityException} if not permitted by
 158  * the currently installed security manager</td>
 159  * </tr>
 160  *
 161  * <tr>
 162  *   <th scope="row">a class name</th>
 163  *   <td>the named class</td>
 164  *   <td>Success or throws {@code SecurityException} if not permitted by
 165  * the currently installed security manager</td>
 166  * </tr>
 167  *
 168  * </tbody>
 169  * </table>
 170  * <p> A future release of the JDK may change the default value of the
 171  * {@code java.security.manager} system property to "{@code disallow}".
 172  * <p>
 173  * The current security manager is returned by the
 174  * {@link System#getSecurityManager() getSecurityManager} method.
 175  * <p>
 176  * The special method
 177  * {@link SecurityManager#checkPermission(java.security.Permission)}
 178  * determines whether an access request indicated by a specified
 179  * permission should be granted or denied. The
 180  * default implementation calls
 181  *
 182  * <pre>
 183  *   AccessController.checkPermission(perm);
 184  * </pre>
 185  *
 186  * <p>
 187  * If a requested access is allowed,
 188  * <code>checkPermission</code> returns quietly. If denied, a
 189  * <code>SecurityException</code> is thrown.
 190  * <p>
 191  * The default implementation of each of the other
 192  * <code>check</code> methods in <code>SecurityManager</code> is to
 193  * call the <code>SecurityManager checkPermission</code> method
 194  * to determine if the calling thread has permission to perform the requested
 195  * operation.
 196  * <p>
 197  * Note that the <code>checkPermission</code> method with
 198  * just a single permission argument always performs security checks
 199  * within the context of the currently executing thread.
 200  * Sometimes a security check that should be made within a given context
 201  * will actually need to be done from within a
 202  * <i>different</i> context (for example, from within a worker thread).
 203  * The {@link SecurityManager#getSecurityContext getSecurityContext} method
 204  * and the {@link SecurityManager#checkPermission(java.security.Permission,
 205  * java.lang.Object) checkPermission}
 206  * method that includes a context argument are provided
 207  * for this situation. The
 208  * <code>getSecurityContext</code> method returns a "snapshot"
 209  * of the current calling context. (The default implementation
 210  * returns an AccessControlContext object.) A sample call is
 211  * the following:
 212  *
 213  * <pre>
 214  *   Object context = null;
 215  *   SecurityManager sm = System.getSecurityManager();
 216  *   if (sm != null) context = sm.getSecurityContext();
 217  * </pre>
 218  *
 219  * <p>
 220  * The <code>checkPermission</code> method
 221  * that takes a context object in addition to a permission
 222  * makes access decisions based on that context,
 223  * rather than on that of the current execution thread.
 224  * Code within a different context can thus call that method,
 225  * passing the permission and the
 226  * previously-saved context object. A sample call, using the
 227  * SecurityManager <code>sm</code> obtained as in the previous example,
 228  * is the following:
 229  *
 230  * <pre>
 231  *   if (sm != null) sm.checkPermission(permission, context);
 232  * </pre>
 233  *
 234  * <p>Permissions fall into these categories: File, Socket, Net,
 235  * Security, Runtime, Property, AWT, Reflect, and Serializable.
 236  * The classes managing these various
 237  * permission categories are <code>java.io.FilePermission</code>,
 238  * <code>java.net.SocketPermission</code>,
 239  * <code>java.net.NetPermission</code>,
 240  * <code>java.security.SecurityPermission</code>,
 241  * <code>java.lang.RuntimePermission</code>,
 242  * <code>java.util.PropertyPermission</code>,
 243  * <code>java.awt.AWTPermission</code>,
 244  * <code>java.lang.reflect.ReflectPermission</code>, and
 245  * <code>java.io.SerializablePermission</code>.
 246  *
 247  * <p>All but the first two (FilePermission and SocketPermission) are
 248  * subclasses of <code>java.security.BasicPermission</code>, which itself
 249  * is an abstract subclass of the
 250  * top-level class for permissions, which is
 251  * <code>java.security.Permission</code>. BasicPermission defines the
 252  * functionality needed for all permissions that contain a name
 253  * that follows the hierarchical property naming convention
 254  * (for example, "exitVM", "setFactory", "queuePrintJob", etc).
 255  * An asterisk
 256  * may appear at the end of the name, following a ".", or by itself, to
 257  * signify a wildcard match. For example: "a.*" or "*" is valid,
 258  * "*a" or "a*b" is not valid.
 259  *
 260  * <p>FilePermission and SocketPermission are subclasses of the
 261  * top-level class for permissions
 262  * (<code>java.security.Permission</code>). Classes like these
 263  * that have a more complicated name syntax than that used by
 264  * BasicPermission subclass directly from Permission rather than from
 265  * BasicPermission. For example,
 266  * for a <code>java.io.FilePermission</code> object, the permission name is
 267  * the path name of a file (or directory).
 268  *
 269  * <p>Some of the permission classes have an "actions" list that tells
 270  * the actions that are permitted for the object.  For example,
 271  * for a <code>java.io.FilePermission</code> object, the actions list
 272  * (such as "read, write") specifies which actions are granted for the
 273  * specified file (or for files in the specified directory).
 274  *
 275  * <p>Other permission classes are for "named" permissions -
 276  * ones that contain a name but no actions list; you either have the
 277  * named permission or you don't.
 278  *
 279  * <p>Note: There is also a <code>java.security.AllPermission</code>
 280  * permission that implies all permissions. It exists to simplify the work
 281  * of system administrators who might need to perform multiple
 282  * tasks that require all (or numerous) permissions.
 283  * <p>
 284  * See {@extLink security_guide_permissions
 285  * Permissions in the Java Development Kit (JDK)}
 286  * for permission-related information.
 287  * This document includes a table listing the various SecurityManager
 288  * <code>check</code> methods and the permission(s) the default
 289  * implementation of each such method requires.
 290  * It also contains a table of the methods
 291  * that require permissions, and for each such method tells
 292  * which permission it requires.
 293  *
 294  * @author  Arthur van Hoff
 295  * @author  Roland Schemers
 296  *
 297  * @see     java.lang.ClassLoader
 298  * @see     java.lang.SecurityException
 299  * @see     java.lang.System#getSecurityManager() getSecurityManager
 300  * @see     java.lang.System#setSecurityManager(java.lang.SecurityManager)
 301  *  setSecurityManager
 302  * @see     java.security.AccessController AccessController
 303  * @see     java.security.AccessControlContext AccessControlContext
 304  * @see     java.security.AccessControlException AccessControlException
 305  * @see     java.security.Permission
 306  * @see     java.security.BasicPermission
 307  * @see     java.io.FilePermission
 308  * @see     java.net.SocketPermission
 309  * @see     java.util.PropertyPermission
 310  * @see     java.lang.RuntimePermission
 311  * @see     java.security.Policy Policy
 312  * @see     java.security.SecurityPermission SecurityPermission
 313  * @see     java.security.ProtectionDomain
 314  *
 315  * @since   1.0
 316  */
 317 public class SecurityManager {
 318 
 319     /*
 320      * Have we been initialized. Effective against finalizer attacks.
 321      */
 322     private boolean initialized = false;
 323 
 324     /**
 325      * Constructs a new <code>SecurityManager</code>.
 326      *
 327      * <p> If there is a security manager already installed, this method first
 328      * calls the security manager's <code>checkPermission</code> method
 329      * with the <code>RuntimePermission("createSecurityManager")</code>
 330      * permission to ensure the calling thread has permission to create a new
 331      * security manager.
 332      * This may result in throwing a <code>SecurityException</code>.
 333      *
 334      * @exception  java.lang.SecurityException if a security manager already
 335      *             exists and its <code>checkPermission</code> method
 336      *             doesn't allow creation of a new security manager.
 337      * @see        java.lang.System#getSecurityManager()
 338      * @see        #checkPermission(java.security.Permission) checkPermission
 339      * @see java.lang.RuntimePermission
 340      */
 341     public SecurityManager() {
 342         synchronized(SecurityManager.class) {
 343             SecurityManager sm = System.getSecurityManager();
 344             if (sm != null) {
 345                 // ask the currently installed security manager if we
 346                 // can create a new one.
 347                 sm.checkPermission(new RuntimePermission
 348                                    ("createSecurityManager"));
 349             }
 350             initialized = true;
 351         }
 352     }
 353 
 354     /**
 355      * Returns the current execution stack as an array of classes.
 356      * <p>
 357      * The length of the array is the number of methods on the execution
 358      * stack. The element at index <code>0</code> is the class of the
 359      * currently executing method, the element at index <code>1</code> is
 360      * the class of that method's caller, and so on.
 361      *
 362      * @return  the execution stack.
 363      */
 364     protected native Class<?>[] getClassContext();
 365 
 366     /**
 367      * Creates an object that encapsulates the current execution
 368      * environment. The result of this method is used, for example, by the
 369      * three-argument <code>checkConnect</code> method and by the
 370      * two-argument <code>checkRead</code> method.
 371      * These methods are needed because a trusted method may be called
 372      * on to read a file or open a socket on behalf of another method.
 373      * The trusted method needs to determine if the other (possibly
 374      * untrusted) method would be allowed to perform the operation on its
 375      * own.
 376      * <p> The default implementation of this method is to return
 377      * an <code>AccessControlContext</code> object.
 378      *
 379      * @return  an implementation-dependent object that encapsulates
 380      *          sufficient information about the current execution environment
 381      *          to perform some security checks later.
 382      * @see     java.lang.SecurityManager#checkConnect(java.lang.String, int,
 383      *   java.lang.Object) checkConnect
 384      * @see     java.lang.SecurityManager#checkRead(java.lang.String,
 385      *   java.lang.Object) checkRead
 386      * @see     java.security.AccessControlContext AccessControlContext
 387      */
 388     public Object getSecurityContext() {
 389         return AccessController.getContext();
 390     }
 391 
 392     /**
 393      * Throws a <code>SecurityException</code> if the requested
 394      * access, specified by the given permission, is not permitted based
 395      * on the security policy currently in effect.
 396      * <p>
 397      * This method calls <code>AccessController.checkPermission</code>
 398      * with the given permission.
 399      *
 400      * @param     perm   the requested permission.
 401      * @exception SecurityException if access is not permitted based on
 402      *            the current security policy.
 403      * @exception NullPointerException if the permission argument is
 404      *            <code>null</code>.
 405      * @since     1.2
 406      */
 407     public void checkPermission(Permission perm) {
 408         java.security.AccessController.checkPermission(perm);
 409     }
 410 
 411     /**
 412      * Throws a <code>SecurityException</code> if the
 413      * specified security context is denied access to the resource
 414      * specified by the given permission.
 415      * The context must be a security
 416      * context returned by a previous call to
 417      * <code>getSecurityContext</code> and the access control
 418      * decision is based upon the configured security policy for
 419      * that security context.
 420      * <p>
 421      * If <code>context</code> is an instance of
 422      * <code>AccessControlContext</code> then the
 423      * <code>AccessControlContext.checkPermission</code> method is
 424      * invoked with the specified permission.
 425      * <p>
 426      * If <code>context</code> is not an instance of
 427      * <code>AccessControlContext</code> then a
 428      * <code>SecurityException</code> is thrown.
 429      *
 430      * @param      perm      the specified permission
 431      * @param      context   a system-dependent security context.
 432      * @exception  SecurityException  if the specified security context
 433      *             is not an instance of <code>AccessControlContext</code>
 434      *             (e.g., is <code>null</code>), or is denied access to the
 435      *             resource specified by the given permission.
 436      * @exception  NullPointerException if the permission argument is
 437      *             <code>null</code>.
 438      * @see        java.lang.SecurityManager#getSecurityContext()
 439      * @see java.security.AccessControlContext#checkPermission(java.security.Permission)
 440      * @since      1.2
 441      */
 442     public void checkPermission(Permission perm, Object context) {
 443         if (context instanceof AccessControlContext) {
 444             ((AccessControlContext)context).checkPermission(perm);
 445         } else {
 446             throw new SecurityException();
 447         }
 448     }
 449 
 450     /**
 451      * Throws a <code>SecurityException</code> if the
 452      * calling thread is not allowed to create a new class loader.
 453      * <p>
 454      * This method calls <code>checkPermission</code> with the
 455      * <code>RuntimePermission("createClassLoader")</code>
 456      * permission.
 457      * <p>
 458      * If you override this method, then you should make a call to
 459      * <code>super.checkCreateClassLoader</code>
 460      * at the point the overridden method would normally throw an
 461      * exception.
 462      *
 463      * @exception SecurityException if the calling thread does not
 464      *             have permission
 465      *             to create a new class loader.
 466      * @see        java.lang.ClassLoader#ClassLoader()
 467      * @see        #checkPermission(java.security.Permission) checkPermission
 468      */
 469     public void checkCreateClassLoader() {
 470         checkPermission(SecurityConstants.CREATE_CLASSLOADER_PERMISSION);
 471     }
 472 
 473     /**
 474      * reference to the root thread group, used for the checkAccess
 475      * methods.
 476      */
 477 
 478     private static ThreadGroup rootGroup = getRootGroup();
 479 
 480     private static ThreadGroup getRootGroup() {
 481         ThreadGroup root =  Thread.currentThread().getThreadGroup();
 482         while (root.getParent() != null) {
 483             root = root.getParent();
 484         }
 485         return root;
 486     }
 487 
 488     /**
 489      * Throws a <code>SecurityException</code> if the
 490      * calling thread is not allowed to modify the thread argument.
 491      * <p>
 492      * This method is invoked for the current security manager by the
 493      * <code>stop</code>, <code>suspend</code>, <code>resume</code>,
 494      * <code>setPriority</code>, <code>setName</code>, and
 495      * <code>setDaemon</code> methods of class <code>Thread</code>.
 496      * <p>
 497      * If the thread argument is a system thread (belongs to
 498      * the thread group with a <code>null</code> parent) then
 499      * this method calls <code>checkPermission</code> with the
 500      * <code>RuntimePermission("modifyThread")</code> permission.
 501      * If the thread argument is <i>not</i> a system thread,
 502      * this method just returns silently.
 503      * <p>
 504      * Applications that want a stricter policy should override this
 505      * method. If this method is overridden, the method that overrides
 506      * it should additionally check to see if the calling thread has the
 507      * <code>RuntimePermission("modifyThread")</code> permission, and
 508      * if so, return silently. This is to ensure that code granted
 509      * that permission (such as the JDK itself) is allowed to
 510      * manipulate any thread.
 511      * <p>
 512      * If this method is overridden, then
 513      * <code>super.checkAccess</code> should
 514      * be called by the first statement in the overridden method, or the
 515      * equivalent security check should be placed in the overridden method.
 516      *
 517      * @param      t   the thread to be checked.
 518      * @exception  SecurityException  if the calling thread does not have
 519      *             permission to modify the thread.
 520      * @exception  NullPointerException if the thread argument is
 521      *             <code>null</code>.
 522      * @see        java.lang.Thread#resume() resume
 523      * @see        java.lang.Thread#setDaemon(boolean) setDaemon
 524      * @see        java.lang.Thread#setName(java.lang.String) setName
 525      * @see        java.lang.Thread#setPriority(int) setPriority
 526      * @see        java.lang.Thread#stop() stop
 527      * @see        java.lang.Thread#suspend() suspend
 528      * @see        #checkPermission(java.security.Permission) checkPermission
 529      */
 530     public void checkAccess(Thread t) {
 531         if (t == null) {
 532             throw new NullPointerException("thread can't be null");
 533         }
 534         if (t.getThreadGroup() == rootGroup) {
 535             checkPermission(SecurityConstants.MODIFY_THREAD_PERMISSION);
 536         } else {
 537             // just return
 538         }
 539     }
 540     /**
 541      * Throws a <code>SecurityException</code> if the
 542      * calling thread is not allowed to modify the thread group argument.
 543      * <p>
 544      * This method is invoked for the current security manager when a
 545      * new child thread or child thread group is created, and by the
 546      * <code>setDaemon</code>, <code>setMaxPriority</code>,
 547      * <code>stop</code>, <code>suspend</code>, <code>resume</code>, and
 548      * <code>destroy</code> methods of class <code>ThreadGroup</code>.
 549      * <p>
 550      * If the thread group argument is the system thread group (
 551      * has a <code>null</code> parent) then
 552      * this method calls <code>checkPermission</code> with the
 553      * <code>RuntimePermission("modifyThreadGroup")</code> permission.
 554      * If the thread group argument is <i>not</i> the system thread group,
 555      * this method just returns silently.
 556      * <p>
 557      * Applications that want a stricter policy should override this
 558      * method. If this method is overridden, the method that overrides
 559      * it should additionally check to see if the calling thread has the
 560      * <code>RuntimePermission("modifyThreadGroup")</code> permission, and
 561      * if so, return silently. This is to ensure that code granted
 562      * that permission (such as the JDK itself) is allowed to
 563      * manipulate any thread.
 564      * <p>
 565      * If this method is overridden, then
 566      * <code>super.checkAccess</code> should
 567      * be called by the first statement in the overridden method, or the
 568      * equivalent security check should be placed in the overridden method.
 569      *
 570      * @param      g   the thread group to be checked.
 571      * @exception  SecurityException  if the calling thread does not have
 572      *             permission to modify the thread group.
 573      * @exception  NullPointerException if the thread group argument is
 574      *             <code>null</code>.
 575      * @see        java.lang.ThreadGroup#destroy() destroy
 576      * @see        java.lang.ThreadGroup#resume() resume
 577      * @see        java.lang.ThreadGroup#setDaemon(boolean) setDaemon
 578      * @see        java.lang.ThreadGroup#setMaxPriority(int) setMaxPriority
 579      * @see        java.lang.ThreadGroup#stop() stop
 580      * @see        java.lang.ThreadGroup#suspend() suspend
 581      * @see        #checkPermission(java.security.Permission) checkPermission
 582      */
 583     public void checkAccess(ThreadGroup g) {
 584         if (g == null) {
 585             throw new NullPointerException("thread group can't be null");
 586         }
 587         if (g == rootGroup) {
 588             checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
 589         } else {
 590             // just return
 591         }
 592     }
 593 
 594     /**
 595      * Throws a <code>SecurityException</code> if the
 596      * calling thread is not allowed to cause the Java Virtual Machine to
 597      * halt with the specified status code.
 598      * <p>
 599      * This method is invoked for the current security manager by the
 600      * <code>exit</code> method of class <code>Runtime</code>. A status
 601      * of <code>0</code> indicates success; other values indicate various
 602      * errors.
 603      * <p>
 604      * This method calls <code>checkPermission</code> with the
 605      * <code>RuntimePermission("exitVM."+status)</code> permission.
 606      * <p>
 607      * If you override this method, then you should make a call to
 608      * <code>super.checkExit</code>
 609      * at the point the overridden method would normally throw an
 610      * exception.
 611      *
 612      * @param      status   the exit status.
 613      * @exception SecurityException if the calling thread does not have
 614      *              permission to halt the Java Virtual Machine with
 615      *              the specified status.
 616      * @see        java.lang.Runtime#exit(int) exit
 617      * @see        #checkPermission(java.security.Permission) checkPermission
 618      */
 619     public void checkExit(int status) {
 620         checkPermission(new RuntimePermission("exitVM."+status));
 621     }
 622 
 623     /**
 624      * Throws a <code>SecurityException</code> if the
 625      * calling thread is not allowed to create a subprocess.
 626      * <p>
 627      * This method is invoked for the current security manager by the
 628      * <code>exec</code> methods of class <code>Runtime</code>.
 629      * <p>
 630      * This method calls <code>checkPermission</code> with the
 631      * <code>FilePermission(cmd,"execute")</code> permission
 632      * if cmd is an absolute path, otherwise it calls
 633      * <code>checkPermission</code> with
 634      * <code>FilePermission("&lt;&lt;ALL FILES&gt;&gt;","execute")</code>.
 635      * <p>
 636      * If you override this method, then you should make a call to
 637      * <code>super.checkExec</code>
 638      * at the point the overridden method would normally throw an
 639      * exception.
 640      *
 641      * @param      cmd   the specified system command.
 642      * @exception  SecurityException if the calling thread does not have
 643      *             permission to create a subprocess.
 644      * @exception  NullPointerException if the <code>cmd</code> argument is
 645      *             <code>null</code>.
 646      * @see     java.lang.Runtime#exec(java.lang.String)
 647      * @see     java.lang.Runtime#exec(java.lang.String, java.lang.String[])
 648      * @see     java.lang.Runtime#exec(java.lang.String[])
 649      * @see     java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
 650      * @see     #checkPermission(java.security.Permission) checkPermission
 651      */
 652     public void checkExec(String cmd) {
 653         File f = new File(cmd);
 654         if (f.isAbsolute()) {
 655             checkPermission(new FilePermission(cmd,
 656                 SecurityConstants.FILE_EXECUTE_ACTION));
 657         } else {
 658             checkPermission(new FilePermission("<<ALL FILES>>",
 659                 SecurityConstants.FILE_EXECUTE_ACTION));
 660         }
 661     }
 662 
 663     /**
 664      * Throws a <code>SecurityException</code> if the
 665      * calling thread is not allowed to dynamic link the library code
 666      * specified by the string argument file. The argument is either a
 667      * simple library name or a complete filename.
 668      * <p>
 669      * This method is invoked for the current security manager by
 670      * methods <code>load</code> and <code>loadLibrary</code> of class
 671      * <code>Runtime</code>.
 672      * <p>
 673      * This method calls <code>checkPermission</code> with the
 674      * <code>RuntimePermission("loadLibrary."+lib)</code> permission.
 675      * <p>
 676      * If you override this method, then you should make a call to
 677      * <code>super.checkLink</code>
 678      * at the point the overridden method would normally throw an
 679      * exception.
 680      *
 681      * @param      lib   the name of the library.
 682      * @exception  SecurityException if the calling thread does not have
 683      *             permission to dynamically link the library.
 684      * @exception  NullPointerException if the <code>lib</code> argument is
 685      *             <code>null</code>.
 686      * @see        java.lang.Runtime#load(java.lang.String)
 687      * @see        java.lang.Runtime#loadLibrary(java.lang.String)
 688      * @see        #checkPermission(java.security.Permission) checkPermission
 689      */
 690     public void checkLink(String lib) {
 691         if (lib == null) {
 692             throw new NullPointerException("library can't be null");
 693         }
 694         checkPermission(new RuntimePermission("loadLibrary."+lib));
 695     }
 696 
 697     /**
 698      * Throws a <code>SecurityException</code> if the
 699      * calling thread is not allowed to read from the specified file
 700      * descriptor.
 701      * <p>
 702      * This method calls <code>checkPermission</code> with the
 703      * <code>RuntimePermission("readFileDescriptor")</code>
 704      * permission.
 705      * <p>
 706      * If you override this method, then you should make a call to
 707      * <code>super.checkRead</code>
 708      * at the point the overridden method would normally throw an
 709      * exception.
 710      *
 711      * @param      fd   the system-dependent file descriptor.
 712      * @exception  SecurityException  if the calling thread does not have
 713      *             permission to access the specified file descriptor.
 714      * @exception  NullPointerException if the file descriptor argument is
 715      *             <code>null</code>.
 716      * @see        java.io.FileDescriptor
 717      * @see        #checkPermission(java.security.Permission) checkPermission
 718      */
 719     public void checkRead(FileDescriptor fd) {
 720         if (fd == null) {
 721             throw new NullPointerException("file descriptor can't be null");
 722         }
 723         checkPermission(new RuntimePermission("readFileDescriptor"));
 724     }
 725 
 726     /**
 727      * Throws a <code>SecurityException</code> if the
 728      * calling thread is not allowed to read the file specified by the
 729      * string argument.
 730      * <p>
 731      * This method calls <code>checkPermission</code> with the
 732      * <code>FilePermission(file,"read")</code> permission.
 733      * <p>
 734      * If you override this method, then you should make a call to
 735      * <code>super.checkRead</code>
 736      * at the point the overridden method would normally throw an
 737      * exception.
 738      *
 739      * @param      file   the system-dependent file name.
 740      * @exception  SecurityException if the calling thread does not have
 741      *             permission to access the specified file.
 742      * @exception  NullPointerException if the <code>file</code> argument is
 743      *             <code>null</code>.
 744      * @see        #checkPermission(java.security.Permission) checkPermission
 745      */
 746     public void checkRead(String file) {
 747         checkPermission(new FilePermission(file,
 748             SecurityConstants.FILE_READ_ACTION));
 749     }
 750 
 751     /**
 752      * Throws a <code>SecurityException</code> if the
 753      * specified security context is not allowed to read the file
 754      * specified by the string argument. The context must be a security
 755      * context returned by a previous call to
 756      * <code>getSecurityContext</code>.
 757      * <p> If <code>context</code> is an instance of
 758      * <code>AccessControlContext</code> then the
 759      * <code>AccessControlContext.checkPermission</code> method will
 760      * be invoked with the <code>FilePermission(file,"read")</code> permission.
 761      * <p> If <code>context</code> is not an instance of
 762      * <code>AccessControlContext</code> then a
 763      * <code>SecurityException</code> is thrown.
 764      * <p>
 765      * If you override this method, then you should make a call to
 766      * <code>super.checkRead</code>
 767      * at the point the overridden method would normally throw an
 768      * exception.
 769      *
 770      * @param      file      the system-dependent filename.
 771      * @param      context   a system-dependent security context.
 772      * @exception  SecurityException  if the specified security context
 773      *             is not an instance of <code>AccessControlContext</code>
 774      *             (e.g., is <code>null</code>), or does not have permission
 775      *             to read the specified file.
 776      * @exception  NullPointerException if the <code>file</code> argument is
 777      *             <code>null</code>.
 778      * @see        java.lang.SecurityManager#getSecurityContext()
 779      * @see        java.security.AccessControlContext#checkPermission(java.security.Permission)
 780      */
 781     public void checkRead(String file, Object context) {
 782         checkPermission(
 783             new FilePermission(file, SecurityConstants.FILE_READ_ACTION),
 784             context);
 785     }
 786 
 787     /**
 788      * Throws a <code>SecurityException</code> if the
 789      * calling thread is not allowed to write to the specified file
 790      * descriptor.
 791      * <p>
 792      * This method calls <code>checkPermission</code> with the
 793      * <code>RuntimePermission("writeFileDescriptor")</code>
 794      * permission.
 795      * <p>
 796      * If you override this method, then you should make a call to
 797      * <code>super.checkWrite</code>
 798      * at the point the overridden method would normally throw an
 799      * exception.
 800      *
 801      * @param      fd   the system-dependent file descriptor.
 802      * @exception SecurityException  if the calling thread does not have
 803      *             permission to access the specified file descriptor.
 804      * @exception  NullPointerException if the file descriptor argument is
 805      *             <code>null</code>.
 806      * @see        java.io.FileDescriptor
 807      * @see        #checkPermission(java.security.Permission) checkPermission
 808      */
 809     public void checkWrite(FileDescriptor fd) {
 810         if (fd == null) {
 811             throw new NullPointerException("file descriptor can't be null");
 812         }
 813         checkPermission(new RuntimePermission("writeFileDescriptor"));
 814 
 815     }
 816 
 817     /**
 818      * Throws a <code>SecurityException</code> if the
 819      * calling thread is not allowed to write to the file specified by
 820      * the string argument.
 821      * <p>
 822      * This method calls <code>checkPermission</code> with the
 823      * <code>FilePermission(file,"write")</code> permission.
 824      * <p>
 825      * If you override this method, then you should make a call to
 826      * <code>super.checkWrite</code>
 827      * at the point the overridden method would normally throw an
 828      * exception.
 829      *
 830      * @param      file   the system-dependent filename.
 831      * @exception  SecurityException  if the calling thread does not
 832      *             have permission to access the specified file.
 833      * @exception  NullPointerException if the <code>file</code> argument is
 834      *             <code>null</code>.
 835      * @see        #checkPermission(java.security.Permission) checkPermission
 836      */
 837     public void checkWrite(String file) {
 838         checkPermission(new FilePermission(file,
 839             SecurityConstants.FILE_WRITE_ACTION));
 840     }
 841 
 842     /**
 843      * Throws a <code>SecurityException</code> if the
 844      * calling thread is not allowed to delete the specified file.
 845      * <p>
 846      * This method is invoked for the current security manager by the
 847      * <code>delete</code> method of class <code>File</code>.
 848      * <p>
 849      * This method calls <code>checkPermission</code> with the
 850      * <code>FilePermission(file,"delete")</code> permission.
 851      * <p>
 852      * If you override this method, then you should make a call to
 853      * <code>super.checkDelete</code>
 854      * at the point the overridden method would normally throw an
 855      * exception.
 856      *
 857      * @param      file   the system-dependent filename.
 858      * @exception  SecurityException if the calling thread does not
 859      *             have permission to delete the file.
 860      * @exception  NullPointerException if the <code>file</code> argument is
 861      *             <code>null</code>.
 862      * @see        java.io.File#delete()
 863      * @see        #checkPermission(java.security.Permission) checkPermission
 864      */
 865     public void checkDelete(String file) {
 866         checkPermission(new FilePermission(file,
 867             SecurityConstants.FILE_DELETE_ACTION));
 868     }
 869 
 870     /**
 871      * Throws a <code>SecurityException</code> if the
 872      * calling thread is not allowed to open a socket connection to the
 873      * specified host and port number.
 874      * <p>
 875      * A port number of <code>-1</code> indicates that the calling
 876      * method is attempting to determine the IP address of the specified
 877      * host name.
 878      * <p>
 879      * This method calls <code>checkPermission</code> with the
 880      * <code>SocketPermission(host+":"+port,"connect")</code> permission if
 881      * the port is not equal to -1. If the port is equal to -1, then
 882      * it calls <code>checkPermission</code> with the
 883      * <code>SocketPermission(host,"resolve")</code> permission.
 884      * <p>
 885      * If you override this method, then you should make a call to
 886      * <code>super.checkConnect</code>
 887      * at the point the overridden method would normally throw an
 888      * exception.
 889      *
 890      * @param      host   the host name port to connect to.
 891      * @param      port   the protocol port to connect to.
 892      * @exception  SecurityException  if the calling thread does not have
 893      *             permission to open a socket connection to the specified
 894      *               <code>host</code> and <code>port</code>.
 895      * @exception  NullPointerException if the <code>host</code> argument is
 896      *             <code>null</code>.
 897      * @see        #checkPermission(java.security.Permission) checkPermission
 898      */
 899     public void checkConnect(String host, int port) {
 900         if (host == null) {
 901             throw new NullPointerException("host can't be null");
 902         }
 903         if (!host.startsWith("[") && host.indexOf(':') != -1) {
 904             host = "[" + host + "]";
 905         }
 906         if (port == -1) {
 907             checkPermission(new SocketPermission(host,
 908                 SecurityConstants.SOCKET_RESOLVE_ACTION));
 909         } else {
 910             checkPermission(new SocketPermission(host+":"+port,
 911                 SecurityConstants.SOCKET_CONNECT_ACTION));
 912         }
 913     }
 914 
 915     /**
 916      * Throws a <code>SecurityException</code> if the
 917      * specified security context is not allowed to open a socket
 918      * connection to the specified host and port number.
 919      * <p>
 920      * A port number of <code>-1</code> indicates that the calling
 921      * method is attempting to determine the IP address of the specified
 922      * host name.
 923      * <p> If <code>context</code> is not an instance of
 924      * <code>AccessControlContext</code> then a
 925      * <code>SecurityException</code> is thrown.
 926      * <p>
 927      * Otherwise, the port number is checked. If it is not equal
 928      * to -1, the <code>context</code>'s <code>checkPermission</code>
 929      * method is called with a
 930      * <code>SocketPermission(host+":"+port,"connect")</code> permission.
 931      * If the port is equal to -1, then
 932      * the <code>context</code>'s <code>checkPermission</code> method
 933      * is called with a
 934      * <code>SocketPermission(host,"resolve")</code> permission.
 935      * <p>
 936      * If you override this method, then you should make a call to
 937      * <code>super.checkConnect</code>
 938      * at the point the overridden method would normally throw an
 939      * exception.
 940      *
 941      * @param      host      the host name port to connect to.
 942      * @param      port      the protocol port to connect to.
 943      * @param      context   a system-dependent security context.
 944      * @exception  SecurityException if the specified security context
 945      *             is not an instance of <code>AccessControlContext</code>
 946      *             (e.g., is <code>null</code>), or does not have permission
 947      *             to open a socket connection to the specified
 948      *             <code>host</code> and <code>port</code>.
 949      * @exception  NullPointerException if the <code>host</code> argument is
 950      *             <code>null</code>.
 951      * @see        java.lang.SecurityManager#getSecurityContext()
 952      * @see        java.security.AccessControlContext#checkPermission(java.security.Permission)
 953      */
 954     public void checkConnect(String host, int port, Object context) {
 955         if (host == null) {
 956             throw new NullPointerException("host can't be null");
 957         }
 958         if (!host.startsWith("[") && host.indexOf(':') != -1) {
 959             host = "[" + host + "]";
 960         }
 961         if (port == -1)
 962             checkPermission(new SocketPermission(host,
 963                 SecurityConstants.SOCKET_RESOLVE_ACTION),
 964                 context);
 965         else
 966             checkPermission(new SocketPermission(host+":"+port,
 967                 SecurityConstants.SOCKET_CONNECT_ACTION),
 968                 context);
 969     }
 970 
 971     /**
 972      * Throws a <code>SecurityException</code> if the
 973      * calling thread is not allowed to wait for a connection request on
 974      * the specified local port number.
 975      * <p>
 976      * This method calls <code>checkPermission</code> with the
 977      * <code>SocketPermission("localhost:"+port,"listen")</code>.
 978      * <p>
 979      * If you override this method, then you should make a call to
 980      * <code>super.checkListen</code>
 981      * at the point the overridden method would normally throw an
 982      * exception.
 983      *
 984      * @param      port   the local port.
 985      * @exception  SecurityException  if the calling thread does not have
 986      *             permission to listen on the specified port.
 987      * @see        #checkPermission(java.security.Permission) checkPermission
 988      */
 989     public void checkListen(int port) {
 990         checkPermission(new SocketPermission("localhost:"+port,
 991             SecurityConstants.SOCKET_LISTEN_ACTION));
 992     }
 993 
 994     /**
 995      * Throws a <code>SecurityException</code> if the
 996      * calling thread is not permitted to accept a socket connection from
 997      * the specified host and port number.
 998      * <p>
 999      * This method is invoked for the current security manager by the
1000      * <code>accept</code> method of class <code>ServerSocket</code>.
1001      * <p>
1002      * This method calls <code>checkPermission</code> with the
1003      * <code>SocketPermission(host+":"+port,"accept")</code> permission.
1004      * <p>
1005      * If you override this method, then you should make a call to
1006      * <code>super.checkAccept</code>
1007      * at the point the overridden method would normally throw an
1008      * exception.
1009      *
1010      * @param      host   the host name of the socket connection.
1011      * @param      port   the port number of the socket connection.
1012      * @exception  SecurityException  if the calling thread does not have
1013      *             permission to accept the connection.
1014      * @exception  NullPointerException if the <code>host</code> argument is
1015      *             <code>null</code>.
1016      * @see        java.net.ServerSocket#accept()
1017      * @see        #checkPermission(java.security.Permission) checkPermission
1018      */
1019     public void checkAccept(String host, int port) {
1020         if (host == null) {
1021             throw new NullPointerException("host can't be null");
1022         }
1023         if (!host.startsWith("[") && host.indexOf(':') != -1) {
1024             host = "[" + host + "]";
1025         }
1026         checkPermission(new SocketPermission(host+":"+port,
1027             SecurityConstants.SOCKET_ACCEPT_ACTION));
1028     }
1029 
1030     /**
1031      * Throws a <code>SecurityException</code> if the
1032      * calling thread is not allowed to use
1033      * (join/leave/send/receive) IP multicast.
1034      * <p>
1035      * This method calls <code>checkPermission</code> with the
1036      * <code>java.net.SocketPermission(maddr.getHostAddress(),
1037      * "accept,connect")</code> permission.
1038      * <p>
1039      * If you override this method, then you should make a call to
1040      * <code>super.checkMulticast</code>
1041      * at the point the overridden method would normally throw an
1042      * exception.
1043      *
1044      * @param      maddr  Internet group address to be used.
1045      * @exception  SecurityException  if the calling thread is not allowed to
1046      *  use (join/leave/send/receive) IP multicast.
1047      * @exception  NullPointerException if the address argument is
1048      *             <code>null</code>.
1049      * @since      1.1
1050      * @see        #checkPermission(java.security.Permission) checkPermission
1051      */
1052     public void checkMulticast(InetAddress maddr) {
1053         String host = maddr.getHostAddress();
1054         if (!host.startsWith("[") && host.indexOf(':') != -1) {
1055             host = "[" + host + "]";
1056         }
1057         checkPermission(new SocketPermission(host,
1058             SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
1059     }
1060 
1061     /**
1062      * Throws a <code>SecurityException</code> if the
1063      * calling thread is not allowed to use
1064      * (join/leave/send/receive) IP multicast.
1065      * <p>
1066      * This method calls <code>checkPermission</code> with the
1067      * <code>java.net.SocketPermission(maddr.getHostAddress(),
1068      * "accept,connect")</code> permission.
1069      * <p>
1070      * If you override this method, then you should make a call to
1071      * <code>super.checkMulticast</code>
1072      * at the point the overridden method would normally throw an
1073      * exception.
1074      *
1075      * @param      maddr  Internet group address to be used.
1076      * @param      ttl        value in use, if it is multicast send.
1077      * Note: this particular implementation does not use the ttl
1078      * parameter.
1079      * @exception  SecurityException  if the calling thread is not allowed to
1080      *  use (join/leave/send/receive) IP multicast.
1081      * @exception  NullPointerException if the address argument is
1082      *             <code>null</code>.
1083      * @since      1.1
1084      * @deprecated Use #checkPermission(java.security.Permission) instead
1085      * @see        #checkPermission(java.security.Permission) checkPermission
1086      */
1087     @Deprecated(since="1.4")
1088     public void checkMulticast(InetAddress maddr, byte ttl) {
1089         String host = maddr.getHostAddress();
1090         if (!host.startsWith("[") && host.indexOf(':') != -1) {
1091             host = "[" + host + "]";
1092         }
1093         checkPermission(new SocketPermission(host,
1094             SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
1095     }
1096 
1097     /**
1098      * Throws a <code>SecurityException</code> if the
1099      * calling thread is not allowed to access or modify the system
1100      * properties.
1101      * <p>
1102      * This method is used by the <code>getProperties</code> and
1103      * <code>setProperties</code> methods of class <code>System</code>.
1104      * <p>
1105      * This method calls <code>checkPermission</code> with the
1106      * <code>PropertyPermission("*", "read,write")</code> permission.
1107      * <p>
1108      * If you override this method, then you should make a call to
1109      * <code>super.checkPropertiesAccess</code>
1110      * at the point the overridden method would normally throw an
1111      * exception.
1112      *
1113      * @exception  SecurityException  if the calling thread does not have
1114      *             permission to access or modify the system properties.
1115      * @see        java.lang.System#getProperties()
1116      * @see        java.lang.System#setProperties(java.util.Properties)
1117      * @see        #checkPermission(java.security.Permission) checkPermission
1118      */
1119     public void checkPropertiesAccess() {
1120         checkPermission(new PropertyPermission("*",
1121             SecurityConstants.PROPERTY_RW_ACTION));
1122     }
1123 
1124     /**
1125      * Throws a <code>SecurityException</code> if the
1126      * calling thread is not allowed to access the system property with
1127      * the specified <code>key</code> name.
1128      * <p>
1129      * This method is used by the <code>getProperty</code> method of
1130      * class <code>System</code>.
1131      * <p>
1132      * This method calls <code>checkPermission</code> with the
1133      * <code>PropertyPermission(key, "read")</code> permission.
1134      * <p>
1135      * If you override this method, then you should make a call to
1136      * <code>super.checkPropertyAccess</code>
1137      * at the point the overridden method would normally throw an
1138      * exception.
1139      *
1140      * @param      key   a system property key.
1141      *
1142      * @exception  SecurityException  if the calling thread does not have
1143      *             permission to access the specified system property.
1144      * @exception  NullPointerException if the <code>key</code> argument is
1145      *             <code>null</code>.
1146      * @exception  IllegalArgumentException if <code>key</code> is empty.
1147      *
1148      * @see        java.lang.System#getProperty(java.lang.String)
1149      * @see        #checkPermission(java.security.Permission) checkPermission
1150      */
1151     public void checkPropertyAccess(String key) {
1152         checkPermission(new PropertyPermission(key,
1153             SecurityConstants.PROPERTY_READ_ACTION));
1154     }
1155 
1156     /**
1157      * Throws a <code>SecurityException</code> if the
1158      * calling thread is not allowed to initiate a print job request.
1159      * <p>
1160      * This method calls
1161      * <code>checkPermission</code> with the
1162      * <code>RuntimePermission("queuePrintJob")</code> permission.
1163      * <p>
1164      * If you override this method, then you should make a call to
1165      * <code>super.checkPrintJobAccess</code>
1166      * at the point the overridden method would normally throw an
1167      * exception.
1168      *
1169      * @exception  SecurityException  if the calling thread does not have
1170      *             permission to initiate a print job request.
1171      * @since   1.1
1172      * @see        #checkPermission(java.security.Permission) checkPermission
1173      */
1174     public void checkPrintJobAccess() {
1175         checkPermission(new RuntimePermission("queuePrintJob"));
1176     }
1177 
1178     /*
1179      * We have an initial invalid bit (initially false) for the class
1180      * variables which tell if the cache is valid.  If the underlying
1181      * java.security.Security property changes via setProperty(), the
1182      * Security class uses reflection to change the variable and thus
1183      * invalidate the cache.
1184      *
1185      * Locking is handled by synchronization to the
1186      * packageAccessLock/packageDefinitionLock objects.  They are only
1187      * used in this class.
1188      *
1189      * Note that cache invalidation as a result of the property change
1190      * happens without using these locks, so there may be a delay between
1191      * when a thread updates the property and when other threads updates
1192      * the cache.
1193      */
1194     private static boolean packageAccessValid = false;
1195     private static String[] packageAccess;
1196     private static final Object packageAccessLock = new Object();
1197 
1198     private static boolean packageDefinitionValid = false;
1199     private static String[] packageDefinition;
1200     private static final Object packageDefinitionLock = new Object();
1201 
1202     private static String[] getPackages(String p) {
1203         String packages[] = null;
1204         if (p != null && !p.isEmpty()) {
1205             java.util.StringTokenizer tok =
1206                 new java.util.StringTokenizer(p, ",");
1207             int n = tok.countTokens();
1208             if (n > 0) {
1209                 packages = new String[n];
1210                 int i = 0;
1211                 while (tok.hasMoreElements()) {
1212                     String s = tok.nextToken().trim();
1213                     packages[i++] = s;
1214                 }
1215             }
1216         }
1217 
1218         if (packages == null) {
1219             packages = new String[0];
1220         }
1221         return packages;
1222     }
1223 
1224     // The non-exported packages in modules defined to the boot or platform
1225     // class loaders. A non-exported package is a package that is not exported
1226     // or is only exported to specific modules.
1227     private static final Map<String, Boolean> nonExportedPkgs = new ConcurrentHashMap<>();
1228     static {
1229         addNonExportedPackages(ModuleLayer.boot());
1230     }
1231 
1232     /**
1233      * Record the non-exported packages of the modules in the given layer
1234      */
1235     static void addNonExportedPackages(ModuleLayer layer) {
1236         Set<String> bootModules = ModuleLoaderMap.bootModules();
1237         Set<String> platformModules = ModuleLoaderMap.platformModules();
1238         layer.modules().stream()
1239                 .map(Module::getDescriptor)
1240                 .filter(md -> bootModules.contains(md.name())
1241                         || platformModules.contains(md.name()))
1242                 .map(SecurityManager::nonExportedPkgs)
1243                 .flatMap(Set::stream)
1244                 .forEach(pn -> nonExportedPkgs.put(pn, Boolean.TRUE));
1245     }
1246 
1247 
1248     /**
1249      * Called by java.security.Security
1250      */
1251     static void invalidatePackageAccessCache() {
1252         synchronized (packageAccessLock) {
1253             packageAccessValid = false;
1254         }
1255         synchronized (packageDefinitionLock) {
1256             packageDefinitionValid = false;
1257         }
1258     }
1259 
1260     /**
1261      * Returns the non-exported packages of the specified module.
1262      */
1263     private static Set<String> nonExportedPkgs(ModuleDescriptor md) {
1264         // start with all packages in the module
1265         Set<String> pkgs = new HashSet<>(md.packages());
1266 
1267         // remove the non-qualified exported packages
1268         md.exports().stream()
1269                     .filter(p -> !p.isQualified())
1270                     .map(Exports::source)
1271                     .forEach(pkgs::remove);
1272 
1273         // remove the non-qualified open packages
1274         md.opens().stream()
1275                   .filter(p -> !p.isQualified())
1276                   .map(Opens::source)
1277                   .forEach(pkgs::remove);
1278 
1279         return pkgs;
1280     }
1281 
1282     /**
1283      * Throws a {@code SecurityException} if the calling thread is not allowed
1284      * to access the specified package.
1285      * <p>
1286      * During class loading, this method may be called by the {@code loadClass}
1287      * method of class loaders and by the Java Virtual Machine to ensure that
1288      * the caller is allowed to access the package of the class that is
1289      * being loaded.
1290      * <p>
1291      * This method checks if the specified package starts with or equals
1292      * any of the packages in the {@code package.access} Security Property.
1293      * An implementation may also check the package against an additional
1294      * list of restricted packages as noted below. If the package is restricted,
1295      * {@link #checkPermission(Permission)} is called with a
1296      * {@code RuntimePermission("accessClassInPackage."+pkg)} permission.
1297      * <p>
1298      * If this method is overridden, then {@code super.checkPackageAccess}
1299      * should be called as the first line in the overridden method.
1300      *
1301      * @implNote
1302      * This implementation also restricts all non-exported packages of modules
1303      * loaded by {@linkplain ClassLoader#getPlatformClassLoader
1304      * the platform class loader} or its ancestors. A "non-exported package"
1305      * refers to a package that is not exported to all modules. Specifically,
1306      * it refers to a package that either is not exported at all by its
1307      * containing module or is exported in a qualified fashion by its
1308      * containing module.
1309      *
1310      * @param      pkg   the package name.
1311      * @throws     SecurityException  if the calling thread does not have
1312      *             permission to access the specified package.
1313      * @throws     NullPointerException if the package name argument is
1314      *             {@code null}.
1315      * @see        java.lang.ClassLoader#loadClass(String, boolean) loadClass
1316      * @see        java.security.Security#getProperty getProperty
1317      * @see        #checkPermission(Permission) checkPermission
1318      */
1319     public void checkPackageAccess(String pkg) {
1320         Objects.requireNonNull(pkg, "package name can't be null");
1321 
1322         // check if pkg is not exported to all modules
1323         if (nonExportedPkgs.containsKey(pkg)) {
1324             checkPermission(
1325                 new RuntimePermission("accessClassInPackage." + pkg));
1326             return;
1327         }
1328 
1329         String[] restrictedPkgs;
1330         synchronized (packageAccessLock) {
1331             /*
1332              * Do we need to update our property array?
1333              */
1334             if (!packageAccessValid) {
1335                 String tmpPropertyStr =
1336                     AccessController.doPrivileged(
1337                         new PrivilegedAction<>() {
1338                             public String run() {
1339                                 return Security.getProperty("package.access");
1340                             }
1341                         }
1342                     );
1343                 packageAccess = getPackages(tmpPropertyStr);
1344                 packageAccessValid = true;
1345             }
1346 
1347             // Using a snapshot of packageAccess -- don't care if static field
1348             // changes afterwards; array contents won't change.
1349             restrictedPkgs = packageAccess;
1350         }
1351 
1352         /*
1353          * Traverse the list of packages, check for any matches.
1354          */
1355         final int plen = pkg.length();
1356         for (String restrictedPkg : restrictedPkgs) {
1357             final int rlast = restrictedPkg.length() - 1;
1358 
1359             // Optimizations:
1360             //
1361             // If rlast >= plen then restrictedPkg is longer than pkg by at
1362             // least one char. This means pkg cannot start with restrictedPkg,
1363             // since restrictedPkg will be longer than pkg.
1364             //
1365             // Similarly if rlast != plen, then pkg + "." cannot be the same
1366             // as restrictedPkg, since pkg + "." will have a different length
1367             // than restrictedPkg.
1368             //
1369             if (rlast < plen && pkg.startsWith(restrictedPkg) ||
1370                 // The following test is equivalent to
1371                 // restrictedPkg.equals(pkg + ".") but is noticeably more
1372                 // efficient:
1373                 rlast == plen && restrictedPkg.startsWith(pkg) &&
1374                 restrictedPkg.charAt(rlast) == '.')
1375             {
1376                 checkPermission(
1377                     new RuntimePermission("accessClassInPackage." + pkg));
1378                 break;  // No need to continue; only need to check this once
1379             }
1380         }
1381     }
1382 
1383     /**
1384      * Throws a {@code SecurityException} if the calling thread is not
1385      * allowed to define classes in the specified package.
1386      * <p>
1387      * This method is called by the {@code loadClass} method of some
1388      * class loaders.
1389      * <p>
1390      * This method checks if the specified package starts with or equals
1391      * any of the packages in the {@code package.definition} Security
1392      * Property. An implementation may also check the package against an
1393      * additional list of restricted packages as noted below. If the package
1394      * is restricted, {@link #checkPermission(Permission)} is called with a
1395      * {@code RuntimePermission("defineClassInPackage."+pkg)} permission.
1396      * <p>
1397      * If this method is overridden, then {@code super.checkPackageDefinition}
1398      * should be called as the first line in the overridden method.
1399      *
1400      * @implNote
1401      * This implementation also restricts all non-exported packages of modules
1402      * loaded by {@linkplain ClassLoader#getPlatformClassLoader
1403      * the platform class loader} or its ancestors. A "non-exported package"
1404      * refers to a package that is not exported to all modules. Specifically,
1405      * it refers to a package that either is not exported at all by its
1406      * containing module or is exported in a qualified fashion by its
1407      * containing module.
1408      *
1409      * @param      pkg   the package name.
1410      * @throws     SecurityException  if the calling thread does not have
1411      *             permission to define classes in the specified package.
1412      * @throws     NullPointerException if the package name argument is
1413      *             {@code null}.
1414      * @see        java.lang.ClassLoader#loadClass(String, boolean)
1415      * @see        java.security.Security#getProperty getProperty
1416      * @see        #checkPermission(Permission) checkPermission
1417      */
1418     public void checkPackageDefinition(String pkg) {
1419         Objects.requireNonNull(pkg, "package name can't be null");
1420 
1421         // check if pkg is not exported to all modules
1422         if (nonExportedPkgs.containsKey(pkg)) {
1423             checkPermission(
1424                 new RuntimePermission("defineClassInPackage." + pkg));
1425             return;
1426         }
1427 
1428         String[] pkgs;
1429         synchronized (packageDefinitionLock) {
1430             /*
1431              * Do we need to update our property array?
1432              */
1433             if (!packageDefinitionValid) {
1434                 String tmpPropertyStr =
1435                     AccessController.doPrivileged(
1436                         new PrivilegedAction<>() {
1437                             public String run() {
1438                                 return java.security.Security.getProperty(
1439                                     "package.definition");
1440                             }
1441                         }
1442                     );
1443                 packageDefinition = getPackages(tmpPropertyStr);
1444                 packageDefinitionValid = true;
1445             }
1446             // Using a snapshot of packageDefinition -- don't care if static
1447             // field changes afterwards; array contents won't change.
1448             pkgs = packageDefinition;
1449         }
1450 
1451         /*
1452          * Traverse the list of packages, check for any matches.
1453          */
1454         for (String restrictedPkg : pkgs) {
1455             if (pkg.startsWith(restrictedPkg) || restrictedPkg.equals(pkg + ".")) {
1456                 checkPermission(
1457                     new RuntimePermission("defineClassInPackage." + pkg));
1458                 break; // No need to continue; only need to check this once
1459             }
1460         }
1461     }
1462 
1463     /**
1464      * Throws a <code>SecurityException</code> if the
1465      * calling thread is not allowed to set the socket factory used by
1466      * <code>ServerSocket</code> or <code>Socket</code>, or the stream
1467      * handler factory used by <code>URL</code>.
1468      * <p>
1469      * This method calls <code>checkPermission</code> with the
1470      * <code>RuntimePermission("setFactory")</code> permission.
1471      * <p>
1472      * If you override this method, then you should make a call to
1473      * <code>super.checkSetFactory</code>
1474      * at the point the overridden method would normally throw an
1475      * exception.
1476      *
1477      * @exception  SecurityException  if the calling thread does not have
1478      *             permission to specify a socket factory or a stream
1479      *             handler factory.
1480      *
1481      * @see        java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory) setSocketFactory
1482      * @see        java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory) setSocketImplFactory
1483      * @see        java.net.URL#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory) setURLStreamHandlerFactory
1484      * @see        #checkPermission(java.security.Permission) checkPermission
1485      */
1486     public void checkSetFactory() {
1487         checkPermission(new RuntimePermission("setFactory"));
1488     }
1489 
1490     /**
1491      * Determines whether the permission with the specified permission target
1492      * name should be granted or denied.
1493      *
1494      * <p> If the requested permission is allowed, this method returns
1495      * quietly. If denied, a SecurityException is raised.
1496      *
1497      * <p> This method creates a <code>SecurityPermission</code> object for
1498      * the given permission target name and calls <code>checkPermission</code>
1499      * with it.
1500      *
1501      * <p> See the documentation for
1502      * <code>{@link java.security.SecurityPermission}</code> for
1503      * a list of possible permission target names.
1504      *
1505      * <p> If you override this method, then you should make a call to
1506      * <code>super.checkSecurityAccess</code>
1507      * at the point the overridden method would normally throw an
1508      * exception.
1509      *
1510      * @param target the target name of the <code>SecurityPermission</code>.
1511      *
1512      * @exception SecurityException if the calling thread does not have
1513      * permission for the requested access.
1514      * @exception NullPointerException if <code>target</code> is null.
1515      * @exception IllegalArgumentException if <code>target</code> is empty.
1516      *
1517      * @since   1.1
1518      * @see        #checkPermission(java.security.Permission) checkPermission
1519      */
1520     public void checkSecurityAccess(String target) {
1521         checkPermission(new SecurityPermission(target));
1522     }
1523 
1524     /**
1525      * Returns the thread group into which to instantiate any new
1526      * thread being created at the time this is being called.
1527      * By default, it returns the thread group of the current
1528      * thread. This should be overridden by a specific security
1529      * manager to return the appropriate thread group.
1530      *
1531      * @return  ThreadGroup that new threads are instantiated into
1532      * @since   1.1
1533      * @see     java.lang.ThreadGroup
1534      */
1535     public ThreadGroup getThreadGroup() {
1536         return Thread.currentThread().getThreadGroup();
1537     }
1538 
1539 }