       1 /*
       2  * Copyright (c) 1995, 2019, 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} class contains many methods with
      64  * names that begin with the word {@code check}. 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} 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} 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} returns quietly. If denied, a
     189  * {@code SecurityException} is thrown.
     190  * <p>
     191  * The default implementation of each of the other
     192  * {@code check} methods in {@code SecurityManager} is to
     193  * call the {@code SecurityManager checkPermission} method
     194  * to determine if the calling thread has permission to perform the requested
     195  * operation.
     196  * <p>
     197  * Note that the {@code checkPermission} 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} 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} 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} 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},
     238  * {@code java.net.SocketPermission},
     239  * {@code java.net.NetPermission},
     240  * {@code java.security.SecurityPermission},
     241  * {@code java.lang.RuntimePermission},
     242  * {@code java.util.PropertyPermission},
     243  * {@code java.awt.AWTPermission},
     244  * {@code java.lang.reflect.ReflectPermission}, and
     245  * {@code java.io.SerializablePermission}.
     246  *
     247  * <p>All but the first two (FilePermission and SocketPermission) are
     248  * subclasses of {@code java.security.BasicPermission}, which itself
     249  * is an abstract subclass of the
     250  * top-level class for permissions, which is
     251  * {@code java.security.Permission}. 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}). 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} 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} 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}
     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} 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  * @deprecated The Security Manager is deprecated and subject to removal in a
     317  *       future release. There is no replacement for the Security Manager.
     318  *       See <a href="https://openjdk.java.net/jeps/411">JEP 411</a> for
     319  *       discussion and alternatives.
     320  */
     321 @Deprecated(since="17", forRemoval=true)
     322 public class SecurityManager {
     323
     324     /*
     325      * Have we been initialized. Effective against finalizer attacks.
     326      */
     327     private boolean initialized = false;
     328
     329     /**
     330      * Constructs a new {@code SecurityManager}.
     331      *
     332      * <p> If there is a security manager already installed, this method first
     333      * calls the security manager's {@code checkPermission} method
     334      * with the {@code RuntimePermission("createSecurityManager")}
     335      * permission to ensure the calling thread has permission to create a new
     336      * security manager.
     337      * This may result in throwing a {@code SecurityException}.
     338      *
     339      * @throws     java.lang.SecurityException if a security manager already
     340      *             exists and its {@code checkPermission} method
     341      *             doesn't allow creation of a new security manager.
     342      * @see        java.lang.System#getSecurityManager()
     343      * @see        #checkPermission(java.security.Permission) checkPermission
     344      * @see java.lang.RuntimePermission
     345      */
     346     public SecurityManager() {
     347         synchronized(SecurityManager.class) {
     348             SecurityManager sm = System.getSecurityManager();
     349             if (sm != null) {
     350                 // ask the currently installed security manager if we
     351                 // can create a new one.
     352                 sm.checkPermission(new RuntimePermission
     353                                    ("createSecurityManager"));
     354             }
     355             initialized = true;
     356         }
     357     }
     358
     359     /**
     360      * Returns the current execution stack as an array of classes.
     361      * <p>
     362      * The length of the array is the number of methods on the execution
     363      * stack. The element at index {@code 0} is the class of the
     364      * currently executing method, the element at index {@code 1} is
     365      * the class of that method's caller, and so on.
     366      *
     367      * @return  the execution stack.
     368      */
     369     protected native Class<?>[] getClassContext();
     370
     371     /**
     372      * Creates an object that encapsulates the current execution
     373      * environment. The result of this method is used, for example, by the
     374      * three-argument {@code checkConnect} method and by the
     375      * two-argument {@code checkRead} method.
     376      * These methods are needed because a trusted method may be called
     377      * on to read a file or open a socket on behalf of another method.
     378      * The trusted method needs to determine if the other (possibly
     379      * untrusted) method would be allowed to perform the operation on its
     380      * own.
     381      * <p> The default implementation of this method is to return
     382      * an {@code AccessControlContext} object.
     383      *
     384      * @return  an implementation-dependent object that encapsulates
     385      *          sufficient information about the current execution environment
     386      *          to perform some security checks later.
     387      * @see     java.lang.SecurityManager#checkConnect(java.lang.String, int,
     388      *   java.lang.Object) checkConnect
     389      * @see     java.lang.SecurityManager#checkRead(java.lang.String,
     390      *   java.lang.Object) checkRead
     391      * @see     java.security.AccessControlContext AccessControlContext
     392      */
     393     public Object getSecurityContext() {
     394         return AccessController.getContext();
     395     }
     396
     397     /**
     398      * Throws a {@code SecurityException} if the requested
     399      * access, specified by the given permission, is not permitted based
     400      * on the security policy currently in effect.
     401      * <p>
     402      * This method calls {@code AccessController.checkPermission}
     403      * with the given permission.
     404      *
     405      * @param     perm   the requested permission.
     406      * @throws    SecurityException if access is not permitted based on
     407      *            the current security policy.
     408      * @throws    NullPointerException if the permission argument is
     409      *            {@code null}.
     410      * @since     1.2
     411      */
     412     public void checkPermission(Permission perm) {
     413         java.security.AccessController.checkPermission(perm);
     414     }
     415
     416     /**
     417      * Throws a {@code SecurityException} if the
     418      * specified security context is denied access to the resource
     419      * specified by the given permission.
     420      * The context must be a security
     421      * context returned by a previous call to
     422      * {@code getSecurityContext} and the access control
     423      * decision is based upon the configured security policy for
     424      * that security context.
     425      * <p>
     426      * If {@code context} is an instance of
     427      * {@code AccessControlContext} then the
     428      * {@code AccessControlContext.checkPermission} method is
     429      * invoked with the specified permission.
     430      * <p>
     431      * If {@code context} is not an instance of
     432      * {@code AccessControlContext} then a
     433      * {@code SecurityException} is thrown.
     434      *
     435      * @param      perm      the specified permission
     436      * @param      context   a system-dependent security context.
     437      * @throws     SecurityException  if the specified security context
     438      *             is not an instance of {@code AccessControlContext}
     439      *             (e.g., is {@code null}), or is denied access to the
     440      *             resource specified by the given permission.
     441      * @throws     NullPointerException if the permission argument is
     442      *             {@code null}.
     443      * @see        java.lang.SecurityManager#getSecurityContext()
     444      * @see java.security.AccessControlContext#checkPermission(java.security.Permission)
     445      * @since      1.2
     446      */
     447     public void checkPermission(Permission perm, Object context) {
     448         if (context instanceof AccessControlContext) {
     449             ((AccessControlContext)context).checkPermission(perm);
     450         } else {
     451             throw new SecurityException();
     452         }
     453     }
     454
     455     /**
     456      * Throws a {@code SecurityException} if the
     457      * calling thread is not allowed to create a new class loader.
     458      * <p>
     459      * This method calls {@code checkPermission} with the
     460      * {@code RuntimePermission("createClassLoader")}
     461      * permission.
     462      * <p>
     463      * If you override this method, then you should make a call to
     464      * {@code super.checkCreateClassLoader}
     465      * at the point the overridden method would normally throw an
     466      * exception.
     467      *
     468      * @throws    SecurityException if the calling thread does not
     469      *             have permission
     470      *             to create a new class loader.
     471      * @see        java.lang.ClassLoader#ClassLoader()
     472      * @see        #checkPermission(java.security.Permission) checkPermission
     473      */
     474     public void checkCreateClassLoader() {
     475         checkPermission(SecurityConstants.CREATE_CLASSLOADER_PERMISSION);
     476     }
     477
     478     /**
     479      * reference to the root thread group, used for the checkAccess
     480      * methods.
     481      */
     482
     483     private static ThreadGroup rootGroup = getRootGroup();
     484
     485     private static ThreadGroup getRootGroup() {
     486         ThreadGroup root =  Thread.currentThread().getThreadGroup();
     487         while (root.getParent() != null) {
     488             root = root.getParent();
     489         }
     490         return root;
     491     }
     492
     493     /**
     494      * Throws a {@code SecurityException} if the
     495      * calling thread is not allowed to modify the thread argument.
     496      * <p>
     497      * This method is invoked for the current security manager by the
     498      * {@code stop}, {@code suspend}, {@code resume},
     499      * {@code setPriority}, {@code setName}, and
     500      * {@code setDaemon} methods of class {@code Thread}.
     501      * <p>
     502      * If the thread argument is a system thread (belongs to
     503      * the thread group with a {@code null} parent) then
     504      * this method calls {@code checkPermission} with the
     505      * {@code RuntimePermission("modifyThread")} permission.
     506      * If the thread argument is <i>not</i> a system thread,
     507      * this method just returns silently.
     508      * <p>
     509      * Applications that want a stricter policy should override this
     510      * method. If this method is overridden, the method that overrides
     511      * it should additionally check to see if the calling thread has the
     512      * {@code RuntimePermission("modifyThread")} permission, and
     513      * if so, return silently. This is to ensure that code granted
     514      * that permission (such as the JDK itself) is allowed to
     515      * manipulate any thread.
     516      * <p>
     517      * If this method is overridden, then
     518      * {@code super.checkAccess} should
     519      * be called by the first statement in the overridden method, or the
     520      * equivalent security check should be placed in the overridden method.
     521      *
     522      * @param      t   the thread to be checked.
     523      * @throws     SecurityException  if the calling thread does not have
     524      *             permission to modify the thread.
     525      * @throws     NullPointerException if the thread argument is
     526      *             {@code null}.
     527      * @see        java.lang.Thread#resume() resume
     528      * @see        java.lang.Thread#setDaemon(boolean) setDaemon
     529      * @see        java.lang.Thread#setName(java.lang.String) setName
     530      * @see        java.lang.Thread#setPriority(int) setPriority
     531      * @see        java.lang.Thread#stop() stop
     532      * @see        java.lang.Thread#suspend() suspend
     533      * @see        #checkPermission(java.security.Permission) checkPermission
     534      */
     535     public void checkAccess(Thread t) {
     536         if (t == null) {
     537             throw new NullPointerException("thread can't be null");
     538         }
     539         if (t.getThreadGroup() == rootGroup) {
     540             checkPermission(SecurityConstants.MODIFY_THREAD_PERMISSION);
     541         } else {
     542             // just return
     543         }
     544     }
     545     /**
     546      * Throws a {@code SecurityException} if the
     547      * calling thread is not allowed to modify the thread group argument.
     548      * <p>
     549      * This method is invoked for the current security manager when a
     550      * new child thread or child thread group is created, and by the
     551      * {@code setDaemon}, {@code setMaxPriority},
     552      * {@code stop}, {@code suspend}, {@code resume}, and
     553      * {@code destroy} methods of class {@code ThreadGroup}.
     554      * <p>
     555      * If the thread group argument is the system thread group (
     556      * has a {@code null} parent) then
     557      * this method calls {@code checkPermission} with the
     558      * {@code RuntimePermission("modifyThreadGroup")} permission.
     559      * If the thread group argument is <i>not</i> the system thread group,
     560      * this method just returns silently.
     561      * <p>
     562      * Applications that want a stricter policy should override this
     563      * method. If this method is overridden, the method that overrides
     564      * it should additionally check to see if the calling thread has the
     565      * {@code RuntimePermission("modifyThreadGroup")} permission, and
     566      * if so, return silently. This is to ensure that code granted
     567      * that permission (such as the JDK itself) is allowed to
     568      * manipulate any thread.
     569      * <p>
     570      * If this method is overridden, then
     571      * {@code super.checkAccess} should
     572      * be called by the first statement in the overridden method, or the
     573      * equivalent security check should be placed in the overridden method.
     574      *
     575      * @param      g   the thread group to be checked.
     576      * @throws     SecurityException  if the calling thread does not have
     577      *             permission to modify the thread group.
     578      * @throws     NullPointerException if the thread group argument is
     579      *             {@code null}.
     580      * @see        java.lang.ThreadGroup#destroy() destroy
     581      * @see        java.lang.ThreadGroup#resume() resume
     582      * @see        java.lang.ThreadGroup#setDaemon(boolean) setDaemon
     583      * @see        java.lang.ThreadGroup#setMaxPriority(int) setMaxPriority
     584      * @see        java.lang.ThreadGroup#stop() stop
     585      * @see        java.lang.ThreadGroup#suspend() suspend
     586      * @see        #checkPermission(java.security.Permission) checkPermission
     587      */
     588     public void checkAccess(ThreadGroup g) {
     589         if (g == null) {
     590             throw new NullPointerException("thread group can't be null");
     591         }
     592         if (g == rootGroup) {
     593             checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
     594         } else {
     595             // just return
     596         }
     597     }
     598
     599     /**
     600      * Throws a {@code SecurityException} if the
     601      * calling thread is not allowed to cause the Java Virtual Machine to
     602      * halt with the specified status code.
     603      * <p>
     604      * This method is invoked for the current security manager by the
     605      * {@code exit} method of class {@code Runtime}. A status
     606      * of {@code 0} indicates success; other values indicate various
     607      * errors.
     608      * <p>
     609      * This method calls {@code checkPermission} with the
     610      * {@code RuntimePermission("exitVM."+status)} permission.
     611      * <p>
     612      * If you override this method, then you should make a call to
     613      * {@code super.checkExit}
     614      * at the point the overridden method would normally throw an
     615      * exception.
     616      *
     617      * @param      status   the exit status.
     618      * @throws    SecurityException if the calling thread does not have
     619      *              permission to halt the Java Virtual Machine with
     620      *              the specified status.
     621      * @see        java.lang.Runtime#exit(int) exit
     622      * @see        #checkPermission(java.security.Permission) checkPermission
     623      */
     624     public void checkExit(int status) {
     625         checkPermission(new RuntimePermission("exitVM."+status));
     626     }
     627
     628     /**
     629      * Throws a {@code SecurityException} if the
     630      * calling thread is not allowed to create a subprocess.
     631      * <p>
     632      * This method is invoked for the current security manager by the
     633      * {@code exec} methods of class {@code Runtime}.
     634      * <p>
     635      * This method calls {@code checkPermission} with the
     636      * {@code FilePermission(cmd,"execute")} permission
     637      * if cmd is an absolute path, otherwise it calls
     638      * {@code checkPermission} with
     639      * <code>FilePermission("&lt;&lt;ALL FILES&gt;&gt;","execute")</code>.
     640      * <p>
     641      * If you override this method, then you should make a call to
     642      * {@code super.checkExec}
     643      * at the point the overridden method would normally throw an
     644      * exception.
     645      *
     646      * @param      cmd   the specified system command.
     647      * @throws     SecurityException if the calling thread does not have
     648      *             permission to create a subprocess.
     649      * @throws     NullPointerException if the {@code cmd} argument is
     650      *             {@code null}.
     651      * @see     java.lang.Runtime#exec(java.lang.String)
     652      * @see     java.lang.Runtime#exec(java.lang.String, java.lang.String[])
     653      * @see     java.lang.Runtime#exec(java.lang.String[])
     654      * @see     java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
     655      * @see     #checkPermission(java.security.Permission) checkPermission
     656      */
     657     public void checkExec(String cmd) {
     658         File f = new File(cmd);
     659         if (f.isAbsolute()) {
     660             checkPermission(new FilePermission(cmd,
     661                 SecurityConstants.FILE_EXECUTE_ACTION));
     662         } else {
     663             checkPermission(new FilePermission("<<ALL FILES>>",
     664                 SecurityConstants.FILE_EXECUTE_ACTION));
     665         }
     666     }
     667
     668     /**
     669      * Throws a {@code SecurityException} if the
     670      * calling thread is not allowed to dynamic link the library code
     671      * specified by the string argument file. The argument is either a
     672      * simple library name or a complete filename.
     673      * <p>
     674      * This method is invoked for the current security manager by
     675      * methods {@code load} and {@code loadLibrary} of class
     676      * {@code Runtime}.
     677      * <p>
     678      * This method calls {@code checkPermission} with the
     679      * {@code RuntimePermission("loadLibrary."+lib)} permission.
     680      * <p>
     681      * If you override this method, then you should make a call to
     682      * {@code super.checkLink}
     683      * at the point the overridden method would normally throw an
     684      * exception.
     685      *
     686      * @param      lib   the name of the library.
     687      * @throws     SecurityException if the calling thread does not have
     688      *             permission to dynamically link the library.
     689      * @throws     NullPointerException if the {@code lib} argument is
     690      *             {@code null}.
     691      * @see        java.lang.Runtime#load(java.lang.String)
     692      * @see        java.lang.Runtime#loadLibrary(java.lang.String)
     693      * @see        #checkPermission(java.security.Permission) checkPermission
     694      */
     695     public void checkLink(String lib) {
     696         if (lib == null) {
     697             throw new NullPointerException("library can't be null");
     698         }
     699         checkPermission(new RuntimePermission("loadLibrary."+lib));
     700     }
     701
     702     /**
     703      * Throws a {@code SecurityException} if the
     704      * calling thread is not allowed to read from the specified file
     705      * descriptor.
     706      * <p>
     707      * This method calls {@code checkPermission} with the
     708      * {@code RuntimePermission("readFileDescriptor")}
     709      * permission.
     710      * <p>
     711      * If you override this method, then you should make a call to
     712      * {@code super.checkRead}
     713      * at the point the overridden method would normally throw an
     714      * exception.
     715      *
     716      * @param      fd   the system-dependent file descriptor.
     717      * @throws     SecurityException  if the calling thread does not have
     718      *             permission to access the specified file descriptor.
     719      * @throws     NullPointerException if the file descriptor argument is
     720      *             {@code null}.
     721      * @see        java.io.FileDescriptor
     722      * @see        #checkPermission(java.security.Permission) checkPermission
     723      */
     724     public void checkRead(FileDescriptor fd) {
     725         if (fd == null) {
     726             throw new NullPointerException("file descriptor can't be null");
     727         }
     728         checkPermission(new RuntimePermission("readFileDescriptor"));
     729     }
     730
     731     /**
     732      * Throws a {@code SecurityException} if the
     733      * calling thread is not allowed to read the file specified by the
     734      * string argument.
     735      * <p>
     736      * This method calls {@code checkPermission} with the
     737      * {@code FilePermission(file,"read")} permission.
     738      * <p>
     739      * If you override this method, then you should make a call to
     740      * {@code super.checkRead}
     741      * at the point the overridden method would normally throw an
     742      * exception.
     743      *
     744      * @param      file   the system-dependent file name.
     745      * @throws     SecurityException if the calling thread does not have
     746      *             permission to access the specified file.
     747      * @throws     NullPointerException if the {@code file} argument is
     748      *             {@code null}.
     749      * @see        #checkPermission(java.security.Permission) checkPermission
     750      */
     751     public void checkRead(String file) {
     752         checkPermission(new FilePermission(file,
     753             SecurityConstants.FILE_READ_ACTION));
     754     }
     755
     756     /**
     757      * Throws a {@code SecurityException} if the
     758      * specified security context is not allowed to read the file
     759      * specified by the string argument. The context must be a security
     760      * context returned by a previous call to
     761      * {@code getSecurityContext}.
     762      * <p> If {@code context} is an instance of
     763      * {@code AccessControlContext} then the
     764      * {@code AccessControlContext.checkPermission} method will
     765      * be invoked with the {@code FilePermission(file,"read")} permission.
     766      * <p> If {@code context} is not an instance of
     767      * {@code AccessControlContext} then a
     768      * {@code SecurityException} is thrown.
     769      * <p>
     770      * If you override this method, then you should make a call to
     771      * {@code super.checkRead}
     772      * at the point the overridden method would normally throw an
     773      * exception.
     774      *
     775      * @param      file      the system-dependent filename.
     776      * @param      context   a system-dependent security context.
     777      * @throws     SecurityException  if the specified security context
     778      *             is not an instance of {@code AccessControlContext}
     779      *             (e.g., is {@code null}), or does not have permission
     780      *             to read the specified file.
     781      * @throws     NullPointerException if the {@code file} argument is
     782      *             {@code null}.
     783      * @see        java.lang.SecurityManager#getSecurityContext()
     784      * @see        java.security.AccessControlContext#checkPermission(java.security.Permission)
     785      */
     786     public void checkRead(String file, Object context) {
     787         checkPermission(
     788             new FilePermission(file, SecurityConstants.FILE_READ_ACTION),
     789             context);
     790     }
     791
     792     /**
     793      * Throws a {@code SecurityException} if the
     794      * calling thread is not allowed to write to the specified file
     795      * descriptor.
     796      * <p>
     797      * This method calls {@code checkPermission} with the
     798      * {@code RuntimePermission("writeFileDescriptor")}
     799      * permission.
     800      * <p>
     801      * If you override this method, then you should make a call to
     802      * {@code super.checkWrite}
     803      * at the point the overridden method would normally throw an
     804      * exception.
     805      *
     806      * @param      fd   the system-dependent file descriptor.
     807      * @throws    SecurityException  if the calling thread does not have
     808      *             permission to access the specified file descriptor.
     809      * @throws     NullPointerException if the file descriptor argument is
     810      *             {@code null}.
     811      * @see        java.io.FileDescriptor
     812      * @see        #checkPermission(java.security.Permission) checkPermission
     813      */
     814     public void checkWrite(FileDescriptor fd) {
     815         if (fd == null) {
     816             throw new NullPointerException("file descriptor can't be null");
     817         }
     818         checkPermission(new RuntimePermission("writeFileDescriptor"));
     819
     820     }
     821
     822     /**
     823      * Throws a {@code SecurityException} if the
     824      * calling thread is not allowed to write to the file specified by
     825      * the string argument.
     826      * <p>
     827      * This method calls {@code checkPermission} with the
     828      * {@code FilePermission(file,"write")} permission.
     829      * <p>
     830      * If you override this method, then you should make a call to
     831      * {@code super.checkWrite}
     832      * at the point the overridden method would normally throw an
     833      * exception.
     834      *
     835      * @param      file   the system-dependent filename.
     836      * @throws     SecurityException  if the calling thread does not
     837      *             have permission to access the specified file.
     838      * @throws     NullPointerException if the {@code file} argument is
     839      *             {@code null}.
     840      * @see        #checkPermission(java.security.Permission) checkPermission
     841      */
     842     public void checkWrite(String file) {
     843         checkPermission(new FilePermission(file,
     844             SecurityConstants.FILE_WRITE_ACTION));
     845     }
     846
     847     /**
     848      * Throws a {@code SecurityException} if the
     849      * calling thread is not allowed to delete the specified file.
     850      * <p>
     851      * This method is invoked for the current security manager by the
     852      * {@code delete} method of class {@code File}.
     853      * <p>
     854      * This method calls {@code checkPermission} with the
     855      * {@code FilePermission(file,"delete")} permission.
     856      * <p>
     857      * If you override this method, then you should make a call to
     858      * {@code super.checkDelete}
     859      * at the point the overridden method would normally throw an
     860      * exception.
     861      *
     862      * @param      file   the system-dependent filename.
     863      * @throws     SecurityException if the calling thread does not
     864      *             have permission to delete the file.
     865      * @throws     NullPointerException if the {@code file} argument is
     866      *             {@code null}.
     867      * @see        java.io.File#delete()
     868      * @see        #checkPermission(java.security.Permission) checkPermission
     869      */
     870     public void checkDelete(String file) {
     871         checkPermission(new FilePermission(file,
     872             SecurityConstants.FILE_DELETE_ACTION));
     873     }
     874
     875     /**
     876      * Throws a {@code SecurityException} if the
     877      * calling thread is not allowed to open a socket connection to the
     878      * specified host and port number.
     879      * <p>
     880      * A port number of {@code -1} indicates that the calling
     881      * method is attempting to determine the IP address of the specified
     882      * host name.
     883      * <p>
     884      * This method calls {@code checkPermission} with the
     885      * {@code SocketPermission(host+":"+port,"connect")} permission if
     886      * the port is not equal to -1. If the port is equal to -1, then
     887      * it calls {@code checkPermission} with the
     888      * {@code SocketPermission(host,"resolve")} permission.
     889      * <p>
     890      * If you override this method, then you should make a call to
     891      * {@code super.checkConnect}
     892      * at the point the overridden method would normally throw an
     893      * exception.
     894      *
     895      * @param      host   the host name port to connect to.
     896      * @param      port   the protocol port to connect to.
     897      * @throws     SecurityException  if the calling thread does not have
     898      *             permission to open a socket connection to the specified
     899      *               {@code host} and {@code port}.
     900      * @throws     NullPointerException if the {@code host} argument is
     901      *             {@code null}.
     902      * @see        #checkPermission(java.security.Permission) checkPermission
     903      */
     904     public void checkConnect(String host, int port) {
     905         if (host == null) {
     906             throw new NullPointerException("host can't be null");
     907         }
     908         if (!host.startsWith("[") && host.indexOf(':') != -1) {
     909             host = "[" + host + "]";
     910         }
     911         if (port == -1) {
     912             checkPermission(new SocketPermission(host,
     913                 SecurityConstants.SOCKET_RESOLVE_ACTION));
     914         } else {
     915             checkPermission(new SocketPermission(host+":"+port,
     916                 SecurityConstants.SOCKET_CONNECT_ACTION));
     917         }
     918     }
     919
     920     /**
     921      * Throws a {@code SecurityException} if the
     922      * specified security context is not allowed to open a socket
     923      * connection to the specified host and port number.
     924      * <p>
     925      * A port number of {@code -1} indicates that the calling
     926      * method is attempting to determine the IP address of the specified
     927      * host name.
     928      * <p> If {@code context} is not an instance of
     929      * {@code AccessControlContext} then a
     930      * {@code SecurityException} is thrown.
     931      * <p>
     932      * Otherwise, the port number is checked. If it is not equal
     933      * to -1, the {@code context}'s {@code checkPermission}
     934      * method is called with a
     935      * {@code SocketPermission(host+":"+port,"connect")} permission.
     936      * If the port is equal to -1, then
     937      * the {@code context}'s {@code checkPermission} method
     938      * is called with a
     939      * {@code SocketPermission(host,"resolve")} permission.
     940      * <p>
     941      * If you override this method, then you should make a call to
     942      * {@code super.checkConnect}
     943      * at the point the overridden method would normally throw an
     944      * exception.
     945      *
     946      * @param      host      the host name port to connect to.
     947      * @param      port      the protocol port to connect to.
     948      * @param      context   a system-dependent security context.
     949      * @throws     SecurityException if the specified security context
     950      *             is not an instance of {@code AccessControlContext}
     951      *             (e.g., is {@code null}), or does not have permission
     952      *             to open a socket connection to the specified
     953      *             {@code host} and {@code port}.
     954      * @throws     NullPointerException if the {@code host} argument is
     955      *             {@code null}.
     956      * @see        java.lang.SecurityManager#getSecurityContext()
     957      * @see        java.security.AccessControlContext#checkPermission(java.security.Permission)
     958      */
     959     public void checkConnect(String host, int port, Object context) {
     960         if (host == null) {
     961             throw new NullPointerException("host can't be null");
     962         }
     963         if (!host.startsWith("[") && host.indexOf(':') != -1) {
     964             host = "[" + host + "]";
     965         }
     966         if (port == -1)
     967             checkPermission(new SocketPermission(host,
     968                 SecurityConstants.SOCKET_RESOLVE_ACTION),
     969                 context);
     970         else
     971             checkPermission(new SocketPermission(host+":"+port,
     972                 SecurityConstants.SOCKET_CONNECT_ACTION),
     973                 context);
     974     }
     975
     976     /**
     977      * Throws a {@code SecurityException} if the
     978      * calling thread is not allowed to wait for a connection request on
     979      * the specified local port number.
     980      * <p>
     981      * This method calls {@code checkPermission} with the
     982      * {@code SocketPermission("localhost:"+port,"listen")}.
     983      * <p>
     984      * If you override this method, then you should make a call to
     985      * {@code super.checkListen}
     986      * at the point the overridden method would normally throw an
     987      * exception.
     988      *
     989      * @param      port   the local port.
     990      * @throws     SecurityException  if the calling thread does not have
     991      *             permission to listen on the specified port.
     992      * @see        #checkPermission(java.security.Permission) checkPermission
     993      */
     994     public void checkListen(int port) {
     995         checkPermission(new SocketPermission("localhost:"+port,
     996             SecurityConstants.SOCKET_LISTEN_ACTION));
     997     }
     998
     999     /**
    1000      * Throws a {@code SecurityException} if the
    1001      * calling thread is not permitted to accept a socket connection from
    1002      * the specified host and port number.
    1003      * <p>
    1004      * This method is invoked for the current security manager by the
    1005      * {@code accept} method of class {@code ServerSocket}.
    1006      * <p>
    1007      * This method calls {@code checkPermission} with the
    1008      * {@code SocketPermission(host+":"+port,"accept")} permission.
    1009      * <p>
    1010      * If you override this method, then you should make a call to
    1011      * {@code super.checkAccept}
    1012      * at the point the overridden method would normally throw an
    1013      * exception.
    1014      *
    1015      * @param      host   the host name of the socket connection.
    1016      * @param      port   the port number of the socket connection.
    1017      * @throws     SecurityException  if the calling thread does not have
    1018      *             permission to accept the connection.
    1019      * @throws     NullPointerException if the {@code host} argument is
    1020      *             {@code null}.
    1021      * @see        java.net.ServerSocket#accept()
    1022      * @see        #checkPermission(java.security.Permission) checkPermission
    1023      */
    1024     public void checkAccept(String host, int port) {
    1025         if (host == null) {
    1026             throw new NullPointerException("host can't be null");
    1027         }
    1028         if (!host.startsWith("[") && host.indexOf(':') != -1) {
    1029             host = "[" + host + "]";
    1030         }
    1031         checkPermission(new SocketPermission(host+":"+port,
    1032             SecurityConstants.SOCKET_ACCEPT_ACTION));
    1033     }
    1034
    1035     /**
    1036      * Throws a {@code SecurityException} if the
    1037      * calling thread is not allowed to use
    1038      * (join/leave/send/receive) IP multicast.
    1039      * <p>
    1040      * This method calls {@code checkPermission} with the
    1041      * <code>java.net.SocketPermission(maddr.getHostAddress(),
    1042      * "accept,connect")</code> permission.
    1043      * <p>
    1044      * If you override this method, then you should make a call to
    1045      * {@code super.checkMulticast}
    1046      * at the point the overridden method would normally throw an
    1047      * exception.
    1048      *
    1049      * @param      maddr  Internet group address to be used.
    1050      * @throws     SecurityException  if the calling thread is not allowed to
    1051      *  use (join/leave/send/receive) IP multicast.
    1052      * @throws     NullPointerException if the address argument is
    1053      *             {@code null}.
    1054      * @since      1.1
    1055      * @see        #checkPermission(java.security.Permission) checkPermission
    1056      */
    1057     public void checkMulticast(InetAddress maddr) {
    1058         String host = maddr.getHostAddress();
    1059         if (!host.startsWith("[") && host.indexOf(':') != -1) {
    1060             host = "[" + host + "]";
    1061         }
    1062         checkPermission(new SocketPermission(host,
    1063             SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
    1064     }
    1065
    1066     /**
    1067      * Throws a {@code SecurityException} if the
    1068      * calling thread is not allowed to use
    1069      * (join/leave/send/receive) IP multicast.
    1070      * <p>
    1071      * This method calls {@code checkPermission} with the
    1072      * <code>java.net.SocketPermission(maddr.getHostAddress(),
    1073      * "accept,connect")</code> permission.
    1074      * <p>
    1075      * If you override this method, then you should make a call to
    1076      * {@code super.checkMulticast}
    1077      * at the point the overridden method would normally throw an
    1078      * exception.
    1079      *
    1080      * @param      maddr  Internet group address to be used.
    1081      * @param      ttl        value in use, if it is multicast send.
    1082      * Note: this particular implementation does not use the ttl
    1083      * parameter.
    1084      * @throws     SecurityException  if the calling thread is not allowed to
    1085      *  use (join/leave/send/receive) IP multicast.
    1086      * @throws     NullPointerException if the address argument is
    1087      *             {@code null}.
    1088      * @since      1.1
    1089      * @deprecated Use #checkPermission(java.security.Permission) instead
    1090      * @see        #checkPermission(java.security.Permission) checkPermission
    1091      */
    1092     @Deprecated(since="1.4", forRemoval=true)
    1093     public void checkMulticast(InetAddress maddr, byte ttl) {
    1094         String host = maddr.getHostAddress();
    1095         if (!host.startsWith("[") && host.indexOf(':') != -1) {
    1096             host = "[" + host + "]";
    1097         }
    1098         checkPermission(new SocketPermission(host,
    1099             SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
    1100     }
    1101
    1102     /**
    1103      * Throws a {@code SecurityException} if the
    1104      * calling thread is not allowed to access or modify the system
    1105      * properties.
    1106      * <p>
    1107      * This method is used by the {@code getProperties} and
    1108      * {@code setProperties} methods of class {@code System}.
    1109      * <p>
    1110      * This method calls {@code checkPermission} with the
    1111      * {@code PropertyPermission("*", "read,write")} permission.
    1112      * <p>
    1113      * If you override this method, then you should make a call to
    1114      * {@code super.checkPropertiesAccess}
    1115      * at the point the overridden method would normally throw an
    1116      * exception.
    1117      *
    1118      * @throws     SecurityException  if the calling thread does not have
    1119      *             permission to access or modify the system properties.
    1120      * @see        java.lang.System#getProperties()
    1121      * @see        java.lang.System#setProperties(java.util.Properties)
    1122      * @see        #checkPermission(java.security.Permission) checkPermission
    1123      */
    1124     public void checkPropertiesAccess() {
    1125         checkPermission(new PropertyPermission("*",
    1126             SecurityConstants.PROPERTY_RW_ACTION));
    1127     }
    1128
    1129     /**
    1130      * Throws a {@code SecurityException} if the
    1131      * calling thread is not allowed to access the system property with
    1132      * the specified {@code key} name.
    1133      * <p>
    1134      * This method is used by the {@code getProperty} method of
    1135      * class {@code System}.
    1136      * <p>
    1137      * This method calls {@code checkPermission} with the
    1138      * {@code PropertyPermission(key, "read")} permission.
    1139      * <p>
    1140      * If you override this method, then you should make a call to
    1141      * {@code super.checkPropertyAccess}
    1142      * at the point the overridden method would normally throw an
    1143      * exception.
    1144      *
    1145      * @param      key   a system property key.
    1146      *
    1147      * @throws     SecurityException  if the calling thread does not have
    1148      *             permission to access the specified system property.
    1149      * @throws     NullPointerException if the {@code key} argument is
    1150      *             {@code null}.
    1151      * @throws     IllegalArgumentException if {@code key} is empty.
    1152      *
    1153      * @see        java.lang.System#getProperty(java.lang.String)
    1154      * @see        #checkPermission(java.security.Permission) checkPermission
    1155      */
    1156     public void checkPropertyAccess(String key) {
    1157         checkPermission(new PropertyPermission(key,
    1158             SecurityConstants.PROPERTY_READ_ACTION));
    1159     }
    1160
    1161     /**
    1162      * Throws a {@code SecurityException} if the
    1163      * calling thread is not allowed to initiate a print job request.
    1164      * <p>
    1165      * This method calls
    1166      * {@code checkPermission} with the
    1167      * {@code RuntimePermission("queuePrintJob")} permission.
    1168      * <p>
    1169      * If you override this method, then you should make a call to
    1170      * {@code super.checkPrintJobAccess}
    1171      * at the point the overridden method would normally throw an
    1172      * exception.
    1173      *
    1174      * @throws     SecurityException  if the calling thread does not have
    1175      *             permission to initiate a print job request.
    1176      * @since   1.1
    1177      * @see        #checkPermission(java.security.Permission) checkPermission
    1178      */
    1179     public void checkPrintJobAccess() {
    1180         checkPermission(new RuntimePermission("queuePrintJob"));
    1181     }
    1182
    1183     /*
    1184      * We have an initial invalid bit (initially false) for the class
    1185      * variables which tell if the cache is valid.  If the underlying
    1186      * java.security.Security property changes via setProperty(), the
    1187      * Security class uses reflection to change the variable and thus
    1188      * invalidate the cache.
    1189      *
    1190      * Locking is handled by synchronization to the
    1191      * packageAccessLock/packageDefinitionLock objects.  They are only
    1192      * used in this class.
    1193      *
    1194      * Note that cache invalidation as a result of the property change
    1195      * happens without using these locks, so there may be a delay between
    1196      * when a thread updates the property and when other threads updates
    1197      * the cache.
    1198      */
    1199     private static boolean packageAccessValid = false;
    1200     private static String[] packageAccess;
    1201     private static final Object packageAccessLock = new Object();
    1202
    1203     private static boolean packageDefinitionValid = false;
    1204     private static String[] packageDefinition;
    1205     private static final Object packageDefinitionLock = new Object();
    1206
    1207     private static String[] getPackages(String p) {
    1208         String packages[] = null;
    1209         if (p != null && !p.isEmpty()) {
    1210             java.util.StringTokenizer tok =
    1211                 new java.util.StringTokenizer(p, ",");
    1212             int n = tok.countTokens();
    1213             if (n > 0) {
    1214                 packages = new String[n];
    1215                 int i = 0;
    1216                 while (tok.hasMoreElements()) {
    1217                     String s = tok.nextToken().trim();
    1218                     packages[i++] = s;
    1219                 }
    1220             }
    1221         }
    1222
    1223         if (packages == null) {
    1224             packages = new String[0];
    1225         }
    1226         return packages;
    1227     }
    1228
    1229     // The non-exported packages in modules defined to the boot or platform
    1230     // class loaders. A non-exported package is a package that is not exported
    1231     // or is only exported to specific modules.
    1232     private static final Map<String, Boolean> nonExportedPkgs = new ConcurrentHashMap<>();
    1233     static {
    1234         addNonExportedPackages(ModuleLayer.boot());
    1235     }
    1236
    1237     /**
    1238      * Record the non-exported packages of the modules in the given layer
    1239      */
    1240     static void addNonExportedPackages(ModuleLayer layer) {
    1241         Set<String> bootModules = ModuleLoaderMap.bootModules();
    1242         Set<String> platformModules = ModuleLoaderMap.platformModules();
    1243         layer.modules().stream()
    1244                 .map(Module::getDescriptor)
    1245                 .filter(md -> bootModules.contains(md.name())
    1246                         || platformModules.contains(md.name()))
    1247                 .map(SecurityManager::nonExportedPkgs)
    1248                 .flatMap(Set::stream)
    1249                 .forEach(pn -> nonExportedPkgs.put(pn, Boolean.TRUE));
    1250     }
    1251
    1252
    1253     /**
    1254      * Called by java.security.Security
    1255      */
    1256     static void invalidatePackageAccessCache() {
    1257         synchronized (packageAccessLock) {
    1258             packageAccessValid = false;
    1259         }
    1260         synchronized (packageDefinitionLock) {
    1261             packageDefinitionValid = false;
    1262         }
    1263     }
    1264
    1265     /**
    1266      * Returns the non-exported packages of the specified module.
    1267      */
    1268     private static Set<String> nonExportedPkgs(ModuleDescriptor md) {
    1269         // start with all packages in the module
    1270         Set<String> pkgs = new HashSet<>(md.packages());
    1271
    1272         // remove the non-qualified exported packages
    1273         md.exports().stream()
    1274                     .filter(p -> !p.isQualified())
    1275                     .map(Exports::source)
    1276                     .forEach(pkgs::remove);
    1277
    1278         // remove the non-qualified open packages
    1279         md.opens().stream()
    1280                   .filter(p -> !p.isQualified())
    1281                   .map(Opens::source)
    1282                   .forEach(pkgs::remove);
    1283
    1284         return pkgs;
    1285     }
    1286
    1287     /**
    1288      * Throws a {@code SecurityException} if the calling thread is not allowed
    1289      * to access the specified package.
    1290      * <p>
    1291      * During class loading, this method may be called by the {@code loadClass}
    1292      * method of class loaders and by the Java Virtual Machine to ensure that
    1293      * the caller is allowed to access the package of the class that is
    1294      * being loaded.
    1295      * <p>
    1296      * This method checks if the specified package starts with or equals
    1297      * any of the packages in the {@code package.access} Security Property.
    1298      * An implementation may also check the package against an additional
    1299      * list of restricted packages as noted below. If the package is restricted,
    1300      * {@link #checkPermission(Permission)} is called with a
    1301      * {@code RuntimePermission("accessClassInPackage."+pkg)} permission.
    1302      * <p>
    1303      * If this method is overridden, then {@code super.checkPackageAccess}
    1304      * should be called as the first line in the overridden method.
    1305      *
    1306      * @implNote
    1307      * This implementation also restricts all non-exported packages of modules
    1308      * loaded by {@linkplain ClassLoader#getPlatformClassLoader
    1309      * the platform class loader} or its ancestors. A "non-exported package"
    1310      * refers to a package that is not exported to all modules. Specifically,
    1311      * it refers to a package that either is not exported at all by its
    1312      * containing module or is exported in a qualified fashion by its
    1313      * containing module.
    1314      *
    1315      * @param      pkg   the package name.
    1316      * @throws     SecurityException  if the calling thread does not have
    1317      *             permission to access the specified package.
    1318      * @throws     NullPointerException if the package name argument is
    1319      *             {@code null}.
    1320      * @see        java.lang.ClassLoader#loadClass(String, boolean) loadClass
    1321      * @see        java.security.Security#getProperty getProperty
    1322      * @see        #checkPermission(Permission) checkPermission
    1323      */
    1324     public void checkPackageAccess(String pkg) {
    1325         Objects.requireNonNull(pkg, "package name can't be null");
    1326
    1327         // check if pkg is not exported to all modules
    1328         if (nonExportedPkgs.containsKey(pkg)) {
    1329             checkPermission(
    1330                 new RuntimePermission("accessClassInPackage." + pkg));
    1331             return;
    1332         }
    1333
    1334         String[] restrictedPkgs;
    1335         synchronized (packageAccessLock) {
    1336             /*
    1337              * Do we need to update our property array?
    1338              */
    1339             if (!packageAccessValid) {
    1340                 String tmpPropertyStr =
    1341                     AccessController.doPrivileged(
    1342                         new PrivilegedAction<>() {
    1343                             public String run() {
    1344                                 return Security.getProperty("package.access");
    1345                             }
    1346                         }
    1347                     );
    1348                 packageAccess = getPackages(tmpPropertyStr);
    1349                 packageAccessValid = true;
    1350             }
    1351
    1352             // Using a snapshot of packageAccess -- don't care if static field
    1353             // changes afterwards; array contents won't change.
    1354             restrictedPkgs = packageAccess;
    1355         }
    1356
    1357         /*
    1358          * Traverse the list of packages, check for any matches.
    1359          */
    1360         final int plen = pkg.length();
    1361         for (String restrictedPkg : restrictedPkgs) {
    1362             final int rlast = restrictedPkg.length() - 1;
    1363
    1364             // Optimizations:
    1365             //
    1366             // If rlast >= plen then restrictedPkg is longer than pkg by at
    1367             // least one char. This means pkg cannot start with restrictedPkg,
    1368             // since restrictedPkg will be longer than pkg.
    1369             //
    1370             // Similarly if rlast != plen, then pkg + "." cannot be the same
    1371             // as restrictedPkg, since pkg + "." will have a different length
    1372             // than restrictedPkg.
    1373             //
    1374             if (rlast < plen && pkg.startsWith(restrictedPkg) ||
    1375                 // The following test is equivalent to
    1376                 // restrictedPkg.equals(pkg + ".") but is noticeably more
    1377                 // efficient:
    1378                 rlast == plen && restrictedPkg.startsWith(pkg) &&
    1379                 restrictedPkg.charAt(rlast) == '.')
    1380             {
    1381                 checkPermission(
    1382                     new RuntimePermission("accessClassInPackage." + pkg));
    1383                 break;  // No need to continue; only need to check this once
    1384             }
    1385         }
    1386     }
    1387
    1388     /**
    1389      * Throws a {@code SecurityException} if the calling thread is not
    1390      * allowed to define classes in the specified package.
    1391      * <p>
    1392      * This method is called by the {@code loadClass} method of some
    1393      * class loaders.
    1394      * <p>
    1395      * This method checks if the specified package starts with or equals
    1396      * any of the packages in the {@code package.definition} Security
    1397      * Property. An implementation may also check the package against an
    1398      * additional list of restricted packages as noted below. If the package
    1399      * is restricted, {@link #checkPermission(Permission)} is called with a
    1400      * {@code RuntimePermission("defineClassInPackage."+pkg)} permission.
    1401      * <p>
    1402      * If this method is overridden, then {@code super.checkPackageDefinition}
    1403      * should be called as the first line in the overridden method.
    1404      *
    1405      * @implNote
    1406      * This implementation also restricts all non-exported packages of modules
    1407      * loaded by {@linkplain ClassLoader#getPlatformClassLoader
    1408      * the platform class loader} or its ancestors. A "non-exported package"
    1409      * refers to a package that is not exported to all modules. Specifically,
    1410      * it refers to a package that either is not exported at all by its
    1411      * containing module or is exported in a qualified fashion by its
    1412      * containing module.
    1413      *
    1414      * @param      pkg   the package name.
    1415      * @throws     SecurityException  if the calling thread does not have
    1416      *             permission to define classes in the specified package.
    1417      * @throws     NullPointerException if the package name argument is
    1418      *             {@code null}.
    1419      * @see        java.lang.ClassLoader#loadClass(String, boolean)
    1420      * @see        java.security.Security#getProperty getProperty
    1421      * @see        #checkPermission(Permission) checkPermission
    1422      */
    1423     public void checkPackageDefinition(String pkg) {
    1424         Objects.requireNonNull(pkg, "package name can't be null");
    1425
    1426         // check if pkg is not exported to all modules
    1427         if (nonExportedPkgs.containsKey(pkg)) {
    1428             checkPermission(
    1429                 new RuntimePermission("defineClassInPackage." + pkg));
    1430             return;
    1431         }
    1432
    1433         String[] pkgs;
    1434         synchronized (packageDefinitionLock) {
    1435             /*
    1436              * Do we need to update our property array?
    1437              */
    1438             if (!packageDefinitionValid) {
    1439                 String tmpPropertyStr =
    1440                     AccessController.doPrivileged(
    1441                         new PrivilegedAction<>() {
    1442                             public String run() {
    1443                                 return java.security.Security.getProperty(
    1444                                     "package.definition");
    1445                             }
    1446                         }
    1447                     );
    1448                 packageDefinition = getPackages(tmpPropertyStr);
    1449                 packageDefinitionValid = true;
    1450             }
    1451             // Using a snapshot of packageDefinition -- don't care if static
    1452             // field changes afterwards; array contents won't change.
    1453             pkgs = packageDefinition;
    1454         }
    1455
    1456         /*
    1457          * Traverse the list of packages, check for any matches.
    1458          */
    1459         for (String restrictedPkg : pkgs) {
    1460             if (pkg.startsWith(restrictedPkg) || restrictedPkg.equals(pkg + ".")) {
    1461                 checkPermission(
    1462                     new RuntimePermission("defineClassInPackage." + pkg));
    1463                 break; // No need to continue; only need to check this once
    1464             }
    1465         }
    1466     }
    1467
    1468     /**
    1469      * Throws a {@code SecurityException} if the
    1470      * calling thread is not allowed to set the socket factory used by
    1471      * {@code ServerSocket} or {@code Socket}, or the stream
    1472      * handler factory used by {@code URL}.
    1473      * <p>
    1474      * This method calls {@code checkPermission} with the
    1475      * {@code RuntimePermission("setFactory")} permission.
    1476      * <p>
    1477      * If you override this method, then you should make a call to
    1478      * {@code super.checkSetFactory}
    1479      * at the point the overridden method would normally throw an
    1480      * exception.
    1481      *
    1482      * @throws     SecurityException  if the calling thread does not have
    1483      *             permission to specify a socket factory or a stream
    1484      *             handler factory.
    1485      *
    1486      * @see        java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory) setSocketFactory
    1487      * @see        java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory) setSocketImplFactory
    1488      * @see        java.net.URL#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory) setURLStreamHandlerFactory
    1489      * @see        #checkPermission(java.security.Permission) checkPermission
    1490      */
    1491     public void checkSetFactory() {
    1492         checkPermission(new RuntimePermission("setFactory"));
    1493     }
    1494
    1495     /**
    1496      * Determines whether the permission with the specified permission target
    1497      * name should be granted or denied.
    1498      *
    1499      * <p> If the requested permission is allowed, this method returns
    1500      * quietly. If denied, a SecurityException is raised.
    1501      *
    1502      * <p> This method creates a {@code SecurityPermission} object for
    1503      * the given permission target name and calls {@code checkPermission}
    1504      * with it.
    1505      *
    1506      * <p> See the documentation for
    1507      * <code>{@link java.security.SecurityPermission}</code> for
    1508      * a list of possible permission target names.
    1509      *
    1510      * <p> If you override this method, then you should make a call to
    1511      * {@code super.checkSecurityAccess}
    1512      * at the point the overridden method would normally throw an
    1513      * exception.
    1514      *
    1515      * @param target the target name of the {@code SecurityPermission}.
    1516      *
    1517      * @throws    SecurityException if the calling thread does not have
    1518      * permission for the requested access.
    1519      * @throws    NullPointerException if {@code target} is null.
    1520      * @throws    IllegalArgumentException if {@code target} is empty.
    1521      *
    1522      * @since   1.1
    1523      * @see        #checkPermission(java.security.Permission) checkPermission
    1524      */
    1525     public void checkSecurityAccess(String target) {
    1526         checkPermission(new SecurityPermission(target));
    1527     }
    1528
    1529     /**
    1530      * Returns the thread group into which to instantiate any new
    1531      * thread being created at the time this is being called.
    1532      * By default, it returns the thread group of the current
    1533      * thread. This should be overridden by a specific security
    1534      * manager to return the appropriate thread group.
    1535      *
    1536      * @return  ThreadGroup that new threads are instantiated into
    1537      * @since   1.1
    1538      * @see     java.lang.ThreadGroup
    1539      */
    1540     public ThreadGroup getThreadGroup() {
    1541         return Thread.currentThread().getThreadGroup();
    1542     }
    1543
    1544 }