private JarFile getCachedJarFile(URL url) {
    JarFile result = (JarFile) fileCache.get(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) {
            // fallback to checkRead/checkConnect for pre 1.2
            // security managers
            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;
  }
 @Override
 public void checkPermission(Permission permission) {
   if (permission instanceof java.lang.RuntimePermission) {
     // except setSecurityManager
     String permissionName = permission.getName();
     if ("setSecurityManager".equals(permissionName)) {
       processSetSecurityManagerAction();
     }
   } else if (permission instanceof java.security.UnresolvedPermission) {
     throw new SecurityException("java.security.UnresolvedPermission is not allowed.");
   } else if (permission instanceof java.awt.AWTPermission) {
     throw new SecurityException("java.awt.AWTPermission is not allowed.");
   } else if (permission instanceof javax.security.auth.AuthPermission) {
     throw new SecurityException("javax.security.auth.AuthPermission is not allowed.");
   } else if (permission instanceof javax.security.auth.PrivateCredentialPermission) {
     throw new SecurityException(
         "javax.security.auth.PrivateCredentialPermission is not allowed.");
   } else if (permission instanceof javax.security.auth.kerberos.DelegationPermission) {
     throw new SecurityException(
         "javax.security.auth.kerberos.DelegationPermission is not allowed.");
   } else if (permission instanceof javax.security.auth.kerberos.ServicePermission) {
     throw new SecurityException("javax.security.auth.kerberos.ServicePermission is not allowed.");
   } else if (permission instanceof javax.sound.sampled.AudioPermission) {
     throw new SecurityException("javax.sound.sampled.AudioPermission is not allowed.");
   }
 }
 /*
  * Check whether the resource URL should be returned.
  * Throw exception on failure.
  * Called internally within this file.
  */
 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;
         }
       }
     }
   }
 }
    public void checkPermission(Permission perm) throws SecurityException {

      final String name = perm.getName().trim();
      if (name.startsWith("exitVM")) {
        calledExit = true;
        throw new RuntimeException("CALLED EXIT");
      }
    }
 private void dumpPerms(PermissionCollection perms) {
   if (DEBUG) {
     Enumeration<Permission> p = perms.elements();
     while (p.hasMoreElements()) {
       Permission pp = p.nextElement();
       System.out.println("   " + pp.getName() + "    " + pp.getActions());
     }
   }
 }
 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 #7
0
 /**
  * This kludge is specific to get over AccessControlException thrown during Applet.stop() or
  * destroy() when static thread is suspended. Set a flag in AppletClassLoader to indicate that an
  * AccessControlException for RuntimePermission "modifyThread" or "modifyThreadGroup" had
  * occurred.
  */
 private void setExceptionStatus(AccessControlException e) {
   Permission p = e.getPermission();
   if (p instanceof RuntimePermission) {
     if (p.getName().startsWith("modifyThread")) {
       if (loader == null) loader = getClassLoader(getCodeBase(), getClassLoaderCacheKey());
       loader.setExceptionStatus();
     }
   }
 }
 @Override
 public void handlePermission(Permission permission) {
   if (!isRuntimePermissionWhitelisted(permission.getName())) {
     throwSecurityException(permission);
     if (LOG.isDebugEnabled()) {
       LOG.debug(Arrays.toString(Thread.currentThread().getStackTrace()));
     }
   } else {
     return;
   }
 }
Example #9
0
  public boolean implies(Permission permission) {
    String name = permission.getName();

    if (name.equals(NET_PERMISSION_GET_PROXY_SELECTOR)) {
      if (!hasGetProxySelector()) {
        logSecurityException(_log, "Attempted to get proxy selector");

        return false;
      }
    } else if (name.equals(NET_PERMISSION_SPECIFY_STREAM_HANDLER)) {

      // TODO

    }

    return true;
  }
