AWS IoT Core Per-Device Policy Rollout on a Live Fleet

Scoping an IoT Core policy to each device is a two-line change to a JSON document and a rollout problem for every device already in the field. The canary, the proof and the rollback we used on a production fleet.

By VVV Ops ·

AWS IoT Core caches policy documents, so a change to a policy takes between 6 and 8 minutes to become effective. That interval governs the move from one broad fleet policy to an AWS IoT Core per-device policy, because it applies to the rollback as much as to the rollout. We recently moved a client's production fleet onto a scoped policy. Put that number in the schedule before anything is written in JSON.

Most write-ups cover the policy document. The part that goes wrong is getting devices that are already connected onto it, and AWS's own reference pages stop at the syntax. Below is the sequence we used: prove the allow and the deny on a lab device, keep a version to roll back to, move one live certificate, then ten production devices, then the rest.

What a scoped policy resolves at connect time

A per-device policy does not name devices. It uses thing policy variables, which resolve against the registry when the connection is authorized. The one that does the work is iot:Connection.Thing.ThingName, and the docs are specific about where the value comes from: "AWS IoT Core uses the certificate the device presents when it authenticates to determine which thing to use to verify the connection." It is available only over MQTT or MQTT over WebSocket.

There is a condition attached to that convenience. Under non-exclusive thing association, where one certificate can be attached to several things, "the value of clientId in the MQTT connect message or the TLS connection must exactly match the thing name." A device whose client ID is a random UUID will not match, and the variable will not resolve for it. The registry-side alternative is exclusive attachment: attach the certificate to its thing with aws iot attach-thing-principal --thing-principal-type EXCLUSIVE_THING, and AWS IoT makes the association without the client ID having to match.

Two quotas decide the shape of the policy, and both are fixed. A policy document is capped at 2,048 characters excluding white space, and a certificate can carry at most 10 attached policies. That is why the per-device policy exists at all. Enumerating topics per device does not fit in 2,048 characters, and writing one named policy per device does not fit in anyone's operations budget.

The following is an illustrative policy. The account ID and Region are placeholders, and the topic layout is one we invented for the example.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["iot:Connect"],
      "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"],
      "Condition": {
        "Bool": { "iot:Connection.Thing.IsAttached": ["true"] }
      }
    },
    {
      "Effect": "Allow",
      "Action": ["iot:Subscribe"],
      "Resource": ["arn:aws:iot:us-east-1:123456789012:topicfilter/acme/${iot:Connection.Thing.ThingName}/cmd/*"]
    },
    {
      "Effect": "Allow",
      "Action": ["iot:Receive"],
      "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/acme/${iot:Connection.Thing.ThingName}/cmd/*"]
    }
  ]
}

iot:Subscribe is checked against a topicfilter resource and iot:Receive against a topic resource. Grant iot:Subscribe without iot:Receive and the device subscribes successfully and then receives nothing.

The wildcard hiding in ${iot:ClientId}

The policy variable that looks equivalent to the thing name is not. AWS's Device Defender documentation for the overly permissive policy check lists arn:aws:iot:region:account-id:client/${iot:ClientId} as noncompliant and explains why: "Unless iot:Connection.Thing.IsAttached is set to true in the condition keys, this is equivalent to the wildcard \* as in the previous example."

The reasoning is that iot:ClientId is whatever the device sends. A certificate holder who picks a different client ID is still inside the resource pattern. iot:Connection.Thing.IsAttached is the condition that closes it, because it "enforces that only the devices that are both registered in AWS IoT and attached to principal can access the permissions inside the policy."

That check runs as IOT_POLICY_OVERLY_PERMISSIVE_CHECK in the CLI and API, at severity Critical, and it returns the reason code ALLOWS_BROAD_ACCESS_TO_IOT_DATA_PLANE_ACTIONS. Turn it on before you start. The findings are the inventory of policies this work applies to, which beats reading them one at a time.

Prove the allow and the deny before a device moves

