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