Java Code Examples for java.security.cert.X509Certificate#getBasicConstraints()

The following examples show how to use java.security.cert.X509Certificate#getBasicConstraints() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EndEntityExtensionCheck.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void check(Certificate cert,
                  Collection<String> unresolvedCritExts)
        throws CertPathValidatorException {
    X509Certificate currCert = (X509Certificate)cert;
    // check that this is an EE cert
    if (currCert.getBasicConstraints() == -1) {
        if (unresolvedCritExts != null &&
                !unresolvedCritExts.isEmpty()) {
            unresolvedCritExts.remove("1.2.3.4");
        }
    }
}
 
Example 2
Source File: BuildEEBasicConstraints.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 3
Source File: ConstraintsChecker.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Merges the specified maxPathLength with the pathLenConstraint
 * obtained from the certificate.
 *
 * @param cert the <code>X509Certificate</code>
 * @param maxPathLength the previous maximum path length
 * @return the new maximum path length constraint (-1 means no more
 * certificates can follow, Integer.MAX_VALUE means path length is
 * unconstrained)
 */
static int mergeBasicConstraints(X509Certificate cert, int maxPathLength) {

    int pathLenConstraint = cert.getBasicConstraints();

    if (!X509CertImpl.isSelfIssued(cert)) {
        maxPathLength--;
    }

    if (pathLenConstraint < maxPathLength) {
        maxPathLength = pathLenConstraint;
    }

    return maxPathLength;
}
 
Example 4
Source File: TPMAttestationStatementValidator.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
void validateAikCert(X509Certificate certificate) {
    try {
        /// TPM attestation certificate MUST have the following fields/extensions:
        /// Version MUST be set to 3.
        if (!Objects.equals(certificate.getVersion(), 3)) {
            throw new BadAttestationStatementException("x5c must be version 3.");
        }
        /// Subject field MUST be set to empty.
        if (!certificate.getSubjectDN().getName().isEmpty()) {
            throw new BadAttestationStatementException("x5c subject field MUST be set to empty");
        }
        /// The Subject Alternative Name extension MUST be set as defined in [TPMv2-EK-Profile] section 3.2.9.
        validateSubjectAlternativeName(certificate);
        /// The Extended Key Usage extension MUST contain the "joint-iso-itu-t(2) internationalorganizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)" OID.
        if (certificate.getExtendedKeyUsage() == null || !certificate.getExtendedKeyUsage().contains("2.23.133.8.3")) {
            throw new BadAttestationStatementException("Attestation certificate doesn't contain tcg-kp-AIKCertificate (2.23.133.8.3) OID");
        }
        /// The Basic Constraints extension MUST have the CA component set to false.
        if (certificate.getBasicConstraints() != -1) {
            throw new BadAttestationStatementException("The Basic Constraints extension of attestation certificate must have the CA component set to false");
        }
        /// An Authority Information Access (AIA) extension with entry id-ad-ocsp and a CRL Distribution Point
        /// extension [RFC5280] are both OPTIONAL as the status of many attestation certificates is available
        /// through metadata services. See, for example, the FIDO Metadata Service  [FIDOMetadataService].

    } catch (CertificateParsingException e) {
        throw new BadAttestationStatementException("Failed to parse attestation certificate", e);
    }
}
 
Example 5
Source File: BuildEEBasicConstraints.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 6
Source File: RFC3281CertPathUtilities.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
protected static void processAttrCert3(X509Certificate acIssuerCert,
    PKIXExtendedParameters 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.");
    }
}
 
Example 7
Source File: ConstraintsChecker.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Merges the specified maxPathLength with the pathLenConstraint
 * obtained from the certificate.
 *
 * @param cert the <code>X509Certificate</code>
 * @param maxPathLength the previous maximum path length
 * @return the new maximum path length constraint (-1 means no more
 * certificates can follow, Integer.MAX_VALUE means path length is
 * unconstrained)
 */
static int mergeBasicConstraints(X509Certificate cert, int maxPathLength) {

    int pathLenConstraint = cert.getBasicConstraints();

    if (!X509CertImpl.isSelfIssued(cert)) {
        maxPathLength--;
    }

    if (pathLenConstraint < maxPathLength) {
        maxPathLength = pathLenConstraint;
    }

    return maxPathLength;
}
 
