protected static void processAttrCert3(
     X509Certificate acIssuerCert, ExtendedPKIXParameters pkixParams)
     throws CertPathValidatorException {
   if (acIssuerCert.getKeyUsage() != null
       && (!acIssuerCert.getKeyUsage()[0] && !acIssuerCert.getKeyUsage()[1])) {
     throw new CertPathValidatorException(
         "Attribute certificate issuer public key cannot be used to validate digital signatures.");
   }
   if (acIssuerCert.getBasicConstraints() != -1) {
     throw new CertPathValidatorException(
         "Attribute certificate issuer is also a public key certificate issuer.");
   }
 }
 public static String prettyPrint(X509Certificate x509) {
   if (x509 == null) throw new IllegalArgumentException("x509 cannot be null");
   return String.format(
       FORMAT,
       x509.getVersion(),
       x509.getSerialNumber(),
       x509.getSigAlgName(),
       x509.getIssuerX500Principal().getName(),
       x509.getNotBefore(),
       x509.getNotAfter(),
       x509.getSubjectX500Principal().getName(),
       x509.getPublicKey().getAlgorithm(),
       x509.getBasicConstraints(),
       x509.getSigAlgName());
 }
 private static boolean checkBasicConstraintsForCodeSigning(
     X509Certificate paramX509Certificate, Set paramSet, int paramInt)
     throws CertificateException, IOException {
   paramSet.remove("2.5.29.19");
   paramSet.remove("2.16.840.1.113730.1.1");
   if (paramInt == 0) return true;
   if (paramX509Certificate.getExtensionValue("2.5.29.19") == null) {
     if (paramX509Certificate.getExtensionValue("2.16.840.1.113730.1.1") != null) {
       if (!getNetscapeCertTypeBit(paramX509Certificate, "object_signing_ca")) {
         Trace.msgSecurityPrintln("trustdecider.check.basicconstraints.certtypebit");
         return false;
       }
     } else {
       Trace.msgSecurityPrintln("trustdecider.check.basicconstraints.extensionvalue");
       return false;
     }
   } else {
     if ((paramX509Certificate.getExtensionValue("2.16.840.1.113730.1.1") != null)
         && ((getNetscapeCertTypeBit(paramX509Certificate, "ssl_ca"))
             || (getNetscapeCertTypeBit(paramX509Certificate, "s_mime_ca"))
             || (getNetscapeCertTypeBit(paramX509Certificate, "object_signing_ca")))
         && (!getNetscapeCertTypeBit(paramX509Certificate, "object_signing_ca"))) {
       Trace.msgSecurityPrintln("trustdecider.check.basicconstraints.bitvalue");
       return false;
     }
     int i = paramX509Certificate.getBasicConstraints();
     if (i < 0) {
       Trace.msgSecurityPrintln("trustdecider.check.basicconstraints.enduser");
       return false;
     }
     if (paramInt - 1 > i) {
       Trace.msgSecurityPrintln("trustdecider.check.basicconstraints.pathlength");
       return false;
     }
   }
   return true;
 }
 /**
  * Check if is a Certificate Authority Certificate (ICP-BRASIL = AC).<br>
  * * <b>true</b> - If CA.<br>
  * * <b>false</b> -for End User Certificate.<br>
  *
  * @return boolean
  */
 public boolean isCertificadoAc() {
   return certificate.getBasicConstraints() >= 0;
 }
 /**
  * Returns the PathLength value of Certificate BasicConstraint.<br>
  * * <b>0</b> - if CA.<br>
  * * <b>1</b> - for End User Certificate.<br>
  *
  * @return int
  */
 public int getPathLength() {
   return certificate.getBasicConstraints();
 }
