Search in sources :

Example 16 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)

Example 17 with X509CertRecord

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

the class FileCertRecordStoreConnection method getCertRecord.

private synchronized X509CertRecord getCertRecord(String provider, String instanceId) {
    File f = new File(rootDir, provider + "-" + instanceId);
    if (!f.exists()) {
        return null;
    }
    X509CertRecord record = null;
    try {
        Path path = Paths.get(f.toURI());
        record = JSON.fromBytes(Files.readAllBytes(path), X509CertRecord.class);
    } catch (IOException e) {
    }
    return record;
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) File(java.io.File) X509CertRecord(com.yahoo.athenz.zts.cert.X509CertRecord)

Example 18 with X509CertRecord

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

the class ZTSImplTest method testPostInstanceRefreshInformationCertDNSMismatch.

@Test
public void testPostInstanceRefreshInformationCertDNSMismatch() 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);
    Path path = Paths.get("src/test/resources/athenz.instanceid.csr");
    String certCsr = new String(Files.readAllBytes(path));
    InstanceProviderManager instanceProviderManager = Mockito.mock(InstanceProviderManager.class);
    InstanceProvider providerClient = Mockito.mock(InstanceProvider.class);
    InstanceConfirmation confirmation = new InstanceConfirmation().setDomain("athenz").setService("production").setProvider("athenz.provider");
    InstanceCertManager instanceManager = Mockito.spy(ztsImpl.instanceCertManager);
    X509CertRecord certRecord = new X509CertRecord();
    certRecord.setInstanceId("1001");
    certRecord.setProvider("athenz.provider");
    certRecord.setService("athenz.production");
    certRecord.setCurrentSerial("16503746516960996918");
    certRecord.setPrevSerial("16503746516960996918");
    Mockito.when(instanceManager.getX509CertRecord("athenz.provider", "1001")).thenReturn(certRecord);
    Mockito.when(instanceProviderManager.getProvider("athenz.provider")).thenReturn(providerClient);
    Mockito.when(providerClient.refreshInstance(Mockito.any())).thenReturn(confirmation);
    path = Paths.get("src/test/resources/valid_cn_x509.cert");
    String pem = new String(Files.readAllBytes(path));
    InstanceIdentity identity = new InstanceIdentity().setName("athenz.production").setX509Certificate(pem);
    Mockito.doReturn(identity).when(instanceManager).generateIdentity(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyInt());
    ztsImpl.instanceProviderManager = instanceProviderManager;
    ztsImpl.instanceCertManager = instanceManager;
    InstanceRefreshInformation info = new InstanceRefreshInformation().setCsr(certCsr);
    CertificateAuthority certAuthority = new CertificateAuthority();
    SimplePrincipal principal = (SimplePrincipal) SimplePrincipal.create("athenz", "production", "v=S1;d=athenz;n=production;s=signature", 0, certAuthority);
    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(), 400);
        assertTrue(ex.getMessage().contains("dnsName attribute mismatch in CSR"));
    }
}
Also used : Path(java.nio.file.Path) InstanceConfirmation(com.yahoo.athenz.instance.provider.InstanceConfirmation) 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) InstanceProvider(com.yahoo.athenz.instance.provider.InstanceProvider) Test(org.testng.annotations.Test)

Example 19 with X509CertRecord

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

the class FileCertRecordStoreConnectionTest method testX509CertOperations.

@Test
public void testX509CertOperations() {
    // make sure the directory does not exist
    ZMSFileChangeLogStore.deleteDirectory(new File("/tmp/zts-cert-tests"));
    FileCertRecordStore store = new FileCertRecordStore(new File("/tmp/zts-cert-tests"));
    FileCertRecordStoreConnection con = (FileCertRecordStoreConnection) store.getConnection();
    assertNotNull(con);
    con.setOperationTimeout(10);
    // first verify that we don't have the entry
    X509CertRecord certRecordCheck = con.getX509CertRecord("ostk", "instance-id");
    assertNull(certRecordCheck);
    // now write the entry
    X509CertRecord certRecord = new X509CertRecord();
    Date now = new Date();
    certRecord.setService("cn");
    certRecord.setProvider("ostk");
    certRecord.setInstanceId("instance-id");
    certRecord.setCurrentIP("current-ip");
    certRecord.setCurrentSerial("current-serial");
    certRecord.setCurrentTime(now);
    certRecord.setPrevIP("prev-ip");
    certRecord.setPrevSerial("prev-serial");
    certRecord.setPrevTime(now);
    boolean result = con.insertX509CertRecord(certRecord);
    assertTrue(result);
    // now read the entry again
    certRecordCheck = con.getX509CertRecord("ostk", "instance-id");
    assertNotNull(certRecordCheck);
    assertEquals(certRecordCheck.getCurrentIP(), "current-ip");
    assertEquals(certRecordCheck.getCurrentSerial(), "current-serial");
    assertEquals(certRecordCheck.getCurrentTime(), now);
    assertEquals(certRecordCheck.getInstanceId(), "instance-id");
    assertEquals(certRecordCheck.getPrevIP(), "prev-ip");
    assertEquals(certRecordCheck.getPrevSerial(), "prev-serial");
    assertEquals(certRecordCheck.getPrevTime(), now);
    assertEquals(certRecordCheck.getProvider(), "ostk");
    assertEquals(certRecordCheck.getService(), "cn");
    // now update the entry
    certRecord.setCurrentIP("updated-ip");
    certRecord.setCurrentSerial("updated-serial");
    result = con.updateX509CertRecord(certRecord);
    assertTrue(result);
    certRecordCheck = con.getX509CertRecord("ostk", "instance-id");
    assertNotNull(certRecordCheck);
    assertEquals(certRecordCheck.getCurrentIP(), "updated-ip");
    assertEquals(certRecordCheck.getCurrentSerial(), "updated-serial");
    assertEquals(certRecordCheck.getCurrentTime(), now);
    assertEquals(certRecordCheck.getInstanceId(), "instance-id");
    assertEquals(certRecordCheck.getPrevIP(), "prev-ip");
    assertEquals(certRecordCheck.getPrevSerial(), "prev-serial");
    assertEquals(certRecordCheck.getPrevTime(), now);
    assertEquals(certRecordCheck.getProvider(), "ostk");
    assertEquals(certRecordCheck.getService(), "cn");
    // now delete the entry
    con.deleteX509CertRecord("ostk", "instance-id");
    certRecordCheck = con.getX509CertRecord("ostk", "instance-id");
    assertNull(certRecordCheck);
    con.close();
}
Also used : File(java.io.File) X509CertRecord(com.yahoo.athenz.zts.cert.X509CertRecord) Date(java.util.Date) Test(org.testng.annotations.Test)

