Search in sources :

Example 1 with X509CertRecord

use of com.yahoo.athenz.zts.cert.X509CertRecord in project athenz by yahoo.

the class ZTSImplTest method testPostOSTKInstanceRefreshRequestCertRecordCnMismatch.

@Test
public void testPostOSTKInstanceRefreshRequestCertRecordCnMismatch() throws IOException {
    Path path = Paths.get("src/test/resources/athenz.instanceid.csr");
    String certCsr = new String(Files.readAllBytes(path));
    OSTKInstanceRefreshRequest req = new OSTKInstanceRefreshRequest().setCsr(certCsr);
    SimplePrincipal principal = (SimplePrincipal) SimplePrincipal.create("athenz", "production", "v=S1,d=athenz;n=production;s=sig", 0, new CertificateAuthority());
    HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
    Mockito.when(servletRequest.isSecure()).thenReturn(true);
    path = Paths.get("src/test/resources/athenz.instanceid.pem");
    String pem = new String(Files.readAllBytes(path));
    X509Certificate cert = Crypto.loadX509Certificate(pem);
    principal.setX509Certificate(cert);
    ResourceContext context = createResourceContext(principal, servletRequest);
    X509CertRecord certRecord = new X509CertRecord();
    certRecord.setService("athenz2.production");
    certRecord.setProvider("ostk");
    CertRecordStore certStore = Mockito.mock(CertRecordStore.class);
    CertRecordStoreConnection certConnection = Mockito.mock(CertRecordStoreConnection.class);
    Mockito.when(certStore.getConnection()).thenReturn(certConnection);
    Mockito.when(certConnection.getX509CertRecord("ostk", "1001")).thenReturn(certRecord);
    zts.instanceCertManager.setCertStore(certStore);
    try {
        zts.postOSTKInstanceRefreshRequest(context, "athenz", "production", req);
        fail();
    } catch (ResourceException ex) {
        assertEquals(ex.getCode(), 400);
        assertTrue(ex.getMessage().contains("cn mismatch"));
    }
}
Also used : Path(java.nio.file.Path) HttpServletRequest(javax.servlet.http.HttpServletRequest) CertRecordStore(com.yahoo.athenz.zts.cert.CertRecordStore) CertRecordStoreConnection(com.yahoo.athenz.zts.cert.CertRecordStoreConnection) CertificateAuthority(com.yahoo.athenz.auth.impl.CertificateAuthority) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal) X509Certificate(java.security.cert.X509Certificate) X509CertRecord(com.yahoo.athenz.zts.cert.X509CertRecord) Test(org.testng.annotations.Test)

Example 2 with X509CertRecord

use of com.yahoo.athenz.zts.cert.X509CertRecord in project athenz by yahoo.

the class ZTSImplTest method testPostInstanceRefreshInformationSSHMismatchSerial.