示例#6
0
  public void scepCLI() throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyManager km = new KeyManager();
    CertUtil certutil = new CertUtil();

    KeyPair kp = km.createRSA(params.getKeySize());

    X509Certificate cert = certutil.createSelfSignedCertificate(kp, params.getDn());
    CertificationRequest request =
        certutil.createCertificationRequest(kp, params.getDn(), params.getChallenge());
    CallbackHandler handler = new ConsoleCallbackHandler();
    URL serverURL = new URL(params.getUrl());

    try {
      if (params.getCsrFile() != null) {
        saveToPEM(params.getCsrFile(), (PKCS10CertificationRequest) request);
      }

      Client client =
          new Client(serverURL, cert, kp.getPrivate(), handler, params.getCaIdentifier());

      client.getCaCertificate();

      EnrolmentTransaction tx = client.enrol(request);
      Transaction.State response = tx.send();

      /*
       * handle asynchronous response
       */
      while (response == Transaction.State.CERT_REQ_PENDING) {
        Thread.currentThread().sleep(1000);
        System.out.println("CERT_REQ_PENDING, wait 1 second");
        response = tx.poll();
      }

      if (response == Transaction.State.CERT_ISSUED) {
        try {
          saveToPEM(params.getCrlFile(), (X509CRL) client.getRevocationList());
        } catch (Exception e) {
          System.err.println("Exception while saving CRL");
        }

        try {
          saveToPEM(params.getKeyFile(), (RSAPrivateCrtKey) kp.getPrivate());
          CertStore store = tx.getCertStore();
          Collection<? extends Certificate> certs = store.getCertificates(null);
          Iterator it = certs.iterator();
          while (it.hasNext()) {
            X509Certificate certificate = (X509Certificate) it.next();
            if (certificate.getBasicConstraints() != -1) {
              saveToPEM(params.getCaCertificateFile(), (X509Certificate) certificate);
            } else {
              saveToPEM(params.getCertificateFile(), (X509Certificate) certificate);
            }
          }
          System.out.println("Certificate issued");
        } catch (Exception e) {
          System.err.println("Exception while saving files: " + e);
        }
      } else {
        System.err.println("Unknown error" + response);
      }
    } catch (IOException e) {
      if (params.getVerbose()) {
        e.printStackTrace();
      }

      System.err.println(e.getMessage());
      if (e.getMessage().contains("400")) {
        System.err.println(". Probably a template issue, look at PKI log");
      } else if (e.getMessage().contains("404")) {
        System.err.println(". Invalid URL or CA identifier");
      } else if (e.getMessage().contains("401")) {
        System.err.println(". Probably EJBCA invalid entity status");
      }

    } catch (Exception e) {
      System.out.println(e);
    }
  }
  /**
   * Verifies a matching certificate.
   *
   * <p>This method executes any of the validation steps in the PKIX path validation algorithm which
   * were not satisfied via filtering out non-compliant certificates with certificate matching
   * rules.
   *
   * <p>If the last certificate is being verified (the one whose subject matches the target subject,
   * then the steps in Section 6.1.4 of the Certification Path Validation algorithm are NOT
   * executed, regardless of whether or not the last cert is an end-entity cert or not. This allows
   * callers to certify CA certs as well as EE certs.
   *
   * @param cert the certificate to be verified
   * @param currentState the current state against which the cert is verified
   * @param certPathList the certPathList generated thus far
   */
  void verifyCert(X509Certificate cert, State currState, List certPathList)
      throws GeneralSecurityException {
    if (debug != null)
      debug.println(
          "ReverseBuilder.verifyCert(SN: "
              + Debug.toHexString(cert.getSerialNumber())
              + "\n  Subject: "
              + cert.getSubjectX500Principal()
              + ")");

    ReverseState currentState = (ReverseState) currState;

    /* we don't perform any validation of the trusted cert */
    if (currentState.isInitial()) {
      return;
    }

    /*
     * check for looping - abort a loop if
     * ((we encounter the same certificate twice) AND
     * ((policyMappingInhibited = true) OR (no policy mapping
     * extensions can be found between the occurences of the same
     * certificate)))
     * in order to facilitate the check to see if there are
     * any policy mapping extensions found between the occurences
     * of the same certificate, we reverse the certpathlist first
     */
    if ((certPathList != null) && (!certPathList.isEmpty())) {
      List reverseCertList = new ArrayList();
      Iterator iter = certPathList.iterator();
      while (iter.hasNext()) {
        reverseCertList.add(0, iter.next());
      }

      Iterator cpListIter = reverseCertList.iterator();
      boolean policyMappingFound = false;
      while (cpListIter.hasNext()) {
        X509Certificate cpListCert = (X509Certificate) cpListIter.next();
        X509CertImpl cpListCertImpl = X509CertImpl.toImpl(cpListCert);
        PolicyMappingsExtension policyMappingsExt = cpListCertImpl.getPolicyMappingsExtension();
        if (policyMappingsExt != null) {
          policyMappingFound = true;
        }
        if (debug != null) debug.println("policyMappingFound = " + policyMappingFound);
        if (cert.equals(cpListCert)) {
          if ((buildParams.isPolicyMappingInhibited()) || (!policyMappingFound)) {
            if (debug != null) debug.println("loop detected!!");
            throw new CertPathValidatorException("loop detected");
          }
        }
      }
    }

    /* check if target cert */
    boolean finalCert = cert.getSubjectX500Principal().equals(targetSubjectDN);

    /* check if CA cert */
    boolean caCert = (cert.getBasicConstraints() != -1 ? true : false);

    /* if there are more certs to follow, verify certain constraints */
    if (!finalCert) {

      /* check if CA cert */
      if (!caCert) throw new CertPathValidatorException("cert is NOT a CA cert");

      /* If the certificate was not self-issued, verify that
       * remainingCerts is greater than zero
       */
      if ((currentState.remainingCACerts <= 0) && !X509CertImpl.isSelfIssued(cert)) {
        throw new CertPathValidatorException("pathLenConstraint violated, path too long");
      }

      /*
       * Check keyUsage extension (only if CA cert and not final cert)
       */
      KeyChecker.verifyCAKeyUsage(cert);

    } else {

      /*
       * If final cert, check that it satisfies specified target
       * constraints
       */
      if (targetCertSelector.match(cert) == false) {
        throw new CertPathValidatorException("target certificate " + "constraints check failed");
      }
    }

    /*
     * Check revocation.
     */
    if (buildParams.isRevocationEnabled()) {

      boolean crlSign = currentState.crlChecker.check(cert, currentState.pubKey, true);

      // if this cert can't vouch for the CRL on the next cert, and
      // if this wasn't the last cert in the chain, then we can't
      // keep going from here!
      // NOTE: if we ever add indirect/idp support, this will have
      // to change...
      if ((!crlSign) && (!finalCert))
        throw new CertPathValidatorException("cert can't vouch for crl");
    }

    /* Check name constraints if this is not a self-issued cert */
    if (finalCert || !X509CertImpl.isSelfIssued(cert)) {
      if (currentState.nc != null) {
        try {
          if (!currentState.nc.verify(cert)) {
            throw new CertPathValidatorException("name constraints check failed");
          }
        } catch (IOException ioe) {
          throw new CertPathValidatorException(ioe);
        }
      }
    }

    /*
     * Check policy
     */
    X509CertImpl certImpl = X509CertImpl.toImpl(cert);
    currentState.rootNode =
        PolicyChecker.processPolicies(
            currentState.certIndex,
            initPolicies,
            currentState.explicitPolicy,
            currentState.policyMapping,
            currentState.inhibitAnyPolicy,
            buildParams.getPolicyQualifiersRejected(),
            currentState.rootNode,
            certImpl,
            finalCert);

    /*
     * Check CRITICAL private extensions
     */
    Set unresolvedCritExts = cert.getCriticalExtensionOIDs();
    if (unresolvedCritExts == null) {
      unresolvedCritExts = Collections.EMPTY_SET;
    }
    Iterator i = currentState.userCheckers.iterator();
    while (i.hasNext()) {
      PKIXCertPathChecker checker = (PKIXCertPathChecker) i.next();
      checker.check(cert, unresolvedCritExts);
    }
    /*
     * Look at the remaining extensions and remove any ones we have
     * already checked. If there are any left, throw an exception!
     */
    if (!unresolvedCritExts.isEmpty()) {
      unresolvedCritExts.remove(PKIXExtensions.BasicConstraints_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.NameConstraints_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.CertificatePolicies_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.PolicyMappings_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.PolicyConstraints_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.InhibitAnyPolicy_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.SubjectAlternativeName_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.KeyUsage_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.ExtendedKeyUsage_Id.toString());

      if (!unresolvedCritExts.isEmpty())
        throw new CertificateException("Unrecognized critical extension(s)");
    }

    /*
     * Check signature.
     */
    if (buildParams.getSigProvider() != null) {
      cert.verify(currentState.pubKey, buildParams.getSigProvider());
    } else {
      cert.verify(currentState.pubKey);
    }
  }
示例#8
0
 /**
  * Liefert true, wenn es sich um ein CA-Zertifikat handelt.
  *
  * @return true, wenn es sich um ein CA-Zertifikat handelt.
  */
 public boolean isCA() {
   X509Certificate x = this.getCertificate();
   return x.getBasicConstraints() > -1;
 }