Java Code Examples for java.security.Permission

The following examples show how to use java.security.Permission. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: baratine   Source File: DynamicClassLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the permission collection for the given code source.
 */
@Override
protected PermissionCollection getPermissions(CodeSource codeSource)
{
  PermissionCollection perms = super.getPermissions(codeSource);

  ArrayList<Permission> permissions = _permissions;

  int size = permissions != null ? permissions.size() : 0;
  for (int i = 0; i < size; i++) {
    Permission permission = permissions.get(i);

    perms.add(permission);
  }

  return perms;
}
 
Example 2
Source Project: jdk8u-jdk   Source File: ServicePermission.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * @serialData "permissions" field (a Vector containing the ServicePermissions).
 */
/*
 * Writes the contents of the perms field out as a Vector for
 * serialization compatibility with earlier releases.
 */
private void writeObject(ObjectOutputStream out) throws IOException {
    // Don't call out.defaultWriteObject()

    // Write out Vector
    Vector<Permission> permissions = new Vector<>(perms.size());

    synchronized (this) {
        permissions.addAll(perms);
    }

    ObjectOutputStream.PutField pfields = out.putFields();
    pfields.put("permissions", permissions);
    out.writeFields();
}
 
Example 3
Source Project: jdk8u_jdk   Source File: Activation.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prints warning message if installed Policy is the default Policy
 * implementation and globally granted permissions do not include
 * AllPermission or any ExecPermissions/ExecOptionPermissions.
 */
static void checkConfiguration() {
    Policy policy =
        AccessController.doPrivileged(new PrivilegedAction<Policy>() {
            public Policy run() {
                return Policy.getPolicy();
            }
        });
    if (!(policy instanceof PolicyFile)) {
        return;
    }
    PermissionCollection perms = getExecPermissions();
    for (Enumeration<Permission> e = perms.elements();
         e.hasMoreElements();)
    {
        Permission p = e.nextElement();
        if (p instanceof AllPermission ||
            p instanceof ExecPermission ||
            p instanceof ExecOptionPermission)
        {
            return;
        }
    }
    System.err.println(getTextResource("rmid.exec.perms.inadequate"));
}
 
Example 4
Source Project: netty-4.1.22   Source File: PlatformDependent0Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMajorVersionFromJavaSpecificationVersion() {
    final SecurityManager current = System.getSecurityManager();

    try {
        System.setSecurityManager(new SecurityManager() {
            @Override
            public void checkPropertyAccess(String key) {
                if (key.equals("java.specification.version")) {
                    // deny
                    throw new SecurityException(key);
                }
            }

            // so we can restore the security manager
            @Override
            public void checkPermission(Permission perm) {
            }
        });

        assertEquals(6, PlatformDependent0.majorVersionFromJavaSpecificationVersion());
    } finally {
        System.setSecurityManager(current);
    }
}
 
Example 5
/**
 * Check if the connector server creator can assume the identity of each
 * principal in the authenticated subject, i.e. check if the connector
 * server creator codebase contains a subject delegation permission for
 * each principal present in the authenticated subject.
 *
 * @return {@code true} if the connector server creator can delegate to all
 * the authenticated principals in the subject. Otherwise, {@code false}.
 */
public static synchronized boolean
    checkRemoveCallerContext(Subject subject) {
    try {
        for (Principal p : getSubjectPrincipals(subject)) {
            final String pname =
                p.getClass().getName() + "." + p.getName();
            final Permission sdp =
                new SubjectDelegationPermission(pname);
            AccessController.checkPermission(sdp);
        }
    } catch (SecurityException e) {
        return false;
    }
    return true;
}
 
Example 6
public void runTest(AccessControlContext acc, Permission perm,
        boolean expectACE, int id) {

    AccessController.doPrivileged(
            (PrivilegedAction) () -> {
                try {
                    AccessController.getContext().checkPermission(P1);
                } catch (AccessControlException ace) {
                    catchACE = true;
                }
                if (catchACE ^ expectACE) {
                    throw new RuntimeException("test" + id + " failed");
                }
                return null;
            }, acc, perm);
}
 
Example 7
Source Project: jdk8u-jdk   Source File: AuthPolicyFile.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean implies(Permission permission) {
    if (notInit) {
        init();
    }
    return perms.implies(permission);
}
 
Example 8
public String toString() {
    StringBuilder sb = new StringBuilder("policy: ");
    Enumeration<Permission> perms = permissions.elements();
    while (perms.hasMoreElements()) {
        sb.append("\n").append(perms.nextElement().toString());
    }
    return sb.toString();
}
 
Example 9
Source Project: jdk8u-jdk   Source File: SSL.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void checkPermission(Permission perm) {
    if (!(perm instanceof ServicePermission)) {
        return;
    }
    ServicePermission p = (ServicePermission)perm;
    permChecks = permChecks + p.getActions().toUpperCase().charAt(0);
}
 
