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: openjdk8-jdk-master  File: JmxMBeanServer.java View source code
/**
     * De-serializes a byte array in the context of a given MBean class loader.
     * The class loader is the one that loaded the class with name "className".
     *
     * @param className The name of the class whose class loader should be
     *      used for the de-serialization.
     * @param data The byte array to be de-sererialized.
     *
     * @return  The de-serialized object stream.
     *
     * @exception OperationsException Any of the usual Input/Output
     *      related exceptions.
     * @exception ReflectionException The specified class could not be
     *      loaded by the default loader repository
     *
     */
@Deprecated
public ObjectInputStream deserialize(String className, byte[] data) throws OperationsException, ReflectionException {
    if (className == null) {
        throw new RuntimeOperationsException(new IllegalArgumentException(), "Null className passed in parameter");
    }
    /* Permission check */
    // This call requires MBeanPermission 'getClassLoaderRepository'
    final ClassLoaderRepository clr = getClassLoaderRepository();
    Class<?> theClass;
    try {
        if (clr == null)
            throw new ClassNotFoundException(className);
        theClass = clr.loadClass(className);
    } catch (ClassNotFoundException e) {
        throw new ReflectionException(e, "The given class could not be " + "loaded by the default loader " + "repository");
    }
    return instantiator.deserialize(theClass.getClassLoader(), data);
}
Example 2
Project: open-mika-master  File: LoggerTest.java View source code
public void checkPermission(Permission perm) {
    // grant all permissions except getting class loader
    if (perm instanceof RuntimePermission) {
        if ("getClassLoader".equals(perm.getName())) {
            throw new SecurityException();
        }
    }
}
Example 3
Project: hadoop_ekg-master  File: ConfiguredPolicy.java View source code
@Override
public PermissionCollection getPermissions(ProtectionDomain domain) {
    PermissionCollection permissionCollection = super.getPermissions(domain);
    for (Principal principal : domain.getPrincipals()) {
        Set<Permission> principalPermissions = permissions.get(principal);
        if (principalPermissions != null) {
            for (Permission permission : principalPermissions) {
                permissionCollection.add(permission);
            }
        }
        for (Permission permission : allowedPermissions) {
            permissionCollection.add(permission);
        }
    }
    return permissionCollection;
}
Example 4
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 5
Project: JDK-master  File: MBeanPermission.java View source code
private static String makeName(String className, String member, ObjectName objectName) {
    final StringBuilder name = new StringBuilder();
    if (className == null)
        className = "-";
    name.append(className);
    if (member == null)
        member = "-";
    name.append("#" + member);
    if (objectName == null)
        name.append("[-]");
    else
        name.append("[").append(objectName.getCanonicalName()).append("]");
    /* In the interests of legibility for Permission.toString(), we
           transform the empty string into "*".  */
    if (name.length() == 0)
        return "*";
    else
        return name.toString();
}
Example 6
Project: openjdk-master  File: DefaultLoggerTest.java View source code
@Override
public boolean implies(ProtectionDomain domain, Permission permission) {
    if (allowAll.get().get())
        return allPermissions.implies(permission);
    if (allowControl.get().get())
        return controlPermissions.implies(permission);
    return permissions.implies(permission);
}
Example 7
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 8
Project: android_platform_libcore-master  File: SerializationTest.java View source code
public void assertDeserialized(Serializable initial, Serializable deserialized) {
    PermissionCollection initPC = (PermissionCollection) initial;
    PermissionCollection dserPC = (PermissionCollection) deserialized;
    // verify class
    assertEquals(initPC.getClass(), dserPC.getClass());
    // verify 'readOnly' field
    assertEquals(initPC.isReadOnly(), dserPC.isReadOnly());
    // verify collection of permissions
    Collection<Permission> refCollection = new HashSet<Permission>(Collections.list(initPC.elements()));
    Collection<Permission> tstCollection = new HashSet<Permission>(Collections.list(dserPC.elements()));
    assertEquals(refCollection, tstCollection);
}
Example 9
Project: JBossAS51-master  File: UnifiedClassLoader.java View source code
// URLClassLoader overrides --------------------------------------
/** Override the permissions accessor to use the CodeSource
    based on the original URL if one exists. This allows the
    security policy to be defined in terms of the static URL
    namespace rather than the local copy or nested URL.
    This builds a PermissionCollection from:
    1. The origURL CodeSource
    2. The argument CodeSource
    3. The Policy.getPermission(origURL CodeSource)

    This is necessary because we cannot define the CodeSource the
    SecureClassLoader uses to register the class under.

    @param cs the location and signatures of the codebase.
    */
