Exemple #1
0
 private Set<Long> parseMechanisms(String keyword) throws IOException {
   checkDup(keyword);
   Set<Long> mechs = new HashSet<Long>();
   parseEquals();
   parseOpenBraces();
   while (true) {
     int token = nextToken();
     if (isCloseBraces(token)) {
       break;
     }
     if (token == TT_EOL) {
       continue;
     }
     if (token != TT_WORD) {
       throw excToken("Expected mechanism, read");
     }
     long mech = parseMechanism(st.sval);
     mechs.add(Long.valueOf(mech));
   }
   if (DEBUG) {
     System.out.print("mechanisms: [");
     for (Long mech : mechs) {
       System.out.print(Functions.getMechanismName(mech));
       System.out.print(", ");
     }
     System.out.println("]");
   }
   return mechs;
 }
  private void checkStartup(
      Map<String, ServiceData> map,
      List<ServiceData> start,
      ServiceData sd,
      Set<ServiceData> cyclic) {
    if (sd.after.isEmpty() || start.contains(sd)) return;

    if (cyclic.contains(sd)) {
      reporter.error("Cyclic dependency for " + sd.name);
      return;
    }

    cyclic.add(sd);

    for (String dependsOn : sd.after) {
      if (dependsOn.equals("boot")) continue;

      ServiceData deps = map.get(dependsOn);
      if (deps == null) {
        reporter.error("No such service " + dependsOn + " but " + sd.name + " depends on it");
      } else {
        checkStartup(map, start, deps, cyclic);
      }
    }
    start.add(sd);
  }
  public boolean isProtectedMethod(String method) {
    boolean retval = false;

    if (protectedMethods.isEmpty() || protectedMethods.contains(method)) {
      retval = true;
    }

    return retval;
  }
  /**
   * Adds <tt>listener</tt> to the list of {@link CapsVerListener}s that we notify when new features
   * occur and the version hash needs to be regenerated. The method would also notify
   * <tt>listener</tt> if our current caps version has been generated and is different than
   * <tt>null</tt>.
   *
   * @param listener the {@link CapsVerListener} we'd like to register.
   */
  public void addCapsVerListener(CapsVerListener listener) {
    synchronized (capsVerListeners) {
      if (capsVerListeners.contains(listener)) return;

      capsVerListeners.add(listener);

      if (currentCapsVersion != null) listener.capsVerUpdated(currentCapsVersion);
    }
  }
Exemple #5
0
 boolean isEnabled(long m) {
   if (enabledMechanisms != null) {
     return enabledMechanisms.contains(Long.valueOf(m));
   }
   if (disabledMechanisms != null) {
     return !disabledMechanisms.contains(Long.valueOf(m));
   }
   return true;
 }
Exemple #6
0
 PKIXValidator(String variant, Collection trustedCerts) {
   super(TYPE_PKIX, variant);
   if (trustedCerts instanceof Set) {
     this.trustedCerts = (Set) trustedCerts;
   } else {
     this.trustedCerts = new HashSet(trustedCerts);
   }
   Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
   for (Iterator t = trustedCerts.iterator(); t.hasNext(); ) {
     X509Certificate cert = (X509Certificate) t.next();
     trustAnchors.add(new TrustAnchor(cert, null));
   }
   try {
     parameterTemplate = new PKIXBuilderParameters(trustAnchors, null);
   } catch (InvalidAlgorithmParameterException e) {
     throw new RuntimeException("Unexpected error: " + e.toString(), e);
   }
   setDefaultParameters(variant);
   initCommon();
 }
  public static void loadPermissions(URL url) throws IOException, PermissionParseException {

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
    Pattern ignore = Pattern.compile("^\\s*(//.*)?$");
    Pattern valid =
        Pattern.compile("^\\s*permission\\s+(\\S+)" + "(\\s+\"([^\"]*)\"(,\\s+\"([^\"]*)\")?)?;$");

    Set<Permission> perms = new HashSet<Permission>();

    while ((line = in.readLine()) != null) {
      if (ignore.matcher(line).matches()) {
        continue;
      }

      Matcher matcher = valid.matcher(line);
      if (!matcher.matches()) {
        throw new PermissionParseException("invalid syntax: " + line);
      }

      int nGroups = matcher.groupCount();
      String type = matcher.group(1);
      String name = expand(nGroups >= 3 ? matcher.group(3) : null);
      String actions = expand(nGroups >= 5 ? matcher.group(5) : null);

      try {
        Permission perm = getPermission(type, name, actions);
        perms.add(perm);
      } catch (Throwable e) {
        String message =
            String.format(
                "could not instantiate permission: " + "type=%s name=%s actions=",
                type, name, actions);
        throw new PermissionParseException(message, e);
      }
    }

    in.close();

    permSet.addAll(perms);
  }