@Test
public void testPostInstanceRefreshInformationSSHMismatchSerial() throws IOException {
    ChangeLogStore structStore = new ZMSFileChangeLogStore("/tmp/zts_server_unit_tests/zts_root", privateKey, "0");
    DataStore store = new DataStore(structStore, null);
    ZTSImpl ztsImpl = new ZTSImpl(mockCloudStore, store);
    SignedDomain providerDomain = signedAuthorizedProviderDomain();
    store.processDomain(providerDomain, false);
    SignedDomain tenantDomain = signedBootstrapTenantDomain("athenz.provider", "athenz", "production");
    store.processDomain(tenantDomain, false);
    InstanceCertManager instanceManager = Mockito.spy(ztsImpl.instanceCertManager);
    X509CertRecord certRecord = new X509CertRecord();
    certRecord.setInstanceId("1001");
    certRecord.setProvider("athenz.provider");
    certRecord.setService("athenz.production");
    certRecord.setCurrentSerial("123413");
    certRecord.setPrevSerial("123413");
    Mockito.when(instanceManager.getX509CertRecord("athenz.provider", "1001")).thenReturn(certRecord);
    Mockito.when(instanceManager.updateX509CertRecord(Mockito.any())).thenReturn(true);
    ztsImpl.instanceCertManager = instanceManager;
    InstanceRefreshInformation info = new InstanceRefreshInformation().setSsh("ssh-csr");
    CertificateAuthority certAuthority = new CertificateAuthority();
    SimplePrincipal principal = (SimplePrincipal) SimplePrincipal.create("athenz", "production", "v=S1;d=athenz;n=production;s=signature", 0, certAuthority);
    Path path = Paths.get("src/test/resources/athenz.instanceid.pem");
    String pem = new String(Files.readAllBytes(path));
    X509Certificate cert = Crypto.loadX509Certificate(pem);
    principal.setX509Certificate(cert);
    ResourceContext context = createResourceContext(principal);
    try {
        ztsImpl.postInstanceRefreshInformation(context, "athenz.provider", "athenz", "production", "1001", info);
        fail();
    } catch (ResourceException ex) {
        assertEquals(ex.getCode(), 403);
    }
}
Also used : Path(java.nio.file.Path) InstanceCertManager(com.yahoo.athenz.zts.cert.InstanceCertManager) X509CertRecord(com.yahoo.athenz.zts.cert.X509CertRecord) X509Certificate(java.security.cert.X509Certificate) ChangeLogStore(com.yahoo.athenz.zts.store.ChangeLogStore) MockZMSFileChangeLogStore(com.yahoo.athenz.zts.store.impl.MockZMSFileChangeLogStore) ZMSFileChangeLogStore(com.yahoo.athenz.zts.store.impl.ZMSFileChangeLogStore) MockZMSFileChangeLogStore(com.yahoo.athenz.zts.store.impl.MockZMSFileChangeLogStore) ZMSFileChangeLogStore(com.yahoo.athenz.zts.store.impl.ZMSFileChangeLogStore) DataStore(com.yahoo.athenz.zts.store.DataStore) SignedDomain(com.yahoo.athenz.zms.SignedDomain) CertificateAuthority(com.yahoo.athenz.auth.impl.CertificateAuthority) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal) Test(org.testng.annotations.Test)

Example 3 with X509CertRecord

use of com.yahoo.athenz.zts.cert.X509CertRecord in project athenz by yahoo.

the class ZTSImplTest method testPostOSTKInstanceRefreshRequest.

@Test
public void testPostOSTKInstanceRefreshRequest() throws IOException {
    Path path = Paths.get("src/test/resources/athenz.instanceid.csr");
    String certCsr = new String(Files.readAllBytes(path));
    OSTKInstanceRefreshRequest req = new OSTKInstanceRefreshRequest().setCsr(certCsr);
    SimplePrincipal principal = (SimplePrincipal) SimplePrincipal.create("athenz", "production", "v=S1,d=athenz;n=production;s=sig", 0, new CertificateAuthority());
    HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
    Mockito.when(servletRequest.isSecure()).thenReturn(true);
    path = Paths.get("src/test/resources/athenz.instanceid.pem");
    String pem = new String(Files.readAllBytes(path));
    X509Certificate cert = Crypto.loadX509Certificate(pem);
    principal.setX509Certificate(cert);
    ResourceContext context = createResourceContext(principal, servletRequest);
    X509CertRecord certRecord = new X509CertRecord();
    certRecord.setService("athenz.production");
    certRecord.setInstanceId("1001");
    certRecord.setCurrentSerial("16503746516960996918");
    certRecord.setPrevSerial("16503746516960996918");
    CertRecordStore certStore = Mockito.mock(CertRecordStore.class);
    CertRecordStoreConnection certConnection = Mockito.mock(CertRecordStoreConnection.class);
    Mockito.when(certStore.getConnection()).thenReturn(certConnection);
    Mockito.when(certConnection.getX509CertRecord("ostk", "1001")).thenReturn(certRecord);
    Mockito.when(certConnection.updateX509CertRecord(ArgumentMatchers.isA(X509CertRecord.class))).thenReturn(true);
    zts.instanceCertManager.setCertStore(certStore);
    Identity identity = zts.postOSTKInstanceRefreshRequest(context, "athenz", "production", req);
    assertNotNull(identity);
    X509Certificate x509Cert = Crypto.loadX509Certificate(identity.getCertificate());
    assertNotNull(x509Cert);
}
Also used : Path(java.nio.file.Path) HttpServletRequest(javax.servlet.http.HttpServletRequest) CertRecordStore(com.yahoo.athenz.zts.cert.CertRecordStore) CertRecordStoreConnection(com.yahoo.athenz.zts.cert.CertRecordStoreConnection) CertificateAuthority(com.yahoo.athenz.auth.impl.CertificateAuthority) ServiceIdentity(com.yahoo.athenz.zms.ServiceIdentity) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal) X509Certificate(java.security.cert.X509Certificate) X509CertRecord(com.yahoo.athenz.zts.cert.X509CertRecord) Test(org.testng.annotations.Test)

