Search in sources :

Example 6 with CryptoException

use of com.yahoo.athenz.auth.util.CryptoException in project athenz by yahoo.

the class ZTSImpl method postInstanceRefreshRequest.

@Override
public Identity postInstanceRefreshRequest(ResourceContext ctx, String domain, String service, InstanceRefreshRequest req) {
    final String caller = "postinstancerefreshrequest";
    final String callerTiming = "postinstancerefreshrequest_timing";
    metric.increment(HTTP_POST);
    logPrincipal(ctx);
    validateRequest(ctx.request(), caller);
    validate(domain, TYPE_DOMAIN_NAME, caller);
    validate(service, TYPE_SIMPLE_NAME, caller);
    validate(req, TYPE_INSTANCE_REFRESH_REQUEST, 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();
    service = service.toLowerCase();
    Object timerMetric = metric.startTiming(callerTiming, domain);
    metric.increment(HTTP_REQUEST, domain);
    metric.increment(caller, domain);
    // make sure the credentials match to whatever the request is
    Principal principal = ((RsrcCtxWrapper) ctx).principal();
    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);
        }
    }
    if (userDomain.equalsIgnoreCase(domain)) {
        throw requestError("TLS Certificates require ServiceTokens: " + fullServiceName, caller, domain);
    }
    // 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);
    }
    // validate that the cn and public key match to the provided details
    X509CertRequest x509CertReq = null;
    try {
        x509CertReq = new X509CertRequest(req.getCsr());
    } catch (CryptoException ex) {
        throw requestError("Unable to parse PKCS10 certificate request", caller, domain);
    }
    final PKCS10CertificationRequest certReq = x509CertReq.getCertReq();
    if (!ZTSUtils.verifyCertificateRequest(certReq, domain, service, null)) {
        throw requestError("Invalid CSR - data mismatch", caller, domain);
    }
    if (!x509CertReq.comparePublicKeys(publicKey)) {
        throw requestError("Invalid CSR - public key mismatch", caller, domain);
    }
    if (refreshOperation) {
        final String ipAddress = ServletRequestUtil.getRemoteAddress(ctx.request());
        ServiceX509RefreshRequestStatus status = validateServiceX509RefreshRequest(principal, x509CertReq, ipAddress);
        if (status == ServiceX509RefreshRequestStatus.IP_NOT_ALLOWED) {
            throw forbiddenError("IP not allowed for refresh: " + ipAddress, caller, domain);
        }
        if (status != ServiceX509RefreshRequestStatus.SUCCESS) {
            throw requestError("Request valiation failed: " + status, caller, domain);
        }
    }
    // generate identity with the certificate
    int expiryTime = req.getExpiryTime() != null ? req.getExpiryTime() : 0;
    Identity identity = ZTSUtils.generateIdentity(certSigner, req.getCsr(), fullServiceName, null, expiryTime);
    if (identity == null) {
        throw serverError("Unable to generate identity", caller, domain);
    }
    // create our audit log entry
    AuditLogMsgBuilder msgBldr = getAuditLogMsgBuilder(ctx, domain, caller, HTTP_POST);
    msgBldr.whatEntity(fullServiceName);
    X509Certificate newCert = Crypto.loadX509Certificate(identity.getCertificate());
    StringBuilder auditLogDetails = new StringBuilder(512);
    auditLogDetails.append("Provider: ").append(ZTSConsts.ZTS_SERVICE).append(" Domain: ").append(domain).append(" Service: ").append(service).append(" Serial: ").append(newCert.getSerialNumber().toString()).append(" Principal: ").append(principalName).append(" Type: x509");
    msgBldr.whatDetails(auditLogDetails.toString());
    auditLogger.log(msgBldr);
    metric.stopTiming(timerMetric);
    return identity;
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) AuditLogMsgBuilder(com.yahoo.athenz.common.server.log.AuditLogMsgBuilder) Authority(com.yahoo.athenz.auth.Authority) CertificateAuthority(com.yahoo.athenz.auth.impl.CertificateAuthority) X509Certificate(java.security.cert.X509Certificate) X509CertRequest(com.yahoo.athenz.zts.cert.X509CertRequest) CertificateAuthority(com.yahoo.athenz.auth.impl.CertificateAuthority) CryptoException(com.yahoo.athenz.auth.util.CryptoException) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal) Principal(com.yahoo.athenz.auth.Principal)

Example 7 with CryptoException

use of com.yahoo.athenz.auth.util.CryptoException in project athenz by yahoo.

the class CryptoTest method testGenerateX509CertificateInvalid.

@Test
public void testGenerateX509CertificateInvalid() throws IOException {
    Path path = Paths.get("src/test/resources/valid.csr");
    String certStr = new String(Files.readAllBytes(path));
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(certStr);
    PrivateKey caPrivateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    try {
        Crypto.generateX509Certificate(certReq, caPrivateKey, (X500Name) null, 600, true);
        fail();
    } catch (CryptoException ex) {
        assertTrue(true, "Caught excepted exception");
    }
}
Also used : Path(java.nio.file.Path) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) PrivateKey(java.security.PrivateKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) CryptoException(com.yahoo.athenz.auth.util.CryptoException) Test(org.testng.annotations.Test)

Example 8 with CryptoException

use of com.yahoo.athenz.auth.util.CryptoException in project athenz by yahoo.

the class ZTSUtilsTest method testValidateCertReqCommonNameException.

@Test
public void testValidateCertReqCommonNameException() {
    PKCS10CertificationRequest certReq = Mockito.mock(PKCS10CertificationRequest.class);
    Mockito.when(certReq.getSubject()).thenThrow(new CryptoException());
    assertFalse(ZTSUtils.validateCertReqCommonName(certReq, "athenz.syncer"));
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) CryptoException(com.yahoo.athenz.auth.util.CryptoException) Test(org.testng.annotations.Test)

Aggregations

CryptoException (com.yahoo.athenz.auth.util.CryptoException)8 DERIA5String (org.bouncycastle.asn1.DERIA5String)4 Test (org.testng.annotations.Test)4 AuditLogMsgBuilder (com.yahoo.athenz.common.server.log.AuditLogMsgBuilder)3 X509CertRequest (com.yahoo.athenz.zts.cert.X509CertRequest)3 Path (java.nio.file.Path)3 X509Certificate (java.security.cert.X509Certificate)3 PKCS10CertificationRequest (org.bouncycastle.pkcs.PKCS10CertificationRequest)3 Principal (com.yahoo.athenz.auth.Principal)2 SimplePrincipal (com.yahoo.athenz.auth.impl.SimplePrincipal)2 PrincipalToken (com.yahoo.athenz.auth.token.PrincipalToken)2 InstanceConfirmation (com.yahoo.athenz.instance.provider.InstanceConfirmation)2 InstanceProvider (com.yahoo.athenz.instance.provider.InstanceProvider)2 Date (java.util.Date)2 Authority (com.yahoo.athenz.auth.Authority)1 CertificateAuthority (com.yahoo.athenz.auth.impl.CertificateAuthority)1 X509CertRecord (com.yahoo.athenz.zts.cert.X509CertRecord)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 PrivateKey (java.security.PrivateKey)1