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