Example 10
public java.util.Enumeration<Permission> elements() {
    if (perms == null)
        init();
    synchronized (perms) {
        return perms.elements();
    }
}
 
Example 11
private Permission getPermission(JarFile jarFile) {
    try {
        URLConnection uc = getConnection(jarFile);
        if (uc != null)
            return uc.getPermission();
    } catch (IOException ioe) {
        // gulp
    }

    return null;
}
 
Example 12
Source Project: jdk8u-dev-jdk   Source File: bug6694823.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 13
Source Project: jdk8u60   Source File: DelegationPermission.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException
{
    // Don't call defaultReadObject()

    // Read in serialized fields
    ObjectInputStream.GetField gfields = in.readFields();

    // Get the one we want
    Vector<Permission> permissions =
            (Vector<Permission>)gfields.get("permissions", null);
    perms = new ArrayList<Permission>(permissions.size());
    perms.addAll(permissions);
}
 
Example 14
Source Project: openjdk-jdk8u   Source File: AuthPolicyFile.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean implies(Permission permission) {
    if (notInit) {
        init();
    }
    return perms.implies(permission);
}
 
Example 15
static void testOperation(MBeanServer mbs, CustomSecurityManager sm,
        ObjectName on, MBeanOperationInfo opInfo) {
    System.out.println("Testing " + opInfo.getName());
    Descriptor desc = opInfo.getDescriptor();
    if (desc.getFieldValue("dcmd.permissionClass") == null) {
    // No special permission required, execution should not trigger
    // any security exception
        if (invokeOperation(mbs, on, opInfo)) {
            throw new RuntimeException("TEST FAILED");
        }
    } else {
        // Building the required permission
        Permission reqPerm = createPermission(
                (String)desc.getFieldValue("dcmd.permissionClass"),
                (String)desc.getFieldValue("dcmd.permissionName"),
                (String)desc.getFieldValue("dcmd.permissionAction"));
        // Paranoid mode: check that the SecurityManager has not already
        // been granted the permission
        sm.denyPermission(reqPerm);
        // A special permission is required for this operation,
        // invoking it without the permission granted must trigger
        // a security exception
        if(!invokeOperation(mbs, on, opInfo)) {
            throw new RuntimeException("TEST FAILED");
        }
        // grant the permission and re-try invoking the operation
        sm.grantPermission(reqPerm);
        if(invokeOperation(mbs, on, opInfo)) {
            throw new RuntimeException("TEST FAILED");
        }
        // Clean up
        sm.denyPermission(reqPerm);
    }
}
 
Example 16
static void testOperation(MBeanServer mbs, CustomSecurityManager sm,
        ObjectName on, MBeanOperationInfo opInfo) {
    System.out.println("Testing " + opInfo.getName());
    Descriptor desc = opInfo.getDescriptor();
    if (desc.getFieldValue("dcmd.permissionClass") == null) {
    // No special permission required, execution should not trigger
    // any security exception
        if (invokeOperation(mbs, on, opInfo)) {
            throw new RuntimeException("TEST FAILED");
        }
    } else {
        // Building the required permission
        Permission reqPerm = createPermission(
                (String)desc.getFieldValue("dcmd.permissionClass"),
                (String)desc.getFieldValue("dcmd.permissionName"),
                (String)desc.getFieldValue("dcmd.permissionAction"));
        // Paranoid mode: check that the SecurityManager has not already
        // been granted the permission
        sm.denyPermission(reqPerm);
        // A special permission is required for this operation,
        // invoking it without the permission granted must trigger
        // a security exception
        if(!invokeOperation(mbs, on, opInfo)) {
            throw new RuntimeException("TEST FAILED");
        }
        // grant the permission and re-try invoking the operation
        sm.grantPermission(reqPerm);
        if(invokeOperation(mbs, on, opInfo)) {
            throw new RuntimeException("TEST FAILED");
        }
        // Clean up
        sm.denyPermission(reqPerm);
    }
}
 
Example 17
Source Project: astor   Source File: TestDateTimeUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean implies(ProtectionDomain domain, Permission permission) {
                if (permission instanceof JodaTimePermission) {
                    return false;
                }
                return true;
//                return super.implies(domain, permission);
            }
 
Example 18
Source Project: jdk1.8-source-analysis   Source File: JmxMBeanServer.java    License: Apache License 2.0 5 votes vote down vote up
private static void checkMBeanPermission(String classname,
                                         String member,
                                         ObjectName objectName,
                                         String actions)
    throws SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanPermission(classname,
                                              member,
                                              objectName,
                                              actions);
        sm.checkPermission(perm);
    }
}
 
Example 19
Source Project: jdk8u_jdk   Source File: SocketPermission.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds a permission to the SocketPermissions. The key for the hash is
 * the name in the case of wildcards, or all the IP addresses.
 *
 * @param permission the Permission object to add.
 *
 * @exception IllegalArgumentException - if the permission is not a
 *                                       SocketPermission
 *
 * @exception SecurityException - if this SocketPermissionCollection object
 *                                has been marked readonly
 */