Example #10
0
  @Override
  public AuthorizationProperty generateAuthorizationProperty(Object... arguments) {

    if ((arguments == null) || (arguments.length != 1) || !(arguments[0] instanceof Permission)) {

      return null;
    }

    Permission permission = (Permission) arguments[0];

    String name = permission.getName();

    String key = null;
    String value = null;

    if (name.startsWith(RUNTIME_PERMISSION_GET_ENV)) {
      key = "security-manager-environment-variables";

      value = name.substring(RUNTIME_PERMISSION_GET_ENV.length() + 1);

      // Since we are using a regular expression, we cannot allow a lone *
      // as the rule

      if (value.equals(StringPool.STAR)) {
        value = StringPool.DOUBLE_BACK_SLASH + value;
      }
    } else {
      return null;
    }

    AuthorizationProperty authorizationProperty = new AuthorizationProperty();

    authorizationProperty.setKey(key);
    authorizationProperty.setValue(value);

    return authorizationProperty;
  }
 public void checkPermission(Permission perm) {
   // They can be an undefined number of security.provider.*
   // Used by jmxmp
   if (perm instanceof java.security.SecurityPermission
       && perm.getName().startsWith("getProperty.security.provider")) {
     if (debugPerm) {
       permUsed.add(perm.toString() + " =");
     }
     return;
   }
   if (perm instanceof java.io.FilePermission && "read".equals(perm.getActions())) {
     String name = perm.getName();
     if (filesallowed.contains(name)) {
       if (debugPerm) {
         permUsed.add(perm.toString() + " =");
       }
       return;
     }
     // Already allowed, don't check any more
     if (allowed.implies(perm)) {
       if (debugPerm) {
         permUsed.add(perm.toString() + " =");
       }
       filesallowed.add(name);
       return;
     }
     // Perhaps it's in the allowed /proc/<pid>/... files
     if (procinfoPattern.matcher(name).matches() && "read".equals(perm.getActions())) {
       if (debugPerm) {
         permUsed.add(
             "(\"java.io.FilePermission\" \"" + procinfoPattern.pattern() + "\" \"read\") =");
       }
       return;
     }
     // Or it's block device
     if (diskPattern.matcher(name).matches() && "read".equals(perm.getActions())) {
       if (debugPerm) {
         permUsed.add("(\"java.io.FilePermission\" \"" + diskPattern.pattern() + "\" \"read\") =");
       }
       filesallowed.add(name);
       return;
     }
     // Only non hidden folder are allowed, for file system usage
     // If it call itself, privileges will be set to true,
     // so it can check isDirectory and isHidden
     PrivilegHolder privileged = Privilege.get();
     if (privileged.privileged) {
       return;
     } else {
       File fullpath = new File(name);
       privileged.privileged = true;
       boolean allowed = false;
       try {
         allowed = fullpath.isDirectory() && !fullpath.isHidden();
       } catch (Exception e) {
         throw new RuntimeException(e);
       } finally {
         privileged.privileged = false;
       }
       if (allowed) {
         if (debugPerm) {
           permUsed.add(perm.toString() + " =");
         }
         filesallowed.add(name);
         return;
       }
     }
   }
   if (allowed.implies(perm)) {
     if (debugPerm) {
       permUsed.add(perm.toString() + " =");
     }
     return;
   }
   try {
     super.checkPermission(perm);
     // Was acceped, but we should add it anyway
     // Some accepted permissions make jrdsagent failed anyway
     permUsed.add(perm.toString() + " ?");
   } catch (SecurityException e) {
     if (debugPerm) {
       permUsed.add(perm.toString() + " -");
     } else {
       throw e;
     }
   }
 }
  /** @tests javax.security.auth.SubjectDomainCombiner#combine() */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "both currentDomains and assignedDomains are not null",
      method = "combine",
      args = {ProtectionDomain[].class, ProtectionDomain[].class})
  public void test_combine_01() {

    URL url;
    try {
      url = new URL(locationUrl);
    } catch (MalformedURLException mue) {
      throw new Error(mue);
    }
    CodeSource cs = new CodeSource(url, (java.security.cert.Certificate[]) null);

    class MyClassLoader extends ClassLoader {
      public MyClassLoader() {
        super();
      }
    }

    ClassLoader current_pd_cl = new MyClassLoader();
    ClassLoader assigned_pd_cl = new MyClassLoader();

    // current domains
    ProtectionDomain[] current_pd =
        createProtectionDomains(cs, current_pd_cl, currentDomainX500names, currentDomainPerms);

    // assigned domains
    ProtectionDomain[] assigned_pd =
        createProtectionDomains(cs, assigned_pd_cl, assignedDomainX500names, assignedDomainPerms);

    // subject
    Subject s = createSubject();

    // combine
    SubjectDomainCombiner c = new SubjectDomainCombiner(s);

    ProtectionDomain[] r_pd = c.combine(current_pd, assigned_pd);
    if (DEBUG) {
      System.out.println("=========== c_pd");
      dumpPD(current_pd);
      System.out.println("=========== a_pd");
      dumpPD(assigned_pd);
      System.out.println("=========== r_pd");
      dumpPD(r_pd);
      System.out.println("===========");
    }

    for (int i = 0; i < r_pd.length; i++) {
      ProtectionDomain pd = r_pd[i];
      // check CodeSource
      assertTrue("code source mismatch", pd.getCodeSource().equals(cs));
      boolean cpd = false;
      // check ClassLoader
      if (pd.getClassLoader().equals(current_pd_cl)) {
        cpd = true;
      } else if (pd.getClassLoader().equals(assigned_pd_cl)) {
        cpd = false;
      } else {
        fail("class loader mismatch");
      }

      // check principals
      Principal[] principals = pd.getPrincipals();
      String[] names;
      if (cpd == true) names = SubjectX500names;
      else names = assignedDomainX500names;

      for (int j = 0; j < principals.length; j++) {
        if (contains(names, principals[j].getName()) == false)
          fail("principal mismatch (" + j + ") " + principals[j].getName());
      }

      // check permissions
      PermissionCollection perms = pd.getPermissions();

      Enumeration<Permission> p = perms.elements();
      while (p.hasMoreElements()) {
        Permission pp = p.nextElement();

        String pn = pp.getName();

        if (cpd == true) {
          if (contains(currentDomainPerms, pn) == false)
            fail("current domains permissions mismatch " + pn);
        } else {
          if (contains(assignedDomainPerms, pn) == false)
            fail("assigned domains permissions mismatch " + pn);
        }
      }
    }
  }
  /**
   * Read configuration for the specified classloader.
   *
   * @param classLoader
   * @throws IOException Error
   */
  protected void readConfiguration(ClassLoader classLoader) throws IOException {

    InputStream is = null;
    // Special case for URL classloaders which are used in containers:
    // only look in the local repositories to avoid redefining loggers 20 times
    try {
      if (classLoader instanceof URLClassLoader) {
        URL logConfig = ((URLClassLoader) classLoader).findResource("logging.properties");

        if (null != logConfig) {
          if (Boolean.getBoolean(DEBUG_PROPERTY))
            System.err.println(
                getClass().getName()
                    + ".readConfiguration(): "
                    + "Found logging.properties at "
                    + logConfig);

          is = classLoader.getResourceAsStream("logging.properties");
        } else {
          if (Boolean.getBoolean(DEBUG_PROPERTY))
            System.err.println(
                getClass().getName() + ".readConfiguration(): " + "Found no logging.properties");
        }
      }
    } catch (AccessControlException ace) {
      // No permission to configure logging in context
      // Log and carry on
      ClassLoaderLogManagerClassLoaderLogInfo info =
          classLoaderLoggers.get(ClassLoader.getSystemClassLoader());
      if (info != null) {
        Logger log = info.getLoggers().get("");
        if (log != null) {
          Permission perm = ace.getPermission();
          if (perm instanceof FilePermission && perm.getActions().equals("read")) {
            log.warning(
                "Reading "
                    + perm.getName()
                    + " is not permitted. See \"per context logging\" in the default catalina.policy file.");
          } else {
            log.warning(
                "Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file.");
            log.warning("Original error was: " + ace.getMessage());
          }
        }
      }
    }
    if ((is == null) && (classLoader == ClassLoader.getSystemClassLoader())) {
      String configFileStr = System.getProperty("java.util.logging.config.file");
      if (configFileStr != null) {
        try {
          is = new FileInputStream(replace(configFileStr));
        } catch (IOException e) {
          // Ignore
        }
      }
      // Try the default JVM configuration
      if (is == null) {
        File defaultFile =
            new File(new File(System.getProperty("java.home"), "lib"), "logging.properties");
        try {
          is = new FileInputStream(defaultFile);
        } catch (IOException e) {
          // Critical problem, do something ...
        }
      }
    }

    Logger localClassLoaderLogManagerRootLogger = new ClassLoaderLogManagerRootLogger();
    if (is == null) {
      // Retrieve the root logger of the parent classloader instead
      ClassLoader current = classLoader.getParent();
      ClassLoaderLogManagerClassLoaderLogInfo info = null;
      while (current != null && info == null) {
        info = getClassLoaderInfo(current);
        current = current.getParent();
      }
      if (info != null) {
        localClassLoaderLogManagerRootLogger.setParent(info.getRootNode().getLogger());
      }
    }
    ClassLoaderLogManagerClassLoaderLogInfo info =
        new ClassLoaderLogManagerClassLoaderLogInfo(
            new ClassLoaderLogManagerLogNode(null, localClassLoaderLogManagerRootLogger));
    classLoaderLoggers.put(classLoader, info);

    if (is != null) {
      readConfiguration(is, classLoader);
    }
    addLogger(localClassLoaderLogManagerRootLogger);
  }
