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: bug6694823.java View source code
public static void main(String[] args) throws Exception {
    toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {
            createGui();
        }
    });
    toolkit.realSync();
    // Get screen insets
    screenInsets = toolkit.getScreenInsets(frame.getGraphicsConfiguration());
    if (screenInsets.bottom == 0) {
        // This test is only for configurations with taskbar on the bottom
        return;
    }
    System.setSecurityManager(new SecurityManager() {

        private String allowsAlwaysOnTopPermission = SecurityConstants.AWT.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION.getName();

        @Override
        public void checkPermission(Permission perm) {
            if (allowsAlwaysOnTopPermission.equals(perm.getName())) {
                throw new SecurityException();
            }
        }
    });
    // Show popup as if from an applet
    // The popup shouldn't overlap the task bar. It should be shifted up.
    checkPopup();
}
Example 2
Project: openjdk-master  File: SecurityRestrictionsTest.java View source code
private boolean isJvmciPermission(Permission perm) {
    String name = perm.getName();
    boolean isJvmciRuntime = perm instanceof RuntimePermission && (JVMCI_SERVICES.equals(name) || name.startsWith(JVMCI_RT_PERM_START));
    boolean isJvmciProperty = perm instanceof PropertyPermission && name.startsWith(JVMCI_PROP_START);
    return isJvmciRuntime || isJvmciProperty;
}
Example 3
Project: open-mika-master  File: PropertyPermission.java View source code
public boolean implies(Permission p) {
    try {
        PropertyPermission pp = (PropertyPermission) p;
        if ((pp.read && !this.read) || (pp.write && !this.write)) {
            return false;
        }
        String thisname = super.getName();
        String othername = p.getName();
        if (thisname == "*") {
            return true;
        }
        if (thisname.endsWith(".*")) {
            return othername.length() >= thisname.length() && othername.startsWith(thisname.substring(0, thisname.length() - 1));
        } else {
            return othername.equals(thisname);
        }
    } catch (ClassCastException e) {
        return false;
    }
}
Example 4
Project: hadoop_ekg-master  File: ServiceAuthorizationManager.java View source code
/**
   * Check if the given [email protected] Subject} has all of necessary [email protected] Permission} 
   * set.
   * 
   * @param user <code>Subject</code> to be authorized
   * @param permissions <code>Permission</code> set
   * @throws AuthorizationException if the authorization failed
   */
private static void checkPermission(final Subject user, final Permission... permissions) throws AuthorizationException {
    try {
        Subject.doAs(user, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                try {
                    for (Permission permission : permissions) {
                        AccessController.checkPermission(permission);
                    }
                } catch (AccessControlException ace) {
                    LOG.info("Authorization failed for " + UserGroupInformation.getCurrentUGI(), ace);
                    throw new AuthorizationException(ace);
                }
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new AuthorizationException(e.getException());
    }
}
Example 5
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 6
Project: hadoop-20-master  File: ServiceAuthorizationManager.java View source code
/**
   * Check if the given [email protected] Subject} has all of necessary [email protected] Permission} 
   * set.
   * 
   * @param user <code>Subject</code> to be authorized
   * @param permissions <code>Permission</code> set
   * @throws AuthorizationException if the authorization failed
   */
private static void checkPermission(final Subject user, final Permission... permissions) throws AuthorizationException {
    try {
        Subject.doAs(user, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                try {
                    for (Permission permission : permissions) {
                        AccessController.checkPermission(permission);
                    }
                } catch (AccessControlException ace) {
                    LOG.info("Authorization failed for " + UserGroupInformation.getCurrentUGI(), ace);
                    throw new AuthorizationException(ace);
                }
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new AuthorizationException(e.getException());
    }
}
Example 7
Project: jdk7u-jdk-master  File: JarFileFactory.java View source code
private JarFile getCachedJarFile(URL url) {
    JarFile result = fileCache.get(URLUtil.urlNoFragString(url));
    /* if the JAR file is cached, the permission will always be there */
    if (result != null) {
        Permission perm = getPermission(result);
        if (perm != null) {
            SecurityManager sm = System.getSecurityManager();
            if (sm != 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;
                    }
                }
            }
        }
    }
    return result;
}
Example 8
Project: classlib6-master  File: SubjectDelegator.java View source code
/* Return the AccessControlContext appropriate to execute an
       operation on behalf of the delegatedSubject.  If the
       authenticatedAccessControlContext does not have permission to
       delegate to that subject, throw SecurityException.  */