protected PermissionCollection getPermissions(CodeSource cs) {
    CodeSource permCS = cs;
    if (origURL != null) {
        permCS = new CodeSource(origURL, cs.getCertificates());
    }
    Policy policy = Policy.getPolicy();
    PermissionCollection perms = super.getPermissions(permCS);
    PermissionCollection perms2 = super.getPermissions(cs);
    PermissionCollection perms3 = policy.getPermissions(permCS);
    Enumeration iter = perms2.elements();
    while (iter.hasMoreElements()) perms.add((Permission) iter.nextElement());
    iter = perms3.elements();
    while (iter.hasMoreElements()) perms.add((Permission) iter.nextElement());
    if (log.isTraceEnabled())
        log.trace("getPermissions, url=" + url + ", origURL=" + origURL + " -> " + perms);
    return perms;
}
Example 10
Project: jdk7u-jdk-master  File: InvokeDynamicPrintArgs.java View source code
private static void setSM() {
    // Test for severe security manager interactions (7050328).
    class SM extends SecurityManager {

        public void checkPackageAccess(String pkg) {
            if (pkg.startsWith("test."))
                throw new SecurityException("checkPackageAccess " + pkg);
        }

        public void checkMemberAccess(Class<?> clazz, int which) {
            if (clazz == InvokeDynamicPrintArgs.class)
                throw new SecurityException("checkMemberAccess " + clazz.getName() + " #" + which);
        }

        // allow these others:
        public void checkPermission(java.security.Permission perm) {
        }
    }
    System.setSecurityManager(new SM());
}
Example 11
Project: oobd-master  File: ProviderConfigurationPermission.java View source code
public boolean implies(Permission permission) {
    if (!(permission instanceof ProviderConfigurationPermission)) {
        return false;
    }
    if (!this.getName().equals(permission.getName())) {
        return false;
    }
    ProviderConfigurationPermission other = (ProviderConfigurationPermission) permission;
    return (this.permissionMask & other.permissionMask) == other.permissionMask;
}
Example 12
Project: jbosgi-master  File: WebBundleConfigurationProcessor.java View source code
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    DeploymentUnit depUnit = phaseContext.getDeploymentUnit();
    final ModuleSpecification moduleSpecification = depUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
    final List<PermissionFactory> permFactories = moduleSpecification.getPermissionFactories();
    final Enumeration<Permission> e = DEFAULT_PERMISSIONS.elements();
    while (e.hasMoreElements()) {
        permFactories.add(new ImmediatePermissionFactory(e.nextElement()));
    }
    FactoryPermissionCollection permissionCollection = new FactoryPermissionCollection(permFactories.toArray(new PermissionFactory[permFactories.size()]));
    depUnit.putAttachment(Attachments.MODULE_PERMISSIONS, permissionCollection);
}
Example 13
Project: wildfly-core-master  File: DefaultPermissionFactoryTestCase.java View source code
private void testResource(AuthorizerConfiguration authorizerConfiguration, StandardRole[] userRoles, StandardRole[] allowedRoles, boolean accessExpectation) {
    ConstraintFactory constraintFactory = new TestConstraintFactory(allowedRoles);
    TestRoleMapper roleMapper = new TestRoleMapper(userRoles);
    DefaultPermissionFactory permissionFactory = new DefaultPermissionFactory(roleMapper, Collections.singleton(constraintFactory), authorizerConfiguration);
    Action action = new Action(null, null, EnumSet.of(Action.ActionEffect.ADDRESS));
    TargetResource targetResource = TargetResource.forStandalone(PathAddress.EMPTY_ADDRESS, ROOT_RR, null);
    PermissionCollection userPermissions = permissionFactory.getUserPermissions(caller, environment, action, targetResource);
    PermissionCollection requiredPermissions = permissionFactory.getRequiredPermissions(action, targetResource);
    for (Permission requiredPermission : toSet(requiredPermissions)) {
        assertEquals(accessExpectation, userPermissions.implies(requiredPermission));
    }
}
Example 14
Project: Payara-master  File: EJBSecurityManager.java View source code
/**
     * This method is called by the EJB container to decide whether or not
     * a method specified in the Invocation should be allowed.
     *
     * @param compInv invocation object that contains all the details of the
     *                invocation.
     * @return A boolean value indicating if the client should be allowed
     *         to invoke the EJB.
     */
