SecurityManager.java 41 KB

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