Example 8
Source File: X509CredentialsAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected final HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {

    final X509CertificateCredential x509Credential = (X509CertificateCredential) credential;
    final X509Certificate[] certificates = x509Credential.getCertificates();

    X509Certificate clientCert = null;
    boolean hasTrustedIssuer = false;
    for (int i = certificates.length - 1; i >= 0; i--) {
        final X509Certificate certificate = certificates[i];
        logger.debug("Evaluating {}", CertUtils.toString(certificate));

        validate(certificate);

        if (!hasTrustedIssuer) {
            hasTrustedIssuer = isCertificateFromTrustedIssuer(certificate);
        }

        // getBasicConstraints returns pathLenContraint which is generally
        // >=0 when this is a CA cert and -1 when it's not
        final int pathLength = certificate.getBasicConstraints();
        if (pathLength < 0) {
            logger.debug("Found valid client certificate");
            clientCert = certificate;
        } else {
            logger.debug("Found valid CA certificate");
        }
    }
    if (hasTrustedIssuer && clientCert != null) {
        x509Credential.setCertificate(clientCert);
        return new DefaultHandlerResult(this, x509Credential, this.principalFactory.createPrincipal(x509Credential.getId()));
    }
    throw new FailedLoginException();
}
 
Example 9
Source File: ConstraintsChecker.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Merges the specified maxPathLength with the pathLenConstraint
 * obtained from the certificate.
 *
 * @param cert the <code>X509Certificate</code>
 * @param maxPathLength the previous maximum path length
 * @return the new maximum path length constraint (-1 means no more
 * certificates can follow, Integer.MAX_VALUE means path length is
 * unconstrained)
 */
static int mergeBasicConstraints(X509Certificate cert, int maxPathLength) {

    int pathLenConstraint = cert.getBasicConstraints();

    if (!X509CertImpl.isSelfIssued(cert)) {
        maxPathLength--;
    }

    if (pathLenConstraint < maxPathLength) {
        maxPathLength = pathLenConstraint;
    }

    return maxPathLength;
}
 
Example 10
Source File: EndEntityExtensionCheck.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void check(Certificate cert,
                  Collection<String> unresolvedCritExts)
        throws CertPathValidatorException {
    X509Certificate currCert = (X509Certificate)cert;
    // check that this is an EE cert
    if (currCert.getBasicConstraints() == -1) {
        if (unresolvedCritExts != null &&
                !unresolvedCritExts.isEmpty()) {
            unresolvedCritExts.remove("1.2.3.4");
        }
    }
}
 
Example 11
Source File: BuildEEBasicConstraints.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 12
Source File: ConstraintsChecker.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Merges the specified maxPathLength with the pathLenConstraint
 * obtained from the certificate.
 *
 * @param cert the <code>X509Certificate</code>
 * @param maxPathLength the previous maximum path length
 * @return the new maximum path length constraint (-1 means no more
 * certificates can follow, Integer.MAX_VALUE means path length is
 * unconstrained)
 */
static int mergeBasicConstraints(X509Certificate cert, int maxPathLength) {

    int pathLenConstraint = cert.getBasicConstraints();

    if (!X509CertImpl.isSelfIssued(cert)) {
        maxPathLength--;
    }

    if (pathLenConstraint < maxPathLength) {
        maxPathLength = pathLenConstraint;
    }

    return maxPathLength;
}
 