public boolean authorize(ComponentInvocation compInv) {
    if (!(compInv instanceof EjbInvocation)) {
        return false;
    }
    //FIXME: Param type should be EjbInvocation
    EjbInvocation inv = (EjbInvocation) compInv;
    if (inv.getAuth() != null) {
        return inv.getAuth().booleanValue();
    }
    boolean ret = false;
    CachedPermission cp = null;
    Permission ejbmp = null;
    if (inv.invocationInfo == null || inv.invocationInfo.cachedPermission == null) {
        ejbmp = new EJBMethodPermission(ejbName, inv.getMethodInterface(), inv.method);
        cp = new CachedPermissionImpl(uncheckedMethodPermissionCache, ejbmp);
        if (inv.invocationInfo != null) {
            inv.invocationInfo.cachedPermission = cp;
            if (_logger.isLoggable(Level.FINE)) {
                _logger.fine("JACC: permission initialized in InvocationInfo: EJBMethodPermission (Name) = " + ejbmp.getName() + " (Action) = " + ejbmp.getActions());
            }
        }
    } else {
        cp = inv.invocationInfo.cachedPermission;
        ejbmp = cp.getPermission();
    }
    String caller = null;
    SecurityContext sc = null;
    pcHandlerImpl.getHandlerData().setInvocation(inv);
    ret = cp.checkPermission();
    if (!ret) {
        sc = SecurityContext.getCurrent();
        Set principalSet = sc.getPrincipalSet();
        ProtectionDomain prdm = getCachedProtectionDomain(principalSet, true);
        try {
            // set the policy context in the TLS.
            String oldContextId = setPolicyContext(this.contextId);
            try {
                ret = policy.implies(prdm, ejbmp);
            } catch (SecurityException se) {
                _logger.log(Level.SEVERE, "jacc_access_exception", se);
                ret = false;
            } catch (Throwable t) {
                _logger.log(Level.SEVERE, "jacc_access_exception", t);
                ret = false;
            } finally {
                resetPolicyContext(oldContextId, this.contextId);
            }
        } catch (Throwable t) {
            _logger.log(Level.SEVERE, "jacc_policy_context_exception", t);
            ret = false;
        }
    }
    inv.setAuth((ret) ? Boolean.TRUE : Boolean.FALSE);
    if (auditManager.isAuditOn()) {
        if (sc == null) {
            sc = SecurityContext.getCurrent();
        }
        caller = sc.getCallerPrincipal().getName();
        auditManager.ejbInvocation(caller, ejbName, inv.method.toString(), ret);
    }
    if (ret && inv.isWebService && !inv.isPreInvokeDone()) {
        preInvoke(inv);
    }
    if (_logger.isLoggable(Level.FINE)) {
        _logger.fine("JACC: Access Control Decision Result: " + ret + " EJBMethodPermission (Name) = " + ejbmp.getName() + " (Action) = " + ejbmp.getActions() + " (Caller) = " + caller);
    }
    return ret;
}
Example 15
Project: guava-master  File: ClassPathTest.java View source code
private void doTestExistsThrowsSecurityException() throws IOException, URISyntaxException {
    URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
    URL[] urls = myLoader.getURLs();
    ImmutableList.Builder<File> filesBuilder = ImmutableList.builder();
    for (URL url : urls) {
        if (url.getProtocol().equalsIgnoreCase("file")) {
            filesBuilder.add(new File(url.toURI()));
        }
    }
    ImmutableList<File> files = filesBuilder.build();
    assertThat(files).isNotEmpty();
    SecurityManager disallowFilesSecurityManager = new SecurityManager() {

        @Override
        public void checkPermission(Permission p) {
            if (p instanceof FilePermission) {
                throw new SecurityException("Disallowed: " + p);
            }
        }
    };
    System.setSecurityManager(disallowFilesSecurityManager);
    try {
        files.get(0).exists();
        fail("Did not get expected SecurityException");
    } catch (SecurityException expected) {
    }
    ClassPath classPath = ClassPath.from(myLoader);
    assertThat(classPath.getResources()).isEmpty();
}
Example 16
Project: dragome-sdk-master  File: JDKAnalyzer.java View source code
private static void fillGoodBadOverrides() {
    // Problematic:
    // java.security.BasicPermission. Used by many different
    // classes and doing an import on all of java.security.
    // sun.misc.Unsafe: Very low-level functionality.
    GOOD_CLASSES.add("java.security.Permission");
    // Interfaces
    GOOD_CLASSES.add("java.security.Guard");
    // Super-class of a few good classes and not much functionality as it is
    // primarily abstract.
    GOOD_CLASSES.add("java.security.PermissionCollection");
    GOOD_CLASSES.add("java.security.BasicPermission");
    GOOD_CLASSES.add("java.security.PrivilegedAction");
    GOOD_CLASSES.add("java.security.PrivilegedActionException");
    GOOD_CLASSES.add("java.security.PrivilegedExceptionAction");
    // Interfaces from which good classes are created.
    // TODO(Sascha): Maybe do this automatically.
    GOOD_CLASSES.add("sun.reflect.LangReflectAccess");
    GOOD_CLASSES.add("sun.misc.JavaNetAccess");
    GOOD_CLASSES.add("sun.misc.JavaIOAccess");
    GOOD_CLASSES.add("org.xml.sax.EntityResolver");
    GOOD_CLASSES.add("sun.net.spi.nameservice.NameService");
    GOOD_CLASSES.add("org.xml.sax.ErrorHandler");
    GOOD_CLASSES.add("sun.misc.JavaIODeleteOnExitAccess");
    GOOD_CLASSES.add("sun.misc.SignalHandler");
    GOOD_CLASSES.add("sun.misc.JavaLangAccess");
    GOOD_CLASSES.add("sun.misc.JavaUtilJarAccess");
    GOOD_CLASSES.add("sun.misc.JavaIOFileDescriptorAccess");
    GOOD_CLASSES.add("sun.util.LocaleServiceProviderPool$LocalizedObjectGetter");
    GOOD_CLASSES.add("java.nio.channels.Channel");
    GOOD_CLASSES.add("org.apache.harmony.luni.internal.nls.Messages");
    GOOD_CLASSES.add("org.apache.harmony.math.internal.nls.Messages");
    GOOD_CLASSES.add("org.apache.harmony.regex.internal.nls.Messages");
    GOOD_CLASSES.add("org.apache.harmony.archive.internal.nls.Messages");
    BAD_CLASSES.add("java.util.jar.JarVerifier");
    BAD_CLASSES.add("java.lang.management.ManagementFactory");
    BAD_CLASSES.add("java.util.JapaneseImperialCalendar");
    BAD_CLASSES.add("java.lang.ClassLoader");
    BAD_CLASSES.add("java.net.URLClassLoader");
    BAD_CLASSES.add("java.net.URLClassLoader$SubURLClassLoader");
    BAD_CLASSES.add("java.net.FactoryURLClassLoader");
    // This one is a subclass of java.lang.ClassLoader, so it must go as
    // well.
    BAD_CLASSES.add("java.util.ResourceBundle$RBClassLoader");
    // Sub-class of bad class sun.misc.LRUCache.
    BAD_CLASSES.add("java.util.Scanner$1");
    // Sub-class of bad class org.apache.harmony.luni.util.ThreadLocalCache
    BAD_CLASSES.add("java.io.ObjectStreamClass$OSCThreadLocalCache");
    BAD_CLASSES.add("java.io.ObjectStreamClass$OSCThreadLocalCache$1");
    // DEX cannot parse this.
    BAD_CLASSES.add("org.apache.xerces.impl.xpath.regex.ParserForXMLSchema");
}
Example 17
Project: Rio-master  File: JarProxy.java View source code
public JarFile openJarFile(java.net.JarURLConnection conn) throws IOException {
    URL url = conn.getJarFileURL();
    CachedJarFile result;
    synchronized (cache) {
        result = (CachedJarFile) cache.get(url);
    }
    if (result != null) {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkPermission(result.perm);
        }
        return result;
    }
    // we have to download and open the JAR; yet it may be a local file
    try {
        URI uri = new URI(url.toString());
        if (ResourceUtils.isLocalFile(uri)) {
            File file = new File(uri);
            Permission perm = new FilePermission(file.getAbsolutePath(), "read");
            result = new CachedJarFile(file, perm, false);
        }
    } catch (URISyntaxException e) {
    }
    if (result == null) {
        final URLConnection jarconn = url.openConnection();
        // set up the properties based on the JarURLConnection
        jarconn.setAllowUserInteraction(conn.getAllowUserInteraction());
        jarconn.setDoInput(conn.getDoInput());
        jarconn.setDoOutput(conn.getDoOutput());
        jarconn.setIfModifiedSince(conn.getIfModifiedSince());
        Map map = conn.getRequestProperties();
        for (Iterator itr = map.entrySet().iterator(); itr.hasNext(); ) {
            Map.Entry entry = (Map.Entry) itr.next();
            jarconn.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }
        jarconn.setUseCaches(conn.getUseCaches());
        final InputStream in = getJarInputStream(jarconn);
        try {
            result = (CachedJarFile) AccessController.doPrivileged(new PrivilegedExceptionAction() {

                public Object run() throws IOException {
                    File file = File.createTempFile("jar_cache", "");
                    FileOutputStream out = new FileOutputStream(file);
                    try {
                        RedirectibleInput r = new RedirectingInputStream(in, false, false);
                        int len = r.redirectAll(out);
                        out.flush();
                        if (len == 0) {
                            // e.g. HttpURLConnection: "NOT_MODIFIED"
                            return null;
                        }
                    } finally {
                        out.close();
                    }
                    return new CachedJarFile(file, jarconn.getPermission(), true);
                }
            });
        } catch (PrivilegedActionException pae) {
            throw (IOException) pae.getException();
        } finally {
            in.close();
        }
    }
    // if no input came (e.g. due to NOT_MODIFIED), do not cache
    if (result == null)
        return null;
    // optimistic locking
    synchronized (cache) {
        CachedJarFile asyncResult = (CachedJarFile) cache.get(url);
        if (asyncResult != null) {
            // some other thread already retrieved the file; return w/o
            // security check since we already succeeded in getting past it
            result.closeCachedFile();
            return asyncResult;
        }
        cache.put(url, result);
        return result;
    }
}
Example 18
Project: pljava-master  File: Backend.java View source code
void assertPermission(Permission perm) {
    if (perm instanceof RuntimePermission) {
        String name = perm.getName();
        if ("*".equals(name) || "exitVM".equals(name))
            throw new SecurityException();
        else if ("setSecurityManager".equals(name) && !s_inSetTrusted)
            //
            throw new SecurityException();
    } else if (perm instanceof PropertyPermission) {
        if (perm.getActions().indexOf("write") >= 0) {
            // We never allow this to be changed.
            // As for UDT byteorder, the classes that use it only check
            // once so it would be misleading to allow runtime changes;
            // use pljava.vmoptions to provide an initial value.
            //
            String propName = perm.getName();
            if (propName.equals("java.home") || propName.matches("org\\.postgresql\\.pljava\\.udt\\.byteorder(?:\\..*)?"))
                throw new SecurityException();
        }
    }
}
Example 19
Project: btpka3.github.com-master  File: SecurityPolicySpi.java View source code
@Override
protected PermissionCollection engineGetPermissions(CodeSource codesource) {
    Permissions permissions = new Permissions();
    for (int i = 0; i < cache.size(); i++) {
        ProtectionDomain pd = cache.get(i);
        CodeSource cs = pd.getCodeSource();
        if (cs != null && cs.implies(codesource)) {
            Enumeration<Permission> e = pd.getPermissions().elements();
            while (e.hasMoreElements()) {
                Permission p = e.nextElement();
                permissions.add(p);
            }
        }
    }
    if (permissions.elements().hasMoreElements()) {
        return permissions;
    }
    return super.engineGetPermissions(codesource);
}
Example 20
Project: glassfish-main-master  File: WebUserDataPermission.java View source code
/**
     * Determines if the argument Permission is "implied by" this
     * WebUserDataPermission. For this to be the case all of the following
     * must be true:<p>
     * <ul>
     * <li> The argument is an instanceof WebUserDataPermission.
     * <li> The first URLPattern in the name of the argument permission
     *      is matched by the first URLPattern in the name of this permission.
     * <li> The first URLPattern in the name of the argument permission
     *      is NOT matched by any URLPattern in the URLPatternList of the
     *      URLPatternSpec of this permission.
     * <li> If the first URLPattern in the name of the argument permission
     *      matches the first URLPattern in the URLPatternSpec of this 
     *      permission, then every URLPattern in the URLPatternList of the
     *      URLPatternSpec of this permission is matched by a URLPattern
     *      in the URLPatternList of the argument permission.
     * <li> The HTTP methods represented by the actions of the argument 
     *      permission are a subset of the HTTP methods represented by the
     *      actions of this permission.
     * <li> The transportType in the actions of this permission 
     *      either corresponds to the value "NONE", or equals the 
     *      transportType in the actions of the argument permission.
     * </ul>
     * <P>
     * URLPattern matching is performed using the <i>Servlet matching 
     * rules</i> where two URL patterns match if they are related as follows:
     * <p><ul>
     * <li> their pattern values are String equivalent, or
     * <li> this pattern is the path-prefix pattern "/*", or
     * <li> this pattern is a path-prefix pattern (that is, it starts with 
     *      "/" and ends with "/*") and the argument pattern starts with the 
     *      substring of this pattern, minus its last 2 characters, and the
     *      next character of the argument pattern, if there is one, is "/", or
     * <li> this pattern is an extension pattern (that is, it starts with 
     *      "*.") and the argument pattern ends with this pattern, or
     * <li> the reference pattern is the special default pattern, "/",
     *      which matches all argument patterns.
     * </ul>
     * <P>
     * All of the comparisons described above are case sensitive.
     * <P>
     * @param permission "this" WebUserDataPermission is checked to see if
     * it implies the argument permission.
     * <P>
     * @return true if the specified permission is implied by this object,
     * false if not.
     */