aws iot test-authorization answers the question a policy review cannot: given this certificate, this client ID and this topic, what does the broker decide. It takes a --principal (a certificate ARN), up to 10 --auth-infos entries with an actionType of PUBLISH, SUBSCRIBE, RECEIVE or CONNECT, and a --client-id. The CLI reference documents the response: an authDecision of ALLOWED, EXPLICIT_DENY or IMPLICIT_DENY, the policies under allowed and denied, and a missingContextValues list.

# Allowed case: the device's own command topic.
aws iot test-authorization \
  --principal arn:aws:iot:us-east-1:123456789012:cert/EXAMPLECERTID \
  --client-id acme-device-0001 \
  --auth-infos \
    actionType=SUBSCRIBE,resources=arn:aws:iot:us-east-1:123456789012:topicfilter/acme/acme-device-0001/cmd/upgrade \
    actionType=RECEIVE,resources=arn:aws:iot:us-east-1:123456789012:topic/acme/acme-device-0001/cmd/upgrade \
  --query 'authResults[].{action:authInfo.actionType,decision:authDecision,missing:missingContextValues}'

# Denied case: a neighbour's topic, same certificate.
aws iot test-authorization \
  --principal arn:aws:iot:us-east-1:123456789012:cert/EXAMPLECERTID \
  --client-id acme-device-0001 \
  --auth-infos \
    actionType=SUBSCRIBE,resources=arn:aws:iot:us-east-1:123456789012:topicfilter/acme/acme-device-0002/cmd/upgrade \
  --query 'authResults[].authDecision'

On the lab device our engineer moved the certificate to a new, scoped policy version and ran both of these. Subscribe and receive came back allowed on the device's own topic and denied on another device's. The second command is the one worth writing down, because a policy that denies nothing still passes the first.

Check missingContextValues on every deny. The reference describes it as "any missing context values found while evaluating policy", and a deny with entries there says nothing about whether your policy text is correct. AWS states the failure mode for the attribute variant directly: "If the device certificate is not associated with the thing, this variable won't be resolved and will result in an access denied error." Pass --client-id with the thing name on every test, so the call is evaluated the way the device's own connection will be.

The reference scopes --policy-names-to-add and --policy-names-to-skip to custom authorization testing, where listed policies are "treated as if they are attached to the principal being authorized". We did not rely on them. The lab certificate got the real new policy version attached, which is the same code path production will take.

Five policy versions, and Terraform spends them

Named policies are versioned, and the version is the rollback. AWS's own remediation for an overly permissive finding is to call CreatePolicyVersion with setAsDefault set to true, use ListTargetsForPolicy to find every certificate and thing group affected, verify the devices still connect, and if they do not, "use SetPolicyVersion to roll back the default policy to the previous version, revise the policy, and try again." The operation that text means is SetDefaultPolicyVersion, aws iot set-default-policy-version in the CLI. There is no SetPolicyVersion.

The cap is low. A policy can have up to five versions, the quota is not adjustable, and "if the policy has five versions, you must delete an existing version before creating a new one."

This collides with Terraform in a way that is easy to miss. The aws_iot_policy resource notes that updating it creates a new, default policy version, and that if the update would exceed the five-version maximum, the oldest non-default version is deleted first. Iterate on the document through a handful of plan-and-apply cycles, five at most, and the version you wanted to roll back to has been deleted by a successful apply, with no warning.

On this fleet the rollout ran against a policy version created directly, with a rollback ready, and the policy moved into Terraform after the fleet had. We would normally put the policy in Terraform first, and the five-version cap is the argument for doing it afterwards here. Either way, write down the default version ID before the first change. Our Terraform security practices for AWS cover the steady state this ends up in.

Add the 6 to 8 minute cache to the rollback plan. A SetDefaultPolicyVersion call takes effect only once the cache has turned over, so give each wave an observation window longer than the cache.

A canary, a wave of ten, then the fleet

The order we used was one lab device, then one live certificate, then 10 production devices, then the remainder with a rollback ready. All ten production devices in that first wave connected with no errors in AWSIotLogsV2, the CloudWatch log group that AWS IoT V2 logging routes to. Forty-one hours after the fleet rollout everything was still clean, and we recorded the live policy version.

