Example #1
0
  static void addBindPermissions(Permissions policy, Settings settings) throws IOException {
    // http is simple
    String httpRange = HttpTransportSettings.SETTING_HTTP_PORT.get(settings).getPortRangeString();
    // listen is always called with 'localhost' but use wildcard to be sure, no name service is
    // consulted.
    // see SocketPermission implies() code
    policy.add(new SocketPermission("*:" + httpRange, "listen,resolve"));
    // transport is waaaay overengineered
    Map<String, Settings> profiles =
        TransportSettings.TRANSPORT_PROFILES_SETTING.get(settings).getAsGroups();
    if (!profiles.containsKey(TransportSettings.DEFAULT_PROFILE)) {
      profiles = new HashMap<>(profiles);
      profiles.put(TransportSettings.DEFAULT_PROFILE, Settings.EMPTY);
    }

    // loop through all profiles and add permissions for each one, if its valid.
    // (otherwise NettyTransport is lenient and ignores it)
    for (Map.Entry<String, Settings> entry : profiles.entrySet()) {
      Settings profileSettings = entry.getValue();
      String name = entry.getKey();
      String transportRange = profileSettings.get("port", TransportSettings.PORT.get(settings));

      // a profile is only valid if its the default profile, or if it has an actual name and
      // specifies a port
      boolean valid =
          TransportSettings.DEFAULT_PROFILE.equals(name)
              || (Strings.hasLength(name) && profileSettings.get("port") != null);
      if (valid) {
        // listen is always called with 'localhost' but use wildcard to be sure, no name service is
        // consulted.
        // see SocketPermission implies() code
        policy.add(new SocketPermission("*:" + transportRange, "listen,resolve"));
      }
    }
  }
  public ScriptingSecurityManager(
      boolean pWithoutFileRestriction,
      boolean pWithoutWriteRestriction,
      boolean pWithoutNetworkRestriction,
      boolean pWithoutExecRestriction) {
    permissions = new Permissions();
    if (pWithoutExecRestriction
        && pWithoutFileRestriction
        && pWithoutWriteRestriction
        && pWithoutNetworkRestriction) {
      permissions.add(new AllPermission());
    } else {
      if (pWithoutNetworkRestriction) {
        permissions.add(new SocketPermission("*", "connect,accept,listen,resolve"));
        permissions.add(new RuntimePermission("setFactory"));
      }

      if (pWithoutExecRestriction) {
        permissions.add(new FilePermission("<<ALL FILES>>", "execute"));
        permissions.add(new RuntimePermission("loadLibrary.*"));
      }
      if (pWithoutFileRestriction) {
        permissions.add(new FilePermission("<<ALL FILES>>", "read"));
        permissions.add(new RuntimePermission("readFileDescriptor"));
      }

      if (pWithoutWriteRestriction) {
        permissions.add(new RuntimePermission("writeFileDescriptor"));
        permissions.add(new FilePermission("<<ALL FILES>>", "write,delete"));
        permissions.add(new RuntimePermission("preferences"));
      }
    }
    permissions.setReadOnly();
  }
  /**
   * Create permission for groovy scripts of the {@link ScriptingOperator}.
   *
   * @return the permissions, never {@code null}
   */
  private static PermissionCollection createGroovySourcePermissions() {
    Permissions permissions = new Permissions();

    // grant some permissions because the script is something the user himself created
    permissions.add(new PropertyPermission("*", "read, write"));
    permissions.add(new FilePermission("<<ALL FILES>>", "read, write, delete"));

    addCommonPermissions(permissions);

    return permissions;
  }
  /**
   * Create permission for unsigned extensions.
   *
   * @param loader the plugin class loader of the unsigned extensions
   * @return the permissions, never {@code null}
   */
  private static PermissionCollection createUnsignedPermissions(final PluginClassLoader loader) {
    final Permissions permissions = new Permissions();

    permissions.add(new RuntimePermission("shutdownHooks"));

    permissions.add(new PropertyPermission("*", "read"));

    AccessController.doPrivileged(
        new PrivilegedAction<Void>() {

          @Override
          public Void run() {
            String userHome = System.getProperty("user.home");
            String tmpDir = System.getProperty("java.io.tmpdir");
            String pluginKey = loader.getPluginKey();

            // delete access to the general temp directory
            permissions.add(new FilePermission(tmpDir, "read, write"));
            permissions.add(new FilePermission(tmpDir + "/-", "read, write, delete"));

            // extensions can only delete files in their own subfolder of the
            // .RapidMiner/extensions/workspace folder
            if (pluginKey != null) {
              String pluginFolder = pluginKey;

              permissions.add(new FilePermission(userHome + "/.RapidMiner/extensions", "read"));
              permissions.add(
                  new FilePermission(userHome + "/.RapidMiner/extensions/workspace", "read"));
              permissions.add(
                  new FilePermission(
                      userHome + "/.RapidMiner/extensions/workspace/" + pluginFolder,
                      "read, write"));
              permissions.add(
                  new FilePermission(
                      userHome + "/.RapidMiner/extensions/workspace/" + pluginFolder + "/-",
                      "read, write, delete"));
            }

            // unfortunately currently we have to give all location permissons to read/write
            // files to not block extensions that add "Read/Write xyz" operators
            permissions.add(new FilePermission("<<ALL FILES>>", "read, write"));
            return null;
          }
        });

    addCommonPermissions(permissions);

    return permissions;
  }
