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