Skip to content

Commit 85bb4fc

Browse files
authored
Support mutual TLS using a certificate from a Windows cert store (#235)
Add the ability to use a client certificate located in a Windows certificate store. Previously, the client certificate and private key had to be passed by filepath or file contents. With this change, certificates and keys stored on TPM devices can be used. Add new `WindowsCertPubSub.java` sample to show this in action.
1 parent f956ba6 commit 85bb4fc

File tree

8 files changed

+302
-8
lines changed

8 files changed

+302
-8
lines changed

.github/workflows/ci.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ on:
77
- '!main'
88

99
env:
10-
BUILDER_VERSION: v0.9.11
10+
BUILDER_VERSION: v0.9.14
1111
BUILDER_SOURCE: releases
1212
BUILDER_HOST: https://d19elf31gohf1l.cloudfront.net
1313
PACKAGE_NAME: aws-iot-device-sdk-java-v2

pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
<module>samples/PubSubStress</module>
1515
<module>samples/RawPubSub</module>
1616
<module>samples/Pkcs11PubSub</module>
17+
<module>samples/WindowsCertPubSub</module>
1718
<module>samples/Shadow</module>
1819
<module>samples/Identity</module>
1920
</modules>

samples/Pkcs11PubSub/src/main/java/pkcs11pubsub/Pkcs11PubSub.java

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -131,16 +131,18 @@ public void onConnectionResumed(boolean sessionPresent) {
131131
pkcs11Options.withPrivateKeyObjectLabel(pkcs11KeyLabel);
132132
}
133133

134-
try (
135-
AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder
136-
.newMtlsPkcs11Builder(pkcs11Options)) {
134+
try (AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder
135+
.newMtlsPkcs11Builder(pkcs11Options)) {
137136

138137
if (rootCaPath != null) {
139138
builder.withCertificateAuthorityFromPath(null, rootCaPath);
140139
}
141140

142-
builder.withConnectionEventCallbacks(callbacks).withClientId(clientId)
143-
.withEndpoint(endpoint).withPort((short) port).withCleanSession(true)
141+
builder.withConnectionEventCallbacks(callbacks)
142+
.withClientId(clientId)
143+
.withEndpoint(endpoint)
144+
.withPort((short) port)
145+
.withCleanSession(true)
144146
.withProtocolOperationTimeoutMs(60000);
145147

146148
try (MqttClientConnection connection = builder.build()) {

samples/README.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
* [BasicPubSub](#basicpubsub)
44
* [Pkcs11PubSub](#pkcs11pubsub)
5+
* [WindowsCertPubSub](#windowscertpubsub)
56
* [Shadow](#shadow)
67
* [Jobs](#jobs)
78
* [fleet provisioning](#fleet-provisioning)
@@ -91,6 +92,70 @@ To run this sample using [SoftHSM2](https://www.opendnssec.org/softhsm/) as the
9192
mvn compile exec:java -pl samples/Pkcs11PubSub -Dexec.mainClass=pkcs11pubsub.Pkcs11PubSub -Dexec.args='--endpoint <xxxx-ats.iot.xxxx.amazonaws.com> --cert <certificate.pem.crt> --rootca <AmazonRootCA1.pem> --pkcs11Lib <path/to/libsofthsm2.so> --pin <user-pin> --tokenLabel <token-label> --keyLabel <key-label>'
9293
```
9394
95+
## WindowsCertPubSub
96+
97+
WARNING: Windows only
98+
99+
This sample shows connecting to IoT Core using mutual TLS,
100+
but your certificate and private key are in a
101+
[Windows certificate store](https://docs.microsoft.com/en-us/windows-hardware/drivers/install/certificate-stores),
102+
rather than simply being files on disk.
103+
104+
To run this sample you need the path to your certificate in the store,
105+
which will look something like:
106+
"CurrentUser\MY\A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6"
107+
(where "CurrentUser\MY" is the store and "A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6" is the certificate's thumbprint)
108+
109+
If your certificate and private key are in a
110+
[TPM](https://docs.microsoft.com/en-us/windows/security/information-protection/tpm/trusted-platform-module-overview),
111+
you would use them by passing their certificate store path.
112+
113+
source: `samples/WindowsCertPubSub`
114+
115+
To run this sample with a basic certificate from AWS IoT Core:
116+
117+
1) Create an IoT Thing with a certificate and key if you haven't already.
118+
119+
2) Combine the certificate and private key into a single .pfx file.
120+
121+
You will be prompted for a password while creating this file. Remember it for the next step.
122+
123+
If you have OpenSSL installed:
124+
```powershell
125+
openssl pkcs12 -in certificate.pem.crt -inkey private.pem.key -out certificate.pfx
126+
```
127+
128+
Otherwise use [CertUtil](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/certutil).
129+
```powershell
130+
certutil -mergePFX certificate.pem.crt,private.pem.key certificate.pfx
131+
```
132+
133+
3) Add the .pfx file to a Windows certificate store using PowerShell's
134+
[Import-PfxCertificate](https://docs.microsoft.com/en-us/powershell/module/pki/import-pfxcertificate)
135+
136+
In this example we're adding it to "CurrentUser\My"
137+
138+
```powershell
139+
$mypwd = Get-Credential -UserName 'Enter password below' -Message 'Enter password below'
140+
Import-PfxCertificate -FilePath certificate.pfx -CertStoreLocation Cert:\CurrentUser\My -Password $mypwd.Password
141+
```
142+
143+
Note the certificate thumbprint that is printed out:
144+
```
145+
Thumbprint Subject
146+
---------- -------
147+
A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6 CN=AWS IoT Certificate
148+
```
149+
150+
So this certificate's path would be: "CurrentUser\MY\A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6"
151+
152+
4) Now you can run the sample:
153+
154+
```sh
155+
mvn compile exec:java -pl samples/WindowsCertPubSub "-Dexec.mainClass=windowscertpubsub.WindowsCertPubSub" "-Dexec.args=--endpoint xxxx-ats.iot.xxxx.amazonaws.com --cert CurrentUser\MY\A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6 --rootca AmazonRootCA1.pem"
156+
```
157+
158+
94159
## Shadow
95160

96161
This sample uses the AWS IoT

samples/WindowsCertPubSub/pom.xml

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>software.amazon.awssdk.iotdevicesdk</groupId>
5+
<artifactId>WindowsCertPubSub</artifactId>
6+
<packaging>jar</packaging>
7+
<version>1.0-SNAPSHOT</version>
8+
<name>${project.groupId}:${project.artifactId}</name>
9+
<description>Sample for connecting to AWS IoT Core with certificate in a Windows certificate store</description>
10+
<url>https://github.com/awslabs/aws-iot-device-sdk-java-v2</url>
11+
<properties>
12+
<maven.compiler.source>1.8</maven.compiler.source>
13+
<maven.compiler.target>1.8</maven.compiler.target>
14+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15+
</properties>
16+
<dependencies>
17+
<dependency>
18+
<groupId>software.amazon.awssdk.iotdevicesdk</groupId>
19+
<artifactId>aws-iot-device-sdk</artifactId>
20+
<version>1.0.0-SNAPSHOT</version>
21+
</dependency>
22+
</dependencies>
23+
<build>
24+
<plugins>
25+
<plugin>
26+
<groupId>org.codehaus.mojo</groupId>
27+
<artifactId>exec-maven-plugin</artifactId>
28+
<version>1.4.0</version>
29+
<configuration>
30+
<mainclass>main</mainclass>
31+
</configuration>
32+
</plugin>
33+
<plugin>
34+
<groupId>org.codehaus.mojo</groupId>
35+
<artifactId>build-helper-maven-plugin</artifactId>
36+
<version>3.2.0</version>
37+
<executions>
38+
<execution>
39+
<id>add-source</id>
40+
<phase>generate-sources</phase>
41+
<goals>
42+
<goal>add-source</goal>
43+
</goals>
44+
<configuration>
45+
<sources>
46+
<source>../Utils/CommandLineUtils</source>
47+
</sources>
48+
</configuration>
49+
</execution>
50+
</executions>
51+
</plugin>
52+
</plugins>
53+
</build>
54+
</project>
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
/**
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
* SPDX-License-Identifier: Apache-2.0.
4+
*/
5+
6+
package windowscertpubsub;
7+
8+
import software.amazon.awssdk.crt.*;
9+
import software.amazon.awssdk.crt.io.*;
10+
import software.amazon.awssdk.crt.mqtt.*;
11+
import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder;
12+
13+
import java.nio.charset.StandardCharsets;
14+
import java.util.UUID;
15+
import java.util.concurrent.CompletableFuture;
16+
import java.util.concurrent.CountDownLatch;
17+
import java.util.concurrent.ExecutionException;
18+
19+
import utils.commandlineutils.CommandLineUtils;
20+
21+
public class WindowsCertPubSub {
22+
23+
// When run normally, we want to exit nicely even if something goes wrong
24+
// When run from CI, we want to let an exception escape which in turn causes the
25+
// exec:java task to return a non-zero exit code
26+
static String ciPropValue = System.getProperty("aws.crt.ci");
27+
static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue);
28+
29+
static String clientId = "test-" + UUID.randomUUID().toString();
30+
static String rootCaPath;
31+
static String windowsCertStorePath;
32+
static String endpoint;
33+
static String topic = "test/topic";
34+
static String message = "Hello World!";
35+
static int messagesToPublish = 10;
36+
static int port = 8883;
37+
38+
static CommandLineUtils cmdUtils;
39+
40+
/*
41+
* When called during a CI run, throw an exception that will escape and fail the
42+
* exec:java task When called otherwise, print what went wrong (if anything) and
43+
* just continue (return from main)
44+
*/
45+
static void onApplicationFailure(Throwable cause) {
46+
if (isCI) {
47+
throw new RuntimeException("execution failure", cause);
48+
} else if (cause != null) {
49+
System.out.println("Exception encountered: " + cause.toString());
50+
}
51+
}
52+
53+
public static void main(String[] args) {
54+
55+
cmdUtils = new CommandLineUtils();
56+
cmdUtils.registerProgramName("WindowsCertPubSub");
57+
cmdUtils.addCommonMQTTCommands();
58+
cmdUtils.removeCommand("cert");
59+
cmdUtils.removeCommand("key");
60+
cmdUtils.registerCommand("cert", "<str>", "Path to certificate in Windows cert store. " +
61+
"e.g. \"CurrentUser\\MY\\6ac133ac58f0a88b83e9c794eba156a98da39b4c\"");
62+
cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*').");
63+
cmdUtils.registerCommand("port", "<int>", "Port to connect to on the endpoint (optional, default='8883').");
64+
cmdUtils.registerCommand("topic", "<str>", "Topic to subscribe/publish to (optional, default='test/topic').");
65+
cmdUtils.registerCommand("message", "<str>", "Message to publish (optional, default='Hello World').");
66+
cmdUtils.registerCommand("count", "<int>", "Number of messages to publish (optional, default='10').");
67+
cmdUtils.registerCommand("help", "", "Prints this message");
68+
cmdUtils.sendArguments(args);
69+
70+
if (cmdUtils.hasCommand("help")) {
71+
cmdUtils.printHelp();
72+
System.exit(1);
73+
}
74+
75+
endpoint = cmdUtils.getCommandRequired("endpoint", "");
76+
windowsCertStorePath = cmdUtils.getCommandRequired("cert", "");
77+
rootCaPath = cmdUtils.getCommandOrDefault("root_ca", rootCaPath);
78+
clientId = cmdUtils.getCommandOrDefault("client_id", clientId);
79+
port = Integer.parseInt(cmdUtils.getCommandOrDefault("port", String.valueOf(port)));
80+
topic = cmdUtils.getCommandOrDefault("topic", topic);
81+
message = cmdUtils.getCommandOrDefault("message", message);
82+
messagesToPublish = Integer.parseInt(cmdUtils.getCommandOrDefault("count", String.valueOf(messagesToPublish)));
83+
84+
MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {
85+
@Override
86+
public void onConnectionInterrupted(int errorCode) {
87+
if (errorCode != 0) {
88+
System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
89+
}
90+
}
91+
92+
@Override
93+
public void onConnectionResumed(boolean sessionPresent) {
94+
System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
95+
}
96+
};
97+
98+
try (AwsIotMqttConnectionBuilder builder =
99+
AwsIotMqttConnectionBuilder.newMtlsWindowsCertStorePathBuilder(windowsCertStorePath)) {
100+
101+
if (rootCaPath != null) {
102+
builder.withCertificateAuthorityFromPath(null, rootCaPath);
103+
}
104+
105+
builder.withConnectionEventCallbacks(callbacks)
106+
.withClientId(clientId)
107+
.withEndpoint(endpoint)
108+
.withPort((short) port)
109+
.withCleanSession(true)
110+
.withProtocolOperationTimeoutMs(60000);
111+
112+
try (MqttClientConnection connection = builder.build()) {
113+
114+
CompletableFuture<Boolean> connected = connection.connect();
115+
try {
116+
boolean sessionPresent = connected.get();
117+
System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!");
118+
} catch (Exception ex) {
119+
throw new RuntimeException("Exception occurred during connect", ex);
120+
}
121+
122+
CountDownLatch countDownLatch = new CountDownLatch(messagesToPublish);
123+
124+
CompletableFuture<Integer> subscribed = connection.subscribe(topic, QualityOfService.AT_LEAST_ONCE, (message) -> {
125+
String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
126+
System.out.println("MESSAGE: " + payload);
127+
countDownLatch.countDown();
128+
});
129+
130+
subscribed.get();
131+
132+
int count = 0;
133+
while (count++ < messagesToPublish) {
134+
CompletableFuture<Integer> published = connection.publish(new MqttMessage(topic, message.getBytes(), QualityOfService.AT_LEAST_ONCE, false));
135+
published.get();
136+
Thread.sleep(1000);
137+
}
138+
139+
countDownLatch.await();
140+
141+
CompletableFuture<Void> disconnected = connection.disconnect();
142+
disconnected.get();
143+
}
144+
} catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
145+
onApplicationFailure(ex);
146+
}
147+
148+
CrtResource.waitForNoResources();
149+
150+
System.out.println("Complete!");
151+
}
152+
}

sdk/pom.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
<dependency>
4343
<groupId>software.amazon.awssdk.crt</groupId>
4444
<artifactId>aws-crt</artifactId>
45-
<version>0.15.23</version>
45+
<version>0.16.0</version>
4646
</dependency>
4747
<dependency>
4848
<groupId>org.slf4j</groupId>
@@ -169,7 +169,7 @@
169169
<packages>software.amazon.awssdk.eventstream*</packages>
170170
</group>
171171
</groups>
172-
<excludePackageNames>pubsub:greengrass:identity:jobs:pubsubstress:rawpubsub:pkcs11pubsub:shadow</excludePackageNames>
172+
<excludePackageNames>pubsub:greengrass:identity:jobs:pubsubstress:rawpubsub:pkcs11pubsub:windowscertpubsub:shadow</excludePackageNames>
173173
<header>AWS IoT Device SDK Java V2 API Reference</header>
174174
<bottom>Copyright © 2021. All rights reserved.</bottom>
175175
<links>

sdk/src/main/java/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ public static AwsIotMqttConnectionBuilder newMtlsBuilder(byte[] certificate, byt
129129
/**
130130
* Create a new builder with mTLS, using a PKCS#11 library for private key operations.
131131
*
132+
* NOTE: Unix only
133+
*
132134
* @param pkcs11Options PKCS#11 options
133135
* @return {@link AwsIotMqttConnectionBuilder}
134136
*/
@@ -138,6 +140,24 @@ public static AwsIotMqttConnectionBuilder newMtlsPkcs11Builder(TlsContextPkcs11O
138140
}
139141
}
140142

143+
/**
144+
* Create a new builder with mTLS, using a certificate in a Windows certificate store.
145+
*
146+
* NOTE: Windows only
147+
*
148+
* @param certificatePath Path to certificate in a Windows certificate store.
149+
* The path must use backslashes and end with the
150+
* certificate's thumbprint. Example:
151+
* {@code CurrentUser\MY\A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6}
152+
* @return {@link AwsIotMqttConnectionBuilder}
153+
*/
154+
public static AwsIotMqttConnectionBuilder newMtlsWindowsCertStorePathBuilder(String certificatePath) {
155+
try (TlsContextOptions tlsContextOptions = TlsContextOptions
156+
.createWithMtlsWindowsCertStorePath(certificatePath)) {
157+
return new AwsIotMqttConnectionBuilder(tlsContextOptions);
158+
}
159+
}
160+
141161
/**
142162
* Create a new builder with no default Tls options
143163
*

0 commit comments

Comments
 (0)