Example 4 with X509CertRecord

use of com.yahoo.athenz.zts.cert.X509CertRecord in project athenz by yahoo.

the class ZTSImpl method postOSTKInstanceRefreshRequest.

// this method will be removed and replaced with call to postInstanceRefreshInformation
@Override
public Identity postOSTKInstanceRefreshRequest(ResourceContext ctx, String domain, String service, OSTKInstanceRefreshRequest req) {
    final String caller = "postostkinstancerefreshrequest";
    final String callerTiming = "postostkinstancerefreshrequest_timing";
    metric.increment(HTTP_POST);
    logPrincipal(ctx);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("postOSTKInstanceRefreshRequest: " + req);
    }
    validateRequest(ctx.request(), caller);
    validate(domain, TYPE_DOMAIN_NAME, caller);
    validate(service, TYPE_SIMPLE_NAME, caller);
    validate(req, TYPE_OSTK_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 principalName = domain + "." + service;
    if (!principalName.equals(principal.getFullName())) {
        throw requestError("postOSTKInstanceRefreshRequest: Principal mismatch: " + principalName + " vs. " + principal.getFullName(), caller, domain);
    }
    Authority authority = principal.getAuthority();
    if (!(authority instanceof CertificateAuthority)) {
        throw requestError("postOSTKInstanceRefreshRequest: Unsupported authority for TLS Certs: " + authority.toString(), caller, domain);
    }
    X509Certificate cert = principal.getX509Certificate();
    X509CertRecord x509CertRecord = instanceCertManager.getX509CertRecord("ostk", cert);
    if (x509CertRecord == null) {
        throw forbiddenError("postOSTKInstanceRefreshRequest: Unable to find certificate record", caller, domain);
    }
    // validate that the cn and public key (if required) match to
    // the provided details
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(req.getCsr());
    if (certReq == null) {
        throw requestError("postOSTKInstanceRefreshRequest: unable to parse PKCS10 certificate request", caller, domain);
    }
    if (!ZTSUtils.verifyCertificateRequest(certReq, domain, service, x509CertRecord)) {
        throw requestError("postOSTKInstanceRefreshRequest: invalid CSR - cn mismatch", caller, domain);
    }
    // now we need to make sure the serial number for the certificate
    // matches to what we had issued previously. If we have a mismatch
    // then we're going to revoke this instance as it has been possibly
    // compromised
    String serialNumber = cert.getSerialNumber().toString();
    if (x509CertRecord.getCurrentSerial().equals(serialNumber)) {
        // update the record to mark current as previous
        // and we'll update the current set with our existing
        // details
        x509CertRecord.setPrevIP(x509CertRecord.getCurrentIP());
        x509CertRecord.setPrevTime(x509CertRecord.getCurrentTime());
        x509CertRecord.setPrevSerial(x509CertRecord.getCurrentSerial());
    } else if (!x509CertRecord.getPrevSerial().equals(serialNumber)) {
        // we have a mismatch for both current and previous serial
        // numbers so we're going to revoke it
        LOGGER.error("postOSTKInstanceRefreshRequest: Revoking certificate refresh for cn: {} " + "instance id: {}, current serial: {}, previous serial: {}, cert serial: {}", principalName, x509CertRecord.getInstanceId(), x509CertRecord.getCurrentSerial(), x509CertRecord.getPrevSerial(), serialNumber);
        x509CertRecord.setPrevSerial("-1");
        x509CertRecord.setCurrentSerial("-1");
        instanceCertManager.updateX509CertRecord(x509CertRecord);
        throw forbiddenError("postOSTKInstanceRefreshRequest: Certificate revoked", caller, domain);
    }
    // generate identity with the certificate
    Identity identity = ZTSUtils.generateIdentity(certSigner, req.getCsr(), principalName, null, 0);
    if (identity == null) {
        throw serverError("Unable to generate identity", caller, domain);
    }
    // need to update our cert record with new certificate details
    X509Certificate newCert = Crypto.loadX509Certificate(identity.getCertificate());
    x509CertRecord.setCurrentSerial(newCert.getSerialNumber().toString());
    x509CertRecord.setCurrentIP(ServletRequestUtil.getRemoteAddress(ctx.request()));
    x509CertRecord.setCurrentTime(new Date());
    if (!instanceCertManager.updateX509CertRecord(x509CertRecord)) {
        throw serverError("postOSTKInstanceRefreshRequest: unable to update cert db", caller, domain);
    }
    metric.stopTiming(timerMetric);
    return identity;
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Authority(com.yahoo.athenz.auth.Authority) CertificateAuthority(com.yahoo.athenz.auth.impl.CertificateAuthority) CertificateAuthority(com.yahoo.athenz.auth.impl.CertificateAuthority) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal) Principal(com.yahoo.athenz.auth.Principal) X509Certificate(java.security.cert.X509Certificate) X509CertRecord(com.yahoo.athenz.zts.cert.X509CertRecord) Date(java.util.Date)

