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);
}
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;
}
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"));
}
}
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();
}
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();
}
Aggregations