Java Examples for java.security.Permission
The following java examples will help you to understand the usage of java.security.Permission. These source code samples are taken from different open source projects.
Example 1
Project: riena-master File: FilePermissionStoreTest.java View source code |
public void testReadPermission() throws SAXException, IOException, ParserConfigurationException { final InputStream inputStream = this.getClass().getResourceAsStream("policy-def-test.xml"); final FilePermissionStore permStore = new FilePermissionStore(inputStream); final Permissions perms = permStore.loadPermissions(new SimplePrincipal("christian")); assertTrue(perms != null); final Enumeration<Permission> enumPerms = perms.elements(); Permission p; int count = 0; while (enumPerms.hasMoreElements()) { p = enumPerms.nextElement(); count++; if (p instanceof FilePermission) { final FilePermission fp = (FilePermission) p; assertEquals("*.tmp", fp.getName()); assertTrue(fp.getActions().equals("read")); } else { if (p instanceof TestcasePermission) { final TestcasePermission tcp = (TestcasePermission) p; assertEquals("testPerm", tcp.getName()); } else { assertTrue("unknown permission " + p, false); } } } assertTrue(count == 2); }
Example 2
Project: android_libcore-master File: JavaSecurityPolicyTest.java View source code |
@TestTargetNew(level = TestLevel.PARTIAL, notes = "Verifies that java.security.Policy.getPolicy() method calls checkPermission on security manager.", method = "getPolicy", args = {})
public void test_getPolicy() {
class TestSecurityManager extends SecurityManager {
boolean called = false;
void reset() {
called = false;
}
@Override
public void checkPermission(Permission permission) {
if (permission instanceof SecurityPermission && "getPolicy".equals(permission.getName())) {
called = true;
}
}
}
TestSecurityManager s = new TestSecurityManager();
System.setSecurityManager(s);
s.reset();
Policy.getPolicy();
assertTrue("java.security.Policy.getPolicy() must call checkPermission on security permissions", s.called);
}
Example 3
Project: jwmscript-master File: URLSetPolicy.java View source code |
/* (non-Javadoc)
* @see java.security.Policy#getPermissions(java.security.CodeSource)
*/
public PermissionCollection getPermissions(CodeSource codesource) {
PermissionCollection pc = m_outerPolicy != null ? m_outerPolicy.getPermissions(codesource) : new Permissions();
URL url = codesource.getLocation();
if (url != null) {
String s = url.toExternalForm();
if (m_urls.contains(s) || "file:".equals(s)) {
Enumeration e = m_permissions.elements();
while (e.hasMoreElements()) {
pc.add((Permission) e.nextElement());
}
}
}
return pc;
}
Example 4
Project: rt.equinox.framework-master File: AdminPermissionTests.java View source code |
public void testAdminPermission() {
AdminPermission p1 = new AdminPermission();
//$NON-NLS-1$ //$NON-NLS-2$
AdminPermission p2 = new AdminPermission("*", "*");
//$NON-NLS-1$ //$NON-NLS-2$
Permission op = new PropertyPermission("java.home", "read");
shouldImply(p1, p2);
shouldImply(p1, p1);
shouldNotImply(p1, op);
shouldEqual(p1, p2);
shouldNotEqual(p1, op);
PermissionCollection pc = p1.newPermissionCollection();
checkEnumeration(pc.elements(), true);
shouldNotImply(pc, p1);
shouldAdd(pc, p1);
shouldAdd(pc, p2);
shouldNotAdd(pc, op);
pc.setReadOnly();
shouldNotAdd(pc, new AdminPermission());
shouldImply(pc, p1);
shouldImply(pc, p2);
shouldNotImply(pc, op);
checkEnumeration(pc.elements(), false);
testSerialization(p1);
testSerialization(p2);
}
Example 5
Project: svnkit-master File: SvnCliTest.java View source code |
protected static void disableSystemExitCall() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkExit(int status) {
super.checkExit(status);
throw new SecurityException("System.exit calls not allowed!");
}
@Override
public void checkPermission(Permission perm) {
}
};
System.setSecurityManager(securityManager);
}
Example 6
Project: eclipse-examples-master File: BundlePermissions.java View source code |
public boolean implies(Permission permission) {
// first check implied permissions
if ((impliedPermissions != null) && impliedPermissions.implies(permission))
return true;
// We must be allowed by the restricted permissions to have any hope of passing the check
if ((restrictedPermissions != null) && !restrictedPermissions.implies(permission))
return false;
return securityAdmin.checkPermission(permission, this);
}
Example 7
Project: jnode-master File: TestSecurityManager.java View source code |
public static void main(String args[]) throws Exception {
Class sc = SecurityManager.class;
Class sc2 = Security.class;
Class sc3 = java.security.Permission.class;
Class sc4 = java.lang.StringBuffer.class;
Class sc5 = java.io.PrintStream.class;
System.setSecurityManager(new MySM());
URLClassLoader cl = (URLClassLoader) TestSecurityManager.class.getClassLoader();
URLClassLoader cl2 = new URLClassLoader(cl.getURLs());
Class c = Class.forName("org.jnode.test.security.TestSecurityManager$mytest", true, cl2);
c.newInstance();
}
Example 8
Project: jruby-openssl-master File: SecurityManager.java View source code |
public boolean matches(java.security.Permission perm) {
Ruby runtime = lambda.getRuntime();
return lambda.callMethod(runtime.getCurrentContext(), "call", new IRubyObject[] { RubyString.newString(runtime, perm.getClass().getSimpleName()), RubyString.newString(runtime, perm.getName()), RubyString.newString(runtime, perm.getActions()) }).isTrue();
}
Example 9
Project: jspwiki-master File: WikiPermission.java View source code |
/** * WikiPermission can only imply other WikiPermissions; no other permission * types are implied. One WikiPermission implies another if all of the other * WikiPermission's actions are equal to, or a subset of, those for this * permission. * @param permission the permission which may (or may not) be implied by * this instance * @return <code>true</code> if the permission is implied, * <code>false</code> otherwise * @see java.security.Permission#implies(java.security.Permission) */ public boolean implies(Permission permission) { // Permission must be a WikiPermission if (!(permission instanceof WikiPermission)) { return false; } WikiPermission p = (WikiPermission) permission; // See if the wiki is implied boolean impliedWiki = PagePermission.isSubset(m_wiki, p.m_wiki); // Build up an "implied mask" for actions int impliedMask = impliedMask(m_mask); // If actions aren't a proper subset, return false return impliedWiki && (impliedMask & p.m_mask) == p.m_mask; }
Example 10
Project: Desktop-master File: TestUtils.java View source code |
private static void disableSystemExit() {
final SecurityManager securityManager = new SecurityManager() {
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitException();
}
}
};
System.setSecurityManager(securityManager);
}
Example 11
Project: Docear-master File: TestUtils.java View source code |
private static void disableSystemExit() {
final SecurityManager securityManager = new SecurityManager() {
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitException();
}
}
};
System.setSecurityManager(securityManager);
}
Example 12
Project: FML-master File: FMLSecurityManager.java View source code |
@Override
public void checkPermission(Permission perm) {
String permName = perm.getName() != null ? perm.getName() : "missing";
if (permName.startsWith("exitVM")) {
Class<?>[] classContexts = getClassContext();
String callingClass = classContexts.length > 3 ? classContexts[4].getName() : "none";
String callingParent = classContexts.length > 4 ? classContexts[5].getName() : "none";
// FML is allowed to call system exit and the Minecraft applet (from the quit button)
if (!(callingClass.startsWith("net.minecraftforge.fml.") || ("net.minecraft.client.Minecraft".equals(callingClass) && "net.minecraft.client.Minecraft".equals(callingParent)) || ("net.minecraft.server.dedicated.DedicatedServer".equals(callingClass) && "net.minecraft.server.MinecraftServer".equals(callingParent)))) {
throw new ExitTrappedException();
}
} else if ("setSecurityManager".equals(permName)) {
throw new SecurityException("Cannot replace the FML security manager");
}
return;
}
Example 13
Project: infinispan-master File: SurefireTestingPolicy.java View source code |
@Override
public boolean implies(ProtectionDomain domain, Permission permission) {
String location = domain.getCodeSource().getLocation().getPath().replaceAll("\\\\", "/");
// Allow any permissions from dependencies and the actual modules' classes
if (location.endsWith(".jar") || location.endsWith(MODULE_CLASSES)) {
if (logPolicyChecks) {
StringBuilder sb = new StringBuilder();
sb.append(location.substring(location.lastIndexOf(File.separator) + 1));
sb.append("> permission ");
sb.append(permission.getClass().getName());
sb.append(" \"");
sb.append(permission.getName());
sb.append("\"");
if (permission.getActions().length() > 0) {
sb.append(" \"");
sb.append(permission.getActions());
sb.append("\"");
}
sb.append(";");
String grant = sb.toString();
if (!grants.contains(grant)) {
grants.add(grant);
System.out.println(grant);
}
}
return true;
}
// For simplicity deny just our own SecurityPermissions.
if (location.endsWith(MODULE_TEST_CLASSES) && !(permission instanceof CachePermission)) {
return true;
}
// Separate from the above condition to allow setting breakpoints
return false;
}
Example 14
Project: jabref-2.9.2-master File: TestUtils.java View source code |
private static void disableSystemExit() {
final SecurityManager securityManager = new SecurityManager() {
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitException();
}
}
};
System.setSecurityManager(securityManager);
}
Example 15
Project: jolokia-master File: AgentLauncherTest.java View source code |
private static void forbidSystemExitCall() {
final SecurityManager securityManager = new SecurityManager() {
public void checkPermission(Permission permission) {
if ("exitVM".equals(permission.getName())) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
Example 16
Project: mclauncher-api-master File: CustomClassLoader.java View source code |
protected PermissionCollection getPermissions(CodeSource codesource) { PermissionCollection pc = new PermissionCollection() { public boolean implies(Permission permission) { return true; } public Enumeration<Permission> elements() { return null; } public void add(Permission permission) { } }; return pc; }
Example 17
Project: MinecraftForkage-master File: FMLSecurityManager.java View source code |
@Override
public void checkPermission(Permission perm) {
String permName = perm.getName() != null ? perm.getName() : "missing";
if (permName.startsWith("exitVM")) {
Class<?>[] classContexts = getClassContext();
String callingClass = classContexts.length > 3 ? classContexts[4].getName() : "none";
String callingParent = classContexts.length > 4 ? classContexts[5].getName() : "none";
// FML is allowed to call system exit and the Minecraft applet (from the quit button)
if (!(callingClass.startsWith("cpw.mods.fml.") || ("net.minecraft.client.Minecraft".equals(callingClass) && "net.minecraft.client.Minecraft".equals(callingParent)) || ("net.minecraft.server.dedicated.DedicatedServer".equals(callingClass) && "net.minecraft.server.MinecraftServer".equals(callingParent)))) {
throw new ExitTrappedException();
}
} else if ("setSecurityManager".equals(permName)) {
throw new SecurityException("Cannot replace the FML security manager");
}
return;
}
Example 18
Project: Origamist-master File: PermissionConverter.java View source code |
/** * Parse Java Permission from permission string representation * * @param s * @return locale */ public static Permission parse(String s) { return new Permission(s) { private static final long serialVersionUID = -1061029931943379601L; @Override public boolean implies(Permission permission) { return false; } @Override public int hashCode() { return getName().hashCode(); } @Override public String getActions() { return getName(); } @Override public boolean equals(Object obj) { if (obj instanceof Permission) { return ((Permission) obj).getName().equals(getName()); } return false; } }; }
Example 19
Project: WildAnimalsPlus-1.7.10-master File: FMLSecurityManager.java View source code |
@Override
public void checkPermission(Permission perm) {
String permName = perm.getName() != null ? perm.getName() : "missing";
if (permName.startsWith("exitVM")) {
Class<?>[] classContexts = getClassContext();
String callingClass = classContexts.length > 3 ? classContexts[4].getName() : "none";
String callingParent = classContexts.length > 4 ? classContexts[5].getName() : "none";
// FML is allowed to call system exit and the Minecraft applet (from the quit button)
if (!(callingClass.startsWith("cpw.mods.fml.") || ("net.minecraft.client.Minecraft".equals(callingClass) && "net.minecraft.client.Minecraft".equals(callingParent)) || ("net.minecraft.server.dedicated.DedicatedServer".equals(callingClass) && "net.minecraft.server.MinecraftServer".equals(callingParent)))) {
throw new ExitTrappedException();
}
} else if ("setSecurityManager".equals(permName)) {
throw new SecurityException("Cannot replace the FML security manager");
}
return;
}
Example 20
Project: pro-grade-master File: GeneratePolicyFromDeniedPermissions.java View source code |
/** * Writes the given permission under the grant entry with codesource from given {@link ProtectionDomain} into the generated * policy file. * * @see net.sourceforge.prograde.generator.DeniedPermissionListener#permissionDenied(java.security.ProtectionDomain, * java.security.Permission) */ @Override public void permissionDenied(final ProtectionDomain pd, final Permission perm) { if (filePermissionToSkip.equals(perm)) { return; } final CodeSource codeSource = pd.getCodeSource(); Set<Permission> permSet = missingPermissions.get(codeSource); if (permSet == null) { synchronized (missingPermissions) { permSet = missingPermissions.get(codeSource); if (permSet == null) { permSet = Collections.synchronizedSet(new TreeSet<Permission>(new PermissionComparator())); missingPermissions.put(codeSource, permSet); } } } if (permSet.add(perm)) { AccessController.doPrivileged(WRITE_TO_FILE_ACTION); } }
Example 21
Project: apache_ant-master File: XMLResultAggregatorTest.java View source code |
@Test
public void testFrames() throws Exception {
// For now, skip this test on JDK 6 (and below); see below for why:
try {
Class.forName("java.nio.file.Files");
} catch (ClassNotFoundException x) {
Assume.assumeNoException("Skip test on JDK 6 and below", x);
}
final File d = new File(System.getProperty("java.io.tmpdir"), "XMLResultAggregatorTest");
if (d.exists()) {
// is there no utility method for this?
new Delete() {
{
removeDir(d);
}
};
}
assertTrue(d.getAbsolutePath(), d.mkdir());
File xml = new File(d, "x.xml");
PrintWriter pw = new PrintWriter(new FileOutputStream(xml));
try {
pw.println("<testsuite errors='0' failures='0' name='my.UnitTest' tests='1'>");
pw.println(" <testcase classname='my.UnitTest' name='testSomething'/>");
pw.println("</testsuite>");
pw.flush();
} finally {
pw.close();
}
XMLResultAggregator task = new XMLResultAggregator();
task.setTodir(d);
Project project = new Project();
DefaultLogger logger = new DefaultLogger();
logger.setOutputPrintStream(System.out);
logger.setErrorPrintStream(System.err);
logger.setMessageOutputLevel(Project.MSG_INFO);
project.addBuildListener(logger);
project.init();
task.setProject(project);
AggregateTransformer report = task.createReport();
report.setTodir(d);
FileSet fs = new FileSet();
fs.setFile(xml);
task.addFileSet(fs);
/* getResourceAsStream override unnecessary on JDK 7. Ought to work around JAXP #6723276 in JDK 6, but causes a TypeCheckError in FunctionCall for reasons TBD:
Thread.currentThread().setContextClassLoader(new ClassLoader(ClassLoader.getSystemClassLoader().getParent()) {
public InputStream getResourceAsStream(String name) {
if (name.startsWith("META-INF/services/")) {
return new ByteArrayInputStream(new byte[0]);
}
return super.getResourceAsStream(name);
}
});
*/
// Use the JRE's Xerces, not lib/optional/xerces.jar:
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader().getParent());
// Tickle #51668:
System.setSecurityManager(new SecurityManager() {
public void checkPermission(Permission perm) {
}
});
task.execute();
assertTrue(new File(d, "index.html").isFile());
}
Example 22
Project: liferay-portal-master File: SecurityChecker.java View source code |
@Override
public boolean implies(Permission permission) {
String name = permission.getName();
if (name.equals(SECURITY_PERMISSION_GET_POLICY)) {
if (!hasGetPolicy(permission)) {
logSecurityException(_log, "Attempted to get the policy");
return false;
}
} else if (name.equals(SECURITY_PERMISSION_SET_POLICY)) {
if (!hasSetPolicy(permission)) {
logSecurityException(_log, "Attempted to set the policy");
return false;
}
} else {
if (_log.isDebugEnabled()) {
Thread.dumpStack();
}
logSecurityException(_log, "Attempted to " + permission.getName() + " on " + permission.getActions());
return false;
}
return true;
}
Example 23
Project: aries-master File: HelloIsolationImpl.java View source code |
// test java2 security
public void checkPermission(final Permission permission) throws SecurityException {
System.out.println("HelloIsolationImpl: enter checkpermission");
try {
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws SecurityException {
SecurityManager security = System.getSecurityManager();
if (security != null) {
System.out.println("HelloIsolationImpl: system manager is not null");
security.checkPermission(permission);
return null;
}
System.out.println("HelloIsolationImpl: system manager is still null");
return null;
}
});
} catch (PrivilegedActionException e) {
throw (SecurityException) e.getException();
}
}
Example 24
Project: beast-mcmc-master File: RBeastMain.java View source code |
public static void forbidSystemExitCall() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
Example 25
Project: bnd-master File: TraceSecurityManager.java View source code |
public int compare(Permission a, Permission b) { if (a.getClass() == b.getClass()) { if (a.getName().equals(b.getName())) { return a.getActions().compareTo(b.getActions()); } else return a.getName().compareTo(b.getName()); } else return shorten(a.getClass().getName()).compareTo(shorten(b.getClass().getName())); }
Example 26
Project: CoinJoin-master File: DRMWorkaround.java View source code |
public static void maybeDisableExportControls() {
if (done)
return;
done = true;
if (Utils.isAndroidRuntime())
return;
try {
Field gate = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
gate.setAccessible(true);
gate.setBoolean(null, false);
final Field allPerm = Class.forName("javax.crypto.CryptoAllPermission").getDeclaredField("INSTANCE");
allPerm.setAccessible(true);
Object accessAllAreasCard = allPerm.get(null);
final Constructor<?> constructor = Class.forName("javax.crypto.CryptoPermissions").getDeclaredConstructor();
constructor.setAccessible(true);
Object coll = constructor.newInstance();
Method addPerm = Class.forName("javax.crypto.CryptoPermissions").getDeclaredMethod("add", java.security.Permission.class);
addPerm.setAccessible(true);
addPerm.invoke(coll, accessAllAreasCard);
Field defaultPolicy = Class.forName("javax.crypto.JceSecurity").getDeclaredField("defaultPolicy");
defaultPolicy.setAccessible(true);
defaultPolicy.set(null, coll);
} catch (Exception e) {
log.warn("Failed to deactivate AES-256 barrier logic, Tor mode/BIP38 decryption may crash if this JVM requires it: " + e.getMessage());
}
}
Example 27
Project: cruisecontrol-master File: ReggieUtilTest.java View source code |
@Override
public void checkPermission(Permission permission) {
if (expectedPermsToAllow.contains(permission.getName())) {
return;
}
if (!permission.getActions().contains("read")) {
final String msg = "testSetupRMISecurityManager() checked new permission : " + permission.getName();
System.out.println(msg);
// use of LOG here gets dicey with sec manager games...
//LOG.warn(msg);
}
}
Example 28
Project: cxf-master File: SecurityActions.java View source code |
static boolean fileExists(final File file, Permission permission) {
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
return file.exists();
} else {
sm.checkPermission(permission);
return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
return file.exists();
}
});
}
}
Example 29
Project: digidoc4j-master File: RestrictedFileWritingRule.java View source code |
@Override
protected void before() throws Throwable {
super.before();
System.setSecurityManager(new SecurityManager() {
@Override
public void checkWrite(String file) {
if (!isAllowedToWrite(file)) {
throw new FileWritingRestrictedException();
}
}
@Override
public void checkPermission(Permission perm) {
return;
}
});
}
Example 30
Project: eclipselink.runtime-master File: TestSecurityManager.java View source code |
public void checkPermission(Permission perm) {
// don't throw an error, so reset can reset security manager.
if (perm instanceof ReflectPermission && "suppressAccessChecks".equals(perm.getName())) {
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
if (ste.getClassName().startsWith("org.eclipse.persistence.testing.tests.security") && "test".equals(ste.getMethodName())) {
throw new SecurityException("Dummy SecurityException test");
}
}
}
}
Example 31
Project: flex-falcon-master File: JSClosureCompilerUtil.java View source code |
private static void forbidSystemExitCall() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
}
@Override
public void checkExit(int status) {
throw new ExitTrappedException();
}
};
System.setSecurityManager(securityManager);
}
Example 32
Project: Grid-Appliance-Hadoop-master File: ConnectionPermission.java View source code |
@Override
public boolean implies(Permission permission) {
if (permission instanceof ConnectionPermission) {
ConnectionPermission that = (ConnectionPermission) permission;
if (that.protocol.equals(VersionedProtocol.class)) {
return true;
}
return this.protocol.equals(that.protocol);
}
return false;
}
Example 33
Project: hadoop-20-master File: ConnectionPermission.java View source code |
@Override
public boolean implies(Permission permission) {
if (permission instanceof ConnectionPermission) {
ConnectionPermission that = (ConnectionPermission) permission;
if (that.protocol.equals(VersionedProtocol.class)) {
return true;
}
return this.protocol.equals(that.protocol);
}
return false;
}
Example 34
Project: hadoop-20-warehouse-fix-master File: ConnectionPermission.java View source code |
@Override
public boolean implies(Permission permission) {
if (permission instanceof ConnectionPermission) {
ConnectionPermission that = (ConnectionPermission) permission;
if (that.protocol.equals(VersionedProtocol.class)) {
return true;
}
return this.protocol.equals(that.protocol);
}
return false;
}
Example 35
Project: hadoop-20-warehouse-master File: ConnectionPermission.java View source code |
@Override
public boolean implies(Permission permission) {
if (permission instanceof ConnectionPermission) {
ConnectionPermission that = (ConnectionPermission) permission;
if (that.protocol.equals(VersionedProtocol.class)) {
return true;
}
return this.protocol.equals(that.protocol);
}
return false;
}
Example 36
Project: hadoop-gpu-master File: ConnectionPermission.java View source code |
@Override
public boolean implies(Permission permission) {
if (permission instanceof ConnectionPermission) {
ConnectionPermission that = (ConnectionPermission) permission;
if (that.protocol.equals(VersionedProtocol.class)) {
return true;
}
return this.protocol.equals(that.protocol);
}
return false;
}
Example 37
Project: HadoopUSC-master File: ConnectionPermission.java View source code |
@Override
public boolean implies(Permission permission) {
if (permission instanceof ConnectionPermission) {
ConnectionPermission that = (ConnectionPermission) permission;
if (that.protocol.equals(VersionedProtocol.class)) {
return true;
}
return this.protocol.equals(that.protocol);
}
return false;
}
Example 38
Project: hadoop_ekg-master File: ConnectionPermission.java View source code |
@Override
public boolean implies(Permission permission) {
if (permission instanceof ConnectionPermission) {
ConnectionPermission that = (ConnectionPermission) permission;
if (that.protocol.equals(VersionedProtocol.class)) {
return true;
}
return this.protocol.equals(that.protocol);
}
return false;
}
Example 39
Project: impala-master File: SecurityUtil.java View source code |
public void forbidSystemExitCall() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().startsWith("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
Example 40
Project: Izou-master File: SocketPermissionModule.java View source code |
/** * Checks if the given addOn is allowed to access the requested service and registers them if not yet registered. * * @param permission the Permission to check * @param addon the identifiable to check * @throws IzouPermissionException thrown if the addOn is not allowed to access its requested service */ @Override public void checkPermission(Permission permission, AddOnModel addon) throws IzouPermissionException { for (String socket : allowedSocketConnections) { if (permission.getName().contains(socket)) { return; } } if (isRegistered(addon)) return; Function<PluginDescriptor, Boolean> checkPermission = descriptor -> { if (descriptor.getAddOnProperties() == null) throw new IzouPermissionException("addon_config.properties not found for addon:" + addon); try { return descriptor.getAddOnProperties().getProperty("socket_connection") != null && descriptor.getAddOnProperties().getProperty("socket_connection").trim().equals("true") && descriptor.getAddOnProperties().getProperty("socket_usage_descripton") != null && !descriptor.getAddOnProperties().getProperty("socket_usage_descripton").trim().equals("null") && !descriptor.getAddOnProperties().getProperty("socket_usage_descripton").trim().isEmpty(); } catch (NullPointerException e) { return false; } }; String exceptionMessage = "Socket Permission Denied: " + addon + "is not registered to " + "use socket connections, please add the required information to the addon_config.properties " + "file of your addOn."; registerOrThrow(addon, () -> new IzouSocketPermissionException(exceptionMessage), checkPermission); }
Example 41
Project: Jxtadoop-master File: ConnectionPermission.java View source code |
@Override
public boolean implies(Permission permission) {
if (permission instanceof ConnectionPermission) {
ConnectionPermission that = (ConnectionPermission) permission;
if (that.protocol.equals(VersionedProtocol.class)) {
return true;
}
return this.protocol.equals(that.protocol);
}
return false;
}
Example 42
Project: neembuu-uploader-master File: RemoveCryptographyRestrictions.java View source code |
public static void removeCryptographyRestrictions() {
if (!isRestrictedCryptography()) {
NULogger.getLogger().info("Cryptography restrictions removal not needed");
return;
}
try {
/*
* Do the following, but with reflection to bypass access checks:
*
* JceSecurity.isRestricted = false;
* JceSecurity.defaultPolicy.perms.clear();
* JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
*/
final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");
final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
isRestrictedField.setAccessible(true);
isRestrictedField.set(null, false);
final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
defaultPolicyField.setAccessible(true);
final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);
final Field perms = cryptoPermissions.getDeclaredField("perms");
perms.setAccessible(true);
((Map<?, ?>) perms.get(defaultPolicy)).clear();
final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
instance.setAccessible(true);
defaultPolicy.add((Permission) instance.get(null));
NULogger.getLogger().info("Successfully removed cryptography restrictions");
} catch (final Exception e) {
NULogger.getLogger().log(Level.WARNING, "Failed to remove cryptography restrictions", e);
}
}
Example 43
Project: NuBitsj-master File: DRMWorkaround.java View source code |
public static void maybeDisableExportControls() {
if (done)
return;
done = true;
if (Utils.isAndroidRuntime())
return;
try {
Field gate = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
gate.setAccessible(true);
gate.setBoolean(null, false);
final Field allPerm = Class.forName("javax.crypto.CryptoAllPermission").getDeclaredField("INSTANCE");
allPerm.setAccessible(true);
Object accessAllAreasCard = allPerm.get(null);
final Constructor<?> constructor = Class.forName("javax.crypto.CryptoPermissions").getDeclaredConstructor();
constructor.setAccessible(true);
Object coll = constructor.newInstance();
Method addPerm = Class.forName("javax.crypto.CryptoPermissions").getDeclaredMethod("add", java.security.Permission.class);
addPerm.setAccessible(true);
addPerm.invoke(coll, accessAllAreasCard);
Field defaultPolicy = Class.forName("javax.crypto.JceSecurity").getDeclaredField("defaultPolicy");
defaultPolicy.setAccessible(true);
defaultPolicy.set(null, coll);
} catch (Exception e) {
log.warn("Failed to deactivate AES-256 barrier logic, Tor mode/BIP38 decryption may crash if this JVM requires it: " + e.getMessage());
}
}
Example 44
Project: open-mika-master File: MutableSecurityManager.java View source code |
@Override
public void checkPermission(Permission permission, Object context) {
if (permission != null) {
if (denied != null && denied.implies(permission)) {
throw new SecurityException("Denied " + permission);
}
if (enabled.implies(permission)) {
return;
}
}
super.checkPermission(permission, context);
}
Example 45
Project: openjdk-master File: CustomPolicy.java View source code |
@Override
public boolean implies(ProtectionDomain pd, Permission perm) {
System.out.println("CustomPolicy.implies");
// for example, as below.
if (pd == policyPd) {
return true;
}
// Do something that triggers a permission check to make sure that
// we don't cause a StackOverflow error.
String home = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty("user.home"));
return true;
}
Example 46
Project: peercoinj-master File: DRMWorkaround.java View source code |
public static void maybeDisableExportControls() {
if (done)
return;
done = true;
if (Utils.isAndroidRuntime())
return;
try {
Field gate = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
gate.setAccessible(true);
gate.setBoolean(null, false);
final Field allPerm = Class.forName("javax.crypto.CryptoAllPermission").getDeclaredField("INSTANCE");
allPerm.setAccessible(true);
Object accessAllAreasCard = allPerm.get(null);
final Constructor<?> constructor = Class.forName("javax.crypto.CryptoPermissions").getDeclaredConstructor();
constructor.setAccessible(true);
Object coll = constructor.newInstance();
Method addPerm = Class.forName("javax.crypto.CryptoPermissions").getDeclaredMethod("add", java.security.Permission.class);
addPerm.setAccessible(true);
addPerm.invoke(coll, accessAllAreasCard);
Field defaultPolicy = Class.forName("javax.crypto.JceSecurity").getDeclaredField("defaultPolicy");
defaultPolicy.setAccessible(true);
defaultPolicy.set(null, coll);
} catch (Exception e) {
log.warn("Failed to deactivate AES-256 barrier logic, Tor mode/BIP38 decryption may crash if this JVM requires it: " + e.getMessage());
}
}
Example 47
Project: rapidminer-studio-master File: PluginSecurityManager.java View source code |
@Override
public final void checkPermission(Permission perm) {
if (perm instanceof RuntimePermission) {
// prevent ANY code from changing the SecurityManager after it has been installed
if ("setSecurityManager".equals(perm.getName())) {
throw new SecurityException("SecurityManager cannot be replaced!");
}
}
super.checkPermission(perm);
}
Example 48
Project: RDFS-master File: ConnectionPermission.java View source code |
@Override
public boolean implies(Permission permission) {
if (permission instanceof ConnectionPermission) {
ConnectionPermission that = (ConnectionPermission) permission;
if (that.protocol.equals(VersionedProtocol.class)) {
return true;
}
return this.protocol.equals(that.protocol);
}
return false;
}
Example 49
Project: wildfly-elytron-master File: ByNamePermissionCollection.java View source code |
public boolean implies(final Permission permission) { if (permission == null || getSourcePermission().getClass() != permission.getClass()) { return false; } final Permission all = this.all; if (all != null) { return all.implies(permission); } final Permission ourPermission = byName.get(permission.getName()); return ourPermission != null && ourPermission.implies(permission); }
Example 50
Project: wildfly-security-master File: ByNamePermissionCollection.java View source code |
public boolean implies(final Permission permission) { if (permission == null || getSourcePermission().getClass() != permission.getClass()) { return false; } final Permission all = this.all; if (all != null) { return all.implies(permission); } final Permission ourPermission = byName.get(permission.getName()); return ourPermission != null && ourPermission.implies(permission); }
Example 51
Project: zoj-master File: SandboxSecurityManager.java View source code |
private void internalCheckPermision(Permission perm) {
if (Thread.currentThread() == targetThread) {
if (perm instanceof SecurityPermission) {
if (perm.getName().startsWith("getProperty")) {
return;
}
} else if (perm instanceof PropertyPermission) {
if (perm.getActions().equals("read")) {
return;
}
} else if (perm instanceof FilePermission) {
String name = perm.getName();
if (name.length() > 1 && name.charAt(0) != '.' && name.charAt(0) != '/') {
return;
}
}
throw new SecurityException(perm.toString());
}
}
Example 52
Project: openjdk8-jdk-master File: EqualsImplies.java View source code |
public static void main(String[] args) throws Exception { Permission p1 = new A("foo"); Permission p2 = new B("foo"); if (p1.implies(p2) || p2.implies(p1) || p1.equals(p2)) { throw new Exception("Test failed"); } // make sure permissions imply and equal themselves if (!(p1.implies(p1) && p1.equals(p1))) { throw new Exception("Test failed"); } }
Example 53
Project: D-MARLA-master File: ServerAdministration.java View source code |
@Override public void actionPerformed(ActionEvent e) { try { ClientSocketFactory socketFactory = new ClientSocketFactory(InetAddress.getByName(statisticsAddressTextField.getText())); System.setSecurityManager(new RMISecurityManager() { public void checkPermission(java.security.Permission permission) { } public void checkPermission(java.security.Permission permission, java.lang.Object o) { } }); stub = (ICycleStatistics) UnicastRemoteObject.exportObject(new RMIServiceConnector(facade), 0, socketFactory, null); // Bind remote objects stub in registry registry = LocateRegistry.createRegistry(1099); registry.bind("ICycleStatistics", stub); hostStatisticsButton.setEnabled(false); hostStatisticsButton.setText("Hosting..."); statisticsAddressTextField.setEnabled(false); } catch (AccessException e1) { JOptionPane.showMessageDialog(frame, "Hosting of the statistics component could not be initiated, probably an RMI problem.", "Remote Access Problem", JOptionPane.ERROR_MESSAGE); } catch (RemoteException e1) { JOptionPane.showMessageDialog(frame, "Hosting of the statistics component could not be initiated, probably an RMI problem.", "Remote Access Problem", JOptionPane.ERROR_MESSAGE); } catch (AlreadyBoundException e1) { JOptionPane.showMessageDialog(frame, "The connection is already established. Are you running two instances of Overseer?", "Connection already established!", JOptionPane.ERROR_MESSAGE); } catch (UnknownHostException e1) { JOptionPane.showMessageDialog(frame, "The host address can't be resolved, please check it!", "Unknown Host!", JOptionPane.ERROR_MESSAGE); } }
Example 54
Project: JDK-master File: AclImpl.java View source code |
/** * Returns an enumeration for the set of allowed permissions for * the specified principal * (representing an entity such as an individual or a group). * This set of allowed permissions is calculated as follows: * <UL> * <LI>If there is no entry in this Access Control List for the specified * principal, an empty permission set is returned.</LI> * <LI>Otherwise, the principal's group permission sets are determined. * (A principal can belong to one or more groups, where a group is a group * of principals, represented by the Group interface.)</LI> * </UL> * @param user the principal whose permission set is to be returned. * @return the permission set specifying the permissions the principal * is allowed. * @see java.security.Principal */ public Enumeration<Permission> getPermissions(Principal user) { Vector<Permission> empty = new Vector<Permission>(); for (Enumeration<AclEntry> e = entryList.elements(); e.hasMoreElements(); ) { AclEntry ent = e.nextElement(); if (ent.getPrincipal().equals(user)) return ent.permissions(); } return empty.elements(); }
Example 55
Project: kbot-master File: OurPermissionCollection.java View source code |
/** * Returns an enumeration of all the Permission objects in the collection. * * @return an enumeration of all the Permissions. */ @Override public Enumeration<Permission> elements() { return new Enumeration<Permission>() { public boolean hasMore = true; public boolean hasMoreElements() { return hasMore; } public Permission nextElement() { hasMore = false; return scriptPermission; } }; }
Example 56
Project: pentaho-reporting-master File: FirewallingSecurityManager.java View source code |
/**
* Throws a <code>SecurityException</code> if the requested access, specified by the given permission, is not
* permitted based on the security policy currently in effect.
* <p/>
* This method calls <code>AccessController.checkPermission</code> with the given permission.
*
* @param perm the requested permission.
* @throws SecurityException if access is not permitted based on the current security policy.
* @throws NullPointerException if the permission argument is <code>null</code>.
* @since 1.2
*/
public void checkPermission(final Permission perm) {
if (WorkspaceSettings.getInstance().isOfflineMode() && perm instanceof SocketPermission) {
if (permissionCollection.implies(perm) == false) {
throw new SecurityException(UtilMessages.getInstance().getString("FirewallingProxySelector.FilterMessage"));
}
}
if (parent != null) {
parent.checkPermission(perm);
}
}
Example 57
Project: android-libcore64-master File: AccessControllerTest.java View source code |
public void testDoPrivilegedWithCombiner() {
final Permission permission = new RuntimePermission("do stuff");
final DomainCombiner union = new DomainCombiner() {
public ProtectionDomain[] combine(ProtectionDomain[] a, ProtectionDomain[] b) {
throw new AssertionFailedError("Expected combiner to be unused");
}
};
ProtectionDomain protectionDomain = new ProtectionDomain(null, new Permissions());
AccessControlContext accessControlContext = new AccessControlContext(new AccessControlContext(new ProtectionDomain[] { protectionDomain }), union);
final AtomicInteger actionCount = new AtomicInteger();
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
// Calling doPrivileged again would have exercised the combiner
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
actionCount.incrementAndGet();
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
return null;
}
});
return null;
}
}, accessControlContext);
assertEquals(1, actionCount.get());
}
Example 58
Project: android_platform_libcore-master File: AccessControllerTest.java View source code |
public void testDoPrivilegedWithCombiner() {
final Permission permission = new RuntimePermission("do stuff");
final DomainCombiner union = new DomainCombiner() {
public ProtectionDomain[] combine(ProtectionDomain[] a, ProtectionDomain[] b) {
throw new AssertionFailedError("Expected combiner to be unused");
}
};
ProtectionDomain protectionDomain = new ProtectionDomain(null, new Permissions());
AccessControlContext accessControlContext = new AccessControlContext(new AccessControlContext(new ProtectionDomain[] { protectionDomain }), union);
final AtomicInteger actionCount = new AtomicInteger();
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
// Calling doPrivileged again would have exercised the combiner
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
actionCount.incrementAndGet();
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
return null;
}
});
return null;
}
}, accessControlContext);
assertEquals(1, actionCount.get());
}
Example 59
Project: ARTPart-master File: AccessControllerTest.java View source code |
public void testDoPrivilegedWithCombiner() {
final Permission permission = new RuntimePermission("do stuff");
final DomainCombiner union = new DomainCombiner() {
public ProtectionDomain[] combine(ProtectionDomain[] a, ProtectionDomain[] b) {
throw new AssertionFailedError("Expected combiner to be unused");
}
};
ProtectionDomain protectionDomain = new ProtectionDomain(null, new Permissions());
AccessControlContext accessControlContext = new AccessControlContext(new AccessControlContext(new ProtectionDomain[] { protectionDomain }), union);
final AtomicInteger actionCount = new AtomicInteger();
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
// Calling doPrivileged again would have exercised the combiner
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
actionCount.incrementAndGet();
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
return null;
}
});
return null;
}
}, accessControlContext);
assertEquals(1, actionCount.get());
}
Example 60
Project: axis2-java-master File: MorePermissionAccessControlContext.java View source code |
// Implementing Actor's takeAction method
public void takeAction() {
try {
if (_usingDoPrivilege) {
final AccessControlContext acc = AccessController.getContext();
// Print out maven's base,build, and test direcotories
String baseDir = AbstractTestCase.basedir;
System.out.println("basedir => " + baseDir);
// Convert the \ (back slash) to / (forward slash)
String baseDirM = baseDir.replace('\\', '/');
System.out.println("baseDirM => " + baseDirM);
String fs = "/";
String fileName = "private/private.txt";
String fileURL = baseDirM + fs + "test-resources" + fs + "java2sec" + fs + fileName;
Permission perm = new java.io.FilePermission(fileURL, "read");
acc.checkPermission(perm);
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
_actor.takeAction();
return null;
}
}, acc);
} else {
// Use no doPrivileged
_actor.takeAction();
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
Example 61
Project: bitcoinj-master File: DRMWorkaround.java View source code |
public static void maybeDisableExportControls() {
if (done)
return;
done = true;
if (Utils.isAndroidRuntime())
return;
try {
Field gate = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
gate.setAccessible(true);
gate.setBoolean(null, false);
final Field allPerm = Class.forName("javax.crypto.CryptoAllPermission").getDeclaredField("INSTANCE");
allPerm.setAccessible(true);
Object accessAllAreasCard = allPerm.get(null);
final Constructor<?> constructor = Class.forName("javax.crypto.CryptoPermissions").getDeclaredConstructor();
constructor.setAccessible(true);
Object coll = constructor.newInstance();
Method addPerm = Class.forName("javax.crypto.CryptoPermissions").getDeclaredMethod("add", java.security.Permission.class);
addPerm.setAccessible(true);
addPerm.invoke(coll, accessAllAreasCard);
Field defaultPolicy = Class.forName("javax.crypto.JceSecurity").getDeclaredField("defaultPolicy");
defaultPolicy.setAccessible(true);
defaultPolicy.set(null, coll);
} catch (Exception e) {
log.warn("Failed to deactivate AES-256 barrier logic, Tor mode/BIP38 decryption may crash if this JVM requires it: " + e.getMessage());
}
}
Example 62
Project: concourse-master File: CommandLineInterfaceRunnerTest.java View source code |
@Override public void beforeEachTest() { sm = System.getSecurityManager(); System.setSecurityManager(new SecurityManager() { @Override public void checkExit(int status) { super.checkExit(status); throw new SystemExitInvoked(); } @Override public void checkPermission(Permission perm) { // allow anything. } @Override public void checkPermission(Permission perm, Object context) { // allow anything. } }); }
Example 63
Project: datalifecycle-master File: DlcGraphProvider.java View source code |
/**
* Creates the data lifecycle graph. Must be called at the bundle activation
* if the graph doesn't exists yet.
*/
private LockableMGraph createDlcGraph() {
LockableMGraph dlcGraph = tcManager.createMGraph(DATA_LIFECYCLE_GRAPH_REFERENCE);
TcAccessController tca = tcManager.getTcAccessController();
tca.setRequiredReadPermissions(DATA_LIFECYCLE_GRAPH_REFERENCE, Collections.singleton((Permission) new TcPermission("urn:x-localinstance:/content.graph", "read")));
return dlcGraph;
}
Example 64
Project: evosuite-master File: PermissionStatistics.java View source code |
/** * <p> * permissionAllowed * </p> * * @param permission * a {@link java.security.Permission} object. */ public void permissionAllowed(Permission permission) { rememberRecentReadFilePermissions(permission); String name = permission.getClass().getName(); String type = getPermissionType(permission); if (!allowedCount.containsKey(name)) { allowedCount.put(name, new HashMap<String, Integer>()); } if (allowedCount.get(name).containsKey(type)) { allowedCount.get(name).put(type, allowedCount.get(name).get(type) + 1); } else { allowedCount.get(name).put(type, 1); } }
Example 65
Project: flower-platform-3-master File: ModifyTreePermissionsPermissionDescriptor.java View source code |
/**
*
*/
@Override
public Map<String, String> validate(Permission permission) {
if (!(permission instanceof ModifyTreePermissionsPermission)) {
throw new RuntimeException("Can handle only ModifyTreePermissionsPermission");
}
Map<String, String> validationResults = new HashMap<String, String>();
if (!(pathIsRelativeToWorkspace(permission.getName()))) {
validationResults.put(NAME_FIELD, WebPlugin.getInstance().getMessage("entity.permission.validation.invalidPath"));
}
// actions can be a comma separated list of security entities (example: #org1, @group2, $user3)
if (!permission.getActions().equals(PermissionEntity.ANY_ENTITY)) {
String[] entityNames = permission.getActions().split(",");
for (String assignedTo : entityNames) {
assignedTo = assignedTo.trim();
String message = SecurityUtils.validateSecurityEntity(assignedTo);
if (message != null) {
validationResults.put(ACTIONS_FIELD, message);
}
}
}
return validationResults;
}
Example 66
Project: geronimo-master File: GeronimoPolicy.java View source code |
public boolean implies(ProtectionDomain domain, Permission permission) {
if (!loaded) {
factory = GeronimoPolicyConfigurationFactory.getSingleton();
loaded = true;
}
if (factory != null) {
String contextID = PolicyContext.getContextID();
if (contextID != null) {
try {
GeronimoPolicyConfiguration configuration = factory.getGeronimoPolicyConfiguration(contextID);
if (configuration.inService()) {
if (configuration.implies(domain, permission))
return true;
} else {
return false;
}
} catch (PolicyContextException e) {
}
}
}
if (root != null)
return root.implies(domain, permission);
return false;
}
Example 67
Project: gestalt-master File: WarnOnlyProviderFactory.java View source code |
@Override
public PermissionProvider createPermissionProviderFor(Module module) {
return new PermissionProvider() {
private PermissionProvider wrapped = wrappedFactory.createPermissionProviderFor(module);
@Override
public boolean isPermitted(Class<?> type) {
if (!wrapped.isPermitted(type)) {
logger.error("Use of non-permitted class '{}' detected by module '{}': this should be fixed for production use", type.toString(), module);
}
return true;
}
@Override
public boolean isPermitted(Permission permission, Class<?> context) {
if (!wrapped.isPermitted(permission, context)) {
logger.error("Non-permitted permission '{}' required by module '{}', class '{}': this should be fixed for production use", permission, module, context);
}
return true;
}
};
}
Example 68
Project: gradle-master File: BootstrapSecurityManager.java View source code |
@Override
public void checkPermission(Permission permission) {
synchronized (this) {
if (initialised) {
return;
}
if (System.in == null) {
// Still starting up
return;
}
initialised = true;
}
System.clearProperty("java.security.manager");
System.setSecurityManager(null);
URLClassLoader systemClassLoader = target != null ? target : (URLClassLoader) getClass().getClassLoader();
String securityManagerType;
try {
Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addUrlMethod.setAccessible(true);
DataInputStream inputStream = new DataInputStream(new EncodedStream.EncodedInput(System.in));
int count = inputStream.readInt();
StringBuilder classpathStr = new StringBuilder();
for (int i = 0; i < count; i++) {
String entry = inputStream.readUTF();
File file = new File(entry);
addUrlMethod.invoke(systemClassLoader, file.toURI().toURL());
if (i > 0) {
classpathStr.append(File.pathSeparator);
}
classpathStr.append(file.toString());
}
System.setProperty("java.class.path", classpathStr.toString());
securityManagerType = inputStream.readUTF();
} catch (Exception e) {
throw new RuntimeException("Could not initialise system classpath.", e);
}
if (securityManagerType.length() > 0) {
System.setProperty("java.security.manager", securityManagerType);
SecurityManager securityManager;
try {
Class<?> aClass = systemClassLoader.loadClass(securityManagerType);
securityManager = (SecurityManager) aClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("Could not create an instance of '" + securityManagerType + "' specified for system SecurityManager.", e);
}
System.setSecurityManager(securityManager);
}
}
Example 69
Project: GreenBits-master File: DRMWorkaround.java View source code |
public static void maybeDisableExportControls() {
if (done)
return;
done = true;
if (Utils.isAndroidRuntime())
return;
try {
Field gate = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
gate.setAccessible(true);
gate.setBoolean(null, false);
final Field allPerm = Class.forName("javax.crypto.CryptoAllPermission").getDeclaredField("INSTANCE");
allPerm.setAccessible(true);
Object accessAllAreasCard = allPerm.get(null);
final Constructor<?> constructor = Class.forName("javax.crypto.CryptoPermissions").getDeclaredConstructor();
constructor.setAccessible(true);
Object coll = constructor.newInstance();
Method addPerm = Class.forName("javax.crypto.CryptoPermissions").getDeclaredMethod("add", java.security.Permission.class);
addPerm.setAccessible(true);
addPerm.invoke(coll, accessAllAreasCard);
Field defaultPolicy = Class.forName("javax.crypto.JceSecurity").getDeclaredField("defaultPolicy");
defaultPolicy.setAccessible(true);
defaultPolicy.set(null, coll);
} catch (Exception e) {
log.warn("Failed to deactivate AES-256 barrier logic, Tor mode/BIP38 decryption may crash if this JVM requires it: " + e.getMessage());
}
}
Example 70
Project: haze-master File: PermissionTestSupport.java View source code |
void run() { if (requested != null && allowed != null && expectedResult != null) { Permission allowedPermissions = createPermission(allowedName, allowed); Permission requestedPermission = createPermission(requestedName, requested); boolean actualResult = allowedPermissions.implies(requestedPermission); assertEquals("Access applied incorrectly for requested action of " + requestedPermission + " on permitted permissions of " + allowedPermissions, expectedResult, actualResult); } else { fail("Requested and/or allowed and/or expect not set"); } }
Example 71
Project: hazelcast-master File: PermissionTestSupport.java View source code |
void run() { if (requested != null && allowed != null && expectedResult != null) { Permission allowedPermissions = createPermission(allowedName, allowed); Permission requestedPermission = createPermission(requestedName, requested); boolean actualResult = allowedPermissions.implies(requestedPermission); assertEquals("Access applied incorrectly for requested action of " + requestedPermission + " on permitted permissions of " + allowedPermissions, expectedResult, actualResult); } else { fail("Requested and/or allowed and/or expect not set"); } }
Example 72
Project: HERD-master File: SecurityManagerHelper.java View source code |
/** * Executes the given {@link PrivilegedAction} using the given collection of {@link Permission}. * * @param <T> the return type * @param privilegedAction the {@link PrivilegedAction} to execute * @param permissions collection of permissions to apply. May be empty but not null. * @return return value of the privileged action */ public static <T> T doPrivileged(PrivilegedAction<T> privilegedAction, Collection<Permission> permissions) { CodeSource codeSource = new CodeSource(null, (Certificate[]) null); PermissionCollection permissionCollection = new Permissions(); for (Permission permission : permissions) { permissionCollection.add(permission); } ProtectionDomain protectionDomain = new ProtectionDomain(codeSource, permissionCollection); ProtectionDomain[] protectionDomains = { protectionDomain }; AccessControlContext accessControlContext = new AccessControlContext(protectionDomains); return AccessController.doPrivileged(privilegedAction, accessControlContext); }
Example 73
Project: incubator-tamaya-master File: BannerManagerTest.java View source code |
@Test
public void valueConsoleSendsBannerToSystemOut() {
SecurityManager sm = new SecurityManager();
AccessControlContext con = AccessController.getContext();
Permission p = new RuntimePermission("setIO");
/*
* Here we check the precondition for this unit test
* and the correct setup of the test enviroment
* The JVM must have been started with
* -Djava.security.policy=<path_to_core_module</src/test/resources/java-security.policy
*/
sm.checkPermission(p, con);
PrintStream standard = System.out;
PrintStream printStream = Mockito.mock(PrintStream.class);
System.setOut(printStream);
standard.println("Changed stream for STDOUT successfully");
try {
BannerManager bm = new BannerManager("console");
bm.outputBanner();
} finally {
System.setOut(standard);
}
Mockito.verify(printStream, Mockito.atLeastOnce()).println(Mockito.anyString());
}
Example 74
Project: jargo-master File: SecurityTest.java View source code |
@Override public void checkPermission(Permission perm) { if (perm instanceof FilePermission) { // To load the java class if (perm.getActions().equals("read")) return; } else if (perm instanceof NetPermission) { // To load the java class if (perm.getName().equals("specifyStreamHandler")) return; } else if (perm instanceof RuntimePermission) { // To shutdown the executor if (perm.getName().equals("modifyThread")) return; } else if (perm instanceof PropertyPermission) { if (READABLE_PROPERTIES.contains(perm.getName()) && perm.getActions().equals("read")) return; } throw new SecurityException("Permission: " + perm + " not granted"); }
Example 75
Project: jboss-modules-master File: PermissionsTest.java View source code |
@Test public void testExpansion() throws Exception { Module module = moduleLoader.loadModule(MODULE_WITH_INVALID_EXPANSION); Enumeration<Permission> permissions = module.getPermissionCollection().elements(); assertTrue(permissions.hasMoreElements()); Permission firstPermission = permissions.nextElement(); assertEquals(FilePermission.class.getName(), firstPermission.getClass().getName()); assertFalse(permissions.hasMoreElements()); }
Example 76
Project: JBossAS51-master File: NamespacePermission.java View source code |
public boolean implies(Permission p) {
String pactions = p.getActions();
boolean implied = true;
for (int n = 0; n < actions.length(); n++) {
char a = actions.charAt(n);
char pa = pactions.charAt(n);
if ((a != '-' && pa != '-' && pa != a)) {
implied = false;
break;
} else if (a == '-' && pa != '-') {
implied = false;
break;
}
}
return implied;
}
Example 77
Project: JBossAS_5_1_EDG-master File: NamespacePermission.java View source code |
public boolean implies(Permission p) {
String pactions = p.getActions();
boolean implied = true;
for (int n = 0; n < actions.length(); n++) {
char a = actions.charAt(n);
char pa = pactions.charAt(n);
if ((a != '-' && pa != '-' && pa != a)) {
implied = false;
break;
} else if (a == '-' && pa != '-') {
implied = false;
break;
}
}
return implied;
}
Example 78
Project: jdk7u-jdk-master File: AclImpl.java View source code |
/** * Returns an enumeration for the set of allowed permissions for * the specified principal * (representing an entity such as an individual or a group). * This set of allowed permissions is calculated as follows: * <UL> * <LI>If there is no entry in this Access Control List for the specified * principal, an empty permission set is returned.</LI> * <LI>Otherwise, the principal's group permission sets are determined. * (A principal can belong to one or more groups, where a group is a group * of principals, represented by the Group interface.)</LI> * </UL> * @param user the principal whose permission set is to be returned. * @return the permission set specifying the permissions the principal * is allowed. * @see java.security.Principal */ public Enumeration<Permission> getPermissions(Principal user) { Vector<Permission> empty = new Vector<Permission>(); for (Enumeration<AclEntry> e = entryList.elements(); e.hasMoreElements(); ) { AclEntry ent = e.nextElement(); if (ent.getPrincipal().equals(user)) return ent.permissions(); } return empty.elements(); }
Example 79
Project: kernel-master File: AbstractSecureCollectionsTest.java View source code |
/** * Run privileged action with given privileges. */ protected <T> T doActionWithPermissions(PrivilegedExceptionAction<T> action, Permission... permissions) throws PrivilegedActionException { Permissions allPermissions = new Permissions(); for (Permission permission : permissions) { if (permission != null) { allPermissions.add(permission); } } ProtectionDomain[] protectionDomains = new ProtectionDomain[] { new ProtectionDomain(new CodeSource(getCodeSource(), (java.security.cert.Certificate[]) null), allPermissions) }; return AccessController.doPrivileged(action, new AccessControlContext(protectionDomains)); }
Example 80
Project: ManagedRuntimeInitiative-master File: AclImpl.java View source code |
/** * Returns an enumeration for the set of allowed permissions for * the specified principal * (representing an entity such as an individual or a group). * This set of allowed permissions is calculated as follows: * <UL> * <LI>If there is no entry in this Access Control List for the specified * principal, an empty permission set is returned.</LI> * <LI>Otherwise, the principal's group permission sets are determined. * (A principal can belong to one or more groups, where a group is a group * of principals, represented by the Group interface.)</LI> * </UL> * @param user the principal whose permission set is to be returned. * @return the permission set specifying the permissions the principal * is allowed. * @see java.security.Principal */ public Enumeration<Permission> getPermissions(Principal user) { Vector<Permission> empty = new Vector<Permission>(); for (Enumeration<AclEntry> e = entryList.elements(); e.hasMoreElements(); ) { AclEntry ent = e.nextElement(); if (ent.getPrincipal().equals(user)) return ent.permissions(); } return empty.elements(); }
Example 81
Project: MinecraftForge-master File: FMLSecurityManager.java View source code |
@Override
public void checkPermission(Permission perm) {
String permName = perm.getName() != null ? perm.getName() : "missing";
if (permName.startsWith("exitVM")) {
Class<?>[] classContexts = getClassContext();
String callingClass = classContexts.length > 4 ? classContexts[4].getName() : "none";
String callingParent = classContexts.length > 5 ? classContexts[5].getName() : "none";
// FML is allowed to call system exit and the Minecraft applet (from the quit button)
if (!(callingClass.startsWith("net.minecraftforge.fml.") || "net.minecraft.server.dedicated.ServerHangWatchdog$1".equals(callingClass) || "net.minecraft.server.dedicated.ServerHangWatchdog".equals(callingClass) || ("net.minecraft.client.Minecraft".equals(callingClass) && "net.minecraft.client.Minecraft".equals(callingParent)) || ("net.minecraft.server.dedicated.DedicatedServer".equals(callingClass) && "net.minecraft.server.MinecraftServer".equals(callingParent)))) {
throw new ExitTrappedException();
}
} else if ("setSecurityManager".equals(permName)) {
throw new SecurityException("Cannot replace the FML security manager");
}
return;
}
Example 82
Project: Modular-Systems-master File: PermissionsTest.java View source code |
@Test public void testExpansion() throws Exception { Module module = moduleLoader.loadModule(MODULE_WITH_INVALID_EXPANSION); Enumeration<Permission> permissions = module.getPermissionCollection().elements(); assertTrue(permissions.hasMoreElements()); Permission firstPermission = permissions.nextElement(); assertEquals(FilePermission.class.getName(), firstPermission.getClass().getName()); assertFalse(permissions.hasMoreElements()); }
Example 83
Project: montagnesdor-master File: MdoAuthorizationServiceImpl.java View source code |
public String run() {
String path = null;
try {
Permission permission = getPermission(pageReq);
securityManager.checkPermission(permission);
path = pageReq;
} catch (Exception e) {
getLogger().error("message.error.permitted.action", new String[] { pageReq + " " + e.getMessage() });
}
return path;
}
Example 84
Project: offheap-store-master File: PhysicalMemoryTest.java View source code |
@Test
public void testBehaviorWithSecurityManager() {
final Thread testThread = Thread.currentThread();
System.setSecurityManager(new SecurityManager() {
@Override
public void checkMemberAccess(Class<?> clazz, int which) {
if (Thread.currentThread() == testThread && OperatingSystemMXBean.class.isAssignableFrom(clazz)) {
throw new SecurityException();
}
}
@Override
public void checkPackageAccess(String pkg) {
if (Thread.currentThread() == testThread && pkg.startsWith("com.sun.")) {
throw new SecurityException();
}
}
public void checkPermission(Permission perm) {
}
});
try {
Assert.assertThat(PhysicalMemory.totalPhysicalMemory(), nullValue());
Assert.assertThat(PhysicalMemory.freePhysicalMemory(), nullValue());
Assert.assertThat(PhysicalMemory.totalSwapSpace(), nullValue());
Assert.assertThat(PhysicalMemory.freeSwapSpace(), nullValue());
Assert.assertThat(PhysicalMemory.ourCommittedVirtualMemory(), nullValue());
} finally {
System.setSecurityManager(null);
}
}
Example 85
Project: opc-ua-stack-master File: CryptoRestrictions.java View source code |
/**
* Do the following, but with reflection to bypass access checks:
* <p>
* JceSecurity.isRestricted = false;
* JceSecurity.defaultPolicy.perms.clear();
* JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
*/
private static boolean removeCryptographyRestrictions() {
Logger logger = LoggerFactory.getLogger(Stack.class);
if (isRestrictedCryptography()) {
try {
final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");
final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
isRestrictedField.setAccessible(true);
isRestrictedField.set(null, false);
final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
defaultPolicyField.setAccessible(true);
final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);
final Field perms = cryptoPermissions.getDeclaredField("perms");
perms.setAccessible(true);
((Map<?, ?>) perms.get(defaultPolicy)).clear();
final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
instance.setAccessible(true);
defaultPolicy.add((Permission) instance.get(null));
logger.info("Successfully removed cryptography restrictions.");
return true;
} catch (final Exception e) {
logger.warn("Failed to remove cryptography restrictions.", e);
return false;
}
}
return true;
}
Example 86
Project: picketbox-master File: NamespacePermission.java View source code |
public boolean implies(Permission p) {
String pactions = p.getActions();
boolean implied = true;
for (int n = 0; n < actions.length(); n++) {
char a = actions.charAt(n);
char pa = pactions.charAt(n);
if ((a != '-' && pa != '-' && pa != a)) {
implied = false;
break;
} else if (a == '-' && pa != '-') {
implied = false;
break;
}
}
return implied;
}
Example 87
Project: resource-manager-master File: HandleOnlyMyJobsPermission.java View source code |
/**
* check that the given permission matches with this permission
*/
@Override
public boolean implies(Permission p) {
if (!(p instanceof HandleOnlyMyJobsPermission)) {
return false;
}
HandleOnlyMyJobsPermission fsp = (HandleOnlyMyJobsPermission) p;
//check incoming permission and permission given by the security file
return !handleOnlyMyJobsPermissionAllowed || fsp.handleOnlyMyJobsPermissionAllowed;
}
Example 88
Project: Resteasy-master File: PermissionUtil.java View source code |
public static byte[] createPermissionsXml(Permission... permissions) { final Element permissionsElement = new Element("permissions"); permissionsElement.setNamespaceURI("http://xmlns.jcp.org/xml/ns/javaee"); permissionsElement.addAttribute(new Attribute("version", "7")); for (Permission permission : permissions) { final Element permissionElement = new Element("permission"); final Element classNameElement = new Element("class-name"); final Element nameElement = new Element("name"); classNameElement.appendChild(permission.getClass().getName()); nameElement.appendChild(permission.getName()); permissionElement.appendChild(classNameElement); permissionElement.appendChild(nameElement); final String actions = permission.getActions(); if (actions != null && !actions.isEmpty()) { final Element actionsElement = new Element("actions"); actionsElement.appendChild(actions); permissionElement.appendChild(actionsElement); } permissionsElement.appendChild(permissionElement); } Document document = new Document(permissionsElement); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { final NiceSerializer serializer = new NiceSerializer(stream); serializer.setIndent(4); serializer.setLineSeparator("\n"); serializer.write(document); serializer.flush(); return stream.toByteArray(); } catch (IOException e) { throw new IllegalStateException("Generating permissions.xml failed", e); } }
Example 89
Project: robovm-master File: AccessControllerTest.java View source code |
public void testDoPrivilegedWithCombiner() {
final Permission permission = new RuntimePermission("do stuff");
final DomainCombiner union = new DomainCombiner() {
public ProtectionDomain[] combine(ProtectionDomain[] a, ProtectionDomain[] b) {
throw new AssertionFailedError("Expected combiner to be unused");
}
};
ProtectionDomain protectionDomain = new ProtectionDomain(null, new Permissions());
AccessControlContext accessControlContext = new AccessControlContext(new AccessControlContext(new ProtectionDomain[] { protectionDomain }), union);
final AtomicInteger actionCount = new AtomicInteger();
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
// Calling doPrivileged again would have exercised the combiner
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
actionCount.incrementAndGet();
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
return null;
}
});
return null;
}
}, accessControlContext);
assertEquals(1, actionCount.get());
}
Example 90
Project: scheduling-master File: HandleOnlyMyJobsPermission.java View source code |
/**
* check that the given permission matches with this permission
*/
@Override
public boolean implies(Permission p) {
if (!(p instanceof HandleOnlyMyJobsPermission)) {
return false;
}
HandleOnlyMyJobsPermission fsp = (HandleOnlyMyJobsPermission) p;
//check incoming permission and permission given by the security file
return !handleOnlyMyJobsPermissionAllowed || fsp.handleOnlyMyJobsPermissionAllowed;
}
Example 91
Project: tomee-master File: PseudoPolicyConfigurationFactory.java View source code |
public PolicyConfiguration getPolicyConfiguration(final String contextID, final boolean remove) throws PolicyContextException { return new PolicyConfiguration() { public String getContextID() throws PolicyContextException { return contextID; } public void addToRole(final String roleName, final PermissionCollection permissions) throws PolicyContextException { } public void addToRole(final String roleName, final Permission permission) throws PolicyContextException { } public void addToUncheckedPolicy(final PermissionCollection permissions) throws PolicyContextException { } public void addToUncheckedPolicy(final Permission permission) throws PolicyContextException { } public void addToExcludedPolicy(final PermissionCollection permissions) throws PolicyContextException { } public void addToExcludedPolicy(final Permission permission) throws PolicyContextException { } public void removeRole(final String roleName) throws PolicyContextException { } public void removeUncheckedPolicy() throws PolicyContextException { } public void removeExcludedPolicy() throws PolicyContextException { } public void linkConfiguration(final PolicyConfiguration link) throws PolicyContextException { } public void delete() throws PolicyContextException { } public void commit() throws PolicyContextException { } public boolean inService() throws PolicyContextException { return false; } }; }
Example 92
Project: wildfly-master File: EjbJaccService.java View source code |
@Override public void createPermissions(final AttachmentList<EjbJaccConfig> metaData, final PolicyConfiguration policyConfiguration) throws PolicyContextException { for (EjbJaccConfig permission : metaData) { for (Permission deny : permission.getDeny()) { policyConfiguration.addToExcludedPolicy(deny); } for (Permission permit : permission.getPermit()) { policyConfiguration.addToUncheckedPolicy(permit); } for (Entry<String, Permission> role : permission.getRoles()) { policyConfiguration.addToRole(role.getKey(), role.getValue()); } } }
Example 93
Project: xstream-for-android-master File: DynamicSecurityManager.java View source code |
public void addPermission(final CodeSource codeSource, final Permission permission) {
PermissionCollection permissionCollection = (PermissionCollection) permissions.get(codeSource);
if (permissionCollection == null) {
permissionCollection = new Permissions();
permissions.put(codeSource, permissionCollection);
}
permissionCollection.add(permission);
// updateACC();
}
Example 94
Project: eclipse.platform-master File: AntSecurityManager.java View source code |
/* * (non-Javadoc) * * @see java.lang.SecurityManager#checkPermission(java.security.Permission) */ @Override public void checkPermission(Permission perm) { if (!fAllowSettingSystemProperties && fgPropertyPermission.implies(perm) && fRestrictedThread == Thread.currentThread()) { // attempting to write a system property throw new AntSecurityException(); } if (fSecurityManager != null) { fSecurityManager.checkPermission(perm); } }
Example 95
Project: uml-auto-assessment-master File: ProfilingSecurityManager.java View source code |
//~ Public Methods ........................................................
// ----------------------------------------------------------
@Override
public void checkPermission(final Permission permission) {
try {
super.checkPermission(permission);
} catch (SecurityException e) {
final Throwable t = new Throwable("Profiler stack probe");
final StackTraceElement[] stack = t.getStackTrace();
if (!isRecur(stack)) {
buildRules(permission, AccessController.getContext());
}
}
}
Example 96
Project: yajsw-master File: ProfilingSecurityManager.java View source code |
// -----------------
@Override
public void checkPermission(final Permission permission) {
final Throwable t = new Throwable("Profiler stack probe");
final StackTraceElement[] stack = t.getStackTrace();
// Avoid recursion owing to actions in this class itself inducing callbacks
if (!isRecur(stack)) {
buildRules(permission, AccessController.getContext());
}
}
Example 97
Project: yajsw-maven-master File: ProfilingSecurityManager.java View source code |
// -----------------
@Override
public void checkPermission(final Permission permission) {
final Throwable t = new Throwable("Profiler stack probe");
final StackTraceElement[] stack = t.getStackTrace();
// Avoid recursion owing to actions in this class itself inducing callbacks
if (!isRecur(stack)) {
buildRules(permission, AccessController.getContext());
}
}
Example 98
Project: yajsw-maven-mk2-master File: ProfilingSecurityManager.java View source code |
// -----------------
@Override
public void checkPermission(final Permission permission) {
final Throwable t = new Throwable("Profiler stack probe");
final StackTraceElement[] stack = t.getStackTrace();
// Avoid recursion owing to actions in this class itself inducing callbacks
if (!isRecur(stack)) {
buildRules(permission, AccessController.getContext());
}
}
Example 99
Project: ikvm-openjdk-master File: AclImpl.java View source code |
/** * Returns an enumeration for the set of allowed permissions for * the specified principal * (representing an entity such as an individual or a group). * This set of allowed permissions is calculated as follows: * <UL> * <LI>If there is no entry in this Access Control List for the specified * principal, an empty permission set is returned.</LI> * <LI>Otherwise, the principal's group permission sets are determined. * (A principal can belong to one or more groups, where a group is a group * of principals, represented by the Group interface.)</LI> * </UL> * @param user the principal whose permission set is to be returned. * @return the permission set specifying the permissions the principal * is allowed. * @see java.security.Principal */ public Enumeration<Permission> getPermissions(Principal user) { Vector<Permission> empty = new Vector<Permission>(); for (Enumeration<AclEntry> e = entryList.elements(); e.hasMoreElements(); ) { AclEntry ent = e.nextElement(); if (ent.getPrincipal().equals(user)) return ent.permissions(); } return empty.elements(); }
Example 100
Project: jbosstools-arquillian-master File: ArquillianSecurityManager.java View source code |
/* (non-Javadoc) * @see java.lang.SecurityManager#checkPermission(java.security.Permission) */ public void checkPermission(Permission perm) { if (!arquillianPreferences.getBoolean(ArquillianConstants.ALLOW_SP_COMMAND) && fgPropertyPermission.implies(perm) && fRestrictedThread == Thread.currentThread()) { //attempting to write a system property throw new ArquillianSecurityException("SecurityException: Writing a system property is not allowed."); } if (fSecurityManager != null) { fSecurityManager.checkPermission(perm); } }
Example 101
Project: arquillian-container-gae-master File: DevAppServerFactoryHack.java View source code |
private synchronized boolean appHasPermission(Permission perm) {
synchronized (PERMISSION_LOCK) {
AppContext context = this.devAppServer.getAppContext();
if ((context.getUserPermissions().implies(perm)) || (context.getApplicationPermissions().implies(perm))) {
return true;
}
}
return ("read".equals(perm.getActions())) && (perm.getName().endsWith(KEYCHAIN_JNILIB));
}