public boolean implies(Permission permission) {
    if (permission == null || !(permission instanceof WebUserDataPermission))
        return false;
    WebUserDataPermission that = (WebUserDataPermission) permission;
    if (this.transportType != TT_NONE && this.transportType != that.transportType)
        return false;
    if (!this.methodSpec.implies(that.methodSpec))
        return false;
    return this.urlPatternSpec.implies(that.urlPatternSpec);
}
Example 21
Project: concierge-master  File: AdminPermission.java View source code
/**
	 * Determines if the specified permission is implied by this object. This
	 * method throws an exception if the specified permission was not
	 * constructed with a bundle.
	 * 
	 * <p>
	 * This method returns [email protected] true} if the specified permission is an
	 * AdminPermission AND
	 * <ul>
	 * <li>this object's filter matches the specified permission's bundle ID,
	 * bundle symbolic name, bundle location and bundle signer distinguished
	 * name chain OR</li>
	 * <li>this object's filter is "*"</li>
	 * </ul>
	 * AND this object's actions include all of the specified permission's
	 * actions.
	 * <p>
	 * Special case: if the specified permission was constructed with "*"
	 * filter, then this method returns [email protected] true} if this object's filter is
	 * "*" and this object's actions include all of the specified permission's
	 * actions
	 * 
	 * @param p The requested permission.
	 * @return [email protected] true} if the specified permission is implied by this
	 *         object; [email protected] false} otherwise.
	 */