Example 20 with X509CertRecord

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

the class JDBCCertRecordStoreConnectionTest method testUpdateX509Record.

@Test
public void testUpdateX509Record() throws Exception {
    JDBCCertRecordStoreConnection jdbcConn = new JDBCCertRecordStoreConnection(mockConn);
    X509CertRecord certRecord = new X509CertRecord();
    Date now = new Date();
    certRecord.setProvider("ostk");
    certRecord.setService("cn");
    certRecord.setInstanceId("instance-id");
    certRecord.setCurrentIP("current-ip");
    certRecord.setCurrentSerial("current-serial");
    certRecord.setCurrentTime(now);
    certRecord.setPrevIP("prev-ip");
    certRecord.setPrevSerial("prev-serial");
    certRecord.setPrevTime(now);
    Mockito.doReturn(1).when(mockPrepStmt).executeUpdate();
    boolean requestSuccess = jdbcConn.updateX509CertRecord(certRecord);
    assertTrue(requestSuccess);
    Mockito.verify(mockPrepStmt, times(1)).setString(1, "current-serial");
    Mockito.verify(mockPrepStmt, times(1)).setTimestamp(2, new java.sql.Timestamp(now.getTime()));
    Mockito.verify(mockPrepStmt, times(1)).setString(3, "current-ip");
    Mockito.verify(mockPrepStmt, times(1)).setString(4, "prev-serial");
    Mockito.verify(mockPrepStmt, times(1)).setTimestamp(5, new java.sql.Timestamp(now.getTime()));
    Mockito.verify(mockPrepStmt, times(1)).setString(6, "prev-ip");
    Mockito.verify(mockPrepStmt, times(1)).setString(7, "cn");
    Mockito.verify(mockPrepStmt, times(1)).setString(8, "ostk");
    Mockito.verify(mockPrepStmt, times(1)).setString(9, "instance-id");
    jdbcConn.close();
}
Also used : Timestamp(java.sql.Timestamp) X509CertRecord(com.yahoo.athenz.zts.cert.X509CertRecord) Date(java.util.Date) Test(org.testng.annotations.Test)

Aggregations

X509CertRecord (com.yahoo.athenz.zts.cert.X509CertRecord)35 Test (org.testng.annotations.Test)29 SimplePrincipal (com.yahoo.athenz.auth.impl.SimplePrincipal)25 CertificateAuthority (com.yahoo.athenz.auth.impl.CertificateAuthority)24 X509Certificate (java.security.cert.X509Certificate)24 Path (java.nio.file.Path)23 SignedDomain (com.yahoo.athenz.zms.SignedDomain)18 InstanceCertManager (com.yahoo.athenz.zts.cert.InstanceCertManager)18 ChangeLogStore (com.yahoo.athenz.zts.store.ChangeLogStore)18 DataStore (com.yahoo.athenz.zts.store.DataStore)18 MockZMSFileChangeLogStore (com.yahoo.athenz.zts.store.impl.MockZMSFileChangeLogStore)18 ZMSFileChangeLogStore (com.yahoo.athenz.zts.store.impl.ZMSFileChangeLogStore)18 InstanceProvider (com.yahoo.athenz.instance.provider.InstanceProvider)14 InstanceConfirmation (com.yahoo.athenz.instance.provider.InstanceConfirmation)12 Date (java.util.Date)9 CertRecordStore (com.yahoo.athenz.zts.cert.CertRecordStore)4 CertRecordStoreConnection (com.yahoo.athenz.zts.cert.CertRecordStoreConnection)4 Timestamp (java.sql.Timestamp)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 Principal (com.yahoo.athenz.auth.Principal)3