Exemple #8
0
 protected static synchronized String checkCompressors(String compressors) {
   // Syntactic check of compressors
   Set<String> cset = new HashSet<>();
   compressors = compressors.replace(',', ' ');
   compressors = compressors.replace('\t', ' ');
   String[] pieces = compressors.split("[ ]+");
   for (String p : pieces) {
     for (String c : KNOWNCOMPRESSORS) {
       if (p.equalsIgnoreCase(c)) {
         cset.add(c);
         break;
       }
     }
   }
   StringBuilder buf = new StringBuilder();
   for (String s : cset) {
     if (buf.length() > 0) buf.append(",");
     buf.append(s);
   }
   return buf.toString();
 }
  /**
   * Write the output file with a graph format.
   *
   * @param outputFileName the output file to write to
   * @param urlToImageFileMap the map of url's to image files
   * @param edgeList the list of sources and sinks to write
   */
  public void writeDotFile(
      String outputFileName,
      Map<String, String> urlToImageFileMap,
      Map<String, Set<String>> edgeList) {

    try {

      File outputFile = new File(outputFileName);
      FileWriter fileWriter = new FileWriter(outputFile);
      fileWriter.write("digraph G {\n");
      fileWriter.write("  node [shape=box];\n");
      Set<String> urls = urlToImageFileMap.keySet();

      for (String url : urls) {
        String hashedUrl = getHashCode(url);
        String imageFileName = urlToImageFileMap.get(url);
        fileWriter.write("  " + hashedUrl + "[label=\"\" image=\"" + imageFileName + "\"];\n");
      }

      for (String url : urls) {
        Set<String> links = edgeList.get(url);
        if (links != null) {
          for (String link : links) {
            if (urls.contains(link)) {
              String hashUrlSource = getHashCode(url);
              String hashUrlSink = getHashCode(link);
              fileWriter.write("  " + hashUrlSource + " -> " + hashUrlSink + "\n");
            }
          }
        }
      }

      fileWriter.write("}\n");
      fileWriter.flush();
      fileWriter.close();
      System.out.println("Wrote results to [" + outputFileName + "]");
    } catch (Exception e) {
      System.out.println("Exception writing the results to the output file: " + e);
    }
  }
Exemple #10
0
 PKIXValidator(String variant, PKIXBuilderParameters params) {
   super(TYPE_PKIX, variant);
   trustedCerts = new HashSet();
   for (Iterator t = params.getTrustAnchors().iterator(); t.hasNext(); ) {
     TrustAnchor anchor = (TrustAnchor) t.next();
     X509Certificate cert = anchor.getTrustedCert();
     if (cert != null) {
       trustedCerts.add(cert);
     }
   }
   parameterTemplate = params;
   initCommon();
 }