public synchronized AccessControlContext delegatedContext(AccessControlContext authenticatedACC, Subject delegatedSubject, boolean removeCallerContext) throws SecurityException {
    if (principalsCache == null || accCache == null) {
        principalsCache = new CacheMap<Subject, Principal[]>(PRINCIPALS_CACHE_SIZE);
        accCache = new CacheMap<Subject, AccessControlContext>(ACC_CACHE_SIZE);
    }
    // Retrieve the principals for the given
    // delegated subject from the cache
    //
    Principal[] delegatedPrincipals = principalsCache.get(delegatedSubject);
    //
    if (delegatedPrincipals == null) {
        delegatedPrincipals = delegatedSubject.getPrincipals().toArray(new Principal[0]);
        principalsCache.put(delegatedSubject, delegatedPrincipals);
    }
    // Retrieve the access control context for the
    // given delegated subject from the cache
    //
    AccessControlContext delegatedACC = accCache.get(delegatedSubject);
    //
    if (delegatedACC == null) {
        if (removeCallerContext) {
            delegatedACC = JMXSubjectDomainCombiner.getDomainCombinerContext(delegatedSubject);
        } else {
            delegatedACC = JMXSubjectDomainCombiner.getContext(delegatedSubject);
        }
        accCache.put(delegatedSubject, delegatedACC);
    }
    // Check if the subject delegation permission allows the
    // authenticated subject to assume the identity of each
    // principal in the delegated subject
    //
    final Principal[] dp = delegatedPrincipals;
    PrivilegedAction<Void> action = new PrivilegedAction<Void>() {

        public Void run() {
            for (int i = 0; i < dp.length; i++) {
                final String pname = dp[i].getClass().getName() + "." + dp[i].getName();
                Permission sdp = new SubjectDelegationPermission(pname);
                AccessController.checkPermission(sdp);
            }
            return null;
        }
    };
    AccessController.doPrivileged(action, authenticatedACC);
    return delegatedACC;
}
Example 9
Project: property-db-master  File: AllPermission.java View source code
/** [email protected]} 
     * Adds a permission to the AllPermissions. The key for the hash is
     * permission.path.
     *
     * @param permission the Permission object to add.
     *
     * @exception IllegalArgumentException - if the permission is not a
     *                                       AllPermission
     *
     * @exception SecurityException - if this AllPermissionCollection object
     *                                has been marked readonly
     */
public void add(Permission permission) {
    if (!(permission instanceof AllPermission))
        throw new IllegalArgumentException("invalid permission: " + permission);
    if (isReadOnly())
        throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");
    // No sync; staleness OK
    all_allowed = true;
}
Example 10
Project: ikvm-openjdk-master  File: AllPermission.java View source code
/**
     * Adds a permission to the AllPermissions. The key for the hash is
     * permission.path.
     *
     * @param permission the Permission object to add.
     *
     * @exception IllegalArgumentException - if the permission is not a
     *                                       AllPermission
     *
     * @exception SecurityException - if this AllPermissionCollection object
     *                                has been marked readonly
     */
public void add(Permission permission) {
    if (!(permission instanceof AllPermission))
        throw new IllegalArgumentException("invalid permission: " + permission);
    if (isReadOnly())
        throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");
    // No sync; staleness OK
    all_allowed = true;
}
Example 11
Project: ManagedRuntimeInitiative-master  File: AllPermission.java View source code
/**
     * Adds a permission to the AllPermissions. The key for the hash is
     * permission.path.
     *
     * @param permission the Permission object to add.
     *
     * @exception IllegalArgumentException - if the permission is not a
     *                                       AllPermission
     *
     * @exception SecurityException - if this AllPermissionCollection object
     *                                has been marked readonly
     */
public void add(Permission permission) {
    if (!(permission instanceof AllPermission))
        throw new IllegalArgumentException("invalid permission: " + permission);
    if (isReadOnly())
        throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");
    // No sync; staleness OK
    all_allowed = true;
}
Example 12
Project: JDK-master  File: SubjectDelegator.java View source code
/* Return the AccessControlContext appropriate to execute an
       operation on behalf of the delegatedSubject.  If the
       authenticatedAccessControlContext does not have permission to
       delegate to that subject, throw SecurityException.  */
public synchronized AccessControlContext delegatedContext(AccessControlContext authenticatedACC, Subject delegatedSubject, boolean removeCallerContext) throws SecurityException {
    if (principalsCache == null || accCache == null) {
        principalsCache = new CacheMap<Subject, Principal[]>(PRINCIPALS_CACHE_SIZE);
        accCache = new CacheMap<Subject, AccessControlContext>(ACC_CACHE_SIZE);
    }
    // Retrieve the principals for the given
    // delegated subject from the cache
    //
    Principal[] delegatedPrincipals = principalsCache.get(delegatedSubject);
    //
    if (delegatedPrincipals == null) {
        delegatedPrincipals = delegatedSubject.getPrincipals().toArray(new Principal[0]);
        principalsCache.put(delegatedSubject, delegatedPrincipals);
    }
    // Retrieve the access control context for the
    // given delegated subject from the cache
    //
    AccessControlContext delegatedACC = accCache.get(delegatedSubject);
    //
    if (delegatedACC == null) {
        if (removeCallerContext) {
            delegatedACC = JMXSubjectDomainCombiner.getDomainCombinerContext(delegatedSubject);
        } else {
            delegatedACC = JMXSubjectDomainCombiner.getContext(delegatedSubject);
        }
        accCache.put(delegatedSubject, delegatedACC);
    }
    // Check if the subject delegation permission allows the
    // authenticated subject to assume the identity of each
    // principal in the delegated subject
    //
    final Principal[] dp = delegatedPrincipals;
    PrivilegedAction<Void> action = new PrivilegedAction<Void>() {

        public Void run() {
            for (int i = 0; i < dp.length; i++) {
                final String pname = dp[i].getClass().getName() + "." + dp[i].getName();
                Permission sdp = new SubjectDelegationPermission(pname);
                AccessController.checkPermission(sdp);
            }
            return null;
        }
    };
    AccessController.doPrivileged(action, authenticatedACC);
    return delegatedACC;
}
Example 13
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 14
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 15
Project: android-15-master  File: PermissionsHash.java View source code
/**
     * Indicates whether the argument permission is implied by the permissions
     * contained in the receiver.
     *
     * @return boolean <code>true</code> if the argument permission is implied
     *         by the permissions in the receiver, and <code>false</code> if
     *         it is not.
     * @param permission
     *            java.security.Permission the permission to check
     */
