Java Code Examples for java.security.Policy#setPolicy()

The following examples show how to use java.security.Policy#setPolicy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestConfigurationLock.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 2
Source File: TestLoggerBundleSync.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 3
Source File: FieldSetAccessibleTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 4
Source File: ClassDeclaredFieldsTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 5
Source File: XSLTExFuncTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: ClassDeclaredFieldsTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 7
Source File: TestConverterManager.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testRemoveDurationConverterSecurity() {
    if (OLD_JDK) {
        return;
    }
    try {
        Policy.setPolicy(RESTRICT);
        System.setSecurityManager(new SecurityManager());
        ConverterManager.getInstance().removeDurationConverter(StringConverter.INSTANCE);
        fail();
    } catch (SecurityException ex) {
        // ok
    } finally {
        System.setSecurityManager(null);
        Policy.setPolicy(ALLOW);
    }
    assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length);
}
 
Example 8
Source File: OSGILauncher.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected void setupSecurityPolicy( ) throws FrameworkException
{
	String eclipseSecurity = (String) properties
			.get( PROP_ECLIPSE_SECURITY );
	if ( eclipseSecurity != null )
	{
		// setup a policy that grants the launcher and path for the
		// framework AllPermissions.
		// Do not set the security manager, this will be done by the
		// framework itself.
		ProtectionDomain domain = OSGILauncher.class.getProtectionDomain( );
		CodeSource source = null;
		if ( domain != null )
			source = OSGILauncher.class.getProtectionDomain( )
					.getCodeSource( );
		if ( domain == null || source == null )
		{
			throw new FrameworkException(
					"Can not automatically set the security manager. Please use a policy file." );
		}
		// get the list of codesource URLs to grant AllPermission to
		URL[] rootURLs = new URL[]{source.getLocation( ), osgiFramework};
		// replace the security policy
		Policy eclipsePolicy = new OSGIPolicy( Policy.getPolicy( ),
				rootURLs );
		Policy.setPolicy( eclipsePolicy );
	}
}
 
Example 9
Source File: TestBase.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void tearDown() {
    // turn off security manager and restore policy
    System.setSecurityManager(null);
    Policy.setPolicy(origPolicy);
    if (hasSM) {
        System.setSecurityManager(new SecurityManager());
    }
    System.out.println("\nNumber of tests passed: " + passed);
    System.out.println("Number of tests failed: " + failed + "\n");

    if (errMessage != null ) {
        throw new RuntimeException(errMessage);
    }
}
 
Example 10
Source File: TestBase.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void tearDown() {
    // turn off security manager and restore policy
    System.setSecurityManager(null);
    Policy.setPolicy(origPolicy);
    if (hasSM) {
        System.setSecurityManager(new SecurityManager());
    }
    System.out.println("\nNumber of tests passed: " + passed);
    System.out.println("Number of tests failed: " + failed + "\n");

    if (errMessage != null ) {
        throw new RuntimeException(errMessage);
    }
}
 
Example 11
Source File: TestLogConfigurationDeadLockWithConf.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This test will run both with and without a security manager.
 *
 * The test starts a number of threads that will call
 *     LogManager.readConfiguration() concurrently (ReadConf), then starts
 *     a number of threads that will create new loggers concurrently
 *     (AddLogger), and then 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 config =  new File(System.getProperty("test.src", "."),
                    "deadlockconf.properties");
    if (!config.canRead()) {
        System.err.println("Can't read config file: test cannot execute.");
        System.err.println("Please check your test environment: ");
        System.err.println("\t -Dtest.src=" + System.getProperty("test.src", "."));
        System.err.println("\t config file is: " + config.getAbsolutePath());
        throw new RuntimeException("Can't read config file: "
            + config.getAbsolutePath());
    }

    System.setProperty("java.util.logging.config.file",
           config.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();
}
 
Example 12
Source File: TestBase.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void tearDown() {
    // turn off security manager and restore policy
    System.setSecurityManager(null);
    Policy.setPolicy(origPolicy);
    if (hasSM) {
        System.setSecurityManager(new SecurityManager());
    }
    System.out.println("\nNumber of tests passed: " + passed);
    System.out.println("Number of tests failed: " + failed + "\n");

    if (errMsg != null ) {
        throw new RuntimeException(errMsg);
    }
}
 