public void add(Permission permission) {
    if (! (permission instanceof SocketPermission))
        throw new IllegalArgumentException("invalid permission: "+
                                           permission);
    if (isReadOnly())
        throw new SecurityException(
            "attempt to add a Permission to a readonly PermissionCollection");

    // optimization to ensure perms most likely to be tested
    // show up early (4301064)
    synchronized (this) {
        perms.add(0, (SocketPermission)permission);
    }
}
 
Example 20
Source Project: Java8CN   Source File: DelegationPermission.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns an enumeration of all the DelegationPermission objects
 * in the container.
 *
 * @return an enumeration of all the DelegationPermission objects.
 */
public Enumeration<Permission> elements() {
    // Convert Iterator into Enumeration
    synchronized (this) {
        return Collections.enumeration(perms);
    }
}
 
Example 21
public PermissionsBuilder addAll(PermissionCollection col) {
    if (col != null) {
        for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
            perms.add(e.nextElement());
        }
    }
    return this;
}
 
Example 22
public PermissionsBuilder addAll(PermissionCollection col) {
    if (col != null) {
        for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
            perms.add(e.nextElement());
        }
    }
    return this;
}
 
Example 23
public PermissionsBuilder addAll(PermissionCollection col) {
    if (col != null) {
        for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
            perms.add(e.nextElement());
        }
    }
    return this;
}
 
Example 24
public PermissionsBuilder addAll(PermissionCollection col) {
    if (col != null) {
        for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
            perms.add(e.nextElement());
        }
    }
    return this;
}
 
Example 25
Source Project: jdk8u-dev-jdk   Source File: EqualsImplies.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 26
Source Project: dragonwell8_jdk   Source File: TestPolicy.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toString() {
    StringJoiner sj = new StringJoiner("\n", "policy: ", "");
    Enumeration<Permission> perms = permissions.elements();
    while (perms.hasMoreElements()) {
        sj.add(perms.nextElement().toString());
    }
    return sj.toString();

}
 
Example 27
Source Project: JDKSourceCode1.8   Source File: DelegationPermission.java    License: MIT License 5 votes vote down vote up
/**
 * Returns an enumeration of all the DelegationPermission objects
 * in the container.
 *
 * @return an enumeration of all the DelegationPermission objects.
 */
public Enumeration<Permission> elements() {
    // Convert Iterator into Enumeration
    synchronized (this) {
        return Collections.enumeration(perms);
    }
}
 
Example 28
Source Project: Java8CN   Source File: SocketPermission.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds a permission to the SocketPermissions. The key for the hash is
 * the name in the case of wildcards, or all the IP addresses.
 *
 * @param permission the Permission object to add.
 *
 * @exception IllegalArgumentException - if the permission is not a
 *                                       SocketPermission
 *
 * @exception SecurityException - if this SocketPermissionCollection object
 *                                has been marked readonly
 */
public void add(Permission permission) {
    if (! (permission instanceof SocketPermission))
        throw new IllegalArgumentException("invalid permission: "+
                                           permission);
    if (isReadOnly())
        throw new SecurityException(
            "attempt to add a Permission to a readonly PermissionCollection");

    // optimization to ensure perms most likely to be tested
    // show up early (4301064)
    synchronized (this) {
        perms.add(0, (SocketPermission)permission);
    }
}
 
Example 29
/**
 * Check and see if this collection of permissions implies the permissions
 * expressed in "permission".
 *
 * @param permission the Permission object to compare
 *
 * @return true if "permission" is a proper subset of a permission in
 * the collection, false if not.
 */
public boolean implies(Permission permission) {
    if (! (permission instanceof ServicePermission))
            return false;

    ServicePermission np = (ServicePermission) permission;
    int desired = np.getMask();
    int effective = 0;
    int needed = desired;

    synchronized (this) {
        int len = perms.size();

        // need to deal with the case where the needed permission has
        // more than one action and the collection has individual permissions
        // that sum up to the needed.

        for (int i = 0; i < len; i++) {
            ServicePermission x = (ServicePermission) perms.get(i);

            //System.out.println("  trying "+x);
            if (((needed & x.getMask()) != 0) && x.impliesIgnoreMask(np)) {
                effective |=  x.getMask();
                if ((effective & desired) == desired)
                    return true;
                needed = (desired ^ effective);
            }
        }
    }
    return false;
}
 
Example 30
private static PermissionCollection copy(PermissionCollection pc) {
  // TODO, provide a copy-on-write collection?!
  final Permissions pc2 = new Permissions();
  for (final Enumeration<Permission> e = pc.elements(); e.hasMoreElements();) {
    pc2.add(e.nextElement());
  }
  return pc2;
}