public boolean implies(Permission permission) {
    for (Enumeration elements = elements(); elements.hasMoreElements(); ) {
        if (((Permission) elements.nextElement()).implies(permission)) {
            return true;
        }
    }
    return false;
}
Example 16
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 17
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 18
Project: JBossAS51-master  File: InstancePermissionCollection.java View source code
public void add(Permission permission) {
    if (trace) {
        log.trace("adding " + permission);
    }
    if (!(permission instanceof InstancePermission)) {
        throw new IllegalArgumentException();
    }
    permissions.add(permission);
}
Example 19
Project: j2objc-master  File: PermissionsHash.java View source code
/**
     * Indicates whether the argument permission is implied by the permissions
     * contained in the receiver.
     *
     * @return boolean <code>true</code> if the argument permission is implied
     *         by the permissions in the receiver, and <code>false</code> if
     *         it is not.
     * @param permission
     *            java.security.Permission the permission to check
     */
public boolean implies(Permission permission) {
    for (Enumeration elements = elements(); elements.hasMoreElements(); ) {
        if (((Permission) elements.nextElement()).implies(permission)) {
            return true;
        }
    }
    return false;
}
Example 20
Project: JBossAS_5_1_EDG-master  File: InstancePermissionCollection.java View source code
public void add(Permission permission) {
    if (trace) {
        log.trace("adding " + permission);
    }
    if (!(permission instanceof InstancePermission)) {
        throw new IllegalArgumentException();
    }
    permissions.add(permission);
}
Example 21
Project: android-sdk-sources-for-api-level-23-master  File: PermissionsHash.java View source code
/**
     * Indicates whether the argument permission is implied by the permissions
     * contained in the receiver.
     *
     * @return boolean <code>true</code> if the argument permission is implied
     *         by the permissions in the receiver, and <code>false</code> if
     *         it is not.
     * @param permission
     *            java.security.Permission the permission to check
     */
public boolean implies(Permission permission) {
    for (Enumeration elements = elements(); elements.hasMoreElements(); ) {
        if (((Permission) elements.nextElement()).implies(permission)) {
            return true;
        }
    }
    return false;
}
Example 22
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 23
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 24
Project: wildfly-core-master  File: ManagementPermissionCollection.java View source code
@Override
public void add(Permission permission) {
    if (isReadOnly()) {
        throw ControllerLogger.ROOT_LOGGER.permissionCollectionIsReadOnly();
    }
    if (type.equals(permission.getClass())) {
        ManagementPermission mperm = (ManagementPermission) permission;
        synchronized (permissions) {
            permissions.put(mperm.getActionEffect(), mperm);
        }
    } else {
        throw ControllerLogger.ROOT_LOGGER.incompatiblePermissionType(permission.getClass());
    }
}
Example 25
Project: Payara-master  File: PermsHolder.java View source code
public PermissionCollection getPermissions(CodeSource codesource, PermissionCollection parentPC) {
    String codeUrl = codesource.getLocation().toString();
    PermissionCollection cachedPermissons = loaderPC.get(codeUrl);
    if (cachedPermissons != null)
        return cachedPermissons;
    else
        cachedPermissons = new Permissions();
    PermissionCollection pc = parentPC;
    if (pc != null) {
        Enumeration<Permission> perms = pc.elements();
        while (perms.hasMoreElements()) {
            Permission p = perms.nextElement();
            cachedPermissons.add(p);
        }
    }
    if (declaredPermissionCollection != null) {
        Enumeration<Permission> dperms = this.declaredPermissionCollection.elements();
        while (dperms.hasMoreElements()) {
            Permission p = dperms.nextElement();
            cachedPermissons.add(p);
        }
    }
    if (eePermissionCollection != null) {
        Enumeration<Permission> eeperms = eePermissionCollection.elements();
        while (eeperms.hasMoreElements()) {
            Permission p = eeperms.nextElement();
            cachedPermissons.add(p);
        }
    }
    PermissionCollection tmpPc = loaderPC.putIfAbsent(codeUrl, cachedPermissons);
    if (tmpPc != null) {
        cachedPermissons = tmpPc;
    }
    return cachedPermissons;
}