Example #5
0
  /**
   * Add access to path (and all files underneath it)
   *
   * @param policy current policy to add permissions to
   * @param configurationName the configuration name associated with the path (for error messages
   *     only)
   * @param path the path itself
   * @param permissions set of filepermissions to grant to the path
   */
  static void addPath(Permissions policy, String configurationName, Path path, String permissions) {
    // paths may not exist yet, this also checks accessibility
    try {
      ensureDirectoryExists(path);
    } catch (IOException e) {
      throw new IllegalStateException(
          "Unable to access '" + configurationName + "' (" + path + ")", e);
    }

    // add each path twice: once for itself, again for files underneath it
    policy.add(new FilePermission(path.toString(), permissions));
    policy.add(
        new FilePermission(
            path.toString() + path.getFileSystem().getSeparator() + "-", permissions));
  }
Example #6
0
 /**
  * Add access to a directory iff it exists already
  *
  * @param policy current policy to add permissions to
  * @param configurationName the configuration name associated with the path (for error messages
  *     only)
  * @param path the path itself
  * @param permissions set of filepermissions to grant to the path
  */
 static void addPathIfExists(
     Permissions policy, String configurationName, Path path, String permissions) {
   if (Files.isDirectory(path)) {
     // add each path twice: once for itself, again for files underneath it
     policy.add(new FilePermission(path.toString(), permissions));
     policy.add(
         new FilePermission(
             path.toString() + path.getFileSystem().getSeparator() + "-", permissions));
     try {
       path.getFileSystem().provider().checkAccess(path.toRealPath(), AccessMode.READ);
     } catch (IOException e) {
       throw new IllegalStateException(
           "Unable to access '" + configurationName + "' (" + path + ")", e);
     }
   }
 }
  @Test
  public void testAccessController1() throws Exception {
    try {
      Permissions permissions = new Permissions();

      permissions.add(new AllPermission());

      ProtectionDomain[] protectionDomains =
          new ProtectionDomain[] {new ProtectionDomain(null, permissions)};

      AccessControlContext accessControlContext = new AccessControlContext(protectionDomains);

      AccessController.doPrivileged(
          new PrivilegedAction<Void>() {

            @Override
            public Void run() {
              new URLClassLoader(new URL[0]);

              return null;
            }
          },
          accessControlContext);

      Assert.fail();
    } catch (SecurityException se) {
    }
  }
Example #8
0
 /** returns dynamic Permissions to configured paths */
 static void addFilePermissions(Permissions policy, Environment environment) throws IOException {
   // read-only dirs
   addPath(policy, "path.home", environment.binFile(), "read,readlink");
   addPath(policy, "path.home", environment.libFile(), "read,readlink");
   addPath(policy, "path.plugins", environment.pluginsFile(), "read,readlink");
   addPath(policy, "path.conf", environment.configFile(), "read,readlink");
   addPath(policy, "path.scripts", environment.scriptsFile(), "read,readlink");
   // read-write dirs
   addPath(policy, "java.io.tmpdir", environment.tmpFile(), "read,readlink,write,delete");
   addPath(policy, "path.logs", environment.logsFile(), "read,readlink,write,delete");
   if (environment.sharedDataFile() != null) {
     addPath(
         policy, "path.shared_data", environment.sharedDataFile(), "read,readlink,write,delete");
   }
   for (Path path : environment.dataFiles()) {
     addPath(policy, "path.data", path, "read,readlink,write,delete");
   }
   for (Path path : environment.dataWithClusterFiles()) {
     addPath(policy, "path.data", path, "read,readlink,write,delete");
   }
   for (Path path : environment.repoFiles()) {
     addPath(policy, "path.repo", path, "read,readlink,write,delete");
   }
   if (environment.pidFile() != null) {
     // we just need permission to remove the file if its elsewhere.
     policy.add(new FilePermission(environment.pidFile().toString(), "delete"));
   }
 }
  public void testSecuredEngine() throws Exception {
    PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer();

    // jython seems to need these two..
    Permissions perms = new Permissions();
    perms.add(new RuntimePermission("createClassLoader"));
    perms.add(new RuntimePermission("getProtectionDomain"));

    // add permission to read files so that modules can be loaded, but writing should fail
    perms.add(new FilePermission("<<ALL FILES>>", "read"));

    ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), perms);

    try {
      engine.eval("import os\nfp = open('pom.xml', 'w')");
      Assert.fail("Opening a file for writing should have failed with a security exception.");
    } catch (ScriptException e) {
      checkIsCausedByAccessControlException(e);
    }
  }
