/**
   * Return the initialization parameters for the TrustManager. Currently, only the default <code>
   * PKIX</code> is supported.
   *
   * @param algorithm The algorithm to get parameters for.
   * @param crlf The path to the CRL file.
   * @param trustStore The configured TrustStore.
   * @return The parameters including the CRLs and TrustStore.
   */
  protected CertPathParameters getParameters(String algorithm, String crlf, KeyStore trustStore)
      throws Exception {

    CertPathParameters params = null;
    if ("PKIX".equalsIgnoreCase(algorithm)) {
      PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore, new X509CertSelector());
      Collection crls = getCRLs(crlf);
      CertStoreParameters csp = new CollectionCertStoreParameters(crls);
      CertStore store = CertStore.getInstance("Collection", csp);
      xparams.addCertStore(store);
      xparams.setRevocationEnabled(true);
      String trustLength = (String) attributes.get("trustMaxCertLength");
      if (trustLength != null) {
        try {
          xparams.setMaxPathLength(Integer.parseInt(trustLength));
        } catch (Exception ex) {
          log.warn("Bad maxCertLength: " + trustLength);
        }
      }
      params = xparams;
    } else {
      throw new CRLException("CRLs not supported for type: " + algorithm);
    }
    return params;
  }
示例#2
0
 MyX509TrustManager() throws java.security.GeneralSecurityException {
   TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
   KeyStore ks = KeyStore.getInstance("JKS");
   CertificateFactory cf = CertificateFactory.getInstance("X.509");
   try {
     ks.load(null, null);
     File cacert = new File(cafile);
     if (!cacert.exists() || !cacert.canRead()) return;
     InputStream caStream = new FileInputStream(cafile);
     X509Certificate ca = (X509Certificate) cf.generateCertificate(caStream);
     ks.setCertificateEntry("CA", ca);
     PKIXBuilderParameters params = new PKIXBuilderParameters(ks, new X509CertSelector());
     File crlcert = new File(crlfile);
     if (!crlcert.exists() || !crlcert.canRead()) {
       params.setRevocationEnabled(false);
     } else {
       InputStream crlStream = new FileInputStream(crlfile);
       Collection<? extends CRL> crls = cf.generateCRLs(crlStream);
       CertStoreParameters csp = new CollectionCertStoreParameters(crls);
       CertStore store = CertStore.getInstance("Collection", csp);
       params.addCertStore(store);
       params.setRevocationEnabled(true);
     }
     tmf.init(new CertPathTrustManagerParameters(params));
   } catch (java.io.FileNotFoundException e) {
     vlog.error(e.toString());
   } catch (java.io.IOException e) {
     vlog.error(e.toString());
   }
   tm = (X509TrustManager) tmf.getTrustManagers()[0];
 }
示例#3
0
  private X509Certificate[] doBuild(X509Certificate[] chain, Collection otherCerts)
      throws CertificateException {
    try {
      PKIXBuilderParameters params = (PKIXBuilderParameters) parameterTemplate.clone();
      setDate(params);

      // setup target constraints
      X509CertSelector selector = new X509CertSelector();
      selector.setCertificate(chain[0]);
      params.setTargetCertConstraints(selector);

      // setup CertStores
      Collection certs = new ArrayList();
      certs.addAll(Arrays.asList(chain));
      if (otherCerts != null) {
        certs.addAll(otherCerts);
      }
      CertStore store =
          CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs));
      params.addCertStore(store);

      // do the build
      CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
      PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(params);

      return toArray(result.getCertPath(), result.getTrustAnchor());
    } catch (GeneralSecurityException e) {
      throw new ValidatorException("PKIX path building failed: " + e.toString(), e);
    }
  }
示例#4
0
  private void testExceptions() throws Exception {
    byte[] enc = {(byte) 0, (byte) 2, (byte) 3, (byte) 4, (byte) 5};
    MyCertPath mc = new MyCertPath(enc);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ByteArrayInputStream is;
    byte[] arr;

    ObjectOutputStream oOut = new ObjectOutputStream(os);
    oOut.writeObject(mc);
    oOut.flush();
    oOut.close();

    try {
      CertificateFactory cFac = CertificateFactory.getInstance("X.509", "BC");
      arr = os.toByteArray();
      is = new ByteArrayInputStream(arr);
      cFac.generateCertPath(is);
    } catch (CertificateException e) {
      // ignore okay
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List certCol = new ArrayList();

    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certA)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certB)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certC)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certD)));

    CertPathBuilder pathBuilder = CertPathBuilder.getInstance("PKIX", "BC");
    X509CertSelector select = new X509CertSelector();
    select.setSubject(((X509Certificate) certCol.get(0)).getSubjectX500Principal().getEncoded());

    Set trustanchors = new HashSet();
    trustanchors.add(
        new TrustAnchor(
            (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(rootCertBin)), null));

    CertStore certStore =
        CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCol));

    PKIXBuilderParameters params = new PKIXBuilderParameters(trustanchors, select);
    params.addCertStore(certStore);

    try {
      CertPathBuilderResult result = pathBuilder.build(params);
      CertPath path = result.getCertPath();
      fail("found cert path in circular set");
    } catch (CertPathBuilderException e) {
      // expected
    }
  }
  /**
   * Build a path using the given root as the trust anchor, and the passed in end constraints and
   * certificate store.
   *
   * <p>Note: the path is built with revocation checking turned off.
   */
  public static PKIXCertPathBuilderResult buildPath(
      X509Certificate rootCert, X509CertSelector endConstraints, CertStore certsAndCRLs)
      throws Exception {
    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
    PKIXBuilderParameters buildParams =
        new PKIXBuilderParameters(
            Collections.singleton(new TrustAnchor(rootCert, null)), endConstraints);

    buildParams.addCertStore(certsAndCRLs);
    buildParams.setRevocationEnabled(false);

    return (PKIXCertPathBuilderResult) builder.build(buildParams);
  }
