Source for java.lang.SecurityManager

   1: /* SecurityManager.java -- security checks for privileged actions
   2:    Copyright (C) 1998, 1999, 2001, 2002, 2005  Free Software Foundation, Inc.
   3: 
   4: This file is part of GNU Classpath.
   5: 
   6: GNU Classpath is free software; you can redistribute it and/or modify
   7: it under the terms of the GNU General Public License as published by
   8: the Free Software Foundation; either version 2, or (at your option)
   9: any later version.
  10: 
  11: GNU Classpath is distributed in the hope that it will be useful, but
  12: WITHOUT ANY WARRANTY; without even the implied warranty of
  13: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14: General Public License for more details.
  15: 
  16: You should have received a copy of the GNU General Public License
  17: along with GNU Classpath; see the file COPYING.  If not, write to the
  18: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  19: 02110-1301 USA.
  20: 
  21: Linking this library statically or dynamically with other modules is
  22: making a combined work based on this library.  Thus, the terms and
  23: conditions of the GNU General Public License cover the whole
  24: combination.
  25: 
  26: As a special exception, the copyright holders of this library give you
  27: permission to link this library with independent modules to produce an
  28: executable, regardless of the license terms of these independent
  29: modules, and to copy and distribute the resulting executable under
  30: terms of your choice, provided that you also meet, for each linked
  31: independent module, the terms and conditions of the license of that
  32: module.  An independent module is a module which is not derived from
  33: or based on this library.  If you modify this library, you may extend
  34: this exception to your version of the library, but you are not
  35: obligated to do so.  If you do not wish to do so, delete this
  36: exception statement from your version. */
  37: 
  38: 
  39: package java.lang;
  40: 
  41: import java.awt.AWTPermission;
  42: import java.io.File;
  43: import java.io.FileDescriptor;
  44: import java.io.FilePermission;
  45: import java.lang.reflect.Member;
  46: import java.net.InetAddress;
  47: import java.net.SocketPermission;
  48: import java.security.AllPermission;
  49: import java.security.Permission;
  50: import java.security.Security;
  51: import java.security.SecurityPermission;
  52: import java.util.PropertyPermission;
  53: 
  54: /**
  55:  * SecurityManager is a class you can extend to create your own Java
  56:  * security policy.  By default, there is no SecurityManager installed in
  57:  * 1.1, which means that all things are permitted to all people. The security
  58:  * manager, if set, is consulted before doing anything with potentially
  59:  * dangerous results, and throws a <code>SecurityException</code> if the
  60:  * action is forbidden.
  61:  *
  62:  * <p>A typical check is as follows, just before the dangerous operation:<br>
  63:  * <pre>
  64:  * SecurityManager sm = System.getSecurityManager();
  65:  * if (sm != null)
  66:  *   sm.checkABC(<em>argument</em>, ...);
  67:  * </pre>
  68:  * Note that this is thread-safe, by caching the security manager in a local
  69:  * variable rather than risking a NullPointerException if the mangager is
  70:  * changed between the check for null and before the permission check.
  71:  *
  72:  * <p>The special method <code>checkPermission</code> is a catchall, and
  73:  * the default implementation calls
  74:  * <code>AccessController.checkPermission</code>. In fact, all the other
  75:  * methods default to calling checkPermission.
  76:  *
  77:  * <p>Sometimes, the security check needs to happen from a different context,
  78:  * such as when called from a worker thread. In such cases, use
  79:  * <code>getSecurityContext</code> to take a snapshot that can be passed
  80:  * to the worker thread:<br>
  81:  * <pre>
  82:  * Object context = null;
  83:  * SecurityManager sm = System.getSecurityManager();
  84:  * if (sm != null)
  85:  *   context = sm.getSecurityContext(); // defaults to an AccessControlContext
  86:  * // now, in worker thread
  87:  * if (sm != null)
  88:  *   sm.checkPermission(permission, context);
  89:  * </pre>
  90:  *
  91:  * <p>Permissions fall into these categories: File, Socket, Net, Security,
  92:  * Runtime, Property, AWT, Reflect, and Serializable. Each of these
  93:  * permissions have a property naming convention, that follows a hierarchical
  94:  * naming convention, to make it easy to grant or deny several permissions
  95:  * at once. Some permissions also take a list of permitted actions, such
  96:  * as "read" or "write", to fine-tune control even more. The permission
  97:  * <code>java.security.AllPermission</code> grants all permissions.
  98:  *
  99:  * <p>The default methods in this class deny all things to all people. You
 100:  * must explicitly grant permission for anything you want to be legal when
 101:  * subclassing this class.
 102:  *
 103:  * @author John Keiser
 104:  * @author Eric Blake (ebb9@email.byu.edu)
 105:  * @see ClassLoader
 106:  * @see SecurityException
 107:  * @see #checkTopLevelWindow(Object)
 108:  * @see System#getSecurityManager()
 109:  * @see System#setSecurityManager(SecurityManager)
 110:  * @see AccessController
 111:  * @see AccessControlContext
 112:  * @see AccessControlException
 113:  * @see Permission
 114:  * @see BasicPermission
 115:  * @see java.io.FilePermission
 116:  * @see java.net.SocketPermission
 117:  * @see java.util.PropertyPermission
 118:  * @see RuntimePermission
 119:  * @see java.awt.AWTPermission
 120:  * @see Policy
 121:  * @see SecurityPermission
 122:  * @see ProtectionDomain
 123:  * @since 1.0
 124:  * @status still missing 1.4 functionality
 125:  */
 126: public class SecurityManager
 127: {
 128:   /**
 129:    * The current security manager. This is located here instead of in
 130:    * System, to avoid security problems, as well as bootstrap issues.
 131:    * Make sure to access it in a thread-safe manner; it is package visible
 132:    * to avoid overhead in java.lang.
 133:    */
 134:   static volatile SecurityManager current;
 135: 
 136:   /**
 137:    * Tells whether or not the SecurityManager is currently performing a
 138:    * security check.
 139:    * @deprecated Use {@link #checkPermission(Permission)} instead.
 140:    */
 141:   protected boolean inCheck;
 142: 
 143:   /**
 144:    * Construct a new security manager. There may be a security check, of
 145:    * <code>RuntimePermission("createSecurityManager")</code>.
 146:    *
 147:    * @throws SecurityException if permission is denied
 148:    */
 149:   public SecurityManager()
 150:   {
 151:     SecurityManager sm = System.getSecurityManager();
 152:     if (sm != null)
 153:       sm.checkPermission(new RuntimePermission("createSecurityManager"));
 154:   }
 155: 
 156:   /**
 157:    * Tells whether or not the SecurityManager is currently performing a
 158:    * security check.
 159:    *
 160:    * @return true if the SecurityManager is in a security check
 161:    * @see #inCheck
 162:    * @deprecated use {@link #checkPermission(Permission)} instead
 163:    */
 164:   public boolean getInCheck()
 165:   {
 166:     return inCheck;
 167:   }
 168: 
 169:   /**
 170:    * Get a list of all the classes currently executing methods on the Java
 171:    * stack.  getClassContext()[0] is the currently executing method (ie. the
 172:    * class that CALLED getClassContext, not SecurityManager).
 173:    *
 174:    * @return an array of classes on the Java execution stack
 175:    */
 176:   protected Class[] getClassContext()
 177:   {
 178:     return VMSecurityManager.getClassContext(SecurityManager.class);
 179:   }
 180: 
 181:   /**
 182:    * Find the ClassLoader of the first non-system class on the execution
 183:    * stack. A non-system class is one whose ClassLoader is not equal to
 184:    * {@link ClassLoader#getSystemClassLoader()} or its ancestors. This
 185:    * will return null in three cases:
 186:    *
 187:    * <ul>
 188:    * <li>All methods on the stack are from system classes</li>
 189:    * <li>All methods on the stack up to the first "privileged" caller, as
 190:    *  created by {@link AccessController.doPrivileged(PrivilegedAction)},
 191:    *  are from system classes</li>
 192:    * <li>A check of <code>java.security.AllPermission</code> succeeds.</li>
 193:    * </ul>
 194:    * 
 195:    * @return the most recent non-system ClassLoader on the execution stack
 196:    * @deprecated use {@link #checkPermission(Permission)} instead
 197:    */
 198:   protected ClassLoader currentClassLoader()
 199:   {
 200:     return VMSecurityManager.currentClassLoader(SecurityManager.class);
 201:   }
 202: 
 203:   /**
 204:    * Find the first non-system class on the execution stack. A non-system
 205:    * class is one whose ClassLoader is not equal to
 206:    * {@link ClassLoader#getSystemClassLoader()} or its ancestors. This
 207:    * will return null in three cases:
 208:    *
 209:    * <ul>
 210:    * <li>All methods on the stack are from system classes</li>
 211:    * <li>All methods on the stack up to the first "privileged" caller, as
 212:    *  created by {@link AccessController.doPrivileged(PrivilegedAction)},
 213:    *  are from system classes</li>
 214:    * <li>A check of <code>java.security.AllPermission</code> succeeds.</li>
 215:    * </ul>
 216:    * 
 217:    * @return the most recent non-system Class on the execution stack
 218:    * @deprecated use {@link #checkPermission(Permission)} instead
 219:    */
 220:   protected Class currentLoadedClass()
 221:   {
 222:     int i = classLoaderDepth();
 223:     return i >= 0 ? getClassContext()[i] : null;
 224:   }
 225: 
 226:   /**
 227:    * Get the depth of a particular class on the execution stack.
 228:    *
 229:    * @param className the fully-qualified name to search for
 230:    * @return the index of the class on the stack, or -1
 231:    * @deprecated use {@link #checkPermission(Permission)} instead
 232:    */
 233:   protected int classDepth(String className)
 234:   {
 235:     Class[] c = getClassContext();
 236:     for (int i = 0; i < c.length; i++)
 237:       if (className.equals(c[i].getName()))
 238:         return i;
 239:     return -1;
 240:   }
 241: 
 242:   /**
 243:    * Get the depth on the execution stack of the most recent non-system class.
 244:    * A non-system class is one whose ClassLoader is not equal to
 245:    * {@link ClassLoader#getSystemClassLoader()} or its ancestors. This
 246:    * will return -1 in three cases:
 247:    *
 248:    * <ul>
 249:    * <li>All methods on the stack are from system classes</li>
 250:    * <li>All methods on the stack up to the first "privileged" caller, as
 251:    *  created by {@link AccessController.doPrivileged(PrivilegedAction)},
 252:    *  are from system classes</li>
 253:    * <li>A check of <code>java.security.AllPermission</code> succeeds.</li>
 254:    * </ul>
 255:    * 
 256:    * @return the index of the most recent non-system Class on the stack
 257:    * @deprecated use {@link #checkPermission(Permission)} instead
 258:    */
 259:   protected int classLoaderDepth()
 260:   {
 261:     try
 262:       {
 263:         checkPermission(new AllPermission());
 264:       }
 265:     catch (SecurityException e)
 266:       {
 267:         Class[] c = getClassContext();
 268:         for (int i = 0; i < c.length; i++)
 269:           if (c[i].getClassLoader() != null)
 270:             // XXX Check if c[i] is AccessController, or a system class.
 271:             return i;
 272:       }
 273:     return -1;
 274:   }
 275: 
 276:   /**
 277:    * Tell whether the specified class is on the execution stack.
 278:    *
 279:    * @param className the fully-qualified name of the class to find
 280:    * @return whether the specified class is on the execution stack
 281:    * @deprecated use {@link #checkPermission(Permission)} instead
 282:    */
 283:   protected boolean inClass(String className)
 284:   {
 285:     return classDepth(className) != -1;
 286:   }
 287: 
 288:   /**
 289:    * Tell whether there is a class loaded with an explicit ClassLoader on
 290:    * the stack.
 291:    *
 292:    * @return whether a class with an explicit ClassLoader is on the stack
 293:    * @deprecated use {@link #checkPermission(Permission)} instead
 294:    */
 295:   protected boolean inClassLoader()
 296:   {
 297:     return classLoaderDepth() != -1;
 298:   }
 299: 
 300:   /**
 301:    * Get an implementation-dependent Object that contains enough information
 302:    * about the current environment to be able to perform standard security
 303:    * checks later.  This is used by trusted methods that need to verify that
 304:    * their callers have sufficient access to perform certain operations.
 305:    *
 306:    * <p>Currently the only methods that use this are checkRead() and
 307:    * checkConnect(). The default implementation returns an
 308:    * <code>AccessControlContext</code>.
 309:    *
 310:    * @return a security context
 311:    * @see #checkConnect(String, int, Object)
 312:    * @see #checkRead(String, Object)
 313:    * @see AccessControlContext
 314:    * @see AccessController#getContext()
 315:    */
 316:   public Object getSecurityContext()
 317:   {
 318:     // XXX Should be: return AccessController.getContext();
 319:     return new SecurityContext(getClassContext());
 320:   }
 321: 
 322:   /**
 323:    * Check if the current thread is allowed to perform an operation that
 324:    * requires the specified <code>Permission</code>. This defaults to
 325:    * <code>AccessController.checkPermission</code>.
 326:    *
 327:    * @param perm the <code>Permission</code> required
 328:    * @throws SecurityException if permission is denied
 329:    * @throws NullPointerException if perm is null
 330:    * @since 1.2
 331:    */
 332:   public void checkPermission(Permission perm)
 333:   {
 334:     // XXX Should be: AccessController.checkPermission(perm);
 335:     //.throw new SecurityException("Operation not allowed");
 336:   }
 337: 
 338:   /**
 339:    * Check if the current thread is allowed to perform an operation that
 340:    * requires the specified <code>Permission</code>. This is done in a
 341:    * context previously returned by <code>getSecurityContext()</code>. The
 342:    * default implementation expects context to be an AccessControlContext,
 343:    * and it calls <code>AccessControlContext.checkPermission(perm)</code>.
 344:    *
 345:    * @param perm the <code>Permission</code> required
 346:    * @param context a security context
 347:    * @throws SecurityException if permission is denied, or if context is
 348:    *         not an AccessControlContext
 349:    * @throws NullPointerException if perm is null
 350:    * @see #getSecurityContext()
 351:    * @see AccessControlContext#checkPermission(Permission)
 352:    * @since 1.2
 353:    */
 354:   public void checkPermission(Permission perm, Object context)
 355:   {
 356:     // XXX Should be:
 357:     // if (! (context instanceof AccessControlContext))
 358:     //   throw new SecurityException("Missing context");
 359:     // ((AccessControlContext) context).checkPermission(perm);
 360:     throw new SecurityException("Operation not allowed");
 361:   }
 362: 
 363:   /**
 364:    * Check if the current thread is allowed to create a ClassLoader. This
 365:    * method is called from ClassLoader.ClassLoader(), and checks
 366:    * <code>RuntimePermission("createClassLoader")</code>. If you override
 367:    * this, you should call <code>super.checkCreateClassLoader()</code> rather
 368:    * than throwing an exception.
 369:    *
 370:    * @throws SecurityException if permission is denied
 371:    * @see ClassLoader#ClassLoader()
 372:    */
 373:   public void checkCreateClassLoader()
 374:   {
 375:     checkPermission(new RuntimePermission("createClassLoader"));
 376:   }
 377: 
 378:   /**
 379:    * Check if the current thread is allowed to modify another Thread. This is
 380:    * called by Thread.stop(), suspend(), resume(), interrupt(), destroy(),
 381:    * setPriority(), setName(), and setDaemon(). The default implementation
 382:    * checks <code>RuntimePermission("modifyThread")</code> on system threads
 383:    * (ie. threads in ThreadGroup with a null parent), and returns silently on
 384:    * other threads.
 385:    *
 386:    * <p>If you override this, you must do two things. First, call
 387:    * <code>super.checkAccess(t)</code>, to make sure you are not relaxing
 388:    * requirements. Second, if the calling thread has
 389:    * <code>RuntimePermission("modifyThread")</code>, return silently, so that
 390:    * core classes (the Classpath library!) can modify any thread.
 391:    *
 392:    * @param thread the other Thread to check
 393:    * @throws SecurityException if permission is denied
 394:    * @throws NullPointerException if thread is null
 395:    * @see Thread#stop()
 396:    * @see Thread#suspend()
 397:    * @see Thread#resume()
 398:    * @see Thread#setPriority(int)
 399:    * @see Thread#setName(String)
 400:    * @see Thread#setDaemon(boolean)
 401:    */
 402:   public void checkAccess(Thread thread)
 403:   {
 404:     if (thread.getThreadGroup() != null 
 405:     && thread.getThreadGroup().getParent() != null)
 406:       checkPermission(new RuntimePermission("modifyThread"));
 407:   }
 408: 
 409:   /**
 410:    * Check if the current thread is allowed to modify a ThreadGroup. This is
 411:    * called by Thread.Thread() (to add a thread to the ThreadGroup),
 412:    * ThreadGroup.ThreadGroup() (to add this ThreadGroup to a parent),
 413:    * ThreadGroup.stop(), suspend(), resume(), interrupt(), destroy(),
 414:    * setDaemon(), and setMaxPriority(). The default implementation
 415:    * checks <code>RuntimePermission("modifyThread")</code> on the system group
 416:    * (ie. the one with a null parent), and returns silently on other groups.
 417:    *
 418:    * <p>If you override this, you must do two things. First, call
 419:    * <code>super.checkAccess(t)</code>, to make sure you are not relaxing
 420:    * requirements. Second, if the calling thread has
 421:    * <code>RuntimePermission("modifyThreadGroup")</code>, return silently,
 422:    * so that core classes (the Classpath library!) can modify any thread.
 423:    *
 424:    * @param g the ThreadGroup to check
 425:    * @throws SecurityException if permission is denied
 426:    * @throws NullPointerException if g is null
 427:    * @see Thread#Thread()
 428:    * @see ThreadGroup#ThreadGroup()
 429:    * @see ThreadGroup#stop()
 430:    * @see ThreadGroup#suspend()
 431:    * @see ThreadGroup#resume()
 432:    * @see ThreadGroup#interrupt()
 433:    * @see ThreadGroup#setDaemon(boolean)
 434:    * @see ThreadGroup#setMaxPriority(int)
 435:    */
 436:   public void checkAccess(ThreadGroup g)
 437:   {
 438:     if (g.getParent() != null)
 439:       checkPermission(new RuntimePermission("modifyThreadGroup"));
 440:   }
 441: 
 442:   /**
 443:    * Check if the current thread is allowed to exit the JVM with the given
 444:    * status. This method is called from Runtime.exit() and Runtime.halt().
 445:    * The default implementation checks
 446:    * <code>RuntimePermission("exitVM")</code>. If you override this, call
 447:    * <code>super.checkExit</code> rather than throwing an exception.
 448:    *
 449:    * @param status the status to exit with
 450:    * @throws SecurityException if permission is denied
 451:    * @see Runtime#exit(int)
 452:    * @see Runtime#halt(int)
 453:    */
 454:   public void checkExit(int status)
 455:   {
 456:     checkPermission(new RuntimePermission("exitVM"));
 457:   }
 458: 
 459:   /**
 460:    * Check if the current thread is allowed to execute the given program. This
 461:    * method is called from Runtime.exec(). If the name is an absolute path,
 462:    * the default implementation checks
 463:    * <code>FilePermission(program, "execute")</code>, otherwise it checks
 464:    * <code>FilePermission("&lt;&lt;ALL FILES&gt;&gt;", "execute")</code>. If
 465:    * you override this, call <code>super.checkExec</code> rather than
 466:    * throwing an exception.
 467:    *
 468:    * @param program the name of the program to exec
 469:    * @throws SecurityException if permission is denied
 470:    * @throws NullPointerException if program is null
 471:    * @see Runtime#exec(String[], String[], File)
 472:    */
 473:   public void checkExec(String program)
 474:   {
 475:     if (! program.equals(new File(program).getAbsolutePath()))
 476:       program = "<<ALL FILES>>";
 477:     checkPermission(new FilePermission(program, "execute"));
 478:   }
 479: 
 480:   /**
 481:    * Check if the current thread is allowed to link in the given native
 482:    * library. This method is called from Runtime.load() (and hence, by
 483:    * loadLibrary() as well). The default implementation checks
 484:    * <code>RuntimePermission("loadLibrary." + filename)</code>. If you
 485:    * override this, call <code>super.checkLink</code> rather than throwing
 486:    * an exception.
 487:    *
 488:    * @param filename the full name of the library to load
 489:    * @throws SecurityException if permission is denied
 490:    * @throws NullPointerException if filename is null
 491:    * @see Runtime#load(String)
 492:    */
 493:   public void checkLink(String filename)
 494:   {
 495:     // Use the toString() hack to do the null check.
 496:     checkPermission(new RuntimePermission("loadLibrary."
 497:                                           + filename.toString()));
 498:   }
 499: 
 500:   /**
 501:    * Check if the current thread is allowed to read the given file using the
 502:    * FileDescriptor. This method is called from
 503:    * FileInputStream.FileInputStream(). The default implementation checks
 504:    * <code>RuntimePermission("readFileDescriptor")</code>. If you override
 505:    * this, call <code>super.checkRead</code> rather than throwing an
 506:    * exception.
 507:    *
 508:    * @param desc the FileDescriptor representing the file to access
 509:    * @throws SecurityException if permission is denied
 510:    * @throws NullPointerException if desc is null
 511:    * @see FileInputStream#FileInputStream(FileDescriptor)
 512:    */
 513:   public void checkRead(FileDescriptor desc)
 514:   {
 515:     if (desc == null)
 516:       throw new NullPointerException();
 517:     checkPermission(new RuntimePermission("readFileDescriptor"));
 518:   }
 519: 
 520:   /**
 521:    * Check if the current thread is allowed to read the given file. This
 522:    * method is called from FileInputStream.FileInputStream(),
 523:    * RandomAccessFile.RandomAccessFile(), File.exists(), canRead(), isFile(),
 524:    * isDirectory(), lastModified(), length() and list(). The default
 525:    * implementation checks <code>FilePermission(filename, "read")</code>. If
 526:    * you override this, call <code>super.checkRead</code> rather than
 527:    * throwing an exception.
 528:    *
 529:    * @param filename the full name of the file to access
 530:    * @throws SecurityException if permission is denied
 531:    * @throws NullPointerException if filename is null
 532:    * @see File
 533:    * @see FileInputStream#FileInputStream(String)
 534:    * @see RandomAccessFile#RandomAccessFile(String)
 535:    */
 536:   public void checkRead(String filename)
 537:   {
 538:     checkPermission(new FilePermission(filename, "read"));
 539:   }
 540: 
 541:   /**
 542:    * Check if the current thread is allowed to read the given file. using the
 543:    * given security context. The context must be a result of a previous call
 544:    * to <code>getSecurityContext()</code>. The default implementation checks
 545:    * <code>AccessControlContext.checkPermission(new FilePermission(filename,
 546:    * "read"))</code>. If you override this, call <code>super.checkRead</code>
 547:    * rather than throwing an exception.
 548:    *
 549:    * @param filename the full name of the file to access
 550:    * @param context the context to determine access for
 551:    * @throws SecurityException if permission is denied, or if context is
 552:    *         not an AccessControlContext
 553:    * @throws NullPointerException if filename is null
 554:    * @see #getSecurityContext()
 555:    * @see AccessControlContext#checkPermission(Permission)
 556:    */
 557:   public void checkRead(String filename, Object context)
 558:   {
 559:     // XXX Should be:
 560:     // if (! (context instanceof AccessControlContext))
 561:     //   throw new SecurityException("Missing context");
 562:     // AccessControlContext ac = (AccessControlContext) context;
 563:     // ac.checkPermission(new FilePermission(filename, "read"));
 564:     // throw new SecurityException("Cannot read files via file names.");
 565:   }
 566: 
 567:   /**
 568:    * Check if the current thread is allowed to write the given file using the
 569:    * FileDescriptor. This method is called from
 570:    * FileOutputStream.FileOutputStream(). The default implementation checks
 571:    * <code>RuntimePermission("writeFileDescriptor")</code>. If you override
 572:    * this, call <code>super.checkWrite</code> rather than throwing an
 573:    * exception.
 574:    *
 575:    * @param desc the FileDescriptor representing the file to access
 576:    * @throws SecurityException if permission is denied
 577:    * @throws NullPointerException if desc is null
 578:    * @see FileOutputStream#FileOutputStream(FileDescriptor)
 579:    */
 580:   public void checkWrite(FileDescriptor desc)
 581:   {
 582:     if (desc == null)
 583:       throw new NullPointerException();
 584:     checkPermission(new RuntimePermission("writeFileDescriptor"));
 585:   }
 586: 
 587:   /**
 588:    * Check if the current thread is allowed to write the given file. This
 589:    * method is called from FileOutputStream.FileOutputStream(),
 590:    * RandomAccessFile.RandomAccessFile(), File.canWrite(), mkdir(), and
 591:    * renameTo(). The default implementation checks
 592:    * <code>FilePermission(filename, "write")</code>. If you override this,
 593:    * call <code>super.checkWrite</code> rather than throwing an exception.
 594:    *
 595:    * @param filename the full name of the file to access
 596:    * @throws SecurityException if permission is denied
 597:    * @throws NullPointerException if filename is null
 598:    * @see File
 599:    * @see File#canWrite()
 600:    * @see File#mkdir()
 601:    * @see File#renameTo()
 602:    * @see FileOutputStream#FileOutputStream(String)
 603:    * @see RandomAccessFile#RandomAccessFile(String)
 604:    */
 605:   public void checkWrite(String filename)
 606:   {
 607:     checkPermission(new FilePermission(filename, "write"));
 608:   }
 609: 
 610:   /**
 611:    * Check if the current thread is allowed to delete the given file. This
 612:    * method is called from File.delete(). The default implementation checks
 613:    * <code>FilePermission(filename, "delete")</code>. If you override this,
 614:    * call <code>super.checkDelete</code> rather than throwing an exception.
 615:    *
 616:    * @param filename the full name of the file to delete
 617:    * @throws SecurityException if permission is denied
 618:    * @throws NullPointerException if filename is null
 619:    * @see File#delete()
 620:    */
 621:   public void checkDelete(String filename)
 622:   {
 623:     checkPermission(new FilePermission(filename, "delete"));
 624:   }
 625: 
 626:   /**
 627:    * Check if the current thread is allowed to connect to a given host on a
 628:    * given port. This method is called from Socket.Socket(). A port number
 629:    * of -1 indicates the caller is attempting to determine an IP address, so
 630:    * the default implementation checks
 631:    * <code>SocketPermission(host, "resolve")</code>. Otherwise, the default
 632:    * implementation checks
 633:    * <code>SocketPermission(host + ":" + port, "connect")</code>. If you
 634:    * override this, call <code>super.checkConnect</code> rather than throwing
 635:    * an exception.
 636:    *
 637:    * @param host the host to connect to
 638:    * @param port the port to connect on
 639:    * @throws SecurityException if permission is denied
 640:    * @throws NullPointerException if host is null
 641:    * @see Socket#Socket()
 642:    */
 643:   public void checkConnect(String host, int port)
 644:   {
 645:     if (port == -1)
 646:       checkPermission(new SocketPermission(host, "resolve"));
 647:     else
 648:       // Use the toString() hack to do the null check.
 649:       checkPermission(new SocketPermission(host.toString() + ":" + port,
 650:                                            "connect"));
 651:   }
 652: 
 653:   /**
 654:    * Check if the current thread is allowed to connect to a given host on a
 655:    * given port, using the given security context. The context must be a
 656:    * result of a previous call to <code>getSecurityContext</code>. A port
 657:    * number of -1 indicates the caller is attempting to determine an IP
 658:    * address, so the default implementation checks
 659:    * <code>AccessControlContext.checkPermission(new SocketPermission(host,
 660:    * "resolve"))</code>. Otherwise, the default implementation checks
 661:    * <code>AccessControlContext.checkPermission(new SocketPermission(host
 662:    * + ":" + port, "connect"))</code>. If you override this, call
 663:    * <code>super.checkConnect</code> rather than throwing an exception.
 664:    *
 665:    * @param host the host to connect to
 666:    * @param port the port to connect on
 667:    * @param context the context to determine access for
 668:    *
 669:    * @throws SecurityException if permission is denied, or if context is
 670:    *         not an AccessControlContext
 671:    * @throws NullPointerException if host is null
 672:    *
 673:    * @see #getSecurityContext()
 674:    * @see AccessControlContext#checkPermission(Permission)
 675:    */
 676:   public void checkConnect(String host, int port, Object context)
 677:   {
 678:     // XXX Should be:
 679:     // if (! (context instanceof AccessControlContext))
 680:     //   throw new SecurityException("Missing context");
 681:     // AccessControlContext ac = (AccessControlContext) context;
 682:     // if (port == -1)
 683:     //   ac.checkPermission(new SocketPermission(host, "resolve"));
 684:     // else
 685:     //   // Use the toString() hack to do the null check.
 686:     //   ac.checkPermission(new SocketPermission(host.toString + ":" +port,
 687:     //                                           "connect"));
 688:     // throw new SecurityException("Cannot make network connections.");
 689:   }
 690: 
 691:   /**
 692:    * Check if the current thread is allowed to listen to a specific port for
 693:    * data. This method is called by ServerSocket.ServerSocket(). The default
 694:    * implementation checks
 695:    * <code>SocketPermission("localhost:" + (port == 0 ? "1024-" : "" + port),
 696:    * "listen")</code>. If you override this, call
 697:    * <code>super.checkListen</code> rather than throwing an exception.
 698:    *
 699:    * @param port the port to listen on
 700:    * @throws SecurityException if permission is denied
 701:    * @see ServerSocket#ServerSocket(int)
 702:    */
 703:   public void checkListen(int port)
 704:   {
 705:     checkPermission(new SocketPermission("localhost:"
 706:                                          + (port == 0 ? "1024-" : "" +port),
 707:                                          "listen"));
 708:   }
 709: 
 710:   /**
 711:    * Check if the current thread is allowed to accept a connection from a
 712:    * particular host on a particular port. This method is called by
 713:    * ServerSocket.implAccept(). The default implementation checks
 714:    * <code>SocketPermission(host + ":" + port, "accept")</code>. If you
 715:    * override this, call <code>super.checkAccept</code> rather than throwing
 716:    * an exception.
 717:    *
 718:    * @param host the host which wishes to connect
 719:    * @param port the port the connection will be on
 720:    * @throws SecurityException if permission is denied
 721:    * @throws NullPointerException if host is null
 722:    * @see ServerSocket#accept()
 723:    */
 724:   public void checkAccept(String host, int port)
 725:   {
 726:     // Use the toString() hack to do the null check.
 727:     checkPermission(new SocketPermission(host.toString() + ":" + port,
 728:                                          "accept"));
 729:   }
 730: 
 731:   /**
 732:    * Check if the current thread is allowed to read and write multicast to
 733:    * a particular address. The default implementation checks
 734:    * <code>SocketPermission(addr.getHostAddress(), "accept,connect")</code>.
 735:    * If you override this, call <code>super.checkMulticast</code> rather than
 736:    * throwing an exception.
 737:    *
 738:    * @param addr the address to multicast to
 739:    * @throws SecurityException if permission is denied
 740:    * @throws NullPointerException if host is null
 741:    * @since 1.1
 742:    */
 743:   public void checkMulticast(InetAddress addr)
 744:   {
 745:     checkPermission(new SocketPermission(addr.getHostAddress(),
 746:                                          "accept,connect"));
 747:   }
 748: 
 749:   /**
 750:    *Check if the current thread is allowed to read and write multicast to
 751:    * a particular address with a particular ttl (time-to-live) value. The
 752:    * default implementation ignores ttl, and checks
 753:    * <code>SocketPermission(addr.getHostAddress(), "accept,connect")</code>.
 754:    * If you override this, call <code>super.checkMulticast</code> rather than
 755:    * throwing an exception.
 756:    *
 757:    * @param addr the address to multicast to
 758:    * @param ttl value in use for multicast send
 759:    * @throws SecurityException if permission is denied
 760:    * @throws NullPointerException if host is null
 761:    * @since 1.1
 762:    * @deprecated use {@link #checkPermission(Permission)} instead
 763:    */
 764:   public void checkMulticast(InetAddress addr, byte ttl)
 765:   {
 766:     checkPermission(new SocketPermission(addr.getHostAddress(),
 767:                                          "accept,connect"));
 768:   }
 769: 
 770:   /**
 771:    * Check if the current thread is allowed to read or write all the system
 772:    * properties at once. This method is called by System.getProperties()
 773:    * and setProperties(). The default implementation checks
 774:    * <code>PropertyPermission("*", "read,write")</code>. If you override
 775:    * this, call <code>super.checkPropertiesAccess</code> rather than
 776:    * throwing an exception.
 777:    *
 778:    * @throws SecurityException if permission is denied
 779:    * @see System#getProperties()
 780:    * @see System#setProperties(Properties)
 781:    */
 782:   public void checkPropertiesAccess()
 783:   {
 784:     checkPermission(new PropertyPermission("*", "read,write"));
 785:   }
 786: 
 787:   /**
 788:    * Check if the current thread is allowed to read a particular system
 789:    * property (writes are checked directly via checkPermission). This method
 790:    * is called by System.getProperty() and setProperty(). The default
 791:    * implementation checks <code>PropertyPermission(key, "read")</code>. If
 792:    * you override this, call <code>super.checkPropertyAccess</code> rather
 793:    * than throwing an exception.
 794:    *
 795:    * @param key the key of the property to check
 796:    *
 797:    * @throws SecurityException if permission is denied
 798:    * @throws NullPointerException if key is null
 799:    * @throws IllegalArgumentException if key is ""
 800:    *
 801:    * @see System#getProperty(String)
 802:    */
 803:   public void checkPropertyAccess(String key)
 804:   {
 805:     checkPermission(new PropertyPermission(key, "read"));
 806:   }
 807: 
 808:   /**
 809:    * Check if the current thread is allowed to create a top-level window. If
 810:    * it is not, the operation should still go through, but some sort of
 811:    * nonremovable warning should be placed on the window to show that it
 812:    * is untrusted. This method is called by Window.Window(). The default
 813:    * implementation checks
 814:    * <code>AWTPermission("showWindowWithoutWarningBanner")</code>, and returns
 815:    * true if no exception was thrown. If you override this, use
 816:    * <code>return super.checkTopLevelWindow</code> rather than returning
 817:    * false.
 818:    *
 819:    * @param window the window to create
 820:    * @return true if there is permission to show the window without warning
 821:    * @throws NullPointerException if window is null
 822:    * @see Window#Window(Frame)
 823:    */
 824:   public boolean checkTopLevelWindow(Object window)
 825:   {
 826:     if (window == null)
 827:       throw new NullPointerException();
 828:     try
 829:       {
 830:         checkPermission(new AWTPermission("showWindowWithoutWarningBanner"));
 831:         return true;
 832:       }
 833:     catch (SecurityException e)
 834:       {
 835:         return false;
 836:       }
 837:   }
 838: 
 839:   /**
 840:    * Check if the current thread is allowed to create a print job. This
 841:    * method is called by Toolkit.getPrintJob(). The default implementation
 842:    * checks <code>RuntimePermission("queuePrintJob")</code>. If you override
 843:    * this, call <code>super.checkPrintJobAccess</code> rather than throwing
 844:    * an exception.
 845:    *
 846:    * @throws SecurityException if permission is denied
 847:    * @see Toolkit#getPrintJob(Frame, String, Properties)
 848:    * @since 1.1
 849:    */
 850:   public void checkPrintJobAccess()
 851:   {
 852:     checkPermission(new RuntimePermission("queuePrintJob"));
 853:   }
 854: 
 855:   /**
 856:    * Check if the current thread is allowed to use the system clipboard. This
 857:    * method is called by Toolkit.getSystemClipboard(). The default
 858:    * implementation checks <code>AWTPermission("accessClipboard")</code>. If
 859:    * you override this, call <code>super.checkSystemClipboardAccess</code>
 860:    * rather than throwing an exception.
 861:    *
 862:    * @throws SecurityException if permission is denied
 863:    * @see Toolkit#getSystemClipboard()
 864:    * @since 1.1
 865:    */
 866:   public void checkSystemClipboardAccess()
 867:   {
 868:     checkPermission(new AWTPermission("accessClipboard"));
 869:   }
 870: 
 871:   /**
 872:    * Check if the current thread is allowed to use the AWT event queue. This
 873:    * method is called by Toolkit.getSystemEventQueue(). The default
 874:    * implementation checks <code>AWTPermission("accessEventQueue")</code>.
 875:    * you override this, call <code>super.checkAwtEventQueueAccess</code>
 876:    * rather than throwing an exception.
 877:    *
 878:    * @throws SecurityException if permission is denied
 879:    * @see Toolkit#getSystemEventQueue()
 880:    * @since 1.1
 881:    */
 882:   public void checkAwtEventQueueAccess()
 883:   {
 884:     checkPermission(new AWTPermission("accessEventQueue"));
 885:   }
 886: 
 887:   /**
 888:    * Check if the current thread is allowed to access the specified package
 889:    * at all. This method is called by ClassLoader.loadClass() in user-created
 890:    * ClassLoaders. The default implementation gets a list of all restricted
 891:    * packages, via <code>Security.getProperty("package.access")</code>. Then,
 892:    * if packageName starts with or equals any restricted package, it checks
 893:    * <code>RuntimePermission("accessClassInPackage." + packageName)</code>.
 894:    * If you override this, you should call
 895:    * <code>super.checkPackageAccess</code> before doing anything else.
 896:    *
 897:    * @param packageName the package name to check access to
 898:    * @throws SecurityException if permission is denied
 899:    * @throws NullPointerException if packageName is null
 900:    * @see ClassLoader#loadClass(String, boolean)
 901:    * @see Security#getProperty(String)
 902:    */
 903:   public void checkPackageAccess(String packageName)
 904:   {
 905:     checkPackageList(packageName, "access", "accessClassInPackage.");
 906:   }
 907: 
 908:   /**
 909:    * Check if the current thread is allowed to define a class into the
 910:    * specified package. This method is called by ClassLoader.loadClass() in
 911:    * user-created ClassLoaders. The default implementation gets a list of all
 912:    * restricted packages, via
 913:    * <code>Security.getProperty("package.definition")</code>. Then, if
 914:    * packageName starts with or equals any restricted package, it checks
 915:    * <code>RuntimePermission("defineClassInPackage." + packageName)</code>.
 916:    * If you override this, you should call
 917:    * <code>super.checkPackageDefinition</code> before doing anything else.
 918:    *
 919:    * @param packageName the package name to check access to
 920:    * @throws SecurityException if permission is denied
 921:    * @throws NullPointerException if packageName is null
 922:    * @see ClassLoader#loadClass(String, boolean)
 923:    * @see Security#getProperty(String)
 924:    */
 925:   public void checkPackageDefinition(String packageName)
 926:   {
 927:     checkPackageList(packageName, "definition", "defineClassInPackage.");
 928:   }
 929: 
 930:   /**
 931:    * Check if the current thread is allowed to set the current socket factory.
 932:    * This method is called by Socket.setSocketImplFactory(),
 933:    * ServerSocket.setSocketFactory(), and URL.setURLStreamHandlerFactory().
 934:    * The default implementation checks
 935:    * <code>RuntimePermission("setFactory")</code>. If you override this, call
 936:    * <code>super.checkSetFactory</code> rather than throwing an exception.
 937:    *
 938:    * @throws SecurityException if permission is denied
 939:    * @see Socket#setSocketImplFactory(SocketImplFactory)
 940:    * @see ServerSocket#setSocketFactory(SocketImplFactory)
 941:    * @see URL#setURLStreamHandlerFactory(URLStreamHandlerFactory)
 942:    */
 943:   public void checkSetFactory()
 944:   {
 945:     checkPermission(new RuntimePermission("setFactory"));
 946:   }
 947: 
 948:   /**
 949:    * Check if the current thread is allowed to get certain types of Methods,
 950:    * Fields and Constructors from a Class object. This method is called by
 951:    * Class.getMethod[s](), Class.getField[s](), Class.getConstructor[s],
 952:    * Class.getDeclaredMethod[s](), Class.getDeclaredField[s](), and
 953:    * Class.getDeclaredConstructor[s](). The default implementation allows
 954:    * PUBLIC access, and access to classes defined by the same classloader as
 955:    * the code performing the reflection. Otherwise, it checks
 956:    * <code>RuntimePermission("accessDeclaredMembers")</code>. If you override
 957:    * this, do not call <code>super.checkMemberAccess</code>, as this would
 958:    * mess up the stack depth check that determines the ClassLoader requesting
 959:    * the access.
 960:    *
 961:    * @param c the Class to check
 962:    * @param memberType either DECLARED or PUBLIC
 963:    * @throws SecurityException if permission is denied, including when
 964:    *         memberType is not DECLARED or PUBLIC
 965:    * @throws NullPointerException if c is null
 966:    * @see Class
 967:    * @see Member#DECLARED
 968:    * @see Member#PUBLIC
 969:    * @since 1.1
 970:    */
 971:   public void checkMemberAccess(Class c, int memberType)
 972:   {
 973:     if (c == null)
 974:       throw new NullPointerException();
 975:     if (memberType == Member.PUBLIC)
 976:       return;
 977:     // XXX Allow access to classes created by same classloader before next
 978:     // check.
 979:     checkPermission(new RuntimePermission("accessDeclaredMembers"));
 980:   }
 981: 
 982:   /**
 983:    * Test whether a particular security action may be taken. The default
 984:    * implementation checks <code>SecurityPermission(action)</code>. If you
 985:    * override this, call <code>super.checkSecurityAccess</code> rather than
 986:    * throwing an exception.
 987:    *
 988:    * @param action the desired action to take
 989:    * @throws SecurityException if permission is denied
 990:    * @throws NullPointerException if action is null
 991:    * @throws IllegalArgumentException if action is ""
 992:    * @since 1.1
 993:    */
 994:   public void checkSecurityAccess(String action)
 995:   {
 996:     checkPermission(new SecurityPermission(action));
 997:   }
 998: 
 999:   /**
1000:    * Get the ThreadGroup that a new Thread should belong to by default. Called
1001:    * by Thread.Thread(). The default implementation returns the current
1002:    * ThreadGroup of the current Thread. <STRONG>Spec Note:</STRONG> it is not
1003:    * clear whether the new Thread is guaranteed to pass the
1004:    * checkAccessThreadGroup() test when using this ThreadGroup, but I presume
1005:    * so.
1006:    *
1007:    * @return the ThreadGroup to put the new Thread into
1008:    * @since 1.1
1009:    */
1010:   public ThreadGroup getThreadGroup()
1011:   {
1012:     return Thread.currentThread().getThreadGroup();
1013:   }
1014: 
1015:   /**
1016:    * Helper that checks a comma-separated list of restricted packages, from
1017:    * <code>Security.getProperty("package.definition")</code>, for the given
1018:    * package access permission. If packageName starts with or equals any
1019:    * restricted package, it checks
1020:    * <code>RuntimePermission(permission + packageName)</code>.
1021:    *
1022:    * @param packageName the package name to check access to
1023:    * @param restriction the list of restrictions, after "package."
1024:    * @param permission the base permission, including the '.'
1025:    * @throws SecurityException if permission is denied
1026:    * @throws NullPointerException if packageName is null
1027:    * @see #checkPackageAccess(String)
1028:    * @see #checkPackageDefinition(String)
1029:    */
1030:   void checkPackageList(String packageName, String restriction,
1031:                         String permission)
1032:   {
1033:     // Use the toString() hack to do the null check.
1034:     Permission p = new RuntimePermission(permission + packageName.toString());
1035:     String list = Security.getProperty("package." + restriction);
1036:     if (list == null)
1037:       return;
1038:     while (! "".equals(packageName))
1039:       {
1040:         for (int index = list.indexOf(packageName);
1041:              index != -1; index = list.indexOf(packageName, index + 1))
1042:           {
1043:             // Exploit package visibility for speed.
1044:         int packageNameCount = packageName.length();
1045:             if (index + packageNameCount == list.length()
1046:                 || list.charAt(index + packageNameCount) == ',')
1047:               {
1048:                 checkPermission(p);
1049:                 return;
1050:               }
1051:           }
1052:         int index = packageName.lastIndexOf('.');
1053:         packageName = index < 0 ? "" : packageName.substring(0, index);
1054:       }
1055:   }
1056: } // class SecurityManager
1057: 
1058: // XXX This class is unnecessary.
1059: class SecurityContext {
1060:     Class[] classes;
1061:     SecurityContext(Class[] classes) {
1062:         this.classes = classes;
1063:     }
1064: }