Example #10
0
  private final void loadExtension(Extension ext) {
    final String id = ext.getDeclaringPluginDescriptor().getId();
    final URL url;
    try {
      // note: ".../-" match everything starting with "plugin:" + id + "!/"
      url = new URL("plugin:" + id + "!/-");
      final ClassLoader cl = ext.getDeclaringPluginDescriptor().getPluginClassLoader();
      final CodeSource cs = new CodeSource(url, (Certificate[]) null);
      final Permissions perms = new Permissions();
      codeSource2Permissions.put(cs, perms);
      // BootLogInstance.get().debug("Adding permissions for " + cs);
      final ConfigurationElement[] elems = ext.getConfigurationElements();
      final int count = elems.length;
      for (int i = 0; i < count; i++) {
        final ConfigurationElement elem = elems[i];
        final String type = elem.getAttribute("class");
        final String name = elem.getAttribute("name");
        final String actions = elem.getAttribute("actions");

        if (type != null) {
          final Object perm;
          try {
            final Class permClass = cl.loadClass(type);
            if ((name != null) && (actions != null)) {
              final Constructor c = permClass.getConstructor(NAME_ACTIONS_ARGS);
              perm = c.newInstance(new Object[] {name, actions});
            } else if (name != null) {
              final Constructor c = permClass.getConstructor(NAME_ARGS);
              perm = c.newInstance(new Object[] {name});
            } else {
              perm = permClass.newInstance();
            }
            final Permission p = (Permission) perm;
            perms.add(p);
          } catch (ClassNotFoundException ex) {
            BootLogInstance.get().error("Permission class " + type + " not found");
          } catch (InstantiationException ex) {
            BootLogInstance.get().error("Cannot instantiate permission class " + type);
          } catch (IllegalAccessException ex) {
            BootLogInstance.get().error("Illegal access to permission class " + type);
          } catch (NoSuchMethodException ex) {
            BootLogInstance.get()
                .error("Constructor not found on permission class " + type + " in plugin " + id);
          } catch (InvocationTargetException ex) {
            BootLogInstance.get().error("Error constructing permission class " + type, ex);
          } catch (ClassCastException ex) {
            BootLogInstance.get().error("Permission class " + type + " not instance of Permission");
          }
        }
      }
    } catch (MalformedURLException ex) {
      BootLogInstance.get().error("Cannot create plugin codesource", ex);
    }
  }
Example #11
0
 /** Adds access to classpath jars/classes for jar hell scan, etc */
 @SuppressForbidden(reason = "accesses fully qualified URLs to configure security")
 static void addClasspathPermissions(Permissions policy) throws IOException {
   // add permissions to everything in classpath
   // really it should be covered by lib/, but there could be e.g. agents or similar configured)
   for (URL url : JarHell.parseClassPath()) {
     Path path;
     try {
       path = PathUtils.get(url.toURI());
     } catch (URISyntaxException e) {
       throw new RuntimeException(e);
     }
     // resource itself
     policy.add(new FilePermission(path.toString(), "read,readlink"));
     // classes underneath
     if (Files.isDirectory(path)) {
       policy.add(
           new FilePermission(
               path.toString() + path.getFileSystem().getSeparator() + "-", "read,readlink"));
     }
   }
 }
 public EscalateCreateClassLoader() throws Exception {
   ByteArrayOutputStream payloadStream = new ByteArrayOutputStream();
   Class payloadClass = EscalateCreateClassLoaderPayload.class;
   StreamForwarder.forward(
       payloadClass.getResourceAsStream("/" + payloadClass.getName().replace('.', '/') + ".class"),
       payloadStream);
   byte[] payload = payloadStream.toByteArray();
   final Permissions permissions = new Permissions();
   permissions.add(new AllPermission());
   final ProtectionDomain pd =
       new ProtectionDomain(new CodeSource(new URL("file:///"), new Certificate[0]), permissions);
   defineClass(null, payload, 0, payload.length, pd).newInstance();
 }