Example 13
Source File: PackedAttestation.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
@Override
public void verify(JsonObject webAuthnResponse, byte[] clientDataJSON, JsonObject ctapMakeCredResp, AuthenticatorData authDataStruct) throws AttestationException {
  try {
    byte[] clientDataHash = hash(clientDataJSON);

    byte[] signatureBase = Buffer.buffer()
      .appendBytes(authDataStruct.getRaw())
      .appendBytes(clientDataHash)
      .getBytes();

    JsonObject attStmt = ctapMakeCredResp.getJsonObject("attStmt");
    byte[] signature = b64dec.decode(attStmt.getString("sig"));

    boolean signatureValid;

    if (attStmt.containsKey("x5c")) {
      /* ----- Verify FULL attestation ----- */
      JsonArray x5c = attStmt.getJsonArray("x5c");

      final X509Certificate x509Certificate = (X509Certificate) x509.generateCertificate(new ByteArrayInputStream(b64dec.decode(x5c.getString(0))));
      // check the certificate
      x509Certificate.checkValidity();
      // certificate valid lets verify the principal
      String[] values = x509Certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).split(",");
      int count = 0;

      for (String value : values) {
        if (value.startsWith("OU=")) {
          if (!value.equals("OU=Authenticator Attestation")) {
            throw new AttestationException("Batch certificate OU MUST be set strictly to 'Authenticator Attestation'!");
          }
          count++;
          continue;
        }
        if (value.startsWith("CN=")) {
          if (value.equals("CN=")) {
            throw new AttestationException("Batch certificate CN MUST no be empty!");
          }
          count++;
          continue;
        }
        if (value.startsWith("O=")) {
          if (value.equals("O=")) {
            throw new AttestationException("Batch certificate O MUST no be empty!");
          }
          count++;
          continue;
        }
        if (value.startsWith("C=")) {
          if (value.length() != 4) {
            throw new AttestationException("Batch certificate C MUST be set to two character ISO 3166 code!");
          }
          count++;
          continue;
        }
      }

      if (count != 4) {
        throw new AttestationException("Batch certificate does not contain the required subject info!");
      }


      if (x509Certificate.getBasicConstraints() != -1) {
        throw new AttestationException("Batch certificate basic constraints CA MUST be false!");
      }

      if (x509Certificate.getVersion() != 3) {
        throw new AttestationException("Batch certificate version MUST be 3(ASN1 2)!");
      }

      signatureValid = verifySignature(signature, signatureBase, x509Certificate);
      /* ----- Verify FULL attestation ENDS ----- */
    } else if (attStmt.containsKey("ecdaaKeyId")) {
      throw new AttestationException("ECDAA IS NOT SUPPORTED YET!");
    } else {
      /* ----- Verify SURROGATE attestation ----- */
      JWK key = authDataStruct.getCredentialJWK();
      signatureValid = key.verify(signature, signatureBase);
      /* ----- Verify SURROGATE attestation ENDS ----- */
    }

    if (!signatureValid) {
      throw new AttestationException("Failed to verify the signature!");
    }
  } catch (CertificateException | InvalidKeyException | SignatureException e) {
    throw new AttestationException(e);
  }
}
 
Example 14
Source File: ConstraintsChecker.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i +
                    ", maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 15
Source File: ConstraintsChecker.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i);
        debug.println("maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 16
Source File: ConstraintsChecker.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i +
                    ", maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 17
Source File: ConstraintsChecker.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i);
        debug.println("maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 18
Source File: ForwardState.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Update the state with the next certificate added to the path.
 *
 * @param cert the certificate which is used to update the state
 */
@Override
public void updateState(X509Certificate cert)
    throws CertificateException, IOException, CertPathValidatorException {

    if (cert == null)
        return;

    X509CertImpl icert = X509CertImpl.toImpl(cert);

    /* see if certificate key has null parameters */
    if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
        keyParamsNeededFlag = true;
    }

    /* update certificate */
    this.cert = icert;

    /* update issuer DN */
    issuerDN = cert.getIssuerX500Principal();

    if (!X509CertImpl.isSelfIssued(cert)) {

        /*
         * update traversedCACerts only if this is a non-self-issued
         * intermediate CA cert
         */
        if (!init && cert.getBasicConstraints() != -1) {
            traversedCACerts++;
        }
    }

    /* update subjectNamesTraversed only if this is the EE cert or if
       this cert is not self-issued */
    if (init || !X509CertImpl.isSelfIssued(cert)){
        X500Principal subjName = cert.getSubjectX500Principal();
        subjectNamesTraversed.add(X500Name.asX500Name(subjName));

        try {
            SubjectAlternativeNameExtension subjAltNameExt
                = icert.getSubjectAlternativeNameExtension();
            if (subjAltNameExt != null) {
                GeneralNames gNames = subjAltNameExt.get(
                        SubjectAlternativeNameExtension.SUBJECT_NAME);
                for (GeneralName gName : gNames.names()) {
                    subjectNamesTraversed.add(gName.getName());
                }
            }
        } catch (IOException e) {
            if (debug != null) {
                debug.println("ForwardState.updateState() unexpected "
                    + "exception");
                e.printStackTrace();
            }
            throw new CertPathValidatorException(e);
        }
    }

    init = false;
}
 
Example 19
Source File: ConstraintsChecker.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i +
                    ", maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 20
Source File: ConstraintsChecker.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i +
                    ", maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}