Search in sources :

Example 51 with PKCS10CertificationRequest

use of org.bouncycastle.pkcs.PKCS10CertificationRequest in project athenz by yahoo.

the class X509CertRequestTest method testValidatePublicKeysCertCSRFailure.

@Test
public void testValidatePublicKeysCertCSRFailure() throws IOException {
    Path path = Paths.get("src/test/resources/valid_provider_refresh.csr");
    String csr = new String(Files.readAllBytes(path));
    X509CertRequest certReq = new X509CertRequest(csr);
    assertNotNull(certReq);
    PKCS10CertificationRequest req = Mockito.mock(PKCS10CertificationRequest.class);
    Mockito.when(req.getSubjectPublicKeyInfo()).thenReturn(null);
    certReq.setCertReq(req);
    path = Paths.get("src/test/resources/valid_provider_refresh.pem");
    String pem = new String(Files.readAllBytes(path));
    X509Certificate cert = Crypto.loadX509Certificate(pem);
    assertFalse(certReq.validatePublicKeys(cert));
}
Also used : Path(java.nio.file.Path) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) X509Certificate(java.security.cert.X509Certificate) Test(org.testng.annotations.Test)

Example 52 with PKCS10CertificationRequest

use of org.bouncycastle.pkcs.PKCS10CertificationRequest in project athenz by yahoo.

the class X509CertRequestTest method testValidatePublicKeysFailure.

@Test
public void testValidatePublicKeysFailure() throws IOException {
    Path path = Paths.get("src/test/resources/athenz.instanceid.csr");
    String csr = new String(Files.readAllBytes(path));
    X509CertRequest certReq = new X509CertRequest(csr);
    assertNotNull(certReq);
    PKCS10CertificationRequest req = Mockito.mock(PKCS10CertificationRequest.class);
    Mockito.when(req.getSubjectPublicKeyInfo()).thenReturn(null);
    certReq.setCertReq(req);
    assertFalse(certReq.validatePublicKeys("publickey"));
}
Also used : Path(java.nio.file.Path) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Test(org.testng.annotations.Test)

Example 53 with PKCS10CertificationRequest

use of org.bouncycastle.pkcs.PKCS10CertificationRequest in project athenz by yahoo.

the class ZTSClientMock method postInstanceRegisterInformation.

