public static void main(String[] args) throws JAXBException { System.out.println("\nWithout security manager\n"); test(FactoryBase.class, FactoryBase.class); test(Factory1.class, FactoryBase.class); test(Factory2.class, Factory2.class); System.out.println("\nWith security manager\n"); Policy.setPolicy(new Policy() { @Override public boolean implies(ProtectionDomain domain, Permission permission) { return true; // allow all } }); System.setSecurityManager(new SecurityManager()); test(FactoryBase.class, FactoryBase.class); test(Factory1.class, FactoryBase.class); test(Factory2.class, Factory2.class); }
public static void main(String[] args) throws JAXBException { System.out.println("\nWithout security manager\n"); test(FactoryBase.class); test(Factory1.class); test(Factory2.class); System.out.println("\nWith security manager\n"); Policy.setPolicy(new Policy() { @Override public boolean implies(ProtectionDomain domain, Permission permission) { return true; // allow all } }); System.setSecurityManager(new SecurityManager()); test(FactoryBase.class); test(Factory1.class); test(Factory2.class); }
static void setUp(TestCase test) { switch (test) { case SECURE: if (policy == null && System.getSecurityManager() != null) { throw new IllegalStateException("SecurityManager already set"); } else if (policy == null) { policy = new SimplePolicy(TestCase.SECURE, allowAll); Policy.setPolicy(policy); System.setSecurityManager(new SecurityManager()); } if (System.getSecurityManager() == null) { throw new IllegalStateException("No SecurityManager."); } if (policy == null) { throw new IllegalStateException("policy not configured"); } break; case UNSECURE: if (System.getSecurityManager() != null) { throw new IllegalStateException("SecurityManager already set"); } break; default: new InternalError("No such testcase: " + test); } }
@Override public boolean check(Permission permission) { if (!Globals.IS_SECURITY_ENABLED) { return true; } Policy currentPolicy = Policy.getPolicy(); if (currentPolicy != null) { ResourceEntry entry = findResourceInternal("/", "/", false); if (entry != null) { CodeSource cs = new CodeSource( entry.codeBase, (java.security.cert.Certificate[]) null); PermissionCollection pc = currentPolicy.getPermissions(cs); if (pc.implies(permission)) { return true; } } } return false; }
public void testUnloadableWithSecurityManager() throws Exception { // Test that the use of a FinalizableReferenceQueue does not subsequently prevent the // loader of that class from being garbage-collected even if there is a SecurityManager. // The SecurityManager environment makes such leaks more likely because when you create // a URLClassLoader with a SecurityManager, the creating code's AccessControlContext is // captured, and that references the creating code's ClassLoader. Policy oldPolicy = Policy.getPolicy(); SecurityManager oldSecurityManager = System.getSecurityManager(); try { Policy.setPolicy(new PermissivePolicy()); System.setSecurityManager(new SecurityManager()); doTestUnloadable(); } finally { System.setSecurityManager(oldSecurityManager); Policy.setPolicy(oldPolicy); } }
/** * Returns a policy containing all the permissions we ever need. */ public static Policy permissivePolicy() { return new AdjustablePolicy // Permissions j.u.c. needs directly (new RuntimePermission("modifyThread"), new RuntimePermission("getClassLoader"), new RuntimePermission("setContextClassLoader"), // Permissions needed to change permissions! new SecurityPermission("getPolicy"), new SecurityPermission("setPolicy"), new RuntimePermission("setSecurityManager"), // Permissions needed by the junit test harness new RuntimePermission("accessDeclaredMembers"), new PropertyPermission("*", "read"), new java.io.FilePermission("<<ALL FILES>>", "read")); }
public static void launch(TestCase test) { switch(test) { case WITHSECURITY: Policy.setPolicy(new Policy() { @Override public boolean implies(ProtectionDomain domain, Permission permission) { return true; } }); System.setSecurityManager(new SecurityManager()); break; case NOSECURITY: break; default: throw new InternalError("Unexpected enum: " + test); } try { test(test.name(), ".1", ".child"); test(test.name(), ".2", ""); testUpdateConfiguration(test.name(), ".3"); testSetPlatformLevel(test.name(), ".4"); } catch (IOException io) { throw new UncheckedIOException(io); } }
public PolicySpiFile(Policy.Parameters params) { if (params == null) { pf = new PolicyFile(); } else { if (!(params instanceof URIParameter)) { throw new IllegalArgumentException ("Unrecognized policy parameter: " + params); } URIParameter uriParam = (URIParameter)params; try { pf = new PolicyFile(uriParam.getURI().toURL()); } catch (MalformedURLException mue) { throw new IllegalArgumentException("Invalid URIParameter", mue); } } }
/** * Prints warning message if installed Policy is the default Policy * implementation and globally granted permissions do not include * AllPermission or any ExecPermissions/ExecOptionPermissions. */ static void checkConfiguration() { Policy policy = AccessController.doPrivileged(new PrivilegedAction<Policy>() { public Policy run() { return Policy.getPolicy(); } }); if (!(policy instanceof PolicyFile)) { return; } PermissionCollection perms = getExecPermissions(); for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();) { Permission p = e.nextElement(); if (p instanceof AllPermission || p instanceof ExecPermission || p instanceof ExecOptionPermission) { return; } } System.err.println(getTextResource("rmid.exec.perms.inadequate")); }
private static PermissionCollection getExecPermissions() { /* * The approach used here is taken from the similar method * getLoaderAccessControlContext() in the class * sun.rmi.server.LoaderHandler. */ // obtain permissions granted to all code in current policy PermissionCollection perms = AccessController.doPrivileged( new PrivilegedAction<PermissionCollection>() { public PermissionCollection run() { CodeSource codesource = new CodeSource(null, (Certificate[]) null); Policy p = Policy.getPolicy(); if (p != null) { return p.getPermissions(codesource); } else { return new Permissions(); } } }); return perms; }
/** * Get the Permissions for a CodeSource. If this instance * of StandardClassLoader is for a web application context, * add read FilePermissions for the base directory (if unpacked), * the context URL, and jar file resources. * * @param CodeSource where the code was loaded from * @return PermissionCollection for CodeSource */ protected final PermissionCollection getPermissions(CodeSource codeSource) { if (!policy_refresh) { // Refresh the security policies Policy policy = Policy.getPolicy(); policy.refresh(); policy_refresh = true; } String codeUrl = codeSource.getLocation().toString(); PermissionCollection pc; if ((pc = (PermissionCollection)loaderPC.get(codeUrl)) == null) { pc = super.getPermissions(codeSource); if (pc != null) { Iterator perms = permissionList.iterator(); while (perms.hasNext()) { Permission p = (Permission)perms.next(); pc.add(p); } loaderPC.put(codeUrl,pc); } } return (pc); }
static void setUp(TestCase test) { switch (test) { case SECURE: if (policy == null && System.getSecurityManager() != null) { throw new IllegalStateException("SecurityManager already set"); } else if (policy == null) { policy = new SimplePolicy(TestCase.SECURE, allowAll); Policy.setPolicy(policy); System.setSecurityManager(new SecurityManager()); } if (System.getSecurityManager() == null) { throw new IllegalStateException("No SecurityManager."); } if (policy == null) { throw new IllegalStateException("policy not configured"); } break; case UNSECURE: if (System.getSecurityManager() != null) { throw new IllegalStateException("SecurityManager already set"); } break; default: throw new InternalError("No such testcase: " + test); } }
/** * This test will run both with and without a security manager. * * The test starts a number of threads that will attempt to concurrently * set resource bundles on Logger, and verifies the consistency of the * obtained results. * * This is a best effort test. * * @param args the command line arguments */ public static void main(String[] args) throws Exception { try { // test without security System.out.println("No security"); test(); // test with security System.out.println("\nWith security"); Policy.setPolicy(new Policy() { @Override public boolean implies(ProtectionDomain domain, Permission permission) { if (super.implies(domain, permission)) return true; // System.out.println("Granting " + permission); return true; // all permissions } }); System.setSecurityManager(new SecurityManager()); test(); } finally { SetRB.executor.shutdownNow(); SetRBName.executor.shutdownNow(); } }
/** * Security is enabled, extension function not allowed */ public void testExtFuncNotAllowed() { Policy p = new SimplePolicy(new AllPermission()); Policy.setPolicy(p); System.setSecurityManager(new SecurityManager()); TransformerFactory factory = TransformerFactory.newInstance(); try { transform(factory); } catch (TransformerConfigurationException e) { fail(e.getMessage()); } catch (TransformerException ex) { //expected since extension function is disallowed System.out.println("testExtFuncNotAllowed: OK"); } finally { System.setSecurityManager(null); } }
/** * Security is enabled, extension function not allowed */ public void testExtFuncNotAllowed() { Policy p = new SimplePolicy(new AllPermission()); Policy.setPolicy(p); System.setSecurityManager(new SecurityManager()); try { evaluate(false); } catch (XPathFactoryConfigurationException e) { fail(e.getMessage()); } catch (XPathExpressionException ex) { //expected since extension function is disallowed System.out.println("testExtFuncNotAllowed: OK"); } finally { System.setSecurityManager(null); } }
/** * Test the LoggingPermission("control") is required. * @param loggerName The logger to use. */ public static void testPermission(String loggerName) { if (System.getSecurityManager() != null) { throw new Error("Security manager is already set"); } Policy.setPolicy(new SimplePolicy(TestCase.PERMISSION)); System.setSecurityManager(new SecurityManager()); final ResourceBundle bundle = ResourceBundle.getBundle(LIST_BUNDLE_NAME); Logger foobar = Logger.getLogger(loggerName); try { foobar.setResourceBundle(bundle); throw new RuntimeException("Permission not checked!"); } catch (AccessControlException x) { if (x.getPermission() instanceof LoggingPermission) { if ("control".equals(x.getPermission().getName())) { System.out.println("Got expected exception: " + x); return; } } throw new RuntimeException("Unexpected exception: "+x, x); } }
public static void main(String args[]) throws Exception { String hostsFileName = CWD + "/LookupTestHosts"; System.setProperty("jdk.net.hosts.file", hostsFileName); addMappingToHostsFile("allowedAndFound.com", "127.0.0.1", hostsFileName, false); addMappingToHostsFile("notAllowedButFound.com", "99.99.99.99", hostsFileName, true); // name "notAllowedAndNotFound.com" is not in map // name "allowedButNotfound.com" is not in map Server server = new Server(); try { Policy.setPolicy(new LookupTestPolicy()); System.setSecurityManager(new SecurityManager()); server.start(); test("http://allowedAndFound.com:" + port + "/foo", false, false); test("http://notAllowedButFound.com:" + port + "/foo", true, false); test("http://allowedButNotfound.com:" + port + "/foo", false, true); test("http://notAllowedAndNotFound.com:" + port + "/foo", true, false); } finally { server.terminate(); } }
public static void main(String[] args) throws Exception { // Check policy with no java.security.policy property set Policy p = Policy.getPolicy(); checkPolicy(p); // Check policy with java.security.policy '=' option System.setProperty("java.security.policy", "Extra.policy"); p.refresh(); checkPolicy(p); // Check policy with java.security.policy override '==' option System.setProperty("java.security.policy", "=Extra.policy"); p.refresh(); checkPolicy(p); // Check Policy.getInstance URI policyURI = Paths.get(System.getProperty("test.src"), "Extra.policy").toUri(); p = Policy.getInstance("JavaPolicy", new URIParameter(policyURI)); checkPolicy(p); }
public static void main(String... args) throws Exception { if (args.length > 0 && args[0].equals("sm")) { PermissionCollection perms = new Permissions(); perms.add(new RuntimePermission("getStackWalkerWithClassReference")); Policy.setPolicy(new Policy() { @Override public boolean implies(ProtectionDomain domain, Permission p) { return perms.implies(p); } }); System.setSecurityManager(new SecurityManager()); } new GetCallerClassTest(StackWalker.getInstance(), true).test(); new GetCallerClassTest(StackWalker.getInstance(RETAIN_CLASS_REFERENCE), false).test(); new GetCallerClassTest(StackWalker.getInstance(EnumSet.of(RETAIN_CLASS_REFERENCE, SHOW_HIDDEN_FRAMES)), false).test(); }
/** * This test will run both with and without a security manager. * * The test starts a number of threads that will call * LogManager.reset() concurrently (ResetConf), and a number of threads * that will call readConfiguration() (ReadConf), and then starts a * number of threads that will create new loggers concurrently * (AddLogger), and finally two additional threads: * - one (Stopper) that will stop the test after 4secs (TIME ms), * - and one DeadlockDetector that will attempt to detect deadlocks. * If after 4secs no deadlock was detected and no exception was thrown * then the test is considered a success and passes. * * This procedure is done twice: once without a security manager and once * again with a security manager - which means the test takes ~8secs to * run. * * Note that 8sec may not be enough to detect issues if there are some. * This is a best effort test. * * @param args the command line arguments * @throws java.lang.Exception if the test fails */ public static void main(String[] args) throws Exception { File conf = new File(System.getProperty("test.src", "./src"), TestConfigurationLock.class.getSimpleName() + ".properties"); if (!conf.canRead()) { throw new IOException("Can't read config file: " + conf.getAbsolutePath()); } System.setProperty("java.util.logging.config.file", conf.getAbsolutePath()); // test without security System.out.println("No security"); test(); // test with security System.out.println("\nWith security"); Policy.setPolicy(new Policy() { @Override public boolean implies(ProtectionDomain domain, Permission permission) { if (super.implies(domain, permission)) return true; // System.out.println("Granting " + permission); return true; // all permissions } }); System.setSecurityManager(new SecurityManager()); test(); }
/** * Attempt to give the rest of NetBeans all the * permissions. The jars besides the one containing this class * don't have to be signed with this. */ final static void fixPolicy() { if (Boolean.getBoolean("netbeans.jnlp.fixPolicy")) { // NOI18N // Grant all the code all persmission Policy.setPolicy(new RuntimePolicy()); // Replace the security manager by a fresh copy // that does the delegation to the permissions system // -- just to make sure that there is nothing left // from the JWS System.setSecurityManager(new SecurityManager()); } }
/** * Initializes SecurityManager for the environment * Can only happen once! * @param environment configuration for generating dynamic permissions * @param filterBadDefaults true if we should filter out bad java defaults in the system policy. */ static void configure(Environment environment, boolean filterBadDefaults) throws IOException, NoSuchAlgorithmException { // enable security policy: union of template and environment-based paths, and possibly plugin permissions Policy.setPolicy(new ESPolicy(createPermissions(environment), getPluginPermissions(environment), filterBadDefaults)); // enable security manager System.setSecurityManager(new SecureSM(new String[] { "org.elasticsearch.bootstrap.", "org.elasticsearch.cli" })); // do some basic tests selfTest(); }
@Override @SuppressForbidden(reason = "fast equals check is desired") public boolean implies(ProtectionDomain domain, Permission permission) { CodeSource codeSource = domain.getCodeSource(); // codesource can be null when reducing privileges via doPrivileged() if (codeSource == null) { return false; } URL location = codeSource.getLocation(); // location can be null... ??? nobody knows // https://bugs.openjdk.java.net/browse/JDK-8129972 if (location != null) { // run scripts with limited permissions if (BootstrapInfo.UNTRUSTED_CODEBASE.equals(location.getFile())) { return untrusted.implies(domain, permission); } // check for an additional plugin permission: plugin policy is // only consulted for its codesources. Policy plugin = plugins.get(location.getFile()); if (plugin != null && plugin.implies(domain, permission)) { return true; } } // Special handling for broken Hadoop code: "let me execute or my classes will not load" // yeah right, REMOVE THIS when hadoop is fixed if (permission instanceof FilePermission && "<<ALL FILES>>".equals(permission.getName())) { for (StackTraceElement element : Thread.currentThread().getStackTrace()) { if ("org.apache.hadoop.util.Shell".equals(element.getClassName()) && "runCommand".equals(element.getMethodName())) { // we found the horrible method: the hack begins! // force the hadoop code to back down, by throwing an exception that it catches. rethrow(new IOException("no hadoop, you cannot do this.")); } } } // otherwise defer to template + dynamic file permissions return template.implies(domain, permission) || dynamic.implies(permission) || system.implies(domain, permission); }
/** * Refresh the system policy file, to pick up eventual changes. */ protected void refreshPolicy() { try { // The policy file may have been modified to adjust // permissions, so we're reloading it when loading or // reloading a Context Policy policy = Policy.getPolicy(); policy.refresh(); } catch (AccessControlException e) { // Some policy files may restrict this, even for the core, // so this exception is ignored } }
public void testUnloadableInStaticFieldIfClosed() throws Exception { Policy oldPolicy = Policy.getPolicy(); SecurityManager oldSecurityManager = System.getSecurityManager(); try { Policy.setPolicy(new PermissivePolicy()); System.setSecurityManager(new SecurityManager()); WeakReference<ClassLoader> loaderRef = doTestUnloadableInStaticFieldIfClosed(); GcFinalization.awaitClear(loaderRef); } finally { System.setSecurityManager(oldSecurityManager); Policy.setPolicy(oldPolicy); } }
/** * Test with security manager. * @param loggerName The logger to use. * @throws Exception if the test fails. */ public static void testSecure(String loggerName) throws Exception { if (System.getSecurityManager() != null) { throw new Error("Security manager is already set"); } Policy.setPolicy(new SimplePolicy(TestCase.SECURE)); System.setSecurityManager(new SecurityManager()); test(loggerName); }
public static void init() { SharedSecrets.setJavaAWTAccess(javaAwtAccess); if (System.getProperty("test.security", "on").equals("on")) { Policy p = new SimplePolicy(new LoggingPermission("control", null), new RuntimePermission("setContextClassLoader"), new RuntimePermission("shutdownHooks")); Policy.setPolicy(p); System.setSecurityManager(new SecurityManager()); } }
@Override @SuppressForbidden(reason = "fast equals check is desired") public boolean implies(ProtectionDomain domain, Permission permission) { CodeSource codeSource = domain.getCodeSource(); // codesource can be null when reducing privileges via doPrivileged() if (codeSource == null) { return false; } URL location = codeSource.getLocation(); // location can be null... ??? nobody knows // https://bugs.openjdk.java.net/browse/JDK-8129972 if (location != null) { // run scripts with limited permissions if (BootstrapInfo.UNTRUSTED_CODEBASE.equals(location.getFile())) { return untrusted.implies(domain, permission); } // check for an additional plugin permission: plugin policy is // only consulted for its codesources. Policy plugin = plugins.get(location.getFile()); if (plugin != null && plugin.implies(domain, permission)) { return true; } } // otherwise defer to template + dynamic file permissions return template.implies(domain, permission) || dynamic.implies(permission) || system.implies(domain, permission); }