Example 13
Source File: TestBase.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void tearDown() {
    // turn off security manager and restore policy
    System.setSecurityManager(null);
    Policy.setPolicy(origPolicy);
    if (hasSM) {
        System.setSecurityManager(new SecurityManager());
    }
    System.out.println("\nNumber of tests passed: " + passed);
    System.out.println("Number of tests failed: " + failed + "\n");

    if (errMessage != null ) {
        throw new RuntimeException(errMessage);
    }
}
 
Example 14
Source File: TestAppletLoggerContext.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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());
    }
}
 
Example 15
Source File: PolicyFileGeneratorJSM.java    From pro-grade with Apache License 2.0 4 votes vote down vote up
/**
 * JSM Constructor.
 */
public PolicyFileGeneratorJSM() {
    Policy.setPolicy(new NotifyAndAllowPolicy(null, new GeneratePolicyFromDeniedPermissions()));
}
 
Example 16
Source File: BasePlatformLoggerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
static void setSecurityManager() {
    if (System.getSecurityManager() == null) {
        Policy.setPolicy(new SimplePolicy(allowControl, allowAccess, allowAll));
        System.setSecurityManager(new SecurityManager());
    }
}
 
Example 17
Source File: PermissionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void currentWithPermission() {
    Policy.setPolicy(new TestPolicy(new RuntimePermission("manageProcess")));
    ProcessHandle.current();
}
 
Example 18
Source File: TestGetLoggerNPE.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    final String testCase = args.length == 0 ? "getLogger" : args[0];
    final JavaAWTAccessStub access = new JavaAWTAccessStub();
    SharedSecrets.setJavaAWTAccess(access);
    final ThreadGroup tg = new ThreadGroup("TestGroup");
    Thread t = new Thread(tg, "test") {
        public void run() {
            try {
                access.setContext(Context.ONE);
                final PrintStream out = System.out;
                System.setOut(null);
                try {
                    if ("getLogger".equals(testCase)) {
                       Logger.getLogger("sun.plugin");
                    } else {
                       LogManager.getLogManager();
                    }
                } finally {
                    System.setOut(out);
                }

                System.out.println(Logger.global);
            } catch (Throwable x) {
                x.printStackTrace();
                thrown = x;
            }
        }
    };
    Policy.setPolicy(new Policy() {
         public boolean implies(ProtectionDomain domain,
                                Permission permission) {
             return true; // all permissions
         }
    });
    System.setSecurityManager(new SecurityManager());
    t.start();
    t.join();
    if (thrown == null) {
        System.out.println("PASSED: " + testCase);
    } else {
        System.err.println("FAILED: " + testCase);
        throw new Error("Test failed: " + testCase + " - " + thrown, thrown);
    }

}
 
Example 19
Source File: TestGetLoggerNPE.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    final String testCase = args.length == 0 ? "getLogger" : args[0];
    final JavaAWTAccessStub access = new JavaAWTAccessStub();
    SharedSecrets.setJavaAWTAccess(access);
    final ThreadGroup tg = new ThreadGroup("TestGroup");
    Thread t = new Thread(tg, "test") {
        public void run() {
            try {
                access.setContext(Context.ONE);
                final PrintStream out = System.out;
                System.setOut(null);
                try {
                    if ("getLogger".equals(testCase)) {
                       Logger.getLogger("sun.plugin");
                    } else {
                       LogManager.getLogManager();
                    }
                } finally {
                    System.setOut(out);
                }

                System.out.println(Logger.global);
            } catch (Throwable x) {
                x.printStackTrace();
                thrown = x;
            }
        }
    };
    Policy.setPolicy(new Policy() {
         public boolean implies(ProtectionDomain domain,
                                Permission permission) {
             return true; // all permissions
         }
    });
    System.setSecurityManager(new SecurityManager());
    t.start();
    t.join();
    if (thrown == null) {
        System.out.println("PASSED: " + testCase);
    } else {
        System.err.println("FAILED: " + testCase);
        throw new Error("Test failed: " + testCase + " - " + thrown, thrown);
    }

}
 
Example 20
Source File: LoggerFinderLoaderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
static void setSecurityManager() {
    if (System.getSecurityManager() == null) {
        Policy.setPolicy(new SimplePolicy(allowControl, allowAccess));
        System.setSecurityManager(new SecurityManager());
    }
}