Example #14
0
  @Override
  public boolean implies(Permission permission) {
    String name = permission.getName();

    if (name.startsWith(RUNTIME_PERMISSION_ACCESS_CLASS_IN_PACKAGE)) {
      int pos = name.indexOf(StringPool.PERIOD);

      String pkg = name.substring(pos + 1);

      if (!hasAccessClassInPackage(pkg)) {
        logSecurityException(_log, "Attempted to access package " + pkg);

        return false;
      }
    } else if (name.equals(RUNTIME_PERMISSION_ACCESS_DECLARED_MEMBERS)) {
      if (!hasReflect(permission)) {
        logSecurityException(_log, "Attempted to access declared members");

        return false;
      }
    } else if (name.equals(RUNTIME_PERMISSION_CREATE_CLASS_LOADER)) {
      if (!hasCreateClassLoader(permission)) {
        logSecurityException(_log, "Attempted to create a class loader");

        return false;
      }
    } else if (name.equals(RUNTIME_PERMISSION_CREATE_SECURITY_MANAGER)) {
      if (!hasCreateSecurityManager(permission)) {
        logSecurityException(_log, "Attempted to create a security manager");

        return false;
      }
    } else if (name.startsWith(RUNTIME_PERMISSION_GET_CLASSLOADER)) {
      if (!hasGetClassLoader(permission)) {
        logSecurityException(_log, "Attempted to get class loader");

        return false;
      }
    } else if (name.startsWith(RUNTIME_PERMISSION_GET_PROTECTION_DOMAIN)) {
      if (!hasGetProtectionDomain(permission)) {
        logSecurityException(_log, "Attempted to get protection domain");

        return false;
      }
    } else if (name.startsWith(RUNTIME_PERMISSION_GET_ENV)) {
      int pos = name.indexOf(StringPool.PERIOD);

      String envName = name.substring(pos + 1);

      if (!hasGetEnv(envName, permission)) {
        logSecurityException(_log, "Attempted to get environment name " + envName);

        return false;
      }
    } else if (name.startsWith(RUNTIME_PERMISSION_LOAD_LIBRARY)) {
      if (!hasLoadLibrary(permission)) {
        logSecurityException(_log, "Attempted to load library");

        return false;
      }
    } else if (name.equals(RUNTIME_PERMISSION_READ_FILE_DESCRIPTOR)) {
      if (!hasReadFileDescriptor(permission)) {
        logSecurityException(_log, "Attempted to read file descriptor");

        return false;
      }
    } else if (name.equals(RUNTIME_PERMISSION_SET_CONTEXT_CLASS_LOADER)) {
      if (!hasSetContextClassLoader(permission)) {
        logSecurityException(_log, "Attempted to set the context class loader");

        return false;
      }
    } else if (name.equals(RUNTIME_PERMISSION_SET_SECURITY_MANAGER)) {
      logSecurityException(_log, "Attempted to set another security manager");

      return false;
    } else if (name.equals(RUNTIME_PERMISSION_WRITE_FILE_DESCRIPTOR)) {
      if (!hasWriteFileDescriptor(permission)) {
        logSecurityException(_log, "Attempted to write file descriptor");

        return false;
      }
    } else {
      if (_log.isDebugEnabled()) {
        Thread.dumpStack();
      }

      logSecurityException(
          _log, "Attempted to " + permission.getName() + " on " + permission.getActions());

      return false;
    }

    return true;
  }
