Source for java.lang.SecurityManager

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