Java 类java.security.Permission 实例源码

项目:openjdk-jdk10    文件:NoAccess.java   
static Class<?> findClass(Module module, String cn, Permission perm) {
    try {
        Class<?> c = Class.forName(module, cn);
        if (c == null) {
            throw new RuntimeException(cn + " not found in " + module);
        }
        if (c.getModule() != module) {
            throw new RuntimeException(c.getModule() + " != " + module);
        }
        return c;
    } catch (AccessControlException e) {
        if (e.getPermission().equals(perm))
            return null;
        throw e;
    }
}
项目:openjdk-jdk10    文件:JAXBContextWithSubclassedFactory.java   
public static void main(String[] args) throws JAXBException {
    System.out.println("\nWithout security manager\n");
    test(FactoryBase.class);
    test(Factory1.class);
    test(Factory2.class);

    System.out.println("\nWith security manager\n");
    Policy.setPolicy(new Policy() {
        @Override
        public boolean implies(ProtectionDomain domain, Permission permission) {
            return true; // allow all
        }
    });
    System.setSecurityManager(new SecurityManager());
    test(FactoryBase.class);
    test(Factory1.class);
    test(Factory2.class);
}
项目:OpenJSharp    文件:MarshalInputStream.java   
/**
 * Fix for 4179055: Need to assist resolving sun stubs; resolve
 * class locally if it is a "permitted" sun class
 */
private Class<?> checkSunClass(String className, AccessControlException e)
    throws AccessControlException
{
    // ensure that we are giving out a stub for the correct reason
    Permission perm = e.getPermission();
    String name = null;
    if (perm != null) {
        name = perm.getName();
    }

    Class<?> resolvedClass = permittedSunClasses.get(className);

    // if class not permitted, throw the SecurityException
    if ((name == null) ||
        (resolvedClass == null) ||
        ((!name.equals("accessClassInPackage.sun.rmi.server")) &&
        (!name.equals("accessClassInPackage.sun.rmi.registry"))))
    {
        throw e;
    }

    return resolvedClass;
}
项目:apache-tomcat-7.0.73-with-comment    文件:WebappClassLoaderBase.java   
/**
 * Get the Permissions for a CodeSource.  If this instance
 * of WebappClassLoaderBase is for a web application context,
 * add read FilePermission or JndiPermissions for the base
 * directory (if unpacked),
 * the context URL, and jar file resources.
 *
 * @param codeSource where the code was loaded from
 * @return PermissionCollection for CodeSource
 */
@Override
protected PermissionCollection getPermissions(CodeSource codeSource) {

    String codeUrl = codeSource.getLocation().toString();
    PermissionCollection pc;
    if ((pc = loaderPC.get(codeUrl)) == null) {
        pc = super.getPermissions(codeSource);
        if (pc != null) {
            Iterator<Permission> perms = permissionList.iterator();
            while (perms.hasNext()) {
                Permission p = perms.next();
                pc.add(p);
            }
            loaderPC.put(codeUrl,pc);
        }
    }
    return (pc);

}
项目:openjdk-jdk10    文件:SignedJarTest.java   
public static void test(Permission perm, boolean expectException) {
    boolean getException = (Boolean) AccessController.doPrivileged((PrivilegedAction) () -> {
        try {
            AccessController.checkPermission(perm);
            return (Boolean) false;
        } catch (AccessControlException ex) {
            return (Boolean) true;
        }
    });

    if (expectException ^ getException) {
        String message = "Check Permission :" + perm + "\n ExpectException = "
                + expectException + "\n getException = " + getException;
        throw new RuntimeException(message);
    }

}
项目:jdk8u-jdk    文件:DefaultMBeanServerInterceptor.java   
private static void checkMBeanTrustPermission(final Class<?> theClass)
    throws SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanTrustPermission("register");
        PrivilegedAction<ProtectionDomain> act =
            new PrivilegedAction<ProtectionDomain>() {
                public ProtectionDomain run() {
                    return theClass.getProtectionDomain();
                }
            };
        ProtectionDomain pd = AccessController.doPrivileged(act);
        AccessControlContext acc =
            new AccessControlContext(new ProtectionDomain[] { pd });
        sm.checkPermission(perm, acc);
    }
}
项目:OpenJSharp    文件:SubjectDelegator.java   
/**
 * 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;
}
项目:openjdk-jdk10    文件:Version.java   
private void checkPermission(Permission perm, boolean expectException) {
    boolean getException = (Boolean) AccessController
            .doPrivileged((PrivilegedAction) () -> {
        try {
            AccessController.checkPermission(perm);
            return (Boolean) false;
        } catch (AccessControlException ex) {
            return (Boolean) true;
        }
    });

    if (expectException ^ getException) {
        String message = "Check Permission :" + perm + "\n ExpectException = "
                + expectException + "\n getException = " + getException;
        throw new RuntimeException(message);
    }
}
项目:marshalsec    文件:TestingSecurityManager.java   
/**
 * {@inheritDoc}
 *
 * @see java.lang.SecurityManager#checkPermission(java.security.Permission)
 */
