java.util.logging.LoggingPermission#java.security.Policy源码实例Demo

下面列出了java.util.logging.LoggingPermission#java.security.Policy 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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;
}
 
源代码2 项目: openjdk-jdk9   文件: TestLoggerBundleSync.java
/**
 * 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();
    }
}
 
源代码3 项目: joda-time-android   文件: TestDateTimeZone.java
@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);
    }
}
 
源代码4 项目: database   文件: JSR166TestCase.java
/**
 * 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);
}
 
源代码5 项目: hottub   文件: XSLTExFuncTest.java
/**
 * 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);
    }
}
 
源代码6 项目: dragonwell8_jdk   文件: TestSetResourceBundle.java
/**
 * 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);
    }

}
 
源代码7 项目: astor   文件: TestConverterManager.java
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);
}
 
源代码8 项目: jdk8u60   文件: FieldSetAccessibleTest.java
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);
    }
}
 
源代码9 项目: astor   文件: TestConverterManager.java
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);
}
 
源代码10 项目: jdk8u-jdk   文件: Activation.java
/**
 * 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"));
}
 
源代码11 项目: jdk8u-jdk   文件: TestLoggerBundleSync.java
/**
 * 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();
    }
}
 
源代码12 项目: TencentKona-8   文件: Activation.java
/**
 * 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"));
}
 
源代码13 项目: openjdk-8   文件: TestSetResourceBundle.java
/**
 * 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);
    }

}
 
源代码14 项目: TencentKona-8   文件: FieldSetAccessibleTest.java
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);
    }
}
 
源代码15 项目: jdk8u-jdk   文件: FieldSetAccessibleTest.java
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);
    }
}
 
源代码16 项目: openjdk-jdk8u   文件: PolicySpiFile.java
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);
            }
        }
    }
 
源代码17 项目: TencentKona-8   文件: TestSetResourceBundle.java
/**
 * 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);
    }

}
 
源代码18 项目: openjdk-8   文件: XSLTExFuncTest.java
/**
 * 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);
    }
}
 
源代码19 项目: astor   文件: TestConverterManager.java
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);
}
 
源代码20 项目: TencentKona-8   文件: XSLTExFuncTest.java
/**
 * 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);
    }
}
 
源代码21 项目: hadoop-gpu   文件: SecurityUtil.java
/**
 * Set the global security policy for Hadoop.
 * 
 * @param policy {@link Policy} used for authorization.
 */
public static void setPolicy(Policy policy) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("Setting Hadoop security policy");
  }
  Policy.setPolicy(policy);
}
 
源代码22 项目: openjdk-jdk9   文件: TestBase.java
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);
    }
}
 
源代码23 项目: openjdk-jdk8u   文件: TestBase.java
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);
    }
}
 
源代码24 项目: jdk8u-jdk   文件: JarURL.java
public static void main(String[] args) throws Exception {
    String userDir = System.getProperty("user.dir");
    String jarURL = "jar:file:" + userDir + File.separator + "foo.jar!/";
    URL codeSourceURL = new URL(jarURL);
    CodeSource cs = new CodeSource(codeSourceURL, new Certificate[0]);
    PermissionCollection perms = Policy.getPolicy().getPermissions(cs);
    if (!perms.implies(new AllPermission()))
        throw new Exception("FAILED: " + codeSourceURL
                            + " not granted AllPermission");
}
 
源代码25 项目: jdk8u60   文件: RootLevelInConfigFile.java
public static void main(String[] args) throws IOException {
    System.setProperty(CONFIG_FILE_KEY,
            new File(System.getProperty("test.src", "."),
                    "rootlogger.properties").getAbsolutePath());
    System.out.println(CONFIG_FILE_KEY + "="
            + System.getProperty(CONFIG_FILE_KEY));
    if (! new File(System.getProperty(CONFIG_FILE_KEY)).canRead()) {
        throw new RuntimeException("can't read config file: "
                + System.getProperty(CONFIG_FILE_KEY));
    }

    final String configFile = System.getProperty(CONFIG_FILE_KEY);

    test("no security");

    LogManager.getLogManager().readConfiguration();

    Policy.setPolicy(new SimplePolicy(configFile));
    System.setSecurityManager(new SecurityManager());

    test("security");

    LogManager.getLogManager().readConfiguration();

    final JavaAWTAccessStub access = new JavaAWTAccessStub();
    SharedSecrets.setJavaAWTAccess(access);

    test("security and no context");

    for (Context ctx : Context.values()) {

        LogManager.getLogManager().readConfiguration();

        access.setContext(ctx);

        test("security and context " + ctx);
    }
}
 
