java.security.Policy Java Examples

The following examples show how to use java.security.Policy. 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: FieldSetAccessibleTest.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 #2
Source File: XSLTExFuncTest.java    From openjdk-8 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 #3
Source File: XSLTExFuncTest.java    From TencentKona-8 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 #4
Source File: TestSetResourceBundle.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
    }

}
 
Example #5
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 #6
Source File: TestLoggerBundleSync.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 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 #7
Source File: XSLTExFuncTest.java    From hottub 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 #8
Source File: TestDateTimeZone.java    From joda-time-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNameProviderSecurity() {
    if (OLD_JDK) {
        return;
    }
    try {
        Policy.setPolicy(RESTRICT);
        System.setSecurityManager(new SecurityManager());
        DateTimeZone.setNameProvider(new MockOKButNullNameProvider());
        fail();
    } catch (SecurityException ex) {
        // ok
    } finally {
        System.setSecurityManager(null);
        Policy.setPolicy(ALLOW);
    }
}
 
Example #9
Source File: PolicySpiFile.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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);
            }
        }
    }
 
Example #10
Source File: FieldSetAccessibleTest.java    From TencentKona-8 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 #11
Source File: JSR166TestCase.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs all JSR166 unit tests using junit.textui.TestRunner
 */
public static void main(String[] args) {
    if (useSecurityManager) {
        System.err.println("Setting a permissive security manager");
        Policy.setPolicy(permissivePolicy());
        System.setSecurityManager(new SecurityManager());
    }
    int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);

    Test s = suite();
    for (int i = 0; i < iters; ++i) {
        junit.textui.TestRunner.run(s);
        System.gc();
        System.runFinalization();
    }
    System.exit(0);
}
 
Example #12
Source File: TestSetResourceBundle.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
    }

}
 
Example #13
Source File: TestConverterManager.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testRemovePeriodConverterSecurity() {
    if (OLD_JDK) {
        return;
    }
    try {
        Policy.setPolicy(RESTRICT);
        System.setSecurityManager(new SecurityManager());
        ConverterManager.getInstance().removePeriodConverter(StringConverter.INSTANCE);
        fail();
    } catch (SecurityException ex) {
        // ok
    } finally {
        System.setSecurityManager(null);
        Policy.setPolicy(ALLOW);
    }
    assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length);
}
 
Example #14
Source File: FieldSetAccessibleTest.java    From jdk8u60 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 #15
Source File: TestConverterManager.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testRemoveInstantConverterSecurity() {
    if (OLD_JDK) {
        return;
    }
    try {
        Policy.setPolicy(RESTRICT);
        System.setSecurityManager(new SecurityManager());
        ConverterManager.getInstance().removeInstantConverter(StringConverter.INSTANCE);
        fail();
    } catch (SecurityException ex) {
        // ok
    } finally {
        System.setSecurityManager(null);
        Policy.setPolicy(ALLOW);
    }
    assertEquals(6, ConverterManager.getInstance().getInstantConverters().length);
}
 
Example #16
Source File: TestSetResourceBundle.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
    }

}
 
Example #17
Source File: Activation.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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"));
}
 
Example #18
Source File: TestLoggerBundleSync.java    From jdk8u-jdk 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 #19
Source File: Activation.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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"));
}
 
Example #20
Source File: WebappClassLoaderBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public boolean check(Permission permission) {
    if (!Globals.IS_SECURITY_ENABLED) {
        return true;
    }
    Policy currentPolicy = Policy.getPolicy();
    if (currentPolicy != null) {
        URL contextRootUrl = resources.getResource("/").getCodeBase();
        CodeSource cs = new CodeSource(contextRootUrl, (Certificate[]) null);
        PermissionCollection pc = currentPolicy.getPermissions(cs);
        if (pc.implies(permission)) {
            return true;
        }
    }
    return false;
}
 
Example #21
Source File: TestSetResourceBundle.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #22
Source File: TestSetResourceBundle.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #23
Source File: TestLogConfigurationDeadLockWithConf.java    From openjdk-jdk9 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 #24
Source File: TestBase.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() {
    if (System.getSecurityManager() != null) {
        hasSM = true;
        System.setSecurityManager(null);
    }

    filePath = System.getProperty("test.src");
    if (filePath == null) {
        //current directory
        filePath = System.getProperty("user.dir");
    }
    origPolicy = Policy.getPolicy();

}
 
Example #25
Source File: ParameterAnnotations.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void test(String[] args) throws Throwable {
    // Test without a security manager
    test1();

    // Test with a security manager
    Policy defaultPolicy = Policy.getPolicy();
    Policy.setPolicy(new MyPolicy(defaultPolicy));
    System.setSecurityManager(new SecurityManager());
    try {
        test1();
    } finally {
        System.setSecurityManager(null);
        Policy.setPolicy(defaultPolicy);
    }
}
 
Example #26
Source File: TestBase.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() {
    if (System.getSecurityManager() != null) {
        hasSM = true;
        System.setSecurityManager(null);
    }

    filePath = System.getProperty("test.src");
    if (filePath == null) {
        //current directory
        filePath = System.getProperty("user.dir");
    }
    origPolicy = Policy.getPolicy();

}
 
Example #27
Source File: TestBase.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() {
    if (System.getSecurityManager() != null) {
        hasSM = true;
        System.setSecurityManager(null);
    }

    filePath = System.getProperty("test.src");
    if (filePath == null) {
        //current directory
        filePath = System.getProperty("user.dir");
    }
    origPolicy = Policy.getPolicy();

}
 
Example #28
Source File: TestBase.java    From openjdk-jdk8u 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 #29
Source File: TestBase.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() {
    if (System.getSecurityManager() != null) {
        hasSM = true;
        System.setSecurityManager(null);
    }

    filepath = System.getProperty("test.src");
    if (filepath == null) {
        //current directory
        filepath = System.getProperty("user.dir");
    }
    origPolicy = Policy.getPolicy();

}
 
Example #30
Source File: TestBase.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() {
    if (System.getSecurityManager() != null) {
        hasSM = true;
        System.setSecurityManager(null);
    }

    filePath = System.getProperty("test.src");
    if (filePath == null) {
        //current directory
        filePath = System.getProperty("user.dir");
    }
    origPolicy = Policy.getPolicy();

}