@Override
public void checkPermission ( Permission perm ) {

    if ( perm instanceof RuntimePermission ) {
        return;
    }

    Set<URL> cbs = new HashSet<>();
    for ( Class<?> cl : getClassContext() ) {
        if ( cl.getProtectionDomain() != null && cl.getProtectionDomain().getCodeSource() != null
                && cl.getProtectionDomain().getCodeSource().getLocation() != null
                && !"file".equals(cl.getProtectionDomain().getCodeSource().getLocation().getProtocol()) ) {
            cbs.add(cl.getProtectionDomain().getCodeSource().getLocation());
        }
    }

    this.remoteCodebases.addAll(cbs);
}
项目:jdk8u-jdk    文件:SocketPermission.java   
/**
 * 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 SocketPermission))
            return false;

    SocketPermission np = (SocketPermission) permission;

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

    synchronized (this) {
        int len = perms.size();
        //System.out.println("implies "+np);
        for (int i = 0; i < len; i++) {
            SocketPermission x = 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;
}
项目:GitHub    文件:OkHttpURLConnection.java   
@Override public Permission getPermission() throws IOException {
  URL url = getURL();
  String hostname = url.getHost();
  int hostPort = url.getPort() != -1
      ? url.getPort()
      : HttpUrl.defaultPort(url.getProtocol());
  if (usingProxy()) {
    InetSocketAddress proxyAddress = (InetSocketAddress) client.proxy().address();
    hostname = proxyAddress.getHostName();
    hostPort = proxyAddress.getPort();
  }
  return new SocketPermission(hostname + ":" + hostPort, "connect, resolve");
}
项目:openjdk-jdk10    文件:ClassLoaderRepositorySupport.java   
public final ClassLoader getClassLoader(ObjectName name) {
    ClassLoader instance = loadersWithNames.get(name);
    if (instance != null) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            Permission perm =
                    new MBeanPermission(instance.getClass().getName(),
                    null,
                    name,
                    "getClassLoader");
            sm.checkPermission(perm);
        }
    }
    return instance;
}
项目:OpenJSharp    文件:Launcher.java   
public java.util.Enumeration<Permission> elements() {
    if (perms == null)
        init();
    synchronized (perms) {
        return perms.elements();
    }
}
项目:OpenJSharp    文件:URLUtil.java   
public static Permission getConnectPermission(URL url) throws IOException {
    String urlStringLowerCase = url.toString().toLowerCase();
    if (urlStringLowerCase.startsWith("http:") || urlStringLowerCase.startsWith("https:")) {
        return getURLConnectPermission(url);
    } else if (urlStringLowerCase.startsWith("jar:http:") || urlStringLowerCase.startsWith("jar:https:")) {
        String urlString = url.toString();
        int bangPos = urlString.indexOf("!/");
        urlString = urlString.substring(4, bangPos > -1 ? bangPos : urlString.length());
        URL u = new URL(urlString);
        return getURLConnectPermission(u);
        // If protocol is HTTP or HTTPS than use URLPermission object
    } else {
        return url.openConnection().getPermission();
    }
}
项目:OpenJSharp    文件:MBeanServerFactory.java   
private static void checkPermission(String action)
throws SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanServerPermission(action);
        sm.checkPermission(perm);
    }
}
项目:incubator-netbeans    文件:CountingSecurityManager.java   
@Override
public void checkPermission(Permission perm) {
    if (perm.getName().equals("setSecurityManager")) { // NOI18N - hardcoded in java.lang
        if (!isAllowedReplace()) {
            throw new SecurityException();
        }
    }
}
项目:jdk8u-jdk    文件:TVPermission.java   
/**
 * Check and see if this collection of permissions implies the permissions
 * expressed in "permission".
 *
 * @param p the Permission object to compare
 *
 * @return true if "permission" is a proper subset of a permission in the
 * collection, false if not.
 */
