下面列出了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;
}
/**
* 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();
}
}
@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);
}
}
/**
* 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);
}
/**
* 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);
}
}
/**
* 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 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);
}
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);
}
}
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);
}
/**
* 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"));
}
/**
* 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();
}
}
/**
* 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"));
}
/**
* 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);
}
}
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);
}
}
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);
}
}
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);
}
}
}
/**
* 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);
}
}
/**
* 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);
}
}
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);
}
/**
* 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);
}
}
/**
* 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);
}
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);
}
}
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);
}
}
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");
}
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);
}
}
/**
* 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 });
}
@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();
}
}
}
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()));
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
super.afterTestsStopped();
if (setupSM) {
System.setSecurityManager(null);
Policy.setPolicy(null);
}
}
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");
}