Skip to content

Commit

Permalink
trying to decrypt data in enclave
Browse files Browse the repository at this point in the history
  • Loading branch information
patrykorwat committed Dec 15, 2020
1 parent a0d0016 commit ff34da7
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 44 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ To run the example Host + enclave setup and verify communication, run the follow
```
The command should setup necessary resources and run a host application that calls a service in enclave to invoke a DescribeKey call to KMS.

It's recommended to run example in `ap-southeast-1`. Otherwise, enclave [example](https://github.com/Cloud-Architects/awsenclave/blob/main/aws-enclave-example/aws-enclave-example-enclave/src/main/java/solutions/cloudarchitects/awsenclave/example/enclave/ExampleProxyEnclaveMain.java#L30) code must be adjusted.

## aws-enclave-example-enclave
To build (preferable run from host or other linux):
```shell
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CommitmentPolicy;
import com.amazonaws.encryptionsdk.CryptoResult;
import com.amazonaws.encryptionsdk.kms.KmsMasterKey;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider;
import com.amazonaws.handlers.RequestHandler2;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClientBuilder;
Expand All @@ -24,6 +29,10 @@

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.Map;

@SuppressWarnings({"InfiniteLoopStatement", "ResultOfMethodCallIgnored", "MismatchedReadAndWriteOfArray"})
public class ExampleProxyEnclaveMain {
Expand Down Expand Up @@ -60,42 +69,11 @@ public static void main(String[] args) throws IOException {
Request request = MAPPER.readValue(b, Request.class);

try {
AWSKMS kmsClient = AWSKMSClientBuilder.standard()
.withClientConfiguration(new ClientConfiguration()
.withDnsResolver(new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(String host) throws UnknownHostException {
if ("kms.ap-southeast-1.amazonaws.com".equals(host)) {
return new InetAddress[]{loopbackAddress}; // for host redirection
} else {
return super.resolve(host);
}
}
}))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
"kms.ap-southeast-1.amazonaws.com:8443", AWS_REGION // for port redirection
))
.withRequestHandlers(new RequestHandler2() {
@Override
public AmazonWebServiceRequest beforeExecution(AmazonWebServiceRequest request) {
return super.beforeExecution(request);
}
})
.withCredentials(new AWSStaticCredentialsProvider(
new BasicSessionCredentials(request.credential.accessKeyId,
request.credential.secretAccessKey, request.credential.token)))
.build();

String enclaveKeyId = kmsClient.listAliases().getAliases().stream()
.filter(alias -> alias.getAliasName().equals("alias/enclave"))
.map(AliasListEntry::getTargetKeyId)
.findAny().get();

DescribeKeyResult describeKeyResult = kmsClient.describeKey(new DescribeKeyRequest()
.withKeyId(enclaveKeyId));
AWSKMSClientBuilder clientBuilder = getClientBuilder(loopbackAddress, request);
byte[] decryptedSample = decryptSample(clientBuilder, request);

peerVSock.getOutputStream()
.write(MAPPER.writeValueAsBytes(describeKeyResult));
.write(decryptedSample);
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
peerVSock.getOutputStream()
Expand All @@ -110,4 +88,47 @@ public AmazonWebServiceRequest beforeExecution(AmazonWebServiceRequest request)
server.close();
}
}

private static AWSKMSClientBuilder getClientBuilder(InetAddress loopbackAddress, Request request) {
return AWSKMSClientBuilder.standard()
.withClientConfiguration(new ClientConfiguration()
.withDnsResolver(new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(String host) throws UnknownHostException {
if ("kms.ap-southeast-1.amazonaws.com".equals(host)) {
return new InetAddress[]{loopbackAddress}; // for host redirection
} else {
return super.resolve(host);
}
}
}))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
"kms.ap-southeast-1.amazonaws.com:8443", AWS_REGION // for port redirection
))
.withRequestHandlers(new RequestHandler2() {
@Override
public AmazonWebServiceRequest beforeExecution(AmazonWebServiceRequest request) {
return super.beforeExecution(request);
}
})
.withCredentials(new AWSStaticCredentialsProvider(
new BasicSessionCredentials(request.getCredential().accessKeyId,
request.getCredential().secretAccessKey, request.getCredential().token)));
}

private static byte[] decryptSample(AWSKMSClientBuilder clientBuilder, Request request) {
final AwsCrypto crypto = AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt)
.build();

final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder()
.withDefaultRegion(AWS_REGION)
.withClientBuilder(clientBuilder)
.buildStrict(request.getKeyId());
final Map<String, String> encryptionContext = Collections.singletonMap("enclaveName", "aws-enclave");
final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto
.decryptData(keyProvider, Base64.getDecoder().decode(request.getEncryptedText()));

