Permissions getPermissions() { if (allowControl.get().get() || allowAccess.get().get() || allowAll.get().get()) { PermissionsBuilder builder = new PermissionsBuilder() .addAll(permissions); if (allowControl.get().get()) { builder.add(LOGGERFINDER_PERMISSION); } if (allowAccess.get().get()) { builder.add(ACCESS_LOGGER); builder.add(ACCESS_LOGGING); } if (allowAll.get().get()) { builder.addAll(allPermissions); } return builder.toPermissions(); } return permissions; }
/** Adds access to classpath jars/classes for jar hell scan, etc */ @SuppressForbidden(reason = "accesses fully qualified URLs to configure security") static void addClasspathPermissions(Permissions policy) throws IOException { // add permissions to everything in classpath // really it should be covered by lib/, but there could be e.g. agents or similar configured) for (URL url : JarHell.parseClassPath()) { Path path; try { path = PathUtils.get(url.toURI()); } catch (URISyntaxException e) { throw new RuntimeException(e); } // resource itself policy.add(new FilePermission(path.toString(), "read,readlink")); // classes underneath if (Files.isDirectory(path)) { policy.add(new FilePermission(path.toString() + path.getFileSystem().getSeparator() + "-", "read,readlink")); } } }
static PermissionCollection getRestrictedPermissions() { Permissions perms = new Permissions(); // property/env access needed for parsing perms.add(new PropertyPermission("*", "read")); perms.add(new RuntimePermission("getenv.TIKA_CONFIG")); // add permissions for resource access: // classpath addReadPermissions(perms, JarHell.parseClassPath()); // plugin jars if (TikaImpl.class.getClassLoader() instanceof URLClassLoader) { addReadPermissions(perms, ((URLClassLoader)TikaImpl.class.getClassLoader()).getURLs()); } // jvm's java.io.tmpdir (needs read/write) perms.add(new FilePermission(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "-", "read,readlink,write,delete")); // current hacks needed for POI/PDFbox issues: perms.add(new SecurityPermission("putProviderProperty.BC")); perms.add(new SecurityPermission("insertProvider")); perms.add(new ReflectPermission("suppressAccessChecks")); // xmlbeans, use by POI, needs to get the context classloader perms.add(new RuntimePermission("getClassLoader")); perms.setReadOnly(); return perms; }
private Loader(URL[] urls, ClassLoader parent) { super(urls, parent); this.parent = parent; /* * Precompute the permissions required to access the loader. */ permissions = new Permissions(); addPermissionsForURLs(urls, permissions, false); /* * Caching the value of class annotation string here assumes * that the protected method addURL() is never called on this * class loader. */ annotation = urlsToPath(urls); }
private void attemptSetNullSecurityManager() { final Permissions permissions = new Permissions(); permissions.add(new RuntimePermission("setSecurityManager")); final AccessControlContext context = new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null, permissions)}); AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { LOGGER.info("About to call System.setSecurityManager(null)"); System.setSecurityManager(null); LOGGER.info("Progressed beyond call to System.setSecurityManager(null)"); return null; } }, context); }
Permissions getPermissions() { if (allowControl.get().get() || allowAccess.get().get() || allowAll.get().get()) { PermissionsBuilder builder = new PermissionsBuilder() .addAll(permissions); if (allowControl.get().get()) { builder.add(CONTROL); } if (allowAccess.get().get()) { builder.add(ACCESS_LOGGER); builder.add(ACCESS_LOGGING); } if (allowAll.get().get()) { builder.addAll(allPermissions); } return builder.toPermissions(); } return permissions; }
public SimplePolicy(TestCase test, AtomicBoolean allowAll) { this.allowAll = allowAll; permissions = new Permissions(); permissions.add(new LoggingPermission("control", null)); // needed by new FileHandler() permissions.add(new FilePermission("<<ALL FILES>>", "read")); // needed by new FileHandler() permissions.add(new FilePermission(logFile, "write,delete")); // needed by new FileHandler() permissions.add(new FilePermission(logFile+".lck", "write,delete")); // needed by FileHandler.close() permissions.add(new FilePermission(logFile+".1", "write,delete")); // needed by new FileHandler() permissions.add(new FilePermission(logFile+".1.lck", "write,delete")); // needed by FileHandler.close() permissions.add(new FilePermission(tmpLogFile, "write,delete")); // needed by new FileHandler() permissions.add(new FilePermission(tmpLogFile+".lck", "write,delete")); // needed by FileHandler.close() permissions.add(new FilePermission(tmpLogFile+".1", "write,delete")); // needed by new FileHandler() permissions.add(new FilePermission(tmpLogFile+".1.lck", "write,delete")); // needed by FileHandler.close() permissions.add(new FilePermission(userDir, "write")); // needed by new FileHandler() permissions.add(new FilePermission(tmpDir, "write")); // needed by new FileHandler() permissions.add(new PropertyPermission("user.dir", "read")); permissions.add(new PropertyPermission("java.io.tmpdir", "read")); allPermissions = new Permissions(); allPermissions.add(new java.security.AllPermission()); }
@Override protected PermissionCollection getPermissions(CodeSource codeSource) { Permissions perms = new Permissions(); perms.add(new AllPermission()); perms.setReadOnly(); return perms; }
public SystemClassLoader(List<File> files, ClassLoader[] parents, Set<Module> modules) throws IllegalArgumentException { super(files, parents, false); allPermissions = new Permissions(); allPermissions.add(new AllPermission()); allPermissions.setReadOnly(); size = modules.size(); }
public SimplePolicy(ThreadLocal<AtomicBoolean> allowAll, ThreadLocal<AtomicBoolean> allowControl) { this.allowAll = allowAll; this.allowControl = allowControl; permissions = new Permissions(); withControlPermissions = new Permissions(); withControlPermissions.add(LOGGERFINDER_PERMISSION); // these are used for configuring the test itself... allPermissions = new Permissions(); allPermissions.add(new java.security.AllPermission()); }
protected PermissionCollection getPermissions(CodeSource codesource) { Permissions permissions = new Permissions(); permissions.add(new AllPermission()); permissions.setReadOnly(); return permissions; }
private Class<?> defineFinderClass(String name) throws ClassNotFoundException { final Object obj = getClassLoadingLock(name); synchronized(obj) { if (finderClasses.get(name) != null) return finderClasses.get(name); if (testLoggerFinderClass == null) { // Hack: we load testLoggerFinderClass to get its code source. // we can't use this.getClass() since we are in the boot. testLoggerFinderClass = super.loadClass("BaseDefaultLoggerFinderTest$TestLoggerFinder"); } URL url = testLoggerFinderClass.getProtectionDomain().getCodeSource().getLocation(); File file = new File(url.getPath(), name+".class"); if (file.canRead()) { try { byte[] b = Files.readAllBytes(file.toPath()); Permissions perms = new Permissions(); perms.add(new AllPermission()); Class<?> finderClass = defineClass( name, b, 0, b.length, new ProtectionDomain( this.getClass().getProtectionDomain().getCodeSource(), perms)); System.out.println("Loaded " + name); finderClasses.put(name, finderClass); return finderClass; } catch (Throwable ex) { ex.printStackTrace(); throw new ClassNotFoundException(name, ex); } } else { throw new ClassNotFoundException(name, new IOException(file.toPath() + ": can't read")); } } }
/** * test with null location * <p> * its unclear when/if this happens, see https://bugs.openjdk.java.net/browse/JDK-8129972 */ public void testNullLocation() throws Exception { assumeTrue("test cannot run with security manager", System.getSecurityManager() == null); PermissionCollection noPermissions = new Permissions(); ESPolicy policy = new ESPolicy(noPermissions, Collections.emptyMap(), true); assertFalse(policy.implies(new ProtectionDomain(new CodeSource(null, (Certificate[]) null), noPermissions), new FilePermission("foo", "read"))); }
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) { this.allowAll = allowAll; // we don't actually need any permission to create our // FileHandlers because we're passing invalid parameters // which will make the creation fail... permissions = new Permissions(); permissions.add(new RuntimePermission("accessClassInPackage.jdk.internal.misc")); // these are used for configuring the test itself... allPermissions = new Permissions(); allPermissions.add(new java.security.AllPermission()); }
/** * Creates an access control context limited to only the specified permissions. * @param permissions the permissions for the newly created access control context. * @return a new access control context limited to only the specified permissions. */ public static AccessControlContext createAccessControlContext(final Permission... permissions) { final Permissions perms = new Permissions(); for(final Permission permission: permissions) { perms.add(permission); } return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) }); }
/** Test that we can parse the set of permissions correctly for a complex policy */ public void testParseTwoPermissions() throws Exception { assumeTrue("test cannot run with security manager enabled", System.getSecurityManager() == null); Path scratch = createTempDir(); Path testFile = this.getDataPath("security/complex-plugin-security.policy"); Permissions expected = new Permissions(); expected.add(new RuntimePermission("getClassLoader")); expected.add(new RuntimePermission("closeClassLoader")); PermissionCollection actual = PluginSecurity.parsePermissions(Terminal.DEFAULT, testFile, scratch); assertEquals(expected, actual); }
private Class<?> defineFinderClass(String name) throws ClassNotFoundException { final Object obj = getClassLoadingLock(name); synchronized(obj) { if (finderClass != null) return finderClass; URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); File file = new File(url.getPath(), name+".class"); if (file.canRead()) { try { byte[] b = Files.readAllBytes(file.toPath()); Permissions perms = new Permissions(); perms.add(new AllPermission()); finderClass = defineClass( name, b, 0, b.length, new ProtectionDomain( this.getClass().getProtectionDomain().getCodeSource(), perms)); System.out.println("Loaded " + name); return finderClass; } catch (Throwable ex) { ex.printStackTrace(); throw new ClassNotFoundException(name, ex); } } else { throw new ClassNotFoundException(name, new IOException(file.toPath() + ": can't read")); } } }
/** * Add dynamic {@link SocketPermission} based on transport settings. This method will first check if there is a port range specified in * the transport profile specified by {@code profileSettings} and will fall back to {@code settings}. * * @param policy the {@link Permissions} instance to apply the dynamic {@link SocketPermission}s to * @param settings the {@link Settings} instance to read the transport settings from */ private static void addSocketPermissionForTransportProfiles( final Permissions policy, final Settings settings) { // transport is way over-engineered final Map<String, Settings> profiles = new HashMap<>(TransportSettings.TRANSPORT_PROFILES_SETTING.get(settings).getAsGroups()); profiles.putIfAbsent(TransportSettings.DEFAULT_PROFILE, Settings.EMPTY); // loop through all profiles and add permissions for each one, if it's valid; otherwise Netty transports are lenient and ignores it for (final Map.Entry<String, Settings> entry : profiles.entrySet()) { final Settings profileSettings = entry.getValue(); final String name = entry.getKey(); // a profile is only valid if it's the default profile, or if it has an actual name and specifies a port // TODO: can this leniency be removed? final boolean valid = TransportSettings.DEFAULT_PROFILE.equals(name) || (name != null && name.length() > 0 && profileSettings.get("port") != null); if (valid) { final String transportRange = profileSettings.get("port"); if (transportRange != null) { addSocketPermissionForPortRange(policy, transportRange); } else { addSocketPermissionForTransport(policy, settings); } } } }
private static void addSocketPermissionForTribeNodes(final Permissions policy, final Settings settings) { for (final Settings tribeNodeSettings : settings.getGroups("tribe", true).values()) { // tribe nodes have HTTP disabled by default, so we check if HTTP is enabled before granting if (NetworkModule.HTTP_ENABLED.exists(tribeNodeSettings) && NetworkModule.HTTP_ENABLED.get(tribeNodeSettings)) { addSocketPermissionForHttp(policy, tribeNodeSettings); } addSocketPermissionForTransport(policy, tribeNodeSettings); } }
/** * Add access to path (and all files underneath it) * @param policy current policy to add permissions to * @param configurationName the configuration name associated with the path (for error messages only) * @param path the path itself * @param permissions set of file permissions to grant to the path */ static void addPath(Permissions policy, String configurationName, Path path, String permissions) { // paths may not exist yet, this also checks accessibility try { ensureDirectoryExists(path); } catch (IOException e) { throw new IllegalStateException("Unable to access '" + configurationName + "' (" + path + ")", e); } // add each path twice: once for itself, again for files underneath it policy.add(new FilePermission(path.toString(), permissions)); policy.add(new FilePermission(path.toString() + path.getFileSystem().getSeparator() + "-", permissions)); }
/** * Add access to a directory iff it exists already * @param policy current policy to add permissions to * @param configurationName the configuration name associated with the path (for error messages only) * @param path the path itself * @param permissions set of file permissions to grant to the path */ static void addPathIfExists(Permissions policy, String configurationName, Path path, String permissions) { if (Files.isDirectory(path)) { // add each path twice: once for itself, again for files underneath it policy.add(new FilePermission(path.toString(), permissions)); policy.add(new FilePermission(path.toString() + path.getFileSystem().getSeparator() + "-", permissions)); try { path.getFileSystem().provider().checkAccess(path.toRealPath(), AccessMode.READ); } catch (IOException e) { throw new IllegalStateException("Unable to access '" + configurationName + "' (" + path + ")", e); } } }
@Override public PermissionCollection getPermissions(CodeSource codesource) { // code should not rely on this method, or at least use it correctly: // https://bugs.openjdk.java.net/browse/JDK-8014008 // return them a new empty permissions object so jvisualvm etc work for (StackTraceElement element : Thread.currentThread().getStackTrace()) { if ("sun.rmi.server.LoaderHandler".equals(element.getClassName()) && "loadClass".equals(element.getMethodName())) { return new Permissions(); } } // return UNSUPPORTED_EMPTY_COLLECTION since it is safe. return super.getPermissions(codesource); }
@SuppressForbidden(reason = "adds access to jar resources") static void addReadPermissions(Permissions perms, URL resources[]) { try { for (URL url : resources) { Path path = PathUtils.get(url.toURI()); // resource itself perms.add(new FilePermission(path.toString(), "read,readlink")); // classes underneath perms.add(new FilePermission(path.toString() + System.getProperty("file.separator") + "-", "read,readlink")); } } catch (URISyntaxException bogus) { throw new RuntimeException(bogus); } }
public SimplePolicy(ThreadLocal<AtomicBoolean> allowControl, ThreadLocal<AtomicBoolean> allowAll) { this.allowControl = allowControl; this.allowAll = allowAll; permissions = new Permissions(); // these are used for configuring the test itself... controlPermissions = new Permissions(); controlPermissions.add(LOGGERFINDER_PERMISSION); allPermissions = new Permissions(); allPermissions.add(new java.security.AllPermission()); }
@Override protected Permissions execLoadPermissions(String userId) { Permissions permissions = new Permissions(); permissions.add(new RemoteServiceAccessPermission("*.shared.*", "*")); permissions.add(new AllPermission()); return permissions; }
@Override public PermissionCollection getPermissions(final Subject subject, final CodeSource codesource) { // 1) if code instantiates PolicyFile directly, then it will need // all the permissions required for the PolicyFile initialization // 2) if code calls Policy.getPolicy, then it simply needs // AuthPermission(getPolicy), and the javax.security.auth.Policy // implementation instantiates PolicyFile in a doPrivileged block // 3) if after instantiating a Policy (either via #1 or #2), // code calls getPermissions, PolicyFile wraps the call // in a doPrivileged block. return AccessController.doPrivileged (new PrivilegedAction<PermissionCollection>() { @Override public PermissionCollection run() { SubjectCodeSource scs = new SubjectCodeSource( subject, null, codesource == null ? null : codesource.getLocation(), codesource == null ? null : codesource.getCertificates()); if (initialized) { return getPermissions(new Permissions(), scs); } else { return new PolicyPermissions(AuthPolicyFile.this, scs); } } }); }
/** returns dynamic Permissions to configured paths and bind ports */ static Permissions createPermissions(Environment environment) throws IOException { Permissions policy = new Permissions(); addClasspathPermissions(policy); addFilePermissions(policy, environment); addBindPermissions(policy, environment.settings()); return policy; }
public SimplePolicy(ThreadLocal<AtomicBoolean> allowControl, ThreadLocal<AtomicBoolean> allowAccess, ThreadLocal<AtomicBoolean> allowAll) { this.allowControl = allowControl; this.allowAccess = allowAccess; this.allowAll = allowAll; permissions = new Permissions(); allPermissions = new PermissionsBuilder() .add(new java.security.AllPermission()) .toPermissions(); }
public SimplePolicy(TestCase test, AtomicBoolean allowAll) { this.allowAll = allowAll; permissions = new Permissions(); permissions.add(new LoggingPermission("control", null)); permissions.add(new FilePermission(PREFIX+".lck", "read,write,delete")); permissions.add(new FilePermission(PREFIX, "read,write")); // these are used for configuring the test itself... allPermissions = new Permissions(); allPermissions.add(new java.security.AllPermission()); }
public SimplePolicy(TestCase test) { basic = new Permissions(); control = new Permissions(); control.add(new LoggingPermission("control", null)); // these are used for configuring the test itself... all = new Permissions(); all.add(new java.security.AllPermission()); }
@Override protected PermissionCollection getPermissions(final CodeSource codesource) { final Permissions permCollection = new Permissions(); for (final Permission perm : SCRIPT_PERMISSIONS) { permCollection.add(perm); } return permCollection; }
static AccessControlContext createPermAccCtxt(final String... permNames) { final Permissions perms = new Permissions(); for (final String permName : permNames) { perms.add(new RuntimePermission(permName)); } return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) }); }
public static void main(String[] args) throws Exception { /* * If we delay setting the security manager until after the service * configuration file has been installed, then this test still * functions properly, but the -Djava.security.debug output is * lacking, so to ease debugging, we'll set it early-- at the cost * of having to specify the policy even when running standalone. */ TestLibrary.suggestSecurityManager(null); ServiceConfiguration.installServiceConfigurationFile(); /* * Execute use of RMIClassLoader within an AccessControlContext * that has a protection domain with no permissions, to make sure * that RMIClassLoader can still properly initialize itself. */ CodeSource codesource = new CodeSource(null, (Certificate[]) null); Permissions perms = null; ProtectionDomain pd = new ProtectionDomain(codesource, perms); AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { pd }); java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction() { public Object run() throws Exception { TestProvider.exerciseTestProvider( TestProvider2.loadClassReturn, TestProvider2.loadProxyClassReturn, TestProvider2.getClassLoaderReturn, TestProvider2.getClassAnnotationReturn, TestProvider2.invocations); return null; } }, acc); }