@Override
public InstanceIdentity postInstanceRegisterInformation(InstanceRegisterInformation info, Map<String, List<String>> responseHeaders) {
    if (csrUriVerifyValue != null) {
        PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(info.getCsr());
        final List<String> values = Crypto.extractX509CSRURIs(certReq);
        if (values.size() != 1 || !csrUriVerifyValue.equals(values.get(0))) {
            throw new IllegalArgumentException("csr uri value not verified");
        }
    }
    if (csrDnsVerifyValues != null) {
        PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(info.getCsr());
        final List<String> dnsValues = Crypto.extractX509CSRDnsNames(certReq);
        if (!csrDnsVerifyValues.equals(dnsValues)) {
            throw new IllegalArgumentException("csr dns name value not verified");
        }
    }
    InstanceIdentity identity = new InstanceIdentity();
    Path path = Paths.get("./src/test/resources/test_cert.pem");
    try {
        identity.setX509Certificate(new String(Files.readAllBytes(path)));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return identity;
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Path(java.nio.file.Path) IOException(java.io.IOException)

Example 54 with PKCS10CertificationRequest

use of org.bouncycastle.pkcs.PKCS10CertificationRequest in project athenz by yahoo.

the class ZTSImpl method postInstanceRefreshRequest.

@Deprecated
@Override
public Identity postInstanceRefreshRequest(ResourceContext ctx, String domain, String service, InstanceRefreshRequest req) {
    final String caller = ctx.getApiName();
    final String principalDomain = logPrincipalAndGetDomain(ctx);
    if (readOnlyMode.get()) {
        throw requestError("Server in Maintenance Read-Only mode. Please try your request later", caller, ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
    }
    validateRequest(ctx.request(), principalDomain, caller);
    validate(domain, TYPE_DOMAIN_NAME, principalDomain, caller);
    validate(service, TYPE_SIMPLE_NAME, principalDomain, caller);
    validate(req, TYPE_INSTANCE_REFRESH_REQUEST, principalDomain, caller);
    // validate principal object to make sure we're not
    // processing a role identity and instead we require
    // a service identity
    final Principal principal = ((RsrcCtxWrapper) ctx).principal();
    validatePrincipalNotRoleIdentity(principal, caller);
    // for consistent handling of all requests, we're going to convert
    // all incoming object values into lower case (e.g. domain, role,
    // policy, service, etc name)
    domain = domain.toLowerCase();
    setRequestDomain(ctx, domain);
    service = service.toLowerCase();
    // make sure the credentials match to whatever the request is
    String fullServiceName = domain + "." + service;
    final String principalName = principal.getFullName();
    boolean userRequest = false;
    if (!fullServiceName.equals(principalName)) {
        try {
            userRequest = authorizer.access("update", domain + ":service", principal, null);
        } catch (ResourceException ex) {
            LOGGER.error("postInstanceRefreshRequest: access check failure for {}: {}", principalName, ex.getMessage());
        }
        if (!userRequest) {
            throw requestError("Principal mismatch: " + fullServiceName + " vs. " + principalName, caller, domain, principalDomain);
        }
    }
    if (userDomain.equalsIgnoreCase(domain)) {
        throw requestError("TLS Certificates require ServiceTokens: " + fullServiceName, caller, domain, principalDomain);
    }
    // determine if this is a refresh or initial request
    final Authority authority = principal.getAuthority();
    boolean refreshOperation = (!userRequest && (authority instanceof CertificateAuthority));
    // retrieve the public key for the request for verification
    final String keyId = userRequest || refreshOperation ? req.getKeyId() : principal.getKeyId();
    String publicKey = getPublicKey(domain, service, keyId);
    if (publicKey == null) {
        throw requestError("Unable to retrieve public key for " + fullServiceName + " with key id: " + keyId, caller, domain, principalDomain);
    }
    // validate that the cn and public key match to the provided details
    X509CertRequest x509CertReq;
    try {
        x509CertReq = new X509CertRequest(req.getCsr());
    } catch (CryptoException ex) {
        throw requestError("Unable to parse PKCS10 certificate request", caller, domain, principalDomain);
    }
    final PKCS10CertificationRequest certReq = x509CertReq.getCertReq();
    if (!ZTSUtils.verifyCertificateRequest(certReq, domain, service)) {
        throw requestError("Invalid CSR - data mismatch", caller, domain, principalDomain);
    }
    if (!x509CertReq.validateSubjectOField(validCertSubjectOrgValues)) {
        throw requestError("Invalid CSR - invalid Subject O field", caller, domain, principalDomain);
    }
    if (verifyCertSubjectOU && !x509CertReq.validateSubjectOUField(null, null, validCertSubjectOrgUnitValues)) {
        throw requestError("Invalid CSR - invalid Subject OU field", caller, domain, principalDomain);
    }
    if (!x509CertReq.validatePublicKeys(publicKey)) {
        throw requestError("Invalid CSR - public key mismatch", caller, domain, principalDomain);
    }
    // verify the IP address in the request matches where the connection
    // is coming from
    final String ipAddress = ServletRequestUtil.getRemoteAddress(ctx.request());
    if (verifyCertRequestIP && !x509CertReq.validateIPAddress(ipAddress)) {
        throw requestError("Invalid CSR - IP address mismatch", caller, domain, principalDomain);
    }
    if (refreshOperation) {
        ServiceX509RefreshRequestStatus status = validateServiceX509RefreshRequest(principal, x509CertReq, ipAddress);
        if (status == ServiceX509RefreshRequestStatus.IP_NOT_ALLOWED) {
            throw forbiddenError("IP not allowed for refresh: " + ipAddress, caller, domain, principalDomain);
        }
        if (status != ServiceX509RefreshRequestStatus.SUCCESS) {
            throw requestError("Request validation failed: " + status, caller, domain, principalDomain);
        }
    }
    // generate identity with the certificate
    int expiryTime = req.getExpiryTime() != null ? req.getExpiryTime() : 0;
    Identity identity = ZTSUtils.generateIdentity(instanceCertManager, null, null, req.getCsr(), fullServiceName, null, expiryTime);
    if (identity == null) {
        throw serverError("Unable to generate identity", caller, domain, principalDomain);
    }
    identity.setCaCertBundle(instanceCertManager.getX509CertificateSigner(null));
    // log our certificate
    instanceCertManager.logX509Cert(principal, ipAddress, ZTSConsts.ZTS_SERVICE, ZTSUtils.extractCertReqInstanceId(certReq), Crypto.loadX509Certificate(identity.getCertificate()));
    return identity;
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) CertificateAuthority(com.yahoo.athenz.auth.impl.CertificateAuthority) CertificateAuthority(com.yahoo.athenz.auth.impl.CertificateAuthority) CryptoException(com.yahoo.athenz.auth.util.CryptoException) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal)

Example 55 with PKCS10CertificationRequest

use of org.bouncycastle.pkcs.PKCS10CertificationRequest in project athenz by yahoo.

the class ZTSUtilsTest method testValidateCertReqDNSNamesNoDNS.

@Test
public void testValidateCertReqDNSNamesNoDNS() throws IOException {
    Path path = Paths.get("src/test/resources/valid.csr");
    String csr = new String(Files.readAllBytes(path));
    // no dns names so all are valid
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(csr);
    boolean result = ZTSUtils.validateCertReqDNSNames(certReq, "athenz", "production");
    assertTrue(result);
    result = ZTSUtils.validateCertReqDNSNames(certReq, "athenz2", "production");
    assertTrue(result);
    result = ZTSUtils.validateCertReqDNSNames(certReq, "athenz2", "productio2");
    assertTrue(result);
}
Also used : Path(java.nio.file.Path) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Test(org.testng.annotations.Test)

Aggregations

PKCS10CertificationRequest (org.bouncycastle.pkcs.PKCS10CertificationRequest)78 Test (org.testng.annotations.Test)39 Path (java.nio.file.Path)34 DERIA5String (org.bouncycastle.asn1.DERIA5String)19 X509Certificate (java.security.cert.X509Certificate)17 IOException (java.io.IOException)14 X500Name (org.bouncycastle.asn1.x500.X500Name)13 PrivateKey (java.security.PrivateKey)12 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)10 JcaPKCS10CertificationRequestBuilder (org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder)10 KeyPair (java.security.KeyPair)9 KeyPairGenerator (java.security.KeyPairGenerator)8 X500Principal (javax.security.auth.x500.X500Principal)8 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)8 File (java.io.File)7 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)7 ContentSigner (org.bouncycastle.operator.ContentSigner)7 JcaPKCS10CertificationRequest (org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest)7 PemObject (org.bouncycastle.util.io.pem.PemObject)6 CryptoException (org.kse.crypto.CryptoException)6