return decryptResult.getResult();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,22 @@
import com.fasterxml.jackson.annotation.JsonProperty;

public class Request {
public final String encryptedText;
public final EC2MetadataUtils.IAMSecurityCredential credential;
private final String encryptedText;
private final String keyId;
private final EC2MetadataUtils.IAMSecurityCredential credential;

public Request(@JsonProperty("encryptedText") String encryptedText,
@JsonProperty("keyId") String keyId,
@JsonProperty("credential") EC2MetadataUtils.IAMSecurityCredential credential) {
this.encryptedText = encryptedText;
this.keyId = keyId;
this.credential = credential;
}

public String getKeyId() {
return keyId;
}

public String getEncryptedText() {
return encryptedText;
}
Expand Down
1 change: 1 addition & 0 deletions aws-enclave-example/aws-enclave-example-host/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
<argument>solutions.cloudarchitects.awsenclave.example.host.ExampleProxyHostMain</argument>
<argument>${enclave.cid}</argument>
<argument>${encrypted.text}</argument>
<argument>${key.id}</argument>
</arguments>
</configuration>
</plugin>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ public class ExampleProxyHostMain {
private static final Logger LOG = LoggerFactory.getLogger(ExampleProxyHostMain.class);

public static void main(String[] args) throws IOException {
if (args.length != 2) {
throw new IllegalArgumentException("Pass 2 arguments with CID of the enclave and encrypted text");
if (args.length != 3) {
throw new IllegalArgumentException("Pass 2 arguments with CID of the enclave, encrypted text and key id");
}
int enclave_cid = Integer.parseInt(args[0]);
String encryptedText = args[1];
String keyId = args[2];

try (VSock client = new VSock(new VSockAddress(enclave_cid, 5000))) {

Expand All @@ -34,7 +35,7 @@ public static void main(String[] args) throws IOException {
}
EC2MetadataUtils.IAMSecurityCredential credential = credentialOptional.get().getValue();
client.getOutputStream()
.write(MAPPER.writeValueAsBytes(new Request(encryptedText, credential)));
.write(MAPPER.writeValueAsBytes(new Request(encryptedText, keyId, credential)));
byte[] b = new byte[8192];
client.getInputStream().read(b, 0, 8192);
LOG.info("Received: " + new String(b, StandardCharsets.UTF_8));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,22 @@
import com.fasterxml.jackson.annotation.JsonProperty;

public class Request {
public final String encryptedText;
public final EC2MetadataUtils.IAMSecurityCredential credential;
private final String encryptedText;
private final String keyId;
private final EC2MetadataUtils.IAMSecurityCredential credential;

public Request(@JsonProperty("encryptedText") String encryptedText,
@JsonProperty("keyId") String keyId,
@JsonProperty("credential") EC2MetadataUtils.IAMSecurityCredential credential) {
this.encryptedText = encryptedText;
this.keyId = keyId;
this.credential = credential;
}

public String getKeyId() {
return keyId;
}

public String getEncryptedText() {
return encryptedText;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,12 +267,12 @@ public void runVSockProxy(KeyPair keyPair, Ec2Instance ec2Instance, String domai
}
}

public void runHost(KeyPair keyPair, Ec2Instance ec2Instance, String enclaveCid, byte[] bytes) {
public void runHost(KeyPair keyPair, Ec2Instance ec2Instance, String enclaveCid, byte[] bytes, String keyId) {
String encodedEncryptedText = new String(Base64.getEncoder().encode(bytes), StandardCharsets.UTF_8);
String[] setupScript = {
"cd awsenclave",
String.format("./mvnw -f aws-enclave-example/aws-enclave-example-host/pom.xml compile exec:exec " +
"-Denclave.cid=%s -Dencrypted.text=%s", enclaveCid, encodedEncryptedText)
"-Denclave.cid=%s -Dencrypted.text=%s -Dkey.id=%s", enclaveCid, encodedEncryptedText, keyId)
};
try {
LOG.info("running host");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public static void main(String... args) {
byte[] bytes = ownerService.encryptSample(keyId);
ownerService.addPolicy(keyId, enclaveMeasurements, currentUserArn);

parentAdministratorService.runHost(keyPair, ec2Instance, enclaveId, bytes);
parentAdministratorService.runHost(keyPair, ec2Instance, enclaveId, bytes, keyId);
} finally {
TerminateInstancesRequest tir = TerminateInstancesRequest.builder()
.instanceIds(ec2Instance.getInstanceId())
Expand Down

0 comments on commit ff34da7

Please sign in to comment.