Example #13
0
 /** Adds access to all configurable paths. */
 static void addFilePermissions(Permissions policy, Environment environment) {
   // read-only dirs
   addPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.binFile(), "read,readlink");
   addPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.libFile(), "read,readlink");
   addPath(
       policy, Environment.PATH_HOME_SETTING.getKey(), environment.modulesFile(), "read,readlink");
   addPath(
       policy, Environment.PATH_HOME_SETTING.getKey(), environment.pluginsFile(), "read,readlink");
   addPath(
       policy, Environment.PATH_CONF_SETTING.getKey(), environment.configFile(), "read,readlink");
   addPath(
       policy,
       Environment.PATH_SCRIPTS_SETTING.getKey(),
       environment.scriptsFile(),
       "read,readlink");
   // read-write dirs
   addPath(policy, "java.io.tmpdir", environment.tmpFile(), "read,readlink,write,delete");
   addPath(
       policy,
       Environment.PATH_LOGS_SETTING.getKey(),
       environment.logsFile(),
       "read,readlink,write,delete");
   if (environment.sharedDataFile() != null) {
     addPath(
         policy,
         Environment.PATH_SHARED_DATA_SETTING.getKey(),
         environment.sharedDataFile(),
         "read,readlink,write,delete");
   }
   for (Path path : environment.dataFiles()) {
     addPath(policy, Environment.PATH_DATA_SETTING.getKey(), path, "read,readlink,write,delete");
   }
   // TODO: this should be removed in ES 6.0! We will no longer support data paths with the cluster
   // as a folder
   assert Version.CURRENT.major < 6 : "cluster name is no longer used in data path";
   for (Path path : environment.dataWithClusterFiles()) {
     addPathIfExists(
         policy, Environment.PATH_DATA_SETTING.getKey(), path, "read,readlink,write,delete");
   }
   for (Path path : environment.repoFiles()) {
     addPath(policy, Environment.PATH_REPO_SETTING.getKey(), path, "read,readlink,write,delete");
   }
   if (environment.pidFile() != null) {
     // we just need permission to remove the file if its elsewhere.
     policy.add(new FilePermission(environment.pidFile().toString(), "delete"));
   }
 }
Example #14
0
 public PermissionCollection getPermissions(CodeSource codeSource) {
   Permissions perms = new Permissions();
   for (Iterator it = cs2pc.entrySet().iterator(); it.hasNext(); ) {
     Map.Entry e = (Map.Entry) it.next();
     CodeSource cs = (CodeSource) e.getKey();
     if (cs.implies(codeSource)) {
       logger.log(Component.POLICY, "{0} -> {1}", new Object[] {cs, codeSource});
       PermissionCollection pc = (PermissionCollection) e.getValue();
       for (Enumeration ee = pc.elements(); ee.hasMoreElements(); ) {
         perms.add((Permission) ee.nextElement());
       }
     } else logger.log(Component.POLICY, "{0} !-> {1}", new Object[] {cs, codeSource});
   }
   logger.log(
       Component.POLICY, "returning permissions {0} for {1}", new Object[] {perms, codeSource});
   return perms;
 }
 public TunnelInitializerLoader(Stager stager, Object[] args) throws Exception {
   super(TunnelInitializerLoader.class.getClassLoader());
   Permissions permissions = new Permissions();
   byte[] classBytes = (byte[]) args[1];
   permissions.add(new AllPermission());
   Class clazz =
       defineClass(
           null,
           classBytes,
           0,
           classBytes.length,
           new ProtectionDomain(
               new CodeSource(new URL("file:///"), new Certificate[0]), permissions));
   clazz
       .getConstructor(new Class[] {Stager.class, Object[].class})
       .newInstance(new Object[] {stager, args});
 }