public boolean implies(Permission p) {
    if (!(p instanceof AdminPermission)) {
        return false;
    }
    AdminPermission requested = (AdminPermission) p;
    if (bundle != null) {
        return false;
    }
    // if requested permission has a filter, then it is an invalid argument
    if (requested.filter != null) {
        return false;
    }
    return implies0(requested, ACTION_NONE);
}
Example 22
Project: WaveInCloud-master  File: ConsoleClientTest.java View source code
/** "quit" command should clean up and shut down the client */
public void testQuitExitsCleanly() {
    connect();
    createNewWave();
    openWave(0);
    // Set up a custom security manager to intercept System.exit() calls.
    // Taken from http://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit
    SecurityManager oldSecurityManager = System.getSecurityManager();
    System.setSecurityManager(new SecurityManager() {

        @Override
        public void checkPermission(Permission perm) {
        // Allow anything.
        }

        @Override
        public void checkPermission(Permission perm, Object context) {
        // Allow anything.
        }

        @Override
        public void checkExit(int status) {
            throw new ExitException(status);
        }
    });
    int exitStatus = -1;
    try {
        quit();
    } catch (ExitException e) {
        exitStatus = e.status;
    } finally {
        System.setSecurityManager(oldSecurityManager);
        // The client should exit without an error.
        assertEquals(0, exitStatus);
        // The client should have disconnected.
        assertFalse(client.isConnected());
    }
}
Example 23
Project: liferay-maven-support-master  File: AbstractToolsLiferayMojo.java View source code
protected void executeTool(String toolClassName, ClassLoader classLoader, String[] args) throws Exception {
    Thread currentThread = Thread.currentThread();
    ClassLoader contextClassLoader = currentThread.getContextClassLoader();
    currentThread.setContextClassLoader(classLoader);
    SecurityManager currentSecurityManager = System.getSecurityManager();
    // Required to prevent premature exit by DBBuilder. See LPS-7524.
    SecurityManager securityManager = new SecurityManager() {

        public void checkPermission(Permission permission) {
        }

        public void checkExit(int status) {
            throw new SecurityException();
        }
    };
    System.setSecurityManager(securityManager);
    try {
        System.setProperty("external-properties", "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
        Class<?> clazz = classLoader.loadClass(toolClassName);
        Method method = clazz.getMethod("main", String[].class);
        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (ite.getCause() instanceof SecurityException) {
        } else {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);
        System.clearProperty("org.apache.commons.logging.Log");
        System.setSecurityManager(currentSecurityManager);
    }
}
Example 24
Project: classlib6-master  File: SunToolkit.java View source code
static synchronized Image getImageFromHash(Toolkit tk, URL url) {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        try {
            java.security.Permission perm = url.openConnection().getPermission();
            if (perm != null) {
                try {
                    sm.checkPermission(perm);
                } catch (SecurityException se) {
                    if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) {
                        sm.checkRead(perm.getName());
                    } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) {
                        sm.checkConnect(url.getHost(), url.getPort());
                    } else {
                        throw se;
                    }
                }
            }
        } catch (java.io.IOException ioe) {
            sm.checkConnect(url.getHost(), url.getPort());
        }
    }
    Image img = (Image) imgCache.get(url);
    if (img == null) {
        try {
            img = tk.createImage(new URLImageSource(url));
            imgCache.put(url, img);
        } catch (Exception e) {
        }
    }
    return img;
}
Example 25
Project: android-platform-tools-base-master  File: XmlPrettyPrinterTest.java View source code
private static void checkDriver(String expectedOutput, String expectedError, int expectedExitCode, String[] args, File testFile) throws Exception {
    PrintStream previousOut = System.out;
    PrintStream previousErr = System.err;
    try {
        // Trap System.exit calls:
        System.setSecurityManager(new SecurityManager() {

            @Override
            public void checkPermission(Permission perm) {
            // allow anything.
            }

            @Override
            public void checkPermission(Permission perm, Object context) {
            // allow anything.
            }

            @Override
            public void checkExit(int status) {
                throw new ExitException(status);
            }
        });
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        System.setOut(new PrintStream(output));
        final ByteArrayOutputStream error = new ByteArrayOutputStream();
        System.setErr(new PrintStream(error));
        // not set
        int exitCode = 0xCAFEBABE;
        try {
            XmlPrettyPrinter.main(args);
        } catch (ExitException e) {
            exitCode = e.getStatus();
        }
        String testPath = testFile == null ? XmlPrettyPrinterTest.class.getName() : testFile.getPath();
        String pathName = "$TESTFILE";
        assertEquals(expectedError, error.toString().replace(testPath, pathName));
        assertEquals(expectedOutput, output.toString().replace(testPath, pathName));
        assertEquals(expectedExitCode, exitCode);
    } finally {
        // Re-enable system exit for unit test
        System.setSecurityManager(null);
        System.setOut(previousOut);
        System.setErr(previousErr);
    }
}
Example 26
Project: ARTPart-master  File: ClassTest.java View source code
/**
     * java.lang.Class#getClasses()
     */