Example 5 with X509CertRecord

use of com.yahoo.athenz.zts.cert.X509CertRecord in project athenz by yahoo.

the class ZTSImpl method postInstanceRegisterInformation.

@Override
public void postInstanceRegisterInformation(ResourceContext ctx, InstanceRegisterInformation info, PostInstanceRegisterInformationResult instanceResult) {
    final String caller = "postinstanceregisterinformation";
    final String callerTiming = "postinstanceregisterinformation_timing";
    metric.increment(HTTP_POST);
    validateRequest(ctx.request(), caller);
    validate(info, TYPE_INSTANCE_REGISTER_INFO, 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)
    AthenzObject.INSTANCE_REGISTER_INFO.convertToLowerCase(info);
    final String domain = info.getDomain();
    final String service = info.getService();
    final String cn = domain + "." + service;
    ((RsrcCtxWrapper) ctx).logPrincipal(cn);
    Object timerMetric = metric.startTiming(callerTiming, domain);
    metric.increment(HTTP_REQUEST, domain);
    metric.increment(caller, domain);
    // before running any checks make sure it's coming from
    // an authorized ip address
    final String ipAddress = ServletRequestUtil.getRemoteAddress(ctx.request());
    if (!instanceCertManager.verifyInstanceCertIPAddress(ipAddress)) {
        throw forbiddenError("Unknown IP: " + ipAddress, caller, domain);
    }
    // run the authorization checks to make sure the provider has been
    // authorized to launch instances in Athenz and the service has
    // authorized this provider to launch its instances
    final String provider = info.getProvider();
    Principal providerService = createPrincipalForName(provider);
    StringBuilder errorMsg = new StringBuilder(256);
    if (!instanceCertManager.authorizeLaunch(providerService, domain, service, authorizer, errorMsg)) {
        throw forbiddenError(errorMsg.toString(), caller, domain);
    }
    // validate request/csr details
    X509CertRequest certReq = null;
    try {
        certReq = new X509CertRequest(info.getCsr());
    } catch (CryptoException ex) {
        throw requestError("unable to parse PKCS10 CSR: " + ex.getMessage(), caller, domain);
    }
    if (!certReq.validate(providerService, domain, service, null, authorizer, errorMsg)) {
        throw requestError("CSR validation failed - " + errorMsg.toString(), caller, domain);
    }
    final String certReqInstanceId = certReq.getInstanceId();
    // validate attestation data is included in the request
    InstanceProvider instanceProvider = instanceProviderManager.getProvider(provider);
    if (instanceProvider == null) {
        throw requestError("unable to get instance for provider: " + provider, caller, domain);
    }
    InstanceConfirmation instance = generateInstanceConfirmObject(ctx, provider, domain, service, info.getAttestationData(), certReq);
    try {
        instance = instanceProvider.confirmInstance(instance);
    } catch (Exception ex) {
        throw forbiddenError("unable to verify attestation data: " + ex.getMessage(), caller, domain);
    } finally {
        instanceProvider.close();
    }
    // determine what type of certificate the provider is authorizing
    // this instance to get - possible values are: server, client or
    // null (indicating both client and server). Additionally, we're
    // going to see if the provider wants to impose an expiry time
    // though the certificate signer might decide to ignore that
    // request and override it with its own value.
    String certUsage = null;
    int certExpiryTime = 0;
    boolean certRefreshAllowed = true;
    Map<String, String> instanceAttrs = instance.getAttributes();
    if (instanceAttrs != null) {
        certUsage = instanceAttrs.remove(ZTSConsts.ZTS_CERT_USAGE);
        final String expiryTime = instanceAttrs.remove(ZTSConsts.ZTS_CERT_EXPIRY_TIME);
        if (expiryTime != null && !expiryTime.isEmpty()) {
            certExpiryTime = Integer.parseInt(expiryTime);
        }
        final String certRefreshState = instanceAttrs.remove(ZTSConsts.ZTS_CERT_REFRESH);
        if (certRefreshState != null && !certRefreshState.isEmpty()) {
            certRefreshAllowed = Boolean.parseBoolean(certRefreshState);
        }
    }
    // generate certificate for the instance
    InstanceIdentity identity = instanceCertManager.generateIdentity(info.getCsr(), cn, certUsage, certExpiryTime);
    if (identity == null) {
        throw serverError("unable to generate identity", caller, domain);
    }
    // if we're asked then we should also generate a ssh
    // certificate for the instance as well
    instanceCertManager.generateSshIdentity(identity, info.getSsh(), ZTSConsts.ZTS_SSH_HOST);
    // set the other required attributes in the identity object
    identity.setAttributes(instanceAttrs);
    identity.setProvider(provider);
    identity.setInstanceId(certReqInstanceId);
    X509Certificate newCert = Crypto.loadX509Certificate(identity.getX509Certificate());
    final String certSerial = newCert.getSerialNumber().toString();
    if (certRefreshAllowed) {
        X509CertRecord x509CertRecord = new X509CertRecord();
        x509CertRecord.setService(cn);
        x509CertRecord.setProvider(provider);
        x509CertRecord.setInstanceId(certReqInstanceId);
        x509CertRecord.setCurrentSerial(certSerial);
        x509CertRecord.setCurrentIP(ServletRequestUtil.getRemoteAddress(ctx.request()));
        x509CertRecord.setCurrentTime(new Date());
        x509CertRecord.setPrevSerial(x509CertRecord.getCurrentSerial());
        x509CertRecord.setPrevIP(x509CertRecord.getCurrentIP());
        x509CertRecord.setPrevTime(x509CertRecord.getCurrentTime());
        x509CertRecord.setClientCert(ZTSConsts.ZTS_CERT_USAGE_CLIENT.equalsIgnoreCase(certUsage));
        if (!instanceCertManager.insertX509CertRecord(x509CertRecord)) {
            throw serverError("unable to update cert db", caller, domain);
        }
    }
    if (info.getToken() == Boolean.TRUE) {
        PrincipalToken svcToken = new PrincipalToken.Builder("S1", domain, service).expirationWindow(svcTokenTimeout).keyId(privateKeyId).host(serverHostName).ip(ServletRequestUtil.getRemoteAddress(ctx.request())).keyService(ZTSConsts.ZTS_SERVICE).build();
        svcToken.sign(privateKey);
        identity.setServiceToken(svcToken.getSignedToken());
    }
    // create our audit log entry
    AuditLogMsgBuilder msgBldr = getAuditLogMsgBuilder(ctx, domain, caller, HTTP_POST);
    msgBldr.whatEntity(certReqInstanceId);
    StringBuilder auditLogDetails = new StringBuilder(512);
    auditLogDetails.append("Provider: ").append(provider).append(" Domain: ").append(domain).append(" Service: ").append(service).append(" InstanceId: ").append(certReqInstanceId).append(" Serial: ").append(certSerial);
    msgBldr.whatDetails(auditLogDetails.toString());
    auditLogger.log(msgBldr);
    final String location = "/zts/v1/instance/" + provider + "/" + domain + "/" + service + "/" + certReqInstanceId;
    metric.stopTiming(timerMetric);
    instanceResult.done(ResourceException.CREATED, identity, location);
}
Also used : InstanceConfirmation(com.yahoo.athenz.instance.provider.InstanceConfirmation) AuditLogMsgBuilder(com.yahoo.athenz.common.server.log.AuditLogMsgBuilder) AuditLogMsgBuilder(com.yahoo.athenz.common.server.log.AuditLogMsgBuilder) PrincipalToken(com.yahoo.athenz.auth.token.PrincipalToken) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CryptoException(com.yahoo.athenz.auth.util.CryptoException) X509Certificate(java.security.cert.X509Certificate) X509CertRecord(com.yahoo.athenz.zts.cert.X509CertRecord) Date(java.util.Date) X509CertRequest(com.yahoo.athenz.zts.cert.X509CertRequest) CryptoException(com.yahoo.athenz.auth.util.CryptoException) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal) Principal(com.yahoo.athenz.auth.Principal) InstanceProvider(com.yahoo.athenz.instance.provider.InstanceProvider)