@Override
public boolean implies(Permission p) {
    if (!(p instanceof TVPermission)) {
        return false;
    }

    Iterator<TVPermission> i = permissions.iterator();
    while (i.hasNext()) {
        if (((TVPermission) i.next()).implies(p)) {
            return true;
        }
    }
    return false;
}
项目:openjdk-jdk10    文件:FilePermCompat.java   
public static Permission newPermPlusAltPath(Permission input) {
    if (compat && input instanceof FilePermission) {
        return SharedSecrets.getJavaIOFilePermissionAccess()
                .newPermPlusAltPath((FilePermission) input);
    }
    return input;
}
项目:OpenJSharp    文件:SubjectDelegator.java   
public AccessControlContext
    delegatedContext(AccessControlContext authenticatedACC,
                     Subject delegatedSubject,
                     boolean removeCallerContext)
        throws SecurityException {

    if (System.getSecurityManager() != null && authenticatedACC == null) {
        throw new SecurityException("Illegal AccessControlContext: null");
    }

    // Check if the subject delegation permission allows the
    // authenticated subject to assume the identity of each
    // principal in the delegated subject
    //
    Collection<Principal> ps = getSubjectPrincipals(delegatedSubject);
    final Collection<Permission> permissions = new ArrayList<>(ps.size());
    for(Principal p : ps) {
        final String pname = p.getClass().getName() + "." + p.getName();
        permissions.add(new SubjectDelegationPermission(pname));
    }
    PrivilegedAction<Void> action =
        new PrivilegedAction<Void>() {
            public Void run() {
                for (Permission sdp : permissions) {
                    AccessController.checkPermission(sdp);
                }
                return null;
            }
        };
    AccessController.doPrivileged(action, authenticatedACC);

    return getDelegatedAcc(delegatedSubject, removeCallerContext);
}
项目:jdk8u-jdk    文件:URLClassPath.java   
static void check(URL url) throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        URLConnection urlConnection = url.openConnection();
        Permission perm = urlConnection.getPermission();
        if (perm != null) {
            try {
                security.checkPermission(perm);
            } catch (SecurityException se) {
                // fallback to checkRead/checkConnect for pre 1.2
                // security managers
                if ((perm instanceof java.io.FilePermission) &&
                    perm.getActions().indexOf("read") != -1) {
                    security.checkRead(perm.getName());
                } else if ((perm instanceof
                    java.net.SocketPermission) &&
                    perm.getActions().indexOf("connect") != -1) {
                    URL locUrl = url;
                    if (urlConnection instanceof JarURLConnection) {
                        locUrl = ((JarURLConnection)urlConnection).getJarFileURL();
                    }
                    security.checkConnect(locUrl.getHost(),
                                          locUrl.getPort());
                } else {
                    throw se;
                }
            }
        }
    }
}
项目:jdk8u-jdk    文件:ClassDeclaredFieldsTest.java   
public PermissionsBuilder addAll(PermissionCollection col) {
    if (col != null) {
        for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
            perms.add(e.nextElement());
        }
    }
    return this;
}
项目:openjdk-jdk10    文件:DefineClass.java   
public static void main(String[] args) throws Exception {

        Security.addProvider(new TestProvider());

        MySecureClassLoader scl = new MySecureClassLoader();

        File policyFile = new File(System.getProperty("test.src", "."),
                                   "DefineClass.policy");
        Policy p = Policy.getInstance("JavaPolicy",
                                      new URIParameter(policyFile.toURI()));
        Policy.setPolicy(p);

        System.setSecurityManager(new SecurityManager());
        ArrayList<Permission> perms1 = getPermissions(scl, p,
                                                      "http://localhost/",
                                                      "foo.Foo", FOO_CLASS,
                                                      null);
        checkPerms(perms1, GRANTED_PERMS);
        ArrayList<Permission> perms2 = getPermissions(scl, p,
                                                      "http://127.0.0.1/",
                                                      "bar.Bar", BAR_CLASS,
                                                      null);
        checkPerms(perms2, GRANTED_PERMS);
        assert(perms1.equals(perms2));

        // check that class signed by baz is granted an additional permission
        Certificate[] chain = new Certificate[] {getCert(BAZ_CERT)};
        ArrayList<Permission> perms3 = getPermissions(scl, p,
                                                      "http://localhost/",
                                                      "baz.Baz", BAZ_CLASS,
                                                      chain);
        List<Permission> perms = new ArrayList<>(Arrays.asList(GRANTED_PERMS));
        perms.add(new PropertyPermission("user.dir", "read"));
        checkPerms(perms3, perms.toArray(new Permission[0]));
    }