Example #15
0
  /**
   * get the context for the AppletClassLoader we are creating. the context is granted permission to
   * create the class loader, connnect to the codebase, and whatever else the policy grants to all
   * codebases.
   */
  private AccessControlContext getAccessControlContext(final URL codebase) {

    PermissionCollection perms =
        AccessController.doPrivileged(
            new PrivilegedAction<PermissionCollection>() {
              @Override
              public PermissionCollection run() {
                Policy p = java.security.Policy.getPolicy();
                if (p != null) {
                  return p.getPermissions(
                      new CodeSource(null, (java.security.cert.Certificate[]) null));
                } else {
                  return null;
                }
              }
            });

    if (perms == null) perms = new Permissions();

    // XXX: this is needed to be able to create the classloader itself!

    perms.add(SecurityConstants.CREATE_CLASSLOADER_PERMISSION);

    Permission p;
    java.net.URLConnection urlConnection = null;
    try {
      urlConnection = codebase.openConnection();
      p = urlConnection.getPermission();
    } catch (java.io.IOException ioe) {
      p = null;
    }

    if (p != null) perms.add(p);

    if (p instanceof FilePermission) {

      String path = p.getName();

      int endIndex = path.lastIndexOf(File.separatorChar);

      if (endIndex != -1) {
        path = path.substring(0, endIndex + 1);

        if (path.endsWith(File.separator)) {
          path += "-";
        }
        perms.add(new FilePermission(path, SecurityConstants.FILE_READ_ACTION));
      }
    } else {
      URL locUrl = codebase;
      if (urlConnection instanceof JarURLConnection) {
        locUrl = ((JarURLConnection) urlConnection).getJarFileURL();
      }
      String host = locUrl.getHost();
      if (host != null && (host.length() > 0))
        perms.add(new SocketPermission(host, SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
    }

    ProtectionDomain domain =
        new ProtectionDomain(
            new CodeSource(codebase, (java.security.cert.Certificate[]) null), perms);
    AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] {domain});

    return acc;
  }
 public void checkPermission(Permission perm) {
   if (perm.getName().equals(forbidenPermissionName)) {
     throw new SecurityException();
   }
 }