public void test_getClasses_subtest0() {
    final Permission privCheckPermission = new BasicPermission("Privilege check") {

        private static final long serialVersionUID = 1L;
    };
    class MyCombiner implements DomainCombiner {

        boolean combine;

        public ProtectionDomain[] combine(ProtectionDomain[] executionDomains, ProtectionDomain[] parentDomains) {
            combine = true;
            return new ProtectionDomain[0];
        }

        private boolean recurring = false;

        public boolean isPriviledged() {
            if (recurring) {
                return true;
            }
            try {
                recurring = true;
                combine = false;
                try {
                    AccessController.checkPermission(privCheckPermission);
                } catch (SecurityException e) {
                }
                return !combine;
            } finally {
                recurring = false;
            }
        }
    }
}
Example 27
Project: resin-master  File: DynamicClassLoader.java View source code
protected void replace(DynamicClassLoader source) {
    _id = source._id;
    _loaders.addAll(source._loaders);
    _jarLoader = source._jarLoader;
    _dependencies = source._dependencies;
    _makeList = source._makeList;
    _useServletHack = source._useServletHack;
    _parentPriorityPackages = source._parentPriorityPackages;
    if (source._listeners != null) {
        if (_listeners == null)
            _listeners = new ArrayList<ClassLoaderListener>();
        _listeners.addAll(source._listeners);
        source._listeners.clear();
    }
    if (source._permissions != null) {
        if (_permissions == null)
            _permissions = new ArrayList<Permission>();
        _permissions.addAll(source._permissions);
    }
    _codeSource = source._codeSource;
    _lifecycle.copyState(source._lifecycle);
}
Example 28
Project: eclipse.jdt.ui-master  File: ChangeSignatureTests.java View source code
public void testImport06() throws Exception {
    String[] signature = { "QPermission;", "Qjava.security.acl.Permission;" };
    String[] newNames = null;
    String[] newTypes = null;
    String[] newDefaultValues = null;
    ParameterInfo[] newParamInfo = createNewParamInfos(newTypes, newNames, newDefaultValues);
    int[] newIndices = {};
    String[] oldParamNames = { "perm", "acl" };
    String[] newParamNames = { "xacl", "xperm" };
    String[] newParamTypeNames = { "java.security.acl.Permission [] []", "java.security.Permission" };
    int[] permutation = { 1, 0 };
    int[] deletedIndices = null;
    int newVisibility = Modifier.NONE;
    String newReturnTypeName = "java.security.acl.Permission";
    helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName);
}
Example 29
Project: guava-experimental-master  File: JSR166TestCase.java View source code
/**
     * Runs Runnable r with a security policy that permits precisely
     * the specified permissions.  If there is no current security
     * manager, the runnable is run twice, both with and without a
     * security manager.  We require that any security manager permit
     * getPolicy/setPolicy.
     */