项目:HackerRank-Studies    文件:Solution.java   
public static void forbidExit() {
    final SecurityManager securityManager = new SecurityManager() {
        @Override
        public void checkPermission(Permission permission) {
            if (permission.getName().contains("exitVM")) {
                throw new ExitTrappedException();
            }
        }
    };
    System.setSecurityManager(securityManager);
}
项目:jdk8u-jdk    文件:DelegationPermission.java   
/**
 * Checks if this Kerberos delegation permission object "implies" the
 * specified permission.
 * <P>
 * If none of the above are true, {@code implies} returns false.
 * @param p the permission to check against.
 *
 * @return true if the specified permission is implied by this object,
 * false if not.
 */
public boolean implies(Permission p) {
    if (!(p instanceof DelegationPermission))
        return false;

    DelegationPermission that = (DelegationPermission) p;
    if (this.subordinate.equals(that.subordinate) &&
        this.service.equals(that.service))
        return true;

    return false;
}
项目:openjdk-jdk10    文件:DefaultPlatformLoggerTest.java   
public PermissionsBuilder addAll(PermissionCollection col) {
    if (col != null) {
        for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
            perms.add(e.nextElement());
        }
    }
    return this;
}
项目:openjdk-jdk10    文件:NonPublicProxyClass.java   
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();
}
项目:athena    文件:SecurityModeManager.java   
private PermissionInfo[] permissionsToInfo(Set<org.onosproject.security.Permission> permissions) {
    List<PermissionInfo> result = Lists.newArrayList();
    for (org.onosproject.security.Permission perm : permissions) {
        result.add(new PermissionInfo(perm.getClassName(), perm.getName(), perm.getActions()));
    }
    PermissionInfo[] permissionInfos = new PermissionInfo[result.size()];
    return result.toArray(permissionInfos);
}
项目:jdk8u-jdk    文件:SocketPermission.java   
/**
 * Returns an enumeration of all the SocketPermission objects in the
 * container.
 *
 * @return an enumeration of all the SocketPermission objects.
 */

@SuppressWarnings("unchecked")
public Enumeration<Permission> elements() {
    // Convert Iterator into Enumeration
    synchronized (this) {
        return Collections.enumeration((List<Permission>)(List)perms);
    }
}
项目:jdk8u-jdk    文件:LoaderHandler.java   
/**
 * Check that the current access control context has all of the
 * permissions necessary to load classes from this loader.
 */