Aggregations

X509CertRecord (com.yahoo.athenz.zts.cert.X509CertRecord)10 X509Certificate (java.security.cert.X509Certificate)10 SimplePrincipal (com.yahoo.athenz.auth.impl.SimplePrincipal)9 CertificateAuthority (com.yahoo.athenz.auth.impl.CertificateAuthority)8 Path (java.nio.file.Path)7 Test (org.testng.annotations.Test)7 CertRecordStore (com.yahoo.athenz.zts.cert.CertRecordStore)4 CertRecordStoreConnection (com.yahoo.athenz.zts.cert.CertRecordStoreConnection)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 InstanceConfirmation (com.yahoo.athenz.instance.provider.InstanceConfirmation)3 InstanceProvider (com.yahoo.athenz.instance.provider.InstanceProvider)3 SignedDomain (com.yahoo.athenz.zms.SignedDomain)3 InstanceCertManager (com.yahoo.athenz.zts.cert.InstanceCertManager)3 ChangeLogStore (com.yahoo.athenz.zts.store.ChangeLogStore)3 DataStore (com.yahoo.athenz.zts.store.DataStore)3 MockZMSFileChangeLogStore (com.yahoo.athenz.zts.store.impl.MockZMSFileChangeLogStore)3 ZMSFileChangeLogStore (com.yahoo.athenz.zts.store.impl.ZMSFileChangeLogStore)3 Date (java.util.Date)3 Principal (com.yahoo.athenz.auth.Principal)2 ServiceIdentity (com.yahoo.athenz.zms.ServiceIdentity)2