public void runWithPermissions(Runnable r, Permission... permissions) {
    SecurityManager sm = System.getSecurityManager();
    if (sm == null) {
        r.run();
        Policy savedPolicy = Policy.getPolicy();
        try {
            Policy.setPolicy(permissivePolicy());
            System.setSecurityManager(new SecurityManager());
            runWithPermissions(r, permissions);
        } finally {
            System.setSecurityManager(null);
            Policy.setPolicy(savedPolicy);
        }
    } else {
        Policy savedPolicy = Policy.getPolicy();
        AdjustablePolicy policy = new AdjustablePolicy(permissions);
        Policy.setPolicy(policy);
        try {
            r.run();
        } finally {
            policy.addPermission(new SecurityPermission("setPolicy"));
            Policy.setPolicy(savedPolicy);
        }
    }
}
Example 30
Project: j2objc-master  File: LogManagerTest.java View source code
public void checkPermission(Permission permission) {
    if (permission instanceof LoggingPermission) {
        StackTraceElement[] stack = (new Throwable()).getStackTrace();
        for (int i = 0; i < stack.length; i++) {
            if (stack[i].getClassName().equals("java.util.logging.Logger")) {
                return;
            }
        }
        throw new SecurityException("Found LogManager checkAccess()");
    }
}
Example 31
Project: yarn-comment-master  File: TestDFSShell.java View source code
public void checkPermission(Permission perm) {
    if (firstTime) {
        Thread t = Thread.currentThread();
        if (!t.toString().contains("DataNode")) {
            String s = "" + Arrays.asList(t.getStackTrace());
            if (s.contains("FileUtil.copyContent")) {
                //pause at FileUtil.copyContent
                firstTime = false;
                copy2ndFileThread.start();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}
Example 32
Project: radioflow-master  File: FileUtils.java View source code
private boolean needPermission(String nativeURL, int permissionType) throws JSONException {
    JSONObject j = requestAllPaths();
    ArrayList<String> allowedStorageDirectories = new ArrayList<String>();
    allowedStorageDirectories.add(j.getString("applicationStorageDirectory"));
    if (j.has("externalApplicationStorageDirectory")) {
        allowedStorageDirectories.add(j.getString("externalApplicationStorageDirectory"));
    }
    if (permissionType == READ && hasReadPermission()) {
        return false;
    } else if (permissionType == WRITE && hasWritePermission()) {
        return false;
    }
    // Permission required if the native url lies outside the allowed storage directories
    for (String directory : allowedStorageDirectories) {
        if (nativeURL.startsWith(directory)) {
            return false;
        }
    }
    return true;
}
Example 33
Project: google-web-toolkit-svnmirror-master  File: WebappClassLoader.java View source code
/**
     * If there is a Java SecurityManager create a read FilePermission
     * or JndiPermission for the file directory path.
     *
     * @param path file directory path
     */
public void addPermission(String path) {
    if (path == null) {
        return;
    }
    if (securityManager != null) {
        Permission permission = null;
        if (path.startsWith("jndi:") || path.startsWith("jar:jndi:")) {
            if (!path.endsWith("/")) {
                path = path + "/";
            }
            permission = new JndiPermission(path + "*");
            addPermission(permission);
        } else {
            if (!path.endsWith(File.separator)) {
                permission = new FilePermission(path, "read");
                addPermission(permission);
                path = path + File.separator;
            }
            permission = new FilePermission(path + "-", "read");
            addPermission(permission);
        }
    }
}
Example 34
Project: lucene-solr-master  File: LuceneTestCase.java View source code
/** 
   * Runs a code part with restricted permissions (be sure to add all required permissions,
   * because it would start with empty permissions). You cannot grant more permissions than
   * our policy file allows, but you may restrict writing to several dirs...
   * <p><em>Note:</em> This assumes a [email protected] SecurityManager} enabled, otherwise it
   * stops test execution. If enabled, it needs the following [email protected] SecurityPermission}:
   * [email protected] "createAccessControlContext"}
   */
public static <T> T runWithRestrictedPermissions(PrivilegedExceptionAction<T> action, Permission... permissions) throws Exception {
    assumeTrue("runWithRestrictedPermissions requires a SecurityManager enabled", System.getSecurityManager() != null);
    // be sure to have required permission, otherwise doPrivileged runs with *no* permissions:
    AccessController.checkPermission(new SecurityPermission("createAccessControlContext"));
    final PermissionCollection perms = new Permissions();
    Arrays.stream(permissions).forEach(perms::add);
    final AccessControlContext ctx = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
    try {
        return AccessController.doPrivileged(action, ctx);
    } catch (PrivilegedActionException e) {
        throw e.getException();
    }
}