源代码26 项目: openjdk-jdk9   文件: RegistryImpl.java
/**
 * Generates an AccessControlContext with minimal permissions.
 * The approach used here is taken from the similar method
 * getAccessControlContext() in the sun.applet.AppletPanel class.
 */
private static AccessControlContext getAccessControlContext(int port) {
    // begin with permissions granted to all code in current policy
    PermissionCollection perms = AccessController.doPrivileged(
        new java.security.PrivilegedAction<PermissionCollection>() {
            public PermissionCollection run() {
                CodeSource codesource = new CodeSource(null,
                    (java.security.cert.Certificate[]) null);
                Policy p = java.security.Policy.getPolicy();
                if (p != null) {
                    return p.getPermissions(codesource);
                } else {
                    return new Permissions();
                }
            }
        });

    /*
     * Anyone can connect to the registry and the registry can connect
     * to and possibly download stubs from anywhere. Downloaded stubs and
     * related classes themselves are more tightly limited by RMI.
     */
    perms.add(new SocketPermission("*", "connect,accept"));
    perms.add(new SocketPermission("localhost:"+port, "listen,accept"));

    perms.add(new RuntimePermission("accessClassInPackage.sun.jvmstat.*"));
    perms.add(new RuntimePermission("accessClassInPackage.sun.jvm.hotspot.*"));

    perms.add(new FilePermission("<<ALL FILES>>", "read"));

    /*
     * Create an AccessControlContext that consists of a single
     * protection domain with only the permissions calculated above.
     */
    ProtectionDomain pd = new ProtectionDomain(
        new CodeSource(null,
            (java.security.cert.Certificate[]) null), perms);
    return new AccessControlContext(new ProtectionDomain[] { pd });
}
 
源代码27 项目: openjdk-jdk9   文件: PermissionTest.java
@Test
public void processToHandleWithPermission() throws IOException {
    Policy.setPolicy(new TestPolicy(new RuntimePermission("manageProcess")));
    Process p = null;
    try {
        ProcessBuilder pb = new ProcessBuilder("sleep", "30");
        p = pb.start();
        ProcessHandle ph = p.toHandle();
        Assert.assertNotNull(ph, "ProcessHandle expected from Process");
    } finally {
        if (p != null) {
            p.destroy();
        }
    }
}
 
源代码28 项目: jdk8u-jdk   文件: NonPublicProxyClass.java
public static void main(String[] args) throws Exception {
    ClassLoader loader = ClassLoader.getSystemClassLoader();
    Class<?> zipConstantsClass = Class.forName("java.util.zip.ZipConstants", false, null);
    Class<?> fooClass = Class.forName("p.Foo");

    NonPublicProxyClass test1 =
        new NonPublicProxyClass(loader, PublicInterface.class, NonPublicInterface.class);
    NonPublicProxyClass test2 =
        new NonPublicProxyClass(loader, fooClass, PublicInterface.class);
    NonPublicProxyClass test3 =
        new NonPublicProxyClass(null, zipConstantsClass);

    if (args.length == 1) {
        switch (args[0]) {
            case "grant": Policy.setPolicy(new NewInstancePolicy(true));
                          break;
            case "deny" : Policy.setPolicy(new NewInstancePolicy(false));
                          break;
            default: throw new IllegalArgumentException(args[0]);
        }
        System.setSecurityManager(new SecurityManager());
    }

    test1.run();
    test2.run();
    test3.run();
    System.out.format("Test passed: security %s%n",
        (args.length == 0 ? "manager not installed" : Policy.getPolicy()));
}
 
源代码29 项目: ignite   文件: SecuritySubjectPermissionsTest.java
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
    super.afterTestsStopped();

    if (setupSM) {
        System.setSecurityManager(null);
        Policy.setPolicy(null);
    }
}
 
源代码30 项目: openjdk-8   文件: JarURL.java
public static void main(String[] args) throws Exception {
    String userDir = System.getProperty("user.dir");
    String jarURL = "jar:file:" + userDir + File.separator + "foo.jar!/";
    URL codeSourceURL = new URL(jarURL);
    CodeSource cs = new CodeSource(codeSourceURL, new Certificate[0]);
    PermissionCollection perms = Policy.getPolicy().getPermissions(cs);
    if (!perms.implies(new AllPermission()))
        throw new Exception("FAILED: " + codeSourceURL
                            + " not granted AllPermission");
}