示例#6
0
  private void validateChain(List<Certificate> chain, Certificate cert) {

    List<Certificate> certs = new ArrayList<Certificate>();
    List<Certificate> root = new ArrayList<Certificate>();

    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);

    for (Certificate c : certs) {
      if (!(c instanceof X509Certificate))
        throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");

      X509Certificate xCert = (X509Certificate) c;

      Principal subject = xCert.getSubjectDN();
      Principal issuer = xCert.getIssuerDN();

      if (issuer != null && subject.equals(issuer)) {
        root.add(c);
        anchors.add(new TrustAnchor(xCert, null));
      }
    }

    if (root.size() == 0)
      throw new IllegalArgumentException("No root certificates found for certificate chain", null);

    X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
      params = new PKIXBuilderParameters(anchors, target);
      params.setRevocationEnabled(false);
      params.addCertStore(
          CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
      CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
      builder.build(params);

    } catch (InvalidAlgorithmParameterException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (CertPathBuilderException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchProviderException e) {
      throw new CloudRuntimeException("No provider for certificate validation", e);
    }
  }
示例#7
0
  private void checkCircProcessing() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");

    X509Certificate caCert =
        (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(circCA));
    X509Certificate crlCaCert =
        (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(circCRLCA));
    X509CRL crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(circCRL));

    List list = new ArrayList();

    list.add(caCert);
    list.add(crlCaCert);
    list.add(crl);

    CertStoreParameters ccsp = new CollectionCertStoreParameters(list);
    CertStore store = CertStore.getInstance("Collection", ccsp);

    Date validDate = new Date(crl.getThisUpdate().getTime() + 60 * 60 * 1000);

    // validating path
    List certchain = new ArrayList();

    certchain.add(crlCaCert);
    CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain);

    Set trust = new HashSet();
    trust.add(new TrustAnchor(caCert, null));

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC");
    // PKIXParameters param = new PKIXParameters(trust);

    PKIXBuilderParameters param = new PKIXBuilderParameters(trust, null);
    X509CertSelector certSelector = new X509CertSelector();
    certSelector.setCertificate(crlCaCert);
    param.setTargetCertConstraints(certSelector);
    param.addCertStore(store);
    param.setRevocationEnabled(true);
    param.setDate(validDate);

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, param);
  }
  // controlla che il certificato del firmatario sia affidabile controllando la sua catena di
  // certificati
  // valida il certificato X509 del firmatario usando il built-in PKIX support messo a disposizione
  // da java
  // caricando il keystore contenente i certificati degli enti certificatori autorizzati dallo stato
  // italiano
  private PKIXCertPathBuilderResult isTrustedSigner(SignerInformation signer)
      throws FirmapiuException {
    // genera la lista di certificati da controllare  per generare la catena dei certificati del
    // firmatario
    // TODO quali certificati carica esattamente?
    Collection<?> certCollection = certStore.getMatches(signer.getSID());
    Iterator<?> certIt = certCollection.iterator();
    X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
    List<X509Certificate> chain = new LinkedList<X509Certificate>();
    JcaX509CertificateConverter certConverter =
        new JcaX509CertificateConverter().setProvider(this.bcProvName);
    try {
      X509Certificate x509cert = certConverter.getCertificate(cert);
      chain.add(x509cert);
      while (certIt.hasNext()) {
        x509cert = certConverter.getCertificate((X509CertificateHolder) certIt.next());
        chain.add(x509cert);
      }
    } catch (CertificateException e) {
      new FirmapiuException(CERT_DEFAULT_ERROR, e);
    }

    // carica i certificati presenti nel token crittografico passato come parametro
    KeyStore anchors = this.token.loadKeyStore(null);
    X509CertSelector target = new X509CertSelector();
    target.setCertificate(chain.get(0));
    PKIXBuilderParameters params;
    CertPathBuilder builder;
    try {
      params = new PKIXBuilderParameters(anchors, target);
      // disabilita il controllo delle CRL
      params.setRevocationEnabled(false);
      // se il certificato è scaduto cerca di generare lo stesso la catena dei certificati
      try {
        X509Certificate x509cert = certConverter.getCertificate(cert);
        // long before=x509cert.getNotBefore().getTime();
        long after = x509cert.getNotAfter().getTime();
        after -= 10;
        params.setDate(new Date(after));
      } catch (CertificateException e) {
        throw new FirmapiuException(CERT_KEYSTORE_DEFAULT_ERROR, e);
      }
      CertStoreParameters intermediates = new CollectionCertStoreParameters(chain);
      params.addCertStore(CertStore.getInstance("Collection", intermediates));
      params.setSigProvider(this.bcProvName);
      builder = CertPathBuilder.getInstance("PKIX", this.bcProvName);
    } catch (KeyStoreException | InvalidAlgorithmParameterException e) {
      throw new FirmapiuException(CERT_KEYSTORE_DEFAULT_ERROR, e);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
      throw new FirmapiuException(DEFAULT_ERROR, e);
    }
    /*
     * If build() returns successfully, the certificate is valid. More details
     * about the valid path can be obtained through the PKIXBuilderResult.
     * If no valid path can be found, a CertPathBuilderException is thrown.
     */
    try {
      return (PKIXCertPathBuilderResult) builder.build(params);
    } catch (CertPathBuilderException e) {
      throw new FirmapiuException(VERIFY_SIGNER_CERTPATH_ERROR, e);
    } catch (InvalidAlgorithmParameterException e) {
      throw new FirmapiuException(DEFAULT_ERROR, e);
    }
  } // fine metodo