Example #16
0
 private Permissions getPermissions() {
   final Permissions ps = new Permissions();
   ps.add(new AWTPermission("accessEventQueue"));
   ps.add(new PropertyPermission("user.home", "read"));
   ps.add(new PropertyPermission("java.vendor", "read"));
   ps.add(new PropertyPermission("java.version", "read"));
   ps.add(new PropertyPermission("os.name", "read"));
   ps.add(new PropertyPermission("os.arch", "read"));
   ps.add(new PropertyPermission("os.version", "read"));
   ps.add(new SocketPermission("*", "connect,resolve"));
   String uDir = System.getProperty("user.home");
   if (uDir != null) {
     uDir += "/";
   } else {
     uDir = "~/";
   }
   final String[] dirs = {
     "c:/rscache/", "/rscache/", "c:/windows/", "c:/winnt/", "c:/", uDir, "/tmp/", "."
   };
   final String[] rsDirs = {".jagex_cache_32", ".file_store_32"};
   for (String dir : dirs) {
     final File f = new File(dir);
     ps.add(new FilePermission(dir, "read"));
     if (!f.exists()) {
       continue;
     }
     dir = f.getPath();
     for (final String rsDir : rsDirs) {
       ps.add(new FilePermission(dir + File.separator + rsDir + File.separator + "-", "read"));
       ps.add(new FilePermission(dir + File.separator + rsDir + File.separator + "-", "write"));
     }
   }
   Calendar.getInstance();
   // TimeZone.getDefault();//Now the default is set they don't need permission
   // ps.add(new FilePermission())
   ps.setReadOnly();
   return ps;
 }
  public AgentSecurityManager(boolean debugPerm, PROTOCOL proto) {
    this.debugPerm = debugPerm;

    if (debugPerm) {
      permUsed = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
      permCreated = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
      Runtime.getRuntime()
          .addShutdownHook(
              new Thread() {
                public void run() {
                  for (String i : new HashSet<String>(permCreated)) {
                    if (permUsed.contains(i + " =")) {
                      permCreated.remove(i);
                    }
                  }
                  for (String i : permCreated) {
                    permUsed.add(i + " +");
                  }

                  for (String p : new TreeSet<String>(permUsed)) {
                    System.out.println(p);
                  }
                }
              });
    } else {
      permUsed = null;
      permCreated = null;
    }

    // Add the java home to readable files
    Permission newPerm =
        new FilePermission(System.getProperty("java.home") + File.separator + "-", "read");
    allowed.add(newPerm);
    if (debugPerm) {
      permCreated.add(newPerm.toString());
    }

    Map<String, Set<Permission>> permsSets;
    try {
      permsSets = getPermsSets();
    } catch (SecurityException e) {
      throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(e);
    } catch (InstantiationException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException(e);
    }

    for (Permission i : permsSets.get("common")) {
      allowed.add(i);
      if (debugPerm) {
        permCreated.add(i.toString());
      }
    }

    for (Permission i : permsSets.get("forprobes")) {
      allowed.add(i);
      if (debugPerm) {
        permCreated.add(i.toString());
      }
    }

    for (Permission i : permsSets.get(proto.name())) {
      allowed.add(i);
      if (debugPerm) {
        permCreated.add(i.toString());
      }
    }

    allowed.setReadOnly();
  }
 protected PermissionCollection getPermissions(CodeSource codesource) {
   Permissions permissions = new Permissions();
   permissions.add(new AllPermission());
   return permissions;
 }
Example #19
0
 private static AccessControlContext getContextAccCtxt() {
   final Permissions perms = new Permissions();
   perms.add(new RuntimePermission(Context.NASHORN_GET_CONTEXT));
   return new AccessControlContext(new ProtectionDomain[] {new ProtectionDomain(null, perms)});
 }