Exemple #11
0
 private void initCommon() {
   if (TRY_VALIDATOR == false) {
     return;
   }
   trustedSubjects = new HashMap<X500Principal, List<PublicKey>>();
   for (Iterator t = trustedCerts.iterator(); t.hasNext(); ) {
     X509Certificate cert = (X509Certificate) t.next();
     X500Principal dn = cert.getSubjectX500Principal();
     List<PublicKey> keys;
     if (trustedSubjects.containsKey(dn)) {
       keys = trustedSubjects.get(dn);
     } else {
       keys = new ArrayList<PublicKey>();
       trustedSubjects.put(dn, keys);
     }
     keys.add(cert.getPublicKey());
   }
   try {
     factory = CertificateFactory.getInstance("X.509");
   } catch (CertificateException e) {
     throw new RuntimeException("Internal error", e);
   }
   plugin = variant.equals(VAR_PLUGIN_CODE_SIGNING);
 }
  /**
   * Creates an organization, its classification, and its services, and saves it to the registry.
   */
  public String executePublish(String username, String password, String endpoint) {

    String id = null;
    RegistryService rs = null;
    BusinessLifeCycleManager blcm = null;
    BusinessQueryManager bqm = null;

    try {
      rs = connection.getRegistryService();
      blcm = rs.getBusinessLifeCycleManager();
      bqm = rs.getBusinessQueryManager();
      System.out.println("Got registry service, query " + "manager, and life cycle manager");

      // Get authorization from the registry
      PasswordAuthentication passwdAuth =
          new PasswordAuthentication(username, password.toCharArray());

      Set creds = new HashSet();
      creds.add(passwdAuth);
      connection.setCredentials(creds);
      System.out.println("Established security credentials");

      // Get hardcoded strings from a ResourceBundle
      ResourceBundle bundle = ResourceBundle.getBundle("com.sun.cb.CoffeeRegistry");

      // Create organization name and description
      Organization org = blcm.createOrganization(bundle.getString("org.name"));
      InternationalString s = blcm.createInternationalString(bundle.getString("org.description"));
      org.setDescription(s);

      // Create primary contact, set name
      User primaryContact = blcm.createUser();
      PersonName pName = blcm.createPersonName(bundle.getString("person.name"));
      primaryContact.setPersonName(pName);

      // Set primary contact phone number
      TelephoneNumber tNum = blcm.createTelephoneNumber();
      tNum.setNumber(bundle.getString("phone.number"));
      Collection phoneNums = new ArrayList();
      phoneNums.add(tNum);
      primaryContact.setTelephoneNumbers(phoneNums);

      // Set primary contact email address
      EmailAddress emailAddress = blcm.createEmailAddress(bundle.getString("email.address"));
      Collection emailAddresses = new ArrayList();
      emailAddresses.add(emailAddress);
      primaryContact.setEmailAddresses(emailAddresses);

      // Set primary contact for organization
      org.setPrimaryContact(primaryContact);

      // Set classification scheme to NAICS
      ClassificationScheme cScheme =
          bqm.findClassificationSchemeByName(null, bundle.getString("classification.scheme"));

      // Create and add classification
      Classification classification =
          (Classification)
              blcm.createClassification(
                  cScheme,
                  bundle.getString("classification.name"),
                  bundle.getString("classification.value"));
      Collection classifications = new ArrayList();
      classifications.add(classification);
      org.addClassifications(classifications);

      // Create services and service
      Collection services = new ArrayList();
      Service service = blcm.createService(bundle.getString("service.name"));
      InternationalString is =
          blcm.createInternationalString(bundle.getString("service.description"));
      service.setDescription(is);

      // Create service bindings
      Collection serviceBindings = new ArrayList();
      ServiceBinding binding = blcm.createServiceBinding();
      is = blcm.createInternationalString(bundle.getString("service.binding"));
      binding.setDescription(is);
      binding.setValidateURI(false);
      binding.setAccessURI(endpoint);
      serviceBindings.add(binding);

      // Add service bindings to service
      service.addServiceBindings(serviceBindings);

      // Add service to services, then add services to organization
      services.add(service);
      org.addServices(services);

      // Add organization and submit to registry
      // Retrieve key if successful
      Collection orgs = new ArrayList();
      orgs.add(org);
      BulkResponse response = blcm.saveOrganizations(orgs);
      Collection exceptions = response.getExceptions();
      if (exceptions == null) {
        System.out.println("Organization saved");

        Collection keys = response.getCollection();
        Iterator keyIter = keys.iterator();
        if (keyIter.hasNext()) {
          javax.xml.registry.infomodel.Key orgKey =
              (javax.xml.registry.infomodel.Key) keyIter.next();
          id = orgKey.getId();
          System.out.println("Organization key is " + id);
        }
      } else {
        Iterator excIter = exceptions.iterator();
        Exception exception = null;
        while (excIter.hasNext()) {
          exception = (Exception) excIter.next();
          System.err.println("Exception on save: " + exception.toString());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      if (connection != null) {
        try {
          connection.close();
        } catch (JAXRException je) {
          System.err.println("Connection close failed");
        }
      }
    }
    return id;
  }
Exemple #13
0
  X509Certificate[] engineValidate(X509Certificate[] chain, Collection otherCerts, Object parameter)
      throws CertificateException {
    if ((chain == null) || (chain.length == 0)) {
      throw new CertificateException("null or zero-length certificate chain");
    }
    if (TRY_VALIDATOR) {
      // check that chain is in correct order and check if chain contains
      // trust anchor
      X500Principal prevIssuer = null;
      for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        X500Principal dn = cert.getSubjectX500Principal();
        if (i != 0 && !dn.equals(prevIssuer)) {
          // chain is not ordered correctly, call builder instead
          return doBuild(chain, otherCerts);
        }

        // Check if chain[i] is already trusted. It may be inside
        // trustedCerts, or has the same dn and public key as a cert
        // inside trustedCerts. The latter happens when a CA has
        // updated its cert with a stronger signature algorithm in JRE
        // but the weak one is still in circulation.

        if (trustedCerts.contains(cert)
            || // trusted cert
            (trustedSubjects.containsKey(dn)
                && // replacing ...
                trustedSubjects
                    .get(dn)
                    .contains( // ... weak cert
                        cert.getPublicKey()))) {
          if (i == 0) {
            return new X509Certificate[] {chain[0]};
          }
          // Remove and call validator on partial chain [0 .. i-1]
          X509Certificate[] newChain = new X509Certificate[i];
          System.arraycopy(chain, 0, newChain, 0, i);
          return doValidate(newChain);
        }
        prevIssuer = cert.getIssuerX500Principal();
      }

      // apparently issued by trust anchor?
      X509Certificate last = chain[chain.length - 1];
      X500Principal issuer = last.getIssuerX500Principal();
      X500Principal subject = last.getSubjectX500Principal();
      if (trustedSubjects.containsKey(issuer)
          && isSignatureValid(trustedSubjects.get(issuer), last)) {
        return doValidate(chain);
      }

      // don't fallback to builder if called from plugin/webstart
      if (plugin) {
        // Validate chain even if no trust anchor is found. This
        // allows plugin/webstart to make sure the chain is
        // otherwise valid
        if (chain.length > 1) {
          X509Certificate[] newChain = new X509Certificate[chain.length - 1];
          System.arraycopy(chain, 0, newChain, 0, newChain.length);
          // temporarily set last cert as sole trust anchor
          PKIXBuilderParameters params = (PKIXBuilderParameters) parameterTemplate.clone();
          try {
            params.setTrustAnchors(
                Collections.singleton(new TrustAnchor(chain[chain.length - 1], null)));
          } catch (InvalidAlgorithmParameterException iape) {
            // should never occur, but ...
            throw new CertificateException(iape);
          }
          doValidate(newChain, params);
        }
        // if the rest of the chain is valid, throw exception
        // indicating no trust anchor was found
        throw new ValidatorException(ValidatorException.T_NO_TRUST_ANCHOR);
      }
      // otherwise, fall back to builder
    }

    return doBuild(chain, otherCerts);
  }
 /**
  * Removes <tt>listener</tt> from the list of currently registered {@link CapsVerListener}s.
  *
  * @param listener the {@link CapsVerListener} we'd like to unregister.
  */
 public void removeCapsVerListener(CapsVerListener listener) {
   synchronized (capsVerListeners) {
     capsVerListeners.remove(listener);
   }
 }
Exemple #15
0
 private void checkDup(String keyword) throws IOException {
   if (parsedKeywords.contains(keyword)) {
     throw excLine(keyword + " must only be specified once");
   }
 }
Exemple #16
0
 private void parse() throws IOException {
   while (true) {
     int token = nextToken();
     if (token == TT_EOF) {
       break;
     }
     if (token == TT_EOL) {
       continue;
     }
     if (token != TT_WORD) {
       throw excToken("Unexpected token:");
     }
     String word = st.sval;
     if (word.equals("name")) {
       name = parseStringEntry(word);
     } else if (word.equals("library")) {
       library = parseLibrary(word);
     } else if (word.equals("description")) {
       parseDescription(word);
     } else if (word.equals("slot")) {
       parseSlotID(word);
     } else if (word.equals("slotListIndex")) {
       parseSlotListIndex(word);
     } else if (word.equals("enabledMechanisms")) {
       parseEnabledMechanisms(word);
     } else if (word.equals("disabledMechanisms")) {
       parseDisabledMechanisms(word);
     } else if (word.equals("attributes")) {
       parseAttributes(word);
     } else if (word.equals("handleStartupErrors")) {
       parseHandleStartupErrors(word);
     } else if (word.endsWith("insertionCheckInterval")) {
       insertionCheckInterval = parseIntegerEntry(word);
       if (insertionCheckInterval < 100) {
         throw excLine(word + " must be at least 100 ms");
       }
     } else if (word.equals("showInfo")) {
       showInfo = parseBooleanEntry(word);
     } else if (word.equals("keyStoreCompatibilityMode")) {
       keyStoreCompatibilityMode = parseBooleanEntry(word);
     } else if (word.equals("explicitCancel")) {
       explicitCancel = parseBooleanEntry(word);
     } else if (word.equals("omitInitialize")) {
       omitInitialize = parseBooleanEntry(word);
     } else if (word.equals("allowSingleThreadedModules")) {
       allowSingleThreadedModules = parseBooleanEntry(word);
     } else if (word.equals("functionList")) {
       functionList = parseStringEntry(word);
     } else if (word.equals("nssUseSecmod")) {
       nssUseSecmod = parseBooleanEntry(word);
     } else if (word.equals("nssLibraryDirectory")) {
       nssLibraryDirectory = parseLibrary(word);
       nssUseSecmod = true;
     } else if (word.equals("nssSecmodDirectory")) {
       nssSecmodDirectory = expand(parseStringEntry(word));
       nssUseSecmod = true;
     } else if (word.equals("nssModule")) {
       nssModule = parseStringEntry(word);
       nssUseSecmod = true;
     } else if (word.equals("nssDbMode")) {
       String mode = parseStringEntry(word);
       if (mode.equals("readWrite")) {
         nssDbMode = Secmod.DbMode.READ_WRITE;
       } else if (mode.equals("readOnly")) {
         nssDbMode = Secmod.DbMode.READ_ONLY;
       } else if (mode.equals("noDb")) {
         nssDbMode = Secmod.DbMode.NO_DB;
       } else {
         throw excToken("nssDbMode must be one of readWrite, readOnly, and noDb:");
       }
       nssUseSecmod = true;
     } else if (word.equals("nssNetscapeDbWorkaround")) {
       nssNetscapeDbWorkaround = parseBooleanEntry(word);
       nssUseSecmod = true;
     } else if (word.equals("nssArgs")) {
       parseNSSArgs(word);
     } else if (word.equals("nssUseSecmodTrust")) {
       nssUseSecmodTrust = parseBooleanEntry(word);
     } else if (word.equals("useEcX963Encoding")) {
       useEcX963Encoding = parseBooleanEntry(word);
     } else if (word.equals("nssOptimizeSpace")) {
       nssOptimizeSpace = parseBooleanEntry(word);
     } else {
       throw new ConfigurationException("Unknown keyword '" + word + "', line " + st.lineno());
     }
     parsedKeywords.add(word);
   }
   reader.close();
   reader = null;
   st = null;
   parsedKeywords = null;
   if (name == null) {
     throw new ConfigurationException("name must be specified");
   }
   if (nssUseSecmod == false) {
     if (library == null) {
       throw new ConfigurationException("library must be specified");
     }
   } else {
     if (library != null) {
       throw new ConfigurationException("library must not be specified in NSS mode");
     }
     if ((slotID != -1) || (slotListIndex != -1)) {
       throw new ConfigurationException(
           "slot and slotListIndex must not be specified in NSS mode");
     }
     if (nssArgs != null) {
       throw new ConfigurationException("nssArgs must not be specified in NSS mode");
     }
     if (nssUseSecmodTrust != false) {
       throw new ConfigurationException(
           "nssUseSecmodTrust is an " + "internal option and must not be specified in NSS mode");
     }
   }
 }