A clean log is evidence only if you know what a denial would have looked like in it. The documented reason codes for message broker failures do not cover one: a Connect failure reports throttled, client_id_throttled or INTERNAL_SERVER_ERROR, and a Subscribe failure reports throttled, CLIENT_ERROR or INTERNAL_SERVER_ERROR, with details such as "Invalid topic filter" or "Client is not connected". Neither table lists a policy denial. AWS's troubleshooting guide names the entry to look for instead, AUTHORIZATION_FAILURE, and the message broker metrics count denials directly: Connect.AuthError, Subscribe.AuthError, and PublishOut.AuthError for publish requests from the broker "that could not be authorized by AWS IoT". A missing iot:Receive grant should show up in the last one.

Watch those three metrics and the log for each wave, and get the proof from test-authorization and the application. A log filter to run per wave:

# Every ERROR-level entry from the last hour of a wave.
aws logs filter-log-events \
  --log-group-name AWSIotLogsV2 \
  --filter-pattern '{ $.logLevel = "ERROR" }' \
  --start-time "$(( ( $(date +%s) - 3600 ) * 1000 ))" \
  --query 'events[].message'

Connection.AuthNError entries carry error codes including DEVICE_CERTIFICATE_INACTIVE, DEVICE_CERTIFICATE_NOT_REGISTERED and DEVICE_CERTIFICATE_REVOKED, but the log format page says they are "opt-in and disabled by default", so enable them before the first wave. Disconnect entries carry a reason of DUPLICATE_CLIENT_ID with the detail "A new connection was established with the same client ID". Expect that one if the client-ID rule bites, and filter for it separately with { $.reason = "DUPLICATE_CLIENT_ID" }: the documented example is logged at INFO, so the ERROR filter above will not return it.

We also asked the application team to re-run their own probe against a canary device and to perform a real update over the air, and to verify the remote-command flow after the fleet rollout. An application-level check on one device catches a missing iot:Receive grant in a minute, and it exercises the real update path from end to end.

More certificates than things

Partway through the rollout our engineer found the registry held more certificates than things. That matters because a per-device policy derives its permissions from the thing behind the certificate, so every extra certificate is an identity whose policy evaluation you have not tested.

Two commands map it. aws iot list-principal-things --principal <certificate-arn> returns the things attached to a certificate, and list-thing-principals goes the other way. Device Defender has the audit checks for the two failure modes that come out of a mismatch. DEVICE_CERTIFICATE_SHARED_CHECK runs at severity Critical with reason code CERTIFICATE_SHARED_BY_MULTIPLE_DEVICES, and looks at concurrent connections across the 31 days before an on-demand audit. CONFLICTING_CLIENT_IDS_CHECK runs at High with reason code DUPLICATE_CLIENT_ID_ACROSS_CONNECTIONS, and the page gives the consequence: "The MQTT specification allows only one active connection per client ID, so when another device connects using the same client ID, it knocks the previous one off the connection."

That is the collision a per-device policy can create. Under non-exclusive association, tying the client ID to the thing name is what makes the policy variable resolve, and if two devices were sharing an identity under the old wide policy, the new rule turns that into a reconnect loop between them.

We proposed deactivating the superseded certificates. It is a one-line command with a wide blast radius:

# Deactivating disconnects every device using this certificate.
aws iot update-certificate \
  --certificate-id d1eb269fb55a628552143c8f96eb3c258fcd5331ea113e766ba0c82bf225f0be \
  --new-status INACTIVE

The CLI reference states the effect: "Within a few minutes of updating a certificate from the ACTIVE state to any other state, IoT disconnects all devices that used that certificate to connect." Run list-principal-things against the certificate first. A certificate you believe is superseded, attached to one thing you forgot, takes that device offline until someone ships a new certificate to it. The same care applies to certificate identity generally, which we wrote about for Kubernetes in pod certificates and mTLS.

If you are planning this change on a fleet that is already in the field, we would look first at the ratio of certificates to things in the registry, and at whether client IDs already equal thing names or the certificates can be attached exclusively. Those facts decide whether a scoped policy is a config change or a provisioning project. Tell us what the registry looks like and we can say which one you have.

Tags: aws iot core per-device policy, iot core thing policy variables, aws iot test-authorization, least privilege iot policy, devsecops implementation, security automation