Example #20
0
  /**
   * Parse a policy file, incorporating the permission definitions described therein.
   *
   * @param url The URL of the policy file to read.
   * @throws IOException if an I/O error occurs, or if the policy file cannot be parsed.
   */
  private void parse(final URL url) throws IOException {
    logger.log(Component.POLICY, "reading policy file from {0}", url);
    final StreamTokenizer in = new StreamTokenizer(new InputStreamReader(url.openStream()));
    in.resetSyntax();
    in.slashSlashComments(true);
    in.slashStarComments(true);
    in.wordChars('A', 'Z');
    in.wordChars('a', 'z');
    in.wordChars('0', '9');
    in.wordChars('.', '.');
    in.wordChars('_', '_');
    in.wordChars('$', '$');
    in.whitespaceChars(' ', ' ');
    in.whitespaceChars('\t', '\t');
    in.whitespaceChars('\f', '\f');
    in.whitespaceChars('\n', '\n');
    in.whitespaceChars('\r', '\r');
    in.quoteChar('\'');
    in.quoteChar('"');

    int tok;
    int state = STATE_BEGIN;
    List keystores = new LinkedList();
    URL currentBase = null;
    List currentCerts = new LinkedList();
    Permissions currentPerms = new Permissions();
    while ((tok = in.nextToken()) != StreamTokenizer.TT_EOF) {
      switch (tok) {
        case '{':
          if (state != STATE_GRANT) error(url, in, "spurious '{'");
          state = STATE_PERMS;
          tok = in.nextToken();
          break;
        case '}':
          if (state != STATE_PERMS) error(url, in, "spurious '}'");
          state = STATE_BEGIN;
          currentPerms.setReadOnly();
          Certificate[] c = null;
          if (!currentCerts.isEmpty())
            c = (Certificate[]) currentCerts.toArray(new Certificate[currentCerts.size()]);
          cs2pc.put(new CodeSource(currentBase, c), currentPerms);
          currentCerts.clear();
          currentPerms = new Permissions();
          currentBase = null;
          tok = in.nextToken();
          if (tok != ';') in.pushBack();
          continue;
      }
      if (tok != StreamTokenizer.TT_WORD) {
        error(url, in, "expecting word token");
      }

      // keystore "<keystore-path>" [',' "<keystore-type>"] ';'
      if (in.sval.equalsIgnoreCase("keystore")) {
        String alg = KeyStore.getDefaultType();
        tok = in.nextToken();
        if (tok != '"' && tok != '\'') error(url, in, "expecting key store URL");
        String store = in.sval;
        tok = in.nextToken();
        if (tok == ',') {
          tok = in.nextToken();
          if (tok != '"' && tok != '\'') error(url, in, "expecting key store type");
          alg = in.sval;
          tok = in.nextToken();
        }
        if (tok != ';') error(url, in, "expecting semicolon");
        try {
          KeyStore keystore = KeyStore.getInstance(alg);
          keystore.load(new URL(url, store).openStream(), null);
          keystores.add(keystore);
        } catch (Exception x) {
          error(url, in, x.toString());
        }
      } else if (in.sval.equalsIgnoreCase("grant")) {
        if (state != STATE_BEGIN) error(url, in, "extraneous grant keyword");
        state = STATE_GRANT;
      } else if (in.sval.equalsIgnoreCase("signedBy")) {
        if (state != STATE_GRANT && state != STATE_PERMS) error(url, in, "spurious 'signedBy'");
        if (keystores.isEmpty()) error(url, in, "'signedBy' with no keystores");
        tok = in.nextToken();
        if (tok != '"' && tok != '\'') error(url, in, "expecting signedBy name");
        StringTokenizer st = new StringTokenizer(in.sval, ",");
        while (st.hasMoreTokens()) {
          String alias = st.nextToken();
          for (Iterator it = keystores.iterator(); it.hasNext(); ) {
            KeyStore keystore = (KeyStore) it.next();
            try {
              if (keystore.isCertificateEntry(alias))
                currentCerts.add(keystore.getCertificate(alias));
            } catch (KeyStoreException kse) {
              error(url, in, kse.toString());
            }
          }
        }
        tok = in.nextToken();
        if (tok != ',') {
          if (state != STATE_GRANT) error(url, in, "spurious ','");
          in.pushBack();
        }
      } else if (in.sval.equalsIgnoreCase("codeBase")) {
        if (state != STATE_GRANT) error(url, in, "spurious 'codeBase'");
        tok = in.nextToken();
        if (tok != '"' && tok != '\'') error(url, in, "expecting code base URL");
        String base = expand(in.sval);
        if (File.separatorChar != '/') base = base.replace(File.separatorChar, '/');
        try {
          currentBase = new URL(base);
        } catch (MalformedURLException mue) {
          error(url, in, mue.toString());
        }
        tok = in.nextToken();
        if (tok != ',') in.pushBack();
      } else if (in.sval.equalsIgnoreCase("principal")) {
        if (state != STATE_GRANT) error(url, in, "spurious 'principal'");
        tok = in.nextToken();
        if (tok == StreamTokenizer.TT_WORD) {
          tok = in.nextToken();
          if (tok != '"' && tok != '\'') error(url, in, "expecting principal name");
          String name = in.sval;
          Principal p = null;
          try {
            Class pclass = Class.forName(in.sval);
            Constructor c = pclass.getConstructor(new Class[] {String.class});
            p = (Principal) c.newInstance(new Object[] {name});
          } catch (Exception x) {
            error(url, in, x.toString());
          }
          for (Iterator it = keystores.iterator(); it.hasNext(); ) {
            KeyStore ks = (KeyStore) it.next();
            try {
              for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
                String alias = (String) e.nextElement();
                if (ks.isCertificateEntry(alias)) {
                  Certificate cert = ks.getCertificate(alias);
                  if (!(cert instanceof X509Certificate)) continue;
                  if (p.equals(((X509Certificate) cert).getSubjectDN())
                      || p.equals(((X509Certificate) cert).getSubjectX500Principal()))
                    currentCerts.add(cert);
                }
              }
            } catch (KeyStoreException kse) {
              error(url, in, kse.toString());
            }
          }
        } else if (tok == '"' || tok == '\'') {
          String alias = in.sval;
          for (Iterator it = keystores.iterator(); it.hasNext(); ) {
            KeyStore ks = (KeyStore) it.next();
            try {
              if (ks.isCertificateEntry(alias)) currentCerts.add(ks.getCertificate(alias));
            } catch (KeyStoreException kse) {
              error(url, in, kse.toString());
            }
          }
        } else error(url, in, "expecting principal");
        tok = in.nextToken();
        if (tok != ',') in.pushBack();
      } else if (in.sval.equalsIgnoreCase("permission")) {
        if (state != STATE_PERMS) error(url, in, "spurious 'permission'");
        tok = in.nextToken();
        if (tok != StreamTokenizer.TT_WORD) error(url, in, "expecting permission class name");
        String className = in.sval;
        Class clazz = null;
        try {
          clazz = Class.forName(className);
        } catch (ClassNotFoundException cnfe) {
        }
        tok = in.nextToken();
        if (tok == ';') {
          if (clazz == null) {
            currentPerms.add(
                new UnresolvedPermission(
                    className,
                    null,
                    null,
                    (Certificate[]) currentCerts.toArray(new Certificate[currentCerts.size()])));
            continue;
          }
          try {
            currentPerms.add((Permission) clazz.newInstance());
          } catch (Exception x) {
            error(url, in, x.toString());
          }
          continue;
        }
        if (tok != '"' && tok != '\'') error(url, in, "expecting permission target");
        String target = expand(in.sval);
        tok = in.nextToken();
        if (tok == ';') {
          if (clazz == null) {
            currentPerms.add(
                new UnresolvedPermission(
                    className,
                    target,
                    null,
                    (Certificate[]) currentCerts.toArray(new Certificate[currentCerts.size()])));
            continue;
          }
          try {
            Constructor c = clazz.getConstructor(new Class[] {String.class});
            currentPerms.add((Permission) c.newInstance(new Object[] {target}));
          } catch (Exception x) {
            error(url, in, x.toString());
          }
          continue;
        }
        if (tok != ',') error(url, in, "expecting ','");
        tok = in.nextToken();
        if (tok == StreamTokenizer.TT_WORD) {
          if (!in.sval.equalsIgnoreCase("signedBy")) error(url, in, "expecting 'signedBy'");
          try {
            Constructor c = clazz.getConstructor(new Class[] {String.class});
            currentPerms.add((Permission) c.newInstance(new Object[] {target}));
          } catch (Exception x) {
            error(url, in, x.toString());
          }
          in.pushBack();
          continue;
        }
        if (tok != '"' && tok != '\'') error(url, in, "expecting permission action");
        String action = in.sval;
        if (clazz == null) {
          currentPerms.add(
              new UnresolvedPermission(
                  className,
                  target,
                  action,
                  (Certificate[]) currentCerts.toArray(new Certificate[currentCerts.size()])));
          continue;
        } else {
          try {
            Constructor c = clazz.getConstructor(new Class[] {String.class, String.class});
            currentPerms.add((Permission) c.newInstance(new Object[] {target, action}));
          } catch (Exception x) {
            error(url, in, x.toString());
          }
        }
        tok = in.nextToken();
        if (tok != ';' && tok != ',') error(url, in, "expecting ';' or ','");
      }
    }
  }
  static {
    // just like bootstrap, initialize natives, then SM
    Bootstrap.initializeNatives(true, true);

    // initialize probes
    Bootstrap.initializeProbes();

    // check for jar hell
    try {
      JarHell.checkJarHell();
    } catch (Exception e) {
      if (Boolean.parseBoolean(System.getProperty("tests.maven"))) {
        throw new RuntimeException("found jar hell in test classpath", e);
      } else {
        Loggers.getLogger(BootstrapForTesting.class)
            .warn(
                "Your ide or custom test runner has jar hell issues, "
                    + "you might want to look into that",
                e);
      }
    }

    // make sure java.io.tmpdir exists always (in case code uses it in a static initializer)
    Path javaTmpDir =
        PathUtils.get(
            Objects.requireNonNull(
                System.getProperty("java.io.tmpdir"), "please set ${java.io.tmpdir} in pom.xml"));
    try {
      Security.ensureDirectoryExists(javaTmpDir);
    } catch (Exception e) {
      throw new RuntimeException("unable to create test temp directory", e);
    }

    // install security manager if requested
    if (systemPropertyAsBoolean("tests.security.manager", true)) {
      try {
        Security.setCodebaseProperties();
        // if its an insecure plugin, its not easy to simulate here, since we don't have a real
        // plugin install.
        // we just do our best so unit testing can work. integration tests for such plugins are
        // essential.
        String artifact = System.getProperty("tests.artifact");
        String insecurePluginProp = Security.INSECURE_PLUGINS.get(artifact);
        if (insecurePluginProp != null) {
          System.setProperty(insecurePluginProp, "file:/-");
        }
        // initialize paths the same exact way as bootstrap.
        Permissions perms = new Permissions();
        // add permissions to everything in classpath
        for (URL url : JarHell.parseClassPath()) {
          Path path = PathUtils.get(url.toURI());
          // resource itself
          perms.add(new FilePermission(path.toString(), "read,readlink"));
          // classes underneath
          perms.add(
              new FilePermission(
                  path.toString() + path.getFileSystem().getSeparator() + "-", "read,readlink"));

          // crazy jython...
          String filename = path.getFileName().toString();
          if (filename.contains("jython") && filename.endsWith(".jar")) {
            // just enough so it won't fail when it does not exist
            perms.add(new FilePermission(path.getParent().toString(), "read,readlink"));
            perms.add(
                new FilePermission(path.getParent().resolve("Lib").toString(), "read,readlink"));
          }
        }
        // java.io.tmpdir
        Security.addPath(perms, "java.io.tmpdir", javaTmpDir, "read,readlink,write,delete");
        // custom test config file
        if (Strings.hasLength(System.getProperty("tests.config"))) {
          perms.add(new FilePermission(System.getProperty("tests.config"), "read,readlink"));
        }
        // jacoco coverage output file
        if (Boolean.getBoolean("tests.coverage")) {
          Path coverageDir = PathUtils.get(System.getProperty("tests.coverage.dir"));
          perms.add(
              new FilePermission(coverageDir.resolve("jacoco.exec").toString(), "read,write"));
          // in case we get fancy and use the -integration goals later:
          perms.add(
              new FilePermission(coverageDir.resolve("jacoco-it.exec").toString(), "read,write"));
        }
        Policy.setPolicy(new ESPolicy(perms));
        System.setSecurityManager(new TestSecurityManager());
        Security.selfTest();

        if (insecurePluginProp != null) {
          // initialize the plugin class, in case it has one-time hacks (unit tests often won't do
          // this)
          String clazz = System.getProperty("tests.plugin.classname");
          if (clazz == null) {
            throw new IllegalStateException(
                "plugin classname is needed for insecure plugin unit tests");
          }
          Class.forName(clazz);
        }
      } catch (Exception e) {
        throw new RuntimeException("unable to install test security manager", e);
      }
    }
  }
 static {
   Permissions permissions = new Permissions();
   permissions.add(new AllPermission());
   unknownProtectionDomain = new ProtectionDomain(null, permissions);
 }
 public void add(Permission permission) {
   perms.add(permission);
 }
  /**
   * Adds a couple of common permissions for both unsigned extensions as well as Groovy scripts.
   *
   * @param permissions the permissions object which will get the permissions added to it
   */
  private static void addCommonPermissions(Permissions permissions) {
    permissions.add(new AudioPermission("play"));
    permissions.add(new AWTPermission("listenToAllAWTEvents"));
    permissions.add(new AWTPermission("setWindowAlwaysOnTop"));
    permissions.add(new AWTPermission("watchMousePointer"));
    permissions.add(new LoggingPermission("control", ""));
    permissions.add(new SocketPermission("*", "connect, listen, accept, resolve"));
    permissions.add(new URLPermission("http://-", "*:*"));
    permissions.add(new URLPermission("https://-", "*:*"));

    // because random Java library calls use sun classes which may or may not do an acess check,
    // we have to grant access to all of them
    // this is a very unfortunate permission and I would love to not have it
    // so if at any point in the future this won't be necessary any longer, remove it!!!
    permissions.add(new RuntimePermission("accessClassInPackage.sun.*"));

    permissions.add(new RuntimePermission("accessDeclaredMembers"));
    permissions.add(new RuntimePermission("getenv.*"));
    permissions.add(new RuntimePermission("getFileSystemAttributes"));
    permissions.add(new RuntimePermission("readFileDescriptor"));
    permissions.add(new RuntimePermission("writeFileDescriptor"));
    permissions.add(new RuntimePermission("queuePrintJob"));
  }
 AdjustablePolicy(Permission... permissions) {
   for (Permission permission : permissions) perms.add(permission);
 }
 /**
  * Create permission for our trusted code. No restrictions are applied
  *
  * @return the permissions, never {@code null}
  */
 private static PermissionCollection createAllPermissions() {
   Permissions permissions = new Permissions();
   permissions.add(new AllPermission());
   return permissions;
 }
 void addPermission(Permission perm) {
   perms.add(perm);
 }
Example #28
0
 /**
  * Gets the applet permissions. TODO Create a proper permission set.
  *
  * @return The applet permissions.
  */
 public Permissions getAppletPermissions() {
   Permissions permissions = new Permissions();
   permissions.add(new AllPermission());
   return permissions;
 }