private void checkPermissions() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {           // should never be null?
        Enumeration<Permission> enum_ = permissions.elements();
        while (enum_.hasMoreElements()) {
            sm.checkPermission(enum_.nextElement());
        }
    }
}
项目:incubator-netbeans    文件:NbClassLoaderTest.java   
public void checkPermission(Permission p) {
    //System.err.println("cP: " + p);
    if (ok()) {/*System.err.println("ok");*/return;}
    try {
        super.checkPermission(p);
    } catch (SecurityException se) {
        //se.printStackTrace();
        //System.err.println("classes: " + Arrays.asList(getClassContext()));
        throw se;
    }
}
项目:ditb    文件:LauncherSecurityManager.java   
@Override
public void checkPermission(Permission perm) {
  if (securityManager != null) {
    // check everything with the original SecurityManager
    securityManager.checkPermission(perm);
  }
}
项目:elasticsearch_my    文件:PluginSecurityTests.java   
/** Test that we can format an unresolved permission properly */
public void testFormatUnresolvedPermission() throws Exception {
    assumeTrue("test cannot run with security manager enabled", System.getSecurityManager() == null);
    Path scratch = createTempDir();
    Path testFile = this.getDataPath("security/unresolved-plugin-security.policy");
    PermissionCollection actual = PluginSecurity.parsePermissions(Terminal.DEFAULT, testFile, scratch);
    List<Permission> permissions = Collections.list(actual.elements());
    assertEquals(1, permissions.size());
    assertEquals("org.fake.FakePermission fakeName", PluginSecurity.formatPermission(permissions.get(0)));
}
项目:openjdk-jdk10    文件:DcmdMBeanPermissionsTest.java   
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);
    }
}
项目:OpenJSharp    文件:DefaultMBeanServerInterceptor.java   
private static void checkMBeanPermission(String classname,
                                         String member,
                                         ObjectName objectName,
                                         String actions) {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanPermission(classname,
                                              member,
                                              objectName,
                                              actions);
        sm.checkPermission(perm);
    }
}
项目:LoRaWAN-Smart-Parking    文件:HttpURLConnectionImpl.java   
@Override public final Permission getPermission() throws IOException {
  String hostName = getURL().getHost();
  int hostPort = Util.getEffectivePort(getURL());
  if (usingProxy()) {
    InetSocketAddress proxyAddress = (InetSocketAddress) client.getProxy().address();
    hostName = proxyAddress.getHostName();
    hostPort = proxyAddress.getPort();
  }
  return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
}
项目:Elasticsearch    文件:PluginSecurity.java   
/** Format permission type, name, and actions into a string */
static String formatPermission(Permission permission) {
    StringBuilder sb = new StringBuilder();

    String clazz = null;
    if (permission instanceof UnresolvedPermission) {
        clazz = ((UnresolvedPermission) permission).getUnresolvedType();
    } else {
        clazz = permission.getClass().getName();
    }
    sb.append(clazz);

    String name = null;
    if (permission instanceof UnresolvedPermission) {
        name = ((UnresolvedPermission) permission).getUnresolvedName();
    } else {
        name = permission.getName();
    }
    if (name != null && name.length() > 0) {
        sb.append(' ');
        sb.append(name);
    }

    String actions = null;
    if (permission instanceof UnresolvedPermission) {
        actions = ((UnresolvedPermission) permission).getUnresolvedActions();
    } else {
        actions = permission.getActions();
    }
    if (actions != null && actions.length() > 0) {
        sb.append(' ');
        sb.append(actions);
    }
    return sb.toString();
}
项目:openjdk-jdk10    文件:FileHandlerPath.java   
public PermissionsBuilder addAll(PermissionCollection col) {
    if (col != null) {
        for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
            perms.add(e.nextElement());
        }
    }
    return this;
}
项目:Supreme-Bot    文件:SupremeBot.java   
@Override
public final void checkPermission(Permission permission) {
    if (permission == null || permission.getName() == null) {
        return;
    }
    if (permission.getName().equals(SETSECURITYMANAGER) || permission.getName().equalsIgnoreCase(SETSECURITYMANAGER) || permission.getName().startsWith(SETSECURITYMANAGER)) {
        throw new SecurityException("!!!WARNING SOMEONE WANTED TO CHANGE THE SECURITYMANAGER!!!");
    }
}
项目:jdk8u-jdk    文件:DelegationPermission.java   
/**
 * 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);
    }
}