Provisioning a Nerves gateway on AWS IoT Core
A fleet of gateways, each needing an identity no laptop ever touched. Fleet provisioning by claim on AWS IoT Core: the device makes its own key, in Elixir.
I have a batch of gateways to connect to AWS IoT Core. Each one needs its own identity: a private key that never leaves the device and a certificate that AWS trusts. Creating those by hand on a laptop and copying them to each device does not scale, and it means every private key has been on my laptop.
AWS has an answer called fleet provisioning by claim. This post is the whole path as I built it in one day: what goes into the cloud, what the device does, the Elixir code for the interesting parts, and the output I actually got back. I did it as a proof of concept in an ordinary Elixir application on my desk. The end game is a Nerves-based device, and I note along the way what that changes.
Everything specific is replaced by a placeholder in CAPITAL LETTERS. The code is cut down to show the idea; treat it as a map, not as something to paste.
The idea in one picture
factory first boot
| |
every device gets the device connects with the claim,
same CLAIM certificate asks for a certificate of its own
| |
v v
+---------------+ CSR +--------------------------+
| gateway | -------> | AWS IoT Core |
| (makes its | <------- | issues a certificate, |
| own key) | cert | creates the Thing, |
+---------------+ | attaches the policy |
| +--------------------------+
v
from now on: own key + own certificate, the claim is not needed
A claim certificate is an ordinary client certificate with one unusual property: its permissions are tiny. It may connect, and it may talk to the two MQTT topics that make up the provisioning API. It cannot publish telemetry, it cannot read anything. Every device in a batch carries the same one.
The device then does three things:
- generates a private key and a certificate signing request (CSR), locally
- sends the CSR over the claim connection and gets a certificate back
- asks AWS to register it, which creates the Thing (the device's entry in the registry), activates the certificate and attaches the real policy
After that it reconnects with its own certificate.
The cloud side, with Terraform
I keep the cloud side in Terraform, split the way most teams do: one module that describes the resources, and one small folder per environment that calls the module with its own account, region and remote state. State lives in an encrypted, versioned bucket with locking. I log in through the organization's single sign-on (IAM Identity Center), so there are no long-lived access keys anywhere; the Terraform provider is pinned to one named profile and one allowed account id, so a command can never run against the wrong account.
For provisioning by claim the module needs five things.
A thing group. Every provisioned gateway lands in it. Useful later for jobs and for finding them.
The claim policy. This is what makes the shared certificate safe to share:
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": "iot:Connect",
"Resource": "arn:aws:iot:REGION:ACCOUNT_ID:client/bootstrap-*" },
{ "Effect": "Allow", "Action": "iot:Publish",
"Resource": [
"arn:aws:iot:REGION:ACCOUNT_ID:topic/$aws/certificates/create-from-csr/json",
"arn:aws:iot:REGION:ACCOUNT_ID:topic/$aws/provisioning-templates/TEMPLATE_NAME/provision/json"
] },
{ "Effect": "Allow", "Action": "iot:Subscribe",
"Resource": [
"arn:aws:iot:REGION:ACCOUNT_ID:topicfilter/$aws/certificates/create-from-csr/json/accepted",
"arn:aws:iot:REGION:ACCOUNT_ID:topicfilter/$aws/certificates/create-from-csr/json/rejected",
"arn:aws:iot:REGION:ACCOUNT_ID:topicfilter/$aws/provisioning-templates/TEMPLATE_NAME/provision/json/accepted",
"arn:aws:iot:REGION:ACCOUNT_ID:topicfilter/$aws/provisioning-templates/TEMPLATE_NAME/provision/json/rejected"
] },
{ "Effect": "Allow", "Action": "iot:Receive",
"Resource": [ "...the same four topics, as topic/ instead of topicfilter/..." ] }
]
}
Three details that cost me time to get straight:
PublishandReceivetaketopic/ARNs,Subscribetakestopicfilter/ARNs.- With the claim the device must connect with a client id that starts with
bootstrap-. That keeps claim sessions visibly apart from real ones. - You need both
SubscribeandReceive. One lets you ask for the messages, the other lets them be delivered.
The device policy. Attached to every certificate the template issues:
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": "iot:Connect",
"Resource": "arn:aws:iot:REGION:ACCOUNT_ID:client/${iot:Connection.Thing.ThingName}",
"Condition": { "Bool": { "iot:Connection.Thing.IsAttached": "true" } } },
{ "Effect": "Allow", "Action": "iot:Publish",
"Resource": "arn:aws:iot:REGION:ACCOUNT_ID:topic/gw/${iot:Connection.Thing.ThingName}/mgmt/*" },
{ "Effect": "Allow", "Action": "iot:Subscribe",
"Resource": "arn:aws:iot:REGION:ACCOUNT_ID:topicfilter/gw/${iot:Connection.Thing.ThingName}/cmd/*" },
{ "Effect": "Allow", "Action": "iot:Receive",
"Resource": "arn:aws:iot:REGION:ACCOUNT_ID:topic/gw/${iot:Connection.Thing.ThingName}/cmd/*" }
]
}
${iot:Connection.Thing.ThingName} is a policy variable that AWS fills in at
connect time. One policy document serves the whole fleet, and still each device
can only touch its own topics. It works only when the MQTT client id equals
the Thing name, which leads to the decision that simplified everything else:
the Thing name is the device id everywhere. Client id, topic segment,
inventory key. One identity, one variable.
If you write this policy in Terraform, the ${...} must be escaped as
$${...}, or Terraform tries to interpolate it itself.
A role for the provisioning service. IoT Core assumes it to create Things and attach certificates on your behalf. AWS ships a managed policy for exactly this; the trust policy should be limited to your own account.
The provisioning template. A small JSON document that says what happens when a device asks to be registered:
{
"Parameters": {
"SerialNumber": { "Type": "String" },
"HardwareModel": { "Type": "String" },
"AWS::IoT::Certificate::Id": { "Type": "String" }
},
"Resources": {
"thing": {
"Type": "AWS::IoT::Thing",
"Properties": {
"ThingName": { "Ref": "SerialNumber" },
"AttributePayload": { "hardwareModel": { "Ref": "HardwareModel" } },
"ThingGroups": ["THING_GROUP_NAME"]
}
},
"certificate": {
"Type": "AWS::IoT::Certificate",
"Properties": {
"CertificateId": { "Ref": "AWS::IoT::Certificate::Id" },
"Status": "ACTIVE",
"ThingPrincipalType": "EXCLUSIVE_THING"
}
},
"policy": {
"Type": "AWS::IoT::Policy",
"Properties": { "PolicyName": "DEVICE_POLICY_NAME" }
}
}
}
The device sends its serial and model. AWS adds the id of the certificate it
just issued. EXCLUSIVE_THING ties that certificate to this one Thing.
What Terraform does not manage: Things, device certificates and the claim certificate. The first two are created by the template at run time, one per device, and have no business in state. The claim certificate I create with the CLI on purpose, because a certificate created by Terraform has its private key stored in the state file.
Making the claim certificate
Once, per batch, as an administrator:
aws iot create-keys-and-certificate --set-as-active \
--certificate-pem-outfile identity/aws/claim/claim-certificate.pem \
--private-key-outfile identity/aws/claim/claim-private.key \
--query certificateArn --output text
aws iot attach-policy --policy-name CLAIM_POLICY_NAME --target CERTIFICATE_ARN
curl -o identity/aws/trust/AmazonRootCA1.pem \
https://www.amazontrust.com/repository/AmazonRootCA1.pem
Three files come out of this:
- the claim certificate and its private key, which go onto every device
- Amazon's root CA, which is a different kind of thing altogether
The root CA is not a secret and is not yours. It is how the device checks that the server on the other end really is AWS. People mix these up constantly: the claim (and later the device certificate) proves who the device is; the root CA lets the device verify who the server is. Mutual TLS needs both.
In the project the files sit in an identity/ folder that is git-ignored:
identity/aws/
trust/ AmazonRootCA1.pem
claim/ claim-certificate.pem, claim-private.key
pending/ an enrollment in progress
device/ the device's own key and certificate, once enrolled
That administrator login is the last time a human with AWS rights is involved. From here on the device acts alone, with files only.
The device side: an MQTT connection with mutual TLS
I use emqtt, the Erlang MQTT client. One practical note for anyone heading
to Nerves: the Hex package insists on a QUIC NIF that is unpleasant to
cross-compile. Building from the git source with QUIC disabled avoids it:
{:emqtt, github: "emqx/emqtt", tag: "VERSION",
system_env: [{"BUILD_WITHOUT_QUIC", "1"}]}
The connection options are where mutual TLS becomes concrete:
host = ~c"YOUR-ENDPOINT-ats.iot.REGION.amazonaws.com"
opts = [
host: host,
port: 8883,
clientid: "bootstrap-" <> serial,
proto_ver: :v4,
clean_start: true,
keepalive: 30,
reconnect: 0,
ssl: true,
ssl_opts: [
verify: :verify_peer,
cacertfile: ~c"identity/aws/trust/AmazonRootCA1.pem",
certfile: ~c"identity/aws/claim/claim-certificate.pem",
keyfile: ~c"identity/aws/claim/claim-private.key",
server_name_indication: host,
customize_hostname_check: [
match_fun: :public_key.pkix_verify_hostname_match_fun(:https)
]
]
]
{:ok, client} = :emqtt.start_link(opts)
{:ok, _props} = :emqtt.connect(client)
Worth pointing out:
verify: :verify_peerpluscacertfileis the "is this really AWS" half. Never shipverify_none.certfileandkeyfileare the "this is who I am" half.- The
match_funis needed because AWS presents a wildcard certificate and Erlang's default hostname check is stricter than a browser's. reconnect: 0switches off the library's own reconnecting. I want my process to decide when to reconnect. A claim session that quietly comes back to life after the device has moved on to its own certificate is exactly what I do not want.
I wrapped this in one GenServer.
The first time I started the claim connection:
iex> ConnectionManager.start_connection(:aws_claim)
{:ok, #PID<0.439.0>}
[info] MQTT aws_claim: connected to YOUR-ENDPOINT-ats.iot.REGION.amazonaws.com as bootstrap-GATEWAY-SERIAL
iex> ConnectionManager.status(:aws_claim)
%{
name: :aws_claim,
status: :connected,
host: "YOUR-ENDPOINT-ats.iot.REGION.amazonaws.com",
port: 8883,
client_id: "bootstrap-GATEWAY-SERIAL",
subscriptions: [],
last_error: nil
}
That one line proves a lot at once: the endpoint, the root CA, the claim certificate, its policy and the client id rule.
A key and a CSR without OpenSSL
Most examples shell out to the openssl binary. On a Nerves image that binary
may not exist, and I would rather not depend on it. OTP's :public_key can do
the whole thing. I chose an ECC P-256 key: small, fast handshakes, and the
natural fit for a TPM or secure element later.
def generate_key_pem do
key = :public_key.generate_key({:namedCurve, :secp256r1})
:public_key.pem_encode([:public_key.pem_entry_encode(:ECPrivateKey, key)])
end
def csr_pem(key_pem, common_name) do
[entry] = :public_key.pem_decode(key_pem)
{:ECPrivateKey, _, _, _, public_point, _} = key = :public_key.pem_entry_decode(entry)
info =
{:CertificationRequestInfo, :v1,
{:rdnSequence, [[{:AttributeTypeAndValue, {2, 5, 4, 3}, {:utf8String, common_name}}]]},
{:CertificationRequestInfo_subjectPKInfo,
{:CertificationRequestInfo_subjectPKInfo_algorithm, {1, 2, 840, 10045, 2, 1},
{:asn1_OPENTYPE,
:public_key.der_encode(:EcpkParameters, {:namedCurve, {1, 2, 840, 10045, 3, 1, 7}})}},
public_point}, []}
signature =
:public_key.sign(:public_key.der_encode(:CertificationRequestInfo, info), :sha256, key)
request =
{:CertificationRequest, info,
{:CertificationRequest_signatureAlgorithm, {1, 2, 840, 10045, 4, 3, 2}, :asn1_NOVALUE},
signature}
:public_key.pem_encode([
{:CertificationRequest, :public_key.der_encode(:CertificationRequest, request), :not_encrypted}
])
end
The number tuples are object identifiers: common name, EC public key, the P-256 curve, ECDSA with SHA-256. The tuple shapes are what OTP 29 produces when it decodes a CSR made by OpenSSL, which is how I found them: generate one with the tool you trust, decode it, and build the same structure. They differ between OTP generations, so do that exercise on your own version.
To be sure, I checked the result with the tool I was avoiding:
$ openssl req -in device.csr -noout -verify -subject
Certificate request self-signature verify OK
subject=CN=GATEWAY-SERIAL
The private key never appears in the CSR. The CSR carries the public key and a signature that only the private key could have made.
The two calls
The provisioning API is MQTT request and response. You publish to a topic and
the answer arrives on that topic plus /accepted or /rejected.
| Call | Request topic | You send | You get |
|---|---|---|---|
| CreateCertificateFromCsr | $aws/certificates/create-from-csr/json |
the CSR | certificate, its id, an ownership token |
| RegisterThing | $aws/provisioning-templates/TEMPLATE_NAME/provision/json |
the token and the template parameters | the Thing name |
There is no correlation id, so one request at a time, and the order matters: subscribe to both answer topics and wait for the SUBACK before you publish. Otherwise the answer can arrive before you are listening.
def request(client, topic, body, timeout \\ 30_000) do
accepted = topic <> "/accepted"
rejected = topic <> "/rejected"
with {:ok, _, [code1]} when code1 < 0x80 <- :emqtt.subscribe(client, accepted, 1),
{:ok, _, [code2]} when code2 < 0x80 <- :emqtt.subscribe(client, rejected, 1),
{:ok, _packet_id} <- :emqtt.publish(client, topic, Jason.encode!(body), 1) do
receive do
{:publish, %{topic: ^accepted, payload: payload}} ->
Jason.decode(payload)
{:publish, %{topic: ^rejected, payload: payload}} ->
{:error, {:rejected, Jason.decode!(payload)}}
after
timeout -> {:error, :timeout}
end
end
end
The < 0x80 check is not decoration. AWS reports "your policy does not allow
this subscription" as a SUBACK with a failure code, not as an error.
The certificate that comes back from the first call is inactive. The ownership token proves you are the one who requested it, and it is valid for one hour. The second call spends it.
Enrollment as a series of steps that survive a power cut
A gateway can lose power at any moment. If that happens between "AWS issued a certificate" and "I saved it", a naive implementation asks again on the next boot and leaves an orphaned certificate behind each time.
So the rule is: write down what you have before you take the next step, and on every start look at the notes first.
1. key generate the private key -> save it
2. certificate send CSR over the claim -> save certificate + token
3. registered RegisterThing with the token -> note it, forget the token
4. verified connect ONCE with the new cert
5. active rename pending/ to device/
def run(ctx) do
if Store.active?(ctx.dir) do
{:ok, :already_enrolled}
else
with :ok <- ensure_key(ctx),
:ok <- ensure_registered(ctx),
:ok <- verify_and_promote(ctx) do
{:ok, :enrolled}
end
end
end
defp ensure_key(ctx) do
case Store.pending(ctx.dir) do
nil -> Store.put_pending_key(ctx.dir, Keys.generate_key_pem())
_already_there -> :ok
end
end
Each ensure_ function checks the disk and does nothing if its step is
already done. Calling run/1 again after any failure simply continues.
Three checks I would not leave out:
- Does the returned certificate belong to my key? Compare the public key inside the certificate with the public half of the pending key before accepting it.
- Is the Thing name the one I asked for? The answer to RegisterThing must equal the serial.
- Does the new identity actually work? Step 4 opens one real connection with the new certificate, with the real client id. Only then does step 5 make it the active identity.
Step 5 is a single directory rename. Either the device has a complete identity or it has none; there is no moment with a new certificate next to an old key. Files are written to a temporary name, synced, then renamed, and are readable by the owner only.
The real run
Here is what came back when I ran it against AWS, trimmed and with names replaced:
iex> Enrollment.status()
:not_enrolled
iex> Enrollment.run()
[info] MQTT aws_claim: connected to YOUR-ENDPOINT-ats.iot.REGION.amazonaws.com as bootstrap-GATEWAY-SERIAL
subscribe $aws/certificates/create-from-csr/json/accepted
subscribe $aws/certificates/create-from-csr/json/rejected
publish $aws/certificates/create-from-csr/json
{"certificateSigningRequest":"-----BEGIN CERTIFICATE REQUEST-----..."}
received .../create-from-csr/json/accepted
{"certificatePem":"-----BEGIN CERTIFICATE-----...","certificateId":"...","certificateOwnershipToken":"..."}
subscribe $aws/provisioning-templates/TEMPLATE_NAME/provision/json/accepted
subscribe $aws/provisioning-templates/TEMPLATE_NAME/provision/json/rejected
publish $aws/provisioning-templates/TEMPLATE_NAME/provision/json
{"certificateOwnershipToken":"...","parameters":{"SerialNumber":"GATEWAY-SERIAL","HardwareModel":"MODEL"}}
received .../provision/json/accepted
{"deviceConfiguration":{},"thingName":"GATEWAY-SERIAL"}
[info] MQTT aws_enrollment_check: connected to YOUR-ENDPOINT-ats.iot.REGION.amazonaws.com as GATEWAY-SERIAL
[info] Enrollment: GATEWAY-SERIAL is enrolled
{:ok, :enrolled}
[info] MQTT aws_device: connected to YOUR-ENDPOINT-ats.iot.REGION.amazonaws.com as GATEWAY-SERIAL
Watch the client id change: bootstrap-GATEWAY-SERIAL while wearing the
claim, plain GATEWAY-SERIAL afterwards. That is the two policies at work.
It went through on the first attempt, which I credit entirely to having
tested each step against an in-memory fake broker first. The fake is a small
GenServer that implements the five emqtt functions I call and can be told
how to answer. It let me test rejection, timeout, a certificate for the wrong
key and a wrong Thing name without touching AWS.
Things that bit me
The MQTT library logged my token. At debug level emqtt prints every
packet with its payload. During enrollment that payload is the ownership
token. I only noticed because I read my own log. The token was already spent,
but the fix is permanent: that library's log level is capped at warning,
whatever the application's level is.
:logger.set_application_level(:emqtt, :warning)
AWS answers a policy violation by hanging up. Publish to a topic your policy does not allow and you get no error message. The connection closes. If a device mysteriously reconnects in a loop, look at the policy first.
Cleaning up has an order. A certificate must be detached from its Thing, detached from its policies and set inactive before it can be deleted. A policy cannot be deleted while any certificate still uses it. So: devices first, then the claim, then the infrastructure. I wrote small scripts for this on day one, because a proof of concept that enrolls test devices all afternoon leaves a pile behind.
A lost answer leaves an orphan. If the first call times out, AWS may have issued a certificate you never received. It sits there inactive and attached to nothing. It is harmless, but worth a status script that lists certificates with no Thing and no policy.
What is still missing
Anyone holding the claim can register anything. As built, a device that shows the claim and says "I am serial X" gets a certificate for X. For a handful of gateways on my desk that is fine. For a claim baked into thousands of devices it is not: one extracted claim would let someone register fakes.
AWS has a slot for this, the pre-provisioning hook: a Lambda that IoT Core calls just before it registers a Thing, with the parameters the device sent, and that answers yes or no. My plan is to let that Lambda ask the device inventory: is this serial one we built, has it been delivered, and has it not been provisioned already? Two constraints shape that design. AWS waits about five seconds for the answer, so a slow inventory must mean "no, try again later". And the hook runs before the Thing exists, so "provisioned" has to be recorded from a later signal; the device's first connection with its new certificate is the honest one.
Enrollment is still started by hand. Next step: at boot, enrolled means connect; not enrolled with a claim present means enroll, with backoff on network errors and a hard stop on rejections.
What changes on Nerves
The proof of concept runs on a laptop. Moving into firmware changes less than I feared, because the awkward dependencies are already gone:
- No
opensslbinary: keys and CSR are pure OTP. - No QUIC NIF:
emqttis built without it. - The identity folder moves to the writable data partition, which has to
survive an A/B firmware update. The rename-to-promote trick depends on
pending/anddevice/being on the same filesystem. - The claim must not be baked into a firmware image that anyone can download. It belongs to the manufacturing step, written to the device after flashing.
- The private key should eventually live in a secure element, where "save the key file" becomes "keep a handle", and the TLS stack has to sign through it. That is a project of its own.
- Clocks. A device that boots believing it is 1970 fails certificate validation. Time has to be right before TLS.
The short version
- A claim certificate is a shared credential that can do exactly one thing.
- The device makes its own key. Only the CSR travels.
- Two MQTT calls: get a certificate, register the Thing. Subscribe before you publish.
- One identity: Thing name = client id = topic segment. One policy variable then isolates every device.
- Save before each step, verify before you promote, promote with one rename.
- Read your own debug logs before someone else does.