

# Security in AWS IoT
<a name="security"></a>

Cloud security at AWS is the highest priority. As an AWS customer, you benefit from a data center and network architecture that is built to meet the requirements of the most security-sensitive organizations.

Security is a shared responsibility between AWS and you. The [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) describes this as security *of* the cloud and security *in* the cloud:
+ **Security of the cloud** – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud. AWS also provides you with services that you can use securely. Third-party auditors regularly test and verify the effectiveness of our security as part of the [AWS compliance programs](https://aws.amazon.com/compliance/programs/). To learn about the compliance programs that apply to AWS IoT, see [AWS Services in Scope by Compliance Program](https://aws.amazon.com/compliance/services-in-scope/).
+ **Security in the cloud** – Your responsibility is determined by the AWS service that you use. You are also responsible for other factors including the sensitivity of your data, your company's requirements, and applicable laws and regulations. 

This documentation helps you understand how to apply the shared responsibility model when using AWS IoT. The following topics show you how to configure AWS IoT to meet your security and compliance objectives. You also learn how to use other AWS services that help you to monitor and secure your AWS IoT resources. 

**Topics**
+ [AWS IoT security](iot-security.md)
+ [Authentication](authentication.md)
+ [Authorization](iot-authorization.md)
+ [Data protection in AWS IoT Core](data-protection.md)
+ [Identity and access management for AWS IoT](security-iam.md)
+ [Logging and Monitoring](security-logging.md)
+ [Compliance validation for AWS IoT Core](compliance.md)
+ [Resilience in AWS IoT Core](disaster-recovery-resiliency.md)
+ [Using AWS IoT Core with interface VPC endpoints](IoTCore-VPC.md)
+ [Infrastructure security in AWS IoT](infrastructure-security.md)
+ [Security monitoring of production fleets or devices with AWS IoT Core](security-monitoring.md)
+ [Security best practices in AWS IoT Core](security-best-practices.md)
+ [AWS training and certification](#iot-security-training)

# AWS IoT security
<a name="iot-security"></a>

Each connected device or client must have a credential to interact with AWS IoT. All traffic to and from AWS IoT is sent securely over Transport Layer Security (TLS). AWS cloud security mechanisms protect data as it moves between AWS IoT and other AWS services.

![\[AWS IoT security workflows including credentials to interact with AWS IoT, Transport Layer Security to secure connection, and AWS Cloud security mechanisms to protect data.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/thunderball-overview.png)

+ You are responsible for managing device credentials (X.509 certificates, AWS credentials, Amazon Cognito identities, federated identities, or custom authentication tokens) and policies in AWS IoT. You are also responsible for assigning unique identities to each device and managing the permissions for each device or group of devices.
+ Your devices connect to AWS IoT using X.509 certificates or Amazon Cognito identities over a secure TLS connection. During research and development, and for some applications that make API calls or use WebSockets, you can also authenticate using IAM users and groups or custom authentication tokens. For more information, see [IAM users, groups, and roles](iam-users-groups-roles.md).
+ When using AWS IoT authentication, the message broker is responsible for authenticating your devices, securely ingesting device data, and granting or denying access permissions you specify for your devices using AWS IoT policies.
+ When using custom authentication, a custom authorizer is responsible for authenticating your devices and granting or denying access permissions you specify for your devices using AWS IoT or IAM policies.
+ The AWS IoT rules engine forwards device data to other devices or other AWS services according to rules you define. It uses AWS Identity and Access Management to securely transfer data to its final destination. For more information, see [Identity and access management for AWS IoT](security-iam.md).

# Authentication
<a name="authentication"></a>

Authentication is a mechanism where you verify the identity of a client or a server. Server authentication is the process where devices or other clients ensure they are communicating with an actual AWS IoT endpoint. Client authentication is the process where devices or other clients authenticate themselves with AWS IoT. 

## X.509 Certificate overview
<a name="x509-certificate-overview"></a>

X.509 certificates are digital certificates that use the [X.509 public key infrastructure standard](https://en.wikipedia.org/wiki/X.509) to associate a public key with an identity contained in a certificate. X.509 certificates are issued by a trusted entity called a certification authority (CA). The CA maintains one or more special certificates called CA certificates that it uses to issue X.509 certificates. Only the certification authority has access to CA certificates. X.509 certificate chains are used both for server authentication by clients and client authentication by the server.

# Server authentication
<a name="server-authentication"></a>

When your device or other client attempts to connect to AWS IoT Core, the AWS IoT Core server will send an X.509 certificate that your device uses to authenticate the server. Authentication takes place at the TLS layer through validation of the [ X.509 certificate chain](x509-client-certs.md). This is the same method used by your browser when you visit an HTTPS URL. If you want to use certificates from your own certificate authority, see [Manage your CA certificates](manage-your-CA-certs.md).

When your devices or other clients establish a TLS connection to an AWS IoT Core endpoint, AWS IoT Core presents a certificate chain that the devices use to verify that they're communicating with AWS IoT Core and not another server impersonating AWS IoT Core. The chain that is presented depends on a combination of the type of endpoint the device is connecting to and the [cipher suite](transport-security.md) that the client and AWS IoT Core negotiated during the TLS handshake.

## Endpoint types
<a name="endpoint-types"></a>

AWS IoT Core supports `iot:Data-ATS`. `iot:Data-ATS` endpoints present a server certificate signed by an [Amazon Trust Services](https://www.amazontrust.com/repository/) CA.

Certificates presented by ATS endpoints are cross signed by Starfield. Some TLS client implementations require validation of the root of trust and require that the Starfield CA certificates are installed in the client's trust stores.

**Warning**  
Using a method of certificate pinning that hashes the whole certificate (including the issuer name, and so on) is not recommended because this will cause certificate verification to fail because the ATS certificates we provide are cross signed by Starfield and have a different issuer name.

**Important**  
Use `iot:Data-ATS` endpoints. Symantec and Verisign certificates have been deprecated and are no longer supported by AWS IoT Core.

You can use the `describe-endpoint` command to create your ATS endpoint.

```
aws iot describe-endpoint --endpoint-type iot:Data-ATS
```

The `describe-endpoint` command returns an endpoint in the following format.

```
account-specific-prefix.iot.your-region.amazonaws.com
```

**Note**  
The first time `describe-endpoint` is called, an endpoint is created. All subsequent calls to `describe-endpoint` return the same endpoint.

**Note**  
To see your `iot:Data-ATS` endpoint in the AWS IoT Core console, choose **Settings**. The console displays only the `iot:Data-ATS` endpoint.

### Creating an `IotDataPlaneClient` with the AWS SDK for Java
<a name="java-client"></a>

To create an `IotDataPlaneClient` that uses an `iot:Data-ATS` endpoint, you must do the following. 
+ Create an `iot:Data-ATS` endpoint by using the [DescribeEndpoint](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeEndpoint.html) API.
+ Specify that endpoint when you create the `IotDataPlaneClient`.

The following example performs both of these operations.

```
public void setup() throws Exception {
        IotClient client = IotClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).region(Region.US_EAST_1).build();
        String endpoint = client.describeEndpoint(r -> r.endpointType("iot:Data-ATS")).endpointAddress();
        iot = IotDataPlaneClient.builder()
                                .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
                                .endpointOverride(URI.create("https://" + endpoint))
                                .region(Region.US_EAST_1)
                                .build();
}
```

## CA certificates for server authentication
<a name="server-authentication-certs"></a>

Depending on which type of data endpoint you are using and which cipher suite you have negotiated, AWS IoT Core server authentication certificates are signed by one of the following root CA certificates:

**Amazon Trust Services Endpoints (preferred)**

**Note**  
You might need to right click these links and select **Save link as...** to save these certificates as files.
+ RSA 2048 bit key: [https://www.amazontrust.com/repository/AmazonRootCA1.pem](https://www.amazontrust.com/repository/AmazonRootCA1.pem).
+ RSA 4096 bit key: Amazon Root CA 2. Reserved for future use.
+ ECC 256 bit key: [https://www.amazontrust.com/repository/AmazonRootCA3.pem](https://www.amazontrust.com/repository/AmazonRootCA3.pem).
+ ECC 384 bit key: Amazon Root CA 4. Reserved for future use.

These certificates are all cross-signed by the [ Starfield Root CA Certificate](https://www.amazontrust.com/repository/SFSRootCAG2.pem). All new AWS IoT Core regions, beginning with the May 9, 2018 launch of AWS IoT Core in the Asia Pacific (Mumbai) Region, serve only ATS certificates.

**VeriSign Endpoints (legacy)**
+ RSA 2048 bit key: [VeriSign Class 3 Public Primary G5 root CA certificate](https://www.digicert.com/kb/digicert-root-certificates.htm)

## Server authentication guidelines
<a name="server-authentication-guidelines"></a>

There are many variables that can affect a device's ability to validate the AWS IoT Core server authentication certificate. For example, devices may be too memory constrained to hold all possible root CA certificates, or devices may implement a non-standard method of certificate validation. For these reasons we suggest following these guidelines:
+ We recommend that you use your ATS endpoint and install all supported Amazon Root CA certificates.
+ If you cannot store all of these certificates on your device and if your devices do not use ECC-based validation, you can omit the [https://www.amazontrust.com/repository/AmazonRootCA3.pem](https://www.amazontrust.com/repository/AmazonRootCA3.pem) and [https://www.amazontrust.com/repository/AmazonRootCA4.pem](https://www.amazontrust.com/repository/AmazonRootCA4.pem) ECC certificates. If your devices do not implement RSA-based certificate validation, you can omit the [https://www.amazontrust.com/repository/AmazonRootCA1.pem](https://www.amazontrust.com/repository/AmazonRootCA1.pem) and [https://www.amazontrust.com/repository/AmazonRootCA2.pem](https://www.amazontrust.com/repository/AmazonRootCA2.pem) RSA certificates. You might need to right click these links and select **Save link as...** to save these certificates as files.
+ If you are experiencing server certificate validation issues when connecting to your ATS endpoint, try adding the relevant cross-signed Amazon Root CA certificate to your trust store. You might need to right click these links and select **Save link as...** to save these certificates as files.
  + [Cross-signed Amazon Root CA 1](https://www.amazontrust.com/repository/G2-RootCA1.pem)
  + [Cross-signed Amazon Root CA 2](https://www.amazontrust.com/repository/G2-RootCA2.pem) - Reserved for future use.
  + [Cross-signed Amazon Root CA 3](https://www.amazontrust.com/repository/G2-RootCA3.pem)
  + [Cross-signed Amazon Root CA 4 - Reserved for future use.](https://www.amazontrust.com/repository/G2-RootCA4.pem)
+ If you are experiencing server certificate validation issues, your device may need to explicitly trust the root CA. Try adding the [https://www.amazontrust.com/repository/SFSRootCAG2.pem](https://www.amazontrust.com/repository/SFSRootCAG2.pem) to your trust store.
+ If you still experience issues after executing the steps above, please contact [AWS Developer Support](https://aws.amazon.com/premiumsupport/plans/developers/). 

**Note**  
CA certificates have an expiration date after which they cannot be used to validate a server's certificate. CA certificates might have to be replaced before their expiration date. Make sure that you can update the root CA certificates on all of your devices or clients to help ensure ongoing connectivity and to keep up to date with security best practices.

**Note**  
When connecting to AWS IoT Core in your device code, pass the certificate into the API you are using to connect. The API you use will vary by SDK. For more information, see the [AWS IoT Core Device SDKs](iot-sdks.md).

# Client authentication
<a name="client-authentication"></a>

AWS IoT supports three types of identity principals for device or client authentication:
+ [X.509 client certificates](x509-client-certs.md)
+ [IAM users, groups, and roles](iam-users-groups-roles.md)
+ [Amazon Cognito identities](cognito-identities.md)

These identities can be used with devices, mobile, web, or desktop applications. They can even be used by a user typing AWS IoT command line interface (CLI) commands. Typically, AWS IoT devices use X.509 certificates, while mobile applications use Amazon Cognito identities. Web and desktop applications use IAM or federated identities. AWS CLI commands use IAM. For more information about IAM identities, see [Identity and access management for AWS IoT](security-iam.md).

# X.509 client certificates
<a name="x509-client-certs"></a>

X.509 certificates provide AWS IoT with the ability to authenticate client and device connections. Client certificates must be registered with AWS IoT before a client can communicate with AWS IoT. A client certificate can be registered in multiple AWS accounts in the same AWS Region to facilitate moving devices between your AWS accounts in the same region. See [Using X.509 client certificates in multiple AWS accounts with multi-account registration](#multiple-account-cert) for more information. 

We recommend that each device or client be given a unique certificate to enable fine-grained client management actions, including certificate revocation. Devices and clients must also support rotation and replacement of certificates to help ensure smooth operation as certificates expire.

For information about using X.509 certificates to support more than a few devices, see [Device provisioning](iot-provision.md) to review the different certificate management and provisioning options that AWS IoT supports.

**AWS IoT supports these types of X.509 client certificates:**
+  X.509 certificates generated by AWS IoT
+  X.509 certificates signed by a CA registered with AWS IoT.
+  X.509 certificates signed by a CA that is not registered with AWS IoT.

This section describes how to manage X.509 certificates in AWS IoT. You can use the AWS IoT console or AWS CLI to perform these certificate operations:
+ [Create AWS IoT client certificates](device-certs-create.md)
+ [Create your own client certificates](device-certs-your-own.md)
+ [Register a client certificate](register-device-cert.md)
+ [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md)
+ [Revoke a client certificate](revoke-ca-cert.md)

For more information about the AWS CLI commands that perform these operations, see [AWS IoT CLI Reference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/index.html).

## Using X.509 client certificates
<a name="x509-client-cert-basics"></a>

X.509 certificates authenticate client and device connections to AWS IoT. X.509 certificates provide several benefits over other identification and authentication mechanisms. X.509 certificates enable asymmetric keys to be used with devices. For example, you could burn private keys into secure storage on a device so that sensitive cryptographic material never leaves the device. X.509 certificates provide stronger client authentication over other schemes, such as user name and password or bearer tokens, because the private key never leaves the device.

AWS IoT authenticates client certificates using the TLS protocol's client authentication mode. TLS support is available in many programming languages and operating systems and is commonly used for encrypting data. In TLS client authentication, AWS IoT requests an X.509 client certificate and validates the certificate's status and AWS account against a registry of certificates. It then challenges the client for proof of ownership of the private key that corresponds to the public key contained in the certificate. AWS IoT requires clients to send the [Server Name Indication (SNI) extension](https://tools.ietf.org/html/rfc3546#section-3.1) to the Transport Layer Security (TLS) protocol. For more information on configuring the SNI extension, see [Transport security in AWS IoT Core](transport-security.md).

To facilitate a secure and consistent client connection to AWS IoT core, a X.509 client certificate must possess the following:
+ Registered in AWS IoT Core. For more information, see [Register a client certificate](register-device-cert.md).
+ Have a status state of `ACTIVE`. For more information, see [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md).
+ Not yet reached the certificate expiration date.

You can create client certificates that use the Amazon Root CA and you can use your own client certificates signed by another certificate authority (CA). For more information about using the AWS IoT console to create certificates that use the Amazon Root CA, see [Create AWS IoT client certificates](device-certs-create.md). For more information about using your own X.509 certificates, see [Create your own client certificates](device-certs-your-own.md).

The date and time when certificates signed by a CA certificate expire are set when the certificate is created. X.509 certificates generated by AWS IoT expire at midnight UTC on December 31, 2049 (2049-12-31T23:59:59Z).

AWS IoT Device Defender can perform audits on your AWS account and devices supporting common IoT security best practices. This includes managing the expiration dates of X.509 certificates signed by your CA or the Amazon Root CA. For more information on managing a certificate's expiration date, see [Device certificate expiring](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/audit-chk-device-cert-approaching-expiration.html) and [CA certificate expiring](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/audit-chk-ca-cert-approaching-expiration.html).

On the official AWS IoT blog, a deeper dive into the management of device certificate rotation and security best practices is explored in [How to manage IoT device certificate rotation using AWS IoT](https://aws.amazon.com/blogs/iot/how-to-manage-iot-device-certificate-rotation-using-aws-iot/).

## Using X.509 client certificates in multiple AWS accounts with multi-account registration
<a name="multiple-account-cert"></a>

Multi-account registration makes it possible to move devices between your AWS accounts in the same Region or in different Regions. You can register, test, and configure a device in a pre-production account, and then register and use the same device and device certificate in a production account. You can also register the client certificate on the device or the device certificates without a CA that is registered with AWS IoT. For more information, see [Register a client certificate signed by an unregistered CA (CLI).](manual-cert-registration.md#manual-cert-registration-noca-cli)

**Note**  
Certificates used for multi-account registration are supported on the `iot:Data-ATS`, `iot:Data` (legacy), `iot:Jobs`, and `iot:CredentialProvider` endpoint types. For more information about AWS IoT device endpoints, see [AWS IoT device data and service endpoints](iot-connect-devices.md#iot-connect-device-endpoints).

Devices that use multi-account registration must send the [Server Name Indication (SNI) extension](https://tools.ietf.org/html/rfc3546#section-3.1) to the Transport Layer Security (TLS) protocol and provide the complete endpoint address in the `host_name` field, when they connect to AWS IoT. AWS IoT uses the endpoint address in `host_name` to route the connection to the correct AWS IoT account. Existing devices that don't send a valid endpoint address in `host_name` will continue to work, but they will not be able to use the features that require this information. For more information about the SNI extension and to learn how to identify the endpoint address for the `host_name` field, see [Transport security in AWS IoT Core](transport-security.md). 

**To use multi-account registration**

1. You can register the device certificates with a CA. You can register the signing CA in multiple accounts in `SNI_ONLY` mode and use that CA to register the same client certificate to multiple accounts. For more information, see [Register a CA certificate in SNI\$1ONLY mode (CLI) - Recommended](manage-your-CA-certs.md#register-CA-cert-SNI-cli).

1. You can register the device certificates without a CA. See [Register a client certificate signed by an unregistered CA (CLI)](manual-cert-registration.md#manual-cert-registration-noca-cli). Registering a CA is optional. You're not required to register the CA that signed the device certificates with AWS IoT.

## Certificate signing algorithms supported by AWS IoT
<a name="x509-cert-algorithms"></a>

AWS IoT supports the following certificate-signing algorithms:
+ SHA256WITHRSA
+ SHA384WITHRSA
+ SHA512WITHRSA
+ SHA256WITHRSAANDMGF1 (RSASSA-PSS)
+ SHA384WITHRSAANDMGF1 (RSASSA-PSS)
+ SHA512WITHRSAANDMGF1 (RSASSA-PSS)
+ DSA\$1WITH\$1SHA256
+ ECDSA-WITH-SHA256
+ ECDSA-WITH-SHA384
+ ECDSA-WITH-SHA512

For more information about certificate authentication and security, see [Device certificate key quality](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/audit-chk-device-cert-key-quality.html).

**Note**  
The certificate signing request (CSR) must include a public key. The key can be either an RSA key with a length of at least 2,048 bits or an ECC key from NIST P-256, NIST P-384, or NIST P-521 curves. For more information, see [CreateCertificateFromCsr](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateCertificateFromCsr.html) in the *AWS IoT API Reference Guide*.

## Key algorithms supported by AWS IoT
<a name="x509-cert-key-algorithms"></a>

The table below shows how key algorithms are supported:


****  

| Key algorithm | Certificate signing algorithm | TLS version | Supported? Yes or No | 
| --- | --- | --- | --- | 
| RSA with a key size of at least 2048 bits | All | TLS 1.2 TLS 1.3 | Yes | 
| ECC NIST P-256/P-384/P-521 | All | TLS 1.2 TLS 1.3 | Yes | 
| RSA-PSS with a key size of at least 2048 bits | All | TLS 1.2 | No | 
| RSA-PSS with a key size of at least 2048 bits | All | TLS 1.3 | Yes | 

To create a certificate using [CreateCertificateFromCSR](https://docs.aws.amazon.com//iot/latest/apireference/API_CreateCertificateFromCsr.html), you can use a supported key algorithm to generate a public key for your CSR. To register your own certificate using [RegisterCertificate](https://docs.aws.amazon.com//iot/latest/apireference/API_RegisterCertificate.html) or [RegisterCertificateWithoutCA](https://docs.aws.amazon.com//iot/latest/apireference/API_RegisterCertificateWithoutCA.html), you can use a supported key algorithm to generate a public key for the certificate.

For more information, see [Security policies](https://docs.aws.amazon.com//iot/latest/developerguide/transport-security.html#tls-policy-table).

# Create AWS IoT client certificates
<a name="device-certs-create"></a>

AWS IoT provides client certificates that are signed by the Amazon Root certificate authority (CA).

This topic describes how to create a client certificate signed by the Amazon Root certificate authority and download the certificate files. After you create the client certificate files, you must install them on the client.

**Note**  
Each X.509 client certificate provided by AWS IoT holds issuer and subject attributes that you set at the time of certificate creation. The certificate attributes are immutable only after the certificate is created.

You can use the AWS IoT console or the AWS CLI to create an AWS IoT certificate signed by the Amazon Root certificate authority.

## Create an AWS IoT certificate (console)
<a name="device-certs-create-console"></a>

**To create an AWS IoT certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the navigation pane, choose **Security**, then choose **Certificates**, and then choose **Create**.

1. Choose **One-click certificate creation (recommended)** - **Create certificate**.

1. From the **Certificate created** page, download the client certificate files for the thing, public key, and private key to a secure location. These certificates generated by AWS IoT are only available for use with AWS IoT services.

   If you also need the Amazon Root CA certificate file, this page also has the link to the page where you can download it.

1. A client certificate has now been created and registered with AWS IoT. You must activate the certificate before you use it in a client.

    To activate the client certificate now, choose **Activate**. If you don't want to activate the certificate now, see [Activate a client certificate (console)](activate-or-deactivate-device-cert.md#activate-device-cert-console) to learn how to activate the certificate later.

   

1. If you want to attach a policy to the certificate, choose **Attach a policy**.

   If you don't want to attach a policy now, choose **Done** to finish. You can attach a policy later.

After you complete the procedure, install the certificate files on the client.

## Create an AWS IoT certificate (CLI)
<a name="device-certs-create-cli"></a>

The AWS CLI provides the **[create-keys-and-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-keys-and-certificate.html)** command to create client certificates signed by the Amazon Root certificate authority. This command, however, does not download the Amazon Root CA certificate file. You can download the Amazon Root CA certificate file from [CA certificates for server authentication](server-authentication.md#server-authentication-certs). 

This command creates private key, public key, and X.509 certificate files and registers and activates the certificate with AWS IoT.

```
aws iot create-keys-and-certificate \
    --set-as-active \
    --certificate-pem-outfile certificate_filename.pem \
    --public-key-outfile public_filename.key \
    --private-key-outfile private_filename.key
```

If you don't want to activate the certificate when you create and register it, this command creates private key, public key, and X.509 certificate files and registers the certificate, but it does not activate it. [Activate a client certificate (CLI)](activate-or-deactivate-device-cert.md#activate-device-cert-cli) describes how to activate the certificate later.

```
aws iot create-keys-and-certificate \
    --no-set-as-active \
    --certificate-pem-outfile certificate_filename.pem \
    --public-key-outfile public_filename.key \
    --private-key-outfile private_filename.key
```



Install the certificate files on the client.

# Create your own client certificates
<a name="device-certs-your-own"></a>

AWS IoT supports client certificates signed by any root or intermediate certificate authorities (CA). AWS IoT uses CA certificates to verify the ownership of certificates. To use device certificates signed by a CA that’s not Amazon’s CA, the CA’s certificate must be registered with AWS IoT so that we can verify the device certificate’s ownership.

AWS IoT supports multiple ways for bringing your own certificates (BYOC): 
+ First, register the CA that’s used for signing the client certificates and then register individual client certificates. If you want to register the device or client to its client certificate when it first connects to AWS IoT (also known as [Just-in-Time Provisioning](https://docs.aws.amazon.com//iot/latest/developerguide/jit-provisioning.html)), you must register the signing CA with AWS IoT and activate auto-registration.
+ If you can’t register the signing CA, you can choose to register client certificates without CA. For devices registered without CA, you’ll need to present [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) when you connect them to AWS IoT.

**Note**  
To register client certificates using CA, you must register the signing CA with AWS IoT, not any other CAs in the hierarchy.

**Note**  
A CA certificate can be registered in `DEFAULT` mode by only one account in a Region. A CA certificate can be registered in `SNI_ONLY` mode by multiple accounts in a Region. 

For more information about using X.509 certificates to support more than a few devices, see [Device provisioning](iot-provision.md) to review the different certificate management and provisioning options that AWS IoT supports.

**Topics**
+ [Manage your CA certificates](manage-your-CA-certs.md)
+ [Create a client certificate using your CA certificate](create-device-cert.md)

# Manage your CA certificates
<a name="manage-your-CA-certs"></a>

This section describes common tasks for managing your own certificate authority (CA) certificates.

You can register your certificate authority (CA) with AWS IoT if you are using client certificates signed by a CA that AWS IoT doesn't recognize.

If you want clients to automatically register their client certificates with AWS IoT when they first connect, the CA that signed the client certificates must be registered with AWS IoT. Otherwise, you don't need to register the CA certificate that signed the client certificates.

**Note**  
A CA certificate can be registered in `DEFAULT` mode by only one account in a Region. A CA certificate can be registered in `SNI_ONLY` mode by multiple accounts in a Region.

**Topics**
+ [Create a CA certificate](#create-your-CA-cert)
+ [Register your CA certificate](#register-CA-cert)
+ [Deactivate a CA certificate](#deactivate-ca-cert)

## Create a CA certificate
<a name="create-your-CA-cert"></a>

If you do not have a CA certificate, you can use [OpenSSL v1.1.1i](https://www.openssl.org/) tools to create one.

**Note**  
You can't perform this procedure in the AWS IoT console.

**To create a CA certificate using [OpenSSL v1.1.1i](https://www.openssl.org/) tools**

1. Generate a key pair.

   ```
   openssl genrsa -out root_CA_key_filename.key 2048
   ```

1. Use the private key from the key pair to generate a CA certificate.

   ```
   openssl req -x509 -new -nodes \
       -key root_CA_key_filename.key \
       -sha256 -days 1024 \
       -out root_CA_cert_filename.pem
   ```

## Register your CA certificate
<a name="register-CA-cert"></a>

These procedures describe how to register a certificate from a certificate authority (CA) that's not Amazon's CA. AWS IoT Core uses CA certificates to verify the ownership of certificates. To use device certificates signed by a CA that's not Amazon's CA, you must register the CA certificate with AWS IoT Core so that it can verify the device certificate's ownership.

### Register a CA certificate (console)
<a name="register-CA-cert-console"></a>

**Note**  
To register a CA certificate in the console, start in the console at [Register CA certificate](https://console.aws.amazon.com//iot/home#/create/cacertificate). You can register your CA in Multi-account mode and without the need to provide a verification certificate or access to the private key. A CA can be registered in Multi-account mode by multiple AWS accounts in the same AWS Region. You can register your CA in Single-account mode by providing a verification certificate and proof of ownership of CA’s private key.

### Register a CA certificate (CLI)
<a name="register-CA-cert-cli"></a>

You can register a CA certificate in `DEFAULT` mode or `SNI_ONLY` mode. A CA can be registered in `DEFAULT` mode by one AWS account in one AWS Region. A CA can be registered in `SNI_ONLY` mode by multiple AWS accounts in the same AWS Region. For more information about CA certificate mode, see [certificateMode](https://docs.aws.amazon.com//iot/latest/apireference/API_CACertificateDescription.html#iot-Type-CACertificateDescription-certificateMode).

**Note**  
We recommend that you register a CA in `SNI_ONLY` mode. You don't need to provide a verification certificate or access to the private key, and you can register the CA by multiple AWS accounts in the same AWS Region.

#### Register a CA certificate in SNI\$1ONLY mode (CLI) - Recommended
<a name="register-CA-cert-SNI-cli"></a>

**Prerequisites**

Make sure you have the following available on your computer before you continue:
+ The root CA's certificate file (referenced in the following example as `root_CA_cert_filename.pem`)
+ [OpenSSL v1.1.1i](https://www.openssl.org/) or later

**To register a CA certificate in `SNI_ONLY` mode using the AWS CLI**

1. Register the CA certificate with AWS IoT. Using the **register-ca-certificate** command, enter the CA certificate file name. For more information, see [register-ca-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-ca-certificate.html) in the *AWS CLI Command Reference*.

   ```
   aws iot register-ca-certificate \
       --ca-certificate file://root_CA_cert_filename.pem \
       --certificate-mode SNI_ONLY
   ```

   If successful, this command returns the *certificateId*.

1. At this point, the CA certificate has been registered with AWS IoT but is inactive. The CA certificate must be active before you can register any client certificates that it has signed.

   This step activates the CA certificate.

   To activate the CA certificate, use the **update-certificate** command as follows. For more information, see [update-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) in the *AWS CLI Command Reference*.

   ```
   aws iot update-ca-certificate \
       --certificate-id certificateId \
       --new-status ACTIVE
   ```

To see the status of the CA certificate, use the **describe-ca-certificate** command. For more information, see [describe-ca-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html) in the *AWS CLI Command Reference*.

#### Register a CA certificate in `DEFAULT` mode (CLI)
<a name="register-CA-cert-default-cli"></a>

**Prerequisites**

Make sure you have the following available on your computer before you continue:
+ The root CA's certificate file (referenced in the following example as `root_CA_cert_filename.pem`)
+ The root CA certificate's private key file (referenced in the following example as `root_CA_key_filename.key`)
+ [OpenSSL v1.1.1i](https://www.openssl.org/) or later

**To register a CA certificate in `DEFAULT` mode using the AWS CLI**

1. To get a registration code from AWS IoT, use **get-registration-code**. Save the returned `registrationCode` to use as the `Common Name` of the private key verification certificate. For more information, see [get-registration-code](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-registration-code.html) in the *AWS CLI Command Reference*.

   ```
   aws iot get-registration-code
   ```

1. Generate a key pair for the private key verification certificate:

   ```
   openssl genrsa -out verification_cert_key_filename.key 2048
   ```

1. Create a certificate signing request (CSR) for the private key verification certificate. Set the `Common Name` field of the certificate to the `registrationCode` returned by **get-registration-code**.

   ```
   openssl req -new \
       -key verification_cert_key_filename.key \
       -out verification_cert_csr_filename.csr
   ```

   You are prompted for some information, including the `Common Name` for the certificate.

   ```
   You are about to be asked to enter information that will be incorporated
   into your certificate request.
   What you are about to enter is what is called a Distinguished Name or a DN.
   There are quite a few fields but you can leave some blank
   For some fields there will be a default value,
   If you enter '.', the field will be left blank.
   -----
   Country Name (2 letter code) [AU]:
       State or Province Name (full name) []:
       Locality Name (for example, city) []:
       Organization Name (for example, company) []:
       Organizational Unit Name (for example, section) []:
       Common Name (e.g. server FQDN or YOUR name) []:your_registration_code
       Email Address []:
   
       Please enter the following 'extra' attributes
       to be sent with your certificate request
       A challenge password []:
       An optional company name []:
   ```

1. Use the CSR to create a private key verification certificate:

   ```
   openssl x509 -req \
       -in verification_cert_csr_filename.csr \
       -CA root_CA_cert_filename.pem \
       -CAkey root_CA_key_filename.key \
       -CAcreateserial \
       -out verification_cert_filename.pem \
       -days 500 -sha256
   ```

1. Register the CA certificate with AWS IoT. Pass in the CA certificate file name and the private key verification certificate file name to the **register-ca-certificate** command, as follows. For more information, see [register-ca-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-ca-certificate.html) in the *AWS CLI Command Reference*.

   ```
   aws iot register-ca-certificate \
       --ca-certificate file://root_CA_cert_filename.pem \
       --verification-cert file://verification_cert_filename.pem
   ```

   This command returns the *certificateId*, if successful.

1. At this point, the CA certificate has been registered with AWS IoT but is not active. The CA certificate must be active before you can register any client certificates it has signed.

   This step activates the CA certificate.

   To activate the CA certificate, use the **update-certificate** command as follows. For more information, see [update-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) in the *AWS CLI Command Reference*.

   ```
   aws iot update-ca-certificate \
       --certificate-id certificateId \
       --new-status ACTIVE
   ```

To see the status of the CA certificate, use the **describe-ca-certificate** command. For more information, see [describe-ca-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html) in the *AWS CLI Command Reference*.

### Create a CA verification certificate to register the CA certificate in the console
<a name="create-CA-verification-cert"></a>

**Note**  
This procedure is only for use if you are registering a CA certificate from the AWS IoT console.  
If you did not come to this procedure from the AWS IoT console, start the CA certificate registration process in the console at [Register CA certificate](https://console.aws.amazon.com//iot/home#/create/cacertificate). 

Make sure you have the following available on the same computer before you continue:
+ The root CA's certificate file (referenced in the following example as `root_CA_cert_filename.pem`)
+ The root CA certificate's private key file (referenced in the following example as `root_CA_key_filename.key`)
+ [OpenSSL v1.1.1i](https://www.openssl.org/) or later

**To use the command line interface to create a CA verification certificate to register your CA certificate in the console**

1. Replace `verification_cert_key_filename.key` with the name of the verification certificate key file that you want to create (for example, **verification\$1cert.key**). Then run this command to generate a key pair for the private key verification certificate:

   ```
   openssl genrsa -out verification_cert_key_filename.key 2048
   ```

1. Replace `verification_cert_key_filename.key` with the name of the key file that you created in step 1.

   Replace `verification_cert_csr_filename.csr` with the name of the certificate signing request (CSR) file that you want to create. For example, **verification\$1cert.csr**.

   Run this command to create the CSR file.

   ```
   openssl req -new \
       -key verification_cert_key_filename.key \
       -out verification_cert_csr_filename.csr
   ```

   The command prompts you for additional information that's explained later.

1. In the AWS IoT console, in the **Verification certificate** container, copy the registration code.

1. The information that the **openssl** command prompts you for is shown in the following example. Except for the `Common Name` field, you can enter your own values or keep them blank.

   In the `Common Name` field, paste the registration code that you copied in the previous step.

   ```
   You are about to be asked to enter information that will be incorporated
   into your certificate request.
   What you are about to enter is what is called a Distinguished Name or a DN.
   There are quite a few fields but you can leave some blank
   For some fields there will be a default value,
   If you enter '.', the field will be left blank.
   -----
   Country Name (2 letter code) [AU]:
       State or Province Name (full name) []:
       Locality Name (for example, city) []:
       Organization Name (for example, company) []:
       Organizational Unit Name (for example, section) []:
       Common Name (e.g. server FQDN or YOUR name) []:your_registration_code
       Email Address []:
   
       Please enter the following 'extra' attributes
       to be sent with your certificate request
       A challenge password []:
       An optional company name []:
   ```

   After you finish, the command creates the CSR file.

1. Replace `verification_cert_csr_filename.csr` with the `verification_cert_csr_filename.csr` you used in the previous step.

   Replace `root_CA_cert_filename.pem` with the file name of the CA certificate that you want to register.

   Replace `root_CA_key_filename.key` with the file name of the CA certificate's private key file.

   Replace `verification_cert_filename.pem` with the file name of the verification certificate that you want to create. For example, **verification\$1cert.pem**.

   ```
   openssl x509 -req \
       -in verification_cert_csr_filename.csr \
       -CA root_CA_cert_filename.pem \
       -CAkey root_CA_key_filename.key \
       -CAcreateserial \
       -out verification_cert_filename.pem \
       -days 500 -sha256
   ```

1. After the OpenSSL command completes, you should have these files ready to use for when you return to the console.
   + Your CA certificate file (`root_CA_cert_filename.pem` used in the previous command)
   + The verification certificate that you created in the previous step (*verification\$1cert\$1filename.pem* used in the previous command)

## Deactivate a CA certificate
<a name="deactivate-ca-cert"></a>

When a certificate authority (CA) certificate is enabled for automatic client certificate registration, AWS IoT checks the CA certificate to make sure the CA is `ACTIVE`. If the CA certificate is `INACTIVE`, AWS IoT doesn't allow the client certificate to be registered.

By setting the CA certificate to `INACTIVE`, you prevent any new client certificates issued by the CA from being registered automatically.

**Note**  
Any registered client certificates that were signed by the compromised CA certificate continue to work until you explicitly revoke each one of them.

### Deactivate a CA certificate (console)
<a name="deactivate-ca-cert-console"></a>

**To deactivate a CA certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **CAs**.

1. In the list of certificate authorities, find the one that you want to deactivate, and choose the ellipsis icon to open the option menu.

1. On the option menu, choose **Deactivate**.

The certificate authority should show as **Inactive** in the list.

**Note**  
The AWS IoT console does not provide a way to list the certificates that were signed by the CA you deactivated. For an AWS CLI option to list those certificates, see [Deactivate a CA certificate (CLI)](#deactivate-ca-cert-cli).

### Deactivate a CA certificate (CLI)
<a name="deactivate-ca-cert-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-ca-certificate.html) command to deactivate a CA certificate.

```
aws iot update-ca-certificate \
    --certificate-id certificateId \
    --new-status INACTIVE
```

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-certificates-by-ca.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-certificates-by-ca.html) command to get a list of all registered client certificates that were signed by the specified CA. For each client certificate signed by the specified CA certificate, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to revoke the client certificate to prevent it from being used.

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html) command to see the status of the CA certificate.

# Create a client certificate using your CA certificate
<a name="create-device-cert"></a>

You can use your own certificate authority (CA) to create client certificates. The client certificate must be registered with AWS IoT before use. For information about the registration options for your client certificates, see [Register a client certificate](register-device-cert.md).

## Create a client certificate (CLI)
<a name="create-device-cert-cli"></a>

**Note**  
You can't perform this procedure in the AWS IoT console.

**To create a client certificate using the AWS CLI**

1. Generate a key pair.

   ```
   openssl genrsa -out device_cert_key_filename.key 2048
   ```

1. Create a CSR for the client certificate.

   ```
   openssl req -new \
       -key device_cert_key_filename.key \
       -out device_cert_csr_filename.csr
   ```

   You are prompted for some information, as shown here:

   ```
   You are about to be asked to enter information that will be incorporated
   into your certificate request.
   What you are about to enter is what is called a Distinguished Name or a DN.
   There are quite a few fields but you can leave some blank
   For some fields there will be a default value,
   If you enter '.', the field will be left blank.
   -----
   Country Name (2 letter code) [AU]:
       State or Province Name (full name) []:
       Locality Name (for example, city) []:
       Organization Name (for example, company) []:
       Organizational Unit Name (for example, section) []:
       Common Name (e.g. server FQDN or YOUR name) []:
       Email Address []:
   
       Please enter the following 'extra' attributes
       to be sent with your certificate request
       A challenge password []:
       An optional company name []:
   ```

1. Create a client certificate from the CSR.

   ```
   openssl x509 -req \
       -in device_cert_csr_filename.csr \
       -CA root_CA_cert_filename.pem \
       -CAkey root_CA_key_filename.key \
       -CAcreateserial \
       -out device_cert_filename.pem \
       -days 500 -sha256
   ```

 At this point, the client certificate has been created, but it has not yet been registered with AWS IoT. For information about how and when to register the client certificate, see [Register a client certificate](register-device-cert.md). 

# Register a client certificate
<a name="register-device-cert"></a>

Client certificates must be registered with AWS IoT to enable communications between the client and AWS IoT. You can register each client certificate manually, or you can configure the client certificates to register automatically when the client connects to AWS IoT for the first time.

 If you want your clients and devices to register their client certificates when they first connect, you must [Register your CA certificate](manage-your-CA-certs.md#register-CA-cert) used to sign the client certificate with AWS IoT in the Regions in which you want to use it. The Amazon Root CA is automatically registered with AWS IoT. 

Client certificates can be shared by AWS accounts and Regions. The procedures in these topics must be performed in each account and Region in which you want to use the client certificate. The registration of a client certificate in one account or Region is not automatically recognized by another.

**Note**  
Clients that use the Transport Layer Security (TLS) protocol to connect to AWS IoT must support the [Server Name Indication (SNI) extension](https://tools.ietf.org/html/rfc3546#section-3.1) to TLS. For more information, see [Transport security in AWS IoT Core](transport-security.md).

**Topics**
+ [Register a client certificate manually](manual-cert-registration.md)
+ [Register a client certificate when the client connects to AWS IoT just-in-time registration (JITR)](auto-register-device-cert.md)

# Register a client certificate manually
<a name="manual-cert-registration"></a>

You can register a client certificate manually by using the AWS IoT console and AWS CLI.

The registration procedure to use depends on whether the certificate will be shared by AWS accounts and Regions. The registration of a client certificate in one account or Region is not automatically recognized by another.

The procedures in this topic must be performed in each account and Region in which you want to use the client certificate. Client certificates can be shared by AWS accounts and Regions. 

## Register a client certificate signed by a registered CA (console)
<a name="manual-cert-registration-console"></a>

**Note**  
Before you perform this procedure, make sure that you have the client certificate's .pem file and that the client certificate was signed by a CA that you have [registered with AWS IoT](manage-your-CA-certs.md#register-CA-cert).

**To register an existing certificate with AWS IoT using the console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the navigation pane, under the **Manage** section, choose **Security**, and then choose **Certificates**.

1. On the **Certificates** page in the **Certificates** dialog box, choose **Add certificate**, and then choose **Register certificates**.

1. On the **Register certificate** page in the **Certificates to upload** dialog box, do the following:
   + Choose **CA is registered with AWS IoT**.
   + From **Choose a CA certificate**, select your **Certification authority**. 
     + Choose **Register a new CA** to register a new **Certification authority** that's not registered with AWS IoT.
     + Leave **Choose a CA certificate** blank if **Amazon Root certificate authority** is your certification authority.
   + Select up to 10 certificates to upload and register with AWS IoT.
     + Use the certificate files you created in [Create AWS IoT client certificates](device-certs-create.md) and [Create a client certificate using your CA certificate](create-device-cert.md).
   + Choose **Activate** or **Deactivate**. If you choose **Deactive**, [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md) explains how to activate your certificate after certificate registration.
   + Choose **Register**.

On the **Certificates** page in the **Certificates** dialog box, your registered certificates will now appear.

## Register a client certificate signed by an unregistered CA (console)
<a name="manual-cert-registration-console-noca"></a>

**Note**  
Before you perform this procedure, make sure that you have the client certificate's .pem file.

**To register an existing certificate with AWS IoT using the console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**, and then choose **Create**.

1. On **Create a certificate**, locate the **Use my certificate** entry, and choose **Get started**.

1. On **Select a CA**, choose **Next**.

1.  On **Register existing device certificates**, choose **Select certificates**, and select up to 10 certificate files to register. 

1.  After closing the file dialog box, select whether you want to activate or revoke the client certificates when you register them.

   If you don't activate a certificate when it is registered, [Activate a client certificate (console)](activate-or-deactivate-device-cert.md#activate-device-cert-console) describes how to activate it later. 

   If a certificate is revoked when it is registered, it can't be activated later.

   After you choose the certificate files to register, and select the actions to take after registration, select **Register certificates**.

The client certificates that are registered successfully appear in the list of certificates.

## Register a client certificate signed by a registered CA (CLI)
<a name="manual-cert-registration-cli"></a>

**Note**  
Before you perform this procedure, make sure that you have the certificate authority (CA) .pem and the client certificate's .pem file. The client certificate must be signed by a certificate authority (CA) that you have [registered with AWS IoT](manage-your-CA-certs.md#register-CA-cert).

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-certificate.html) command to register, but not activate, a client certificate.

```
aws iot register-certificate \
    --certificate-pem file://device_cert_filename.pem \
    --ca-certificate-pem file://ca_cert_filename.pem
```

The client certificate is registered with AWS IoT, but it is not active yet. See [Activate a client certificate (CLI)](activate-or-deactivate-device-cert.md#activate-device-cert-cli) for information on how to activate it later.

You can also activate the client certificate when you register it by using this command.

```
aws iot register-certificate \
    --set-as-active \
    --certificate-pem file://device_cert_filename.pem \
    --ca-certificate-pem file://ca_cert_filename.pem
```

For more information about activating the certificate so that it can be used to connect to AWS IoT, see [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md)

## Register a client certificate signed by an unregistered CA (CLI)
<a name="manual-cert-registration-noca-cli"></a>

**Note**  
Before you perform this procedure, make sure that you have the certificate's .pem file.

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-certificate-without-ca.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-certificate-without-ca.html) command to register, but not activate, a client certificate.

```
aws iot register-certificate-without-ca \
    --certificate-pem file://device_cert_filename.pem
```

The client certificate is registered with AWS IoT, but it is not active yet. See [Activate a client certificate (CLI)](activate-or-deactivate-device-cert.md#activate-device-cert-cli) for information on how to activate it later.

You can also activate the client certificate when you register it by using this command.

```
aws iot register-certificate-without-ca \
    --status ACTIVE \
    --certificate-pem file://device_cert_filename.pem
```

For more information about activating the certificate so that it can be used to connect to AWS IoT, see [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md).

# Register a client certificate when the client connects to AWS IoT just-in-time registration (JITR)
<a name="auto-register-device-cert"></a>

You can configure a CA certificate to enable client certificates it has signed to register with AWS IoT automatically the first time the client connects to AWS IoT.

To register client certificates when a client connects to AWS IoT for the first time, you must enable the CA certificate for automatic registration and configure the first connection by the client to provide the required certificates.

## Configure a CA certificate to support automatic registration (console)
<a name="enable-auto-registration-console"></a>

**To configure a CA certificate to support automatic client certificate registration using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **CAs**.

1. In the list of certificate authorities, find the one for which you want to enable automatic registration, and open the option menu by using the ellipsis icon.

1. On the option menu, choose **Enable auto-registration**.

**Note**  
The auto-registration status is not shown in the list of certificate authorities. To see the auto-registration status of a certificate authority, you must open the **Details** page of the certificate authority.

## Configure a CA certificate to support automatic registration (CLI)
<a name="enable-auto-registration-cli"></a>

If you have already registered your CA certificate with AWS IoT, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-ca-certificate.html) command to set `autoRegistrationStatus` of the CA certificate to `ENABLE`.

```
aws iot update-ca-certificate \
--certificate-id caCertificateId \
--new-auto-registration-status ENABLE
```

If you want to enable `autoRegistrationStatus` when you register the CA certificate, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-ca-certificate.html) command.

```
aws iot register-ca-certificate \
--allow-auto-registration  \
--ca-certificate file://root_CA_cert_filename.pem \
--verification-cert file://verification_cert_filename.pem
```

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html) command to see the status of the CA certificate.

## Configure the first connection by a client for automatic registration
<a name="configure-auto-reg-first-connect"></a>

When a client attempts to connect to AWS IoT for the first time, the client certificate signed by your CA certificate must be present on the client during the Transport Layer Security (TLS) handshake.

When the client connects to AWS IoT, use the client certificate you created in [Create AWS IoT client certificates](https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-create.html) or [Create your own client certificates](https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-your-own.html). AWS IoT recognizes the CA certificate as a registered CA certificate, registers the client certificate, and sets its status to `PENDING_ACTIVATION`. This means that the client certificate was automatically registered and is awaiting activation. The client certificate's state must be `ACTIVE` before it can be used to connect to AWS IoT. See [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md) for information on activating a client certificate.

**Note**  
You can provision devices using AWS IoT Core just-in-time registration (JITR) feature without having to send the entire trust chain on devices' first connection to AWS IoT Core. Presenting the CA certificate is optional but the device is required to send the [Server Name Indication (SNI)](https://datatracker.ietf.org/doc/html/rfc3546#section-3.1) extension when they connect.

When AWS IoT automatically registers a certificate or when a client presents a certificate in the `PENDING_ACTIVATION` status, AWS IoT publishes a message to the following MQTT topic:

`$aws/events/certificates/registered/caCertificateId`

Where `caCertificateId` is the ID of the CA certificate that issued the client certificate.

The message published to this topic has the following structure:

```
{
        "certificateId": "certificateId",
        "caCertificateId": "caCertificateId",
        "timestamp": timestamp,
        "certificateStatus": "PENDING_ACTIVATION",
        "awsAccountId": "awsAccountId",
        "certificateRegistrationTimestamp": "certificateRegistrationTimestamp"
}
```

You can create a rule that listens on this topic and performs some actions. We recommend that you create a Lambda rule that verifies the client certificate is not on a certificate revocation list (CRL), activates the certificate, and creates and attaches a policy to the certificate. The policy determines which resources the client can access. If the policy you are creating requires the client ID from the connecting devices, you can use rule's clientid() function to retrieve the client ID. An example rule definition can look like the following:

```
SELECT *,
   clientid() as clientid
from $aws/events/certificates/registered/caCertificateId
```

In this example, the rule subscribes to the JITR topic `$aws/events/certificates/registered/caCertificateID` and uses the clientid() function to retrieve the client ID. The rule then appends the client ID to the JITR payload. For more information about rule's clientid() function, see [clientid()](https://docs.aws.amazon.com//iot/latest/developerguide/iot-sql-functions.html#iot-sql-function-clientid).

For more information about how to create a Lambda rule that listens on the `$aws/events/certificates/registered/caCertificateID` topic and performs these actions, see [just-in-time registration of Client Certificates on AWS IoT](https://aws.amazon.com/blogs/iot/just-in-time-registration-of-device-certificates-on-aws-iot/).

If any error or exception occurs during the auto-registration of the client certificates, AWS IoT sends events or messages to your logs in CloudWatch Logs. For more information about setting up the logs for your account, see the [Amazon CloudWatch documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/).

# Manage client certificates
<a name="manage-device-cert"></a>

AWS IoT provides capabilities for you to manage client certificates.

**Topics**
+ [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md)
+ [Attach a thing or policy to a client certificate](attach-to-cert.md)
+ [Revoke a client certificate](revoke-ca-cert.md)
+ [Transfer a certificate to another account](transfer-cert.md)

# Activate or deactivate a client certificate
<a name="activate-or-deactivate-device-cert"></a>

AWS IoT verifies that a client certificate is active when it authenticates a connection.

You can create and register client certificates without activating them so they can't be used until you want to use them. You can also deactivate active client certificates to disable them temporarily. Finally, you can revoke client certificates to prevent them from any future use. 

## Activate a client certificate (console)
<a name="activate-device-cert-console"></a>

**To activate a client certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate that you want to activate, and open the option menu by using the ellipsis icon.

1. In the option menu, choose **Activate**.

The certificate should show as **Active** in the list of certificates.

## Deactivate a client certificate (console)
<a name="deactivate-device-cert-console"></a>

**To deactivate a client certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate that you want to deactivate, and open the option menu by using the ellipsis icon.

1. In the option menu, choose **Deactivate**.

The certificate should show as **Inactive** in the list of certificates.

## Activate a client certificate (CLI)
<a name="activate-device-cert-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to activate a certificate.

```
aws iot update-certificate \
    --certificate-id certificateId \
    --new-status ACTIVE
```

If the command was successful, the certificate's status will be `ACTIVE`. Run [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html) to see the certificate's status.

```
aws iot describe-certificate \
    --certificate-id certificateId
```

## Deactivate a client certificate (CLI)
<a name="deactivate-device-cert-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to deactivate a certificate.

```
aws iot update-certificate \
    --certificate-id certificateId \
    --new-status INACTIVE
```

If the command was successful, the certificate's status will be `INACTIVE`. Run [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html) to see the certificate's status.

```
aws iot describe-certificate \
    --certificate-id certificateId
```

# Attach a thing or policy to a client certificate
<a name="attach-to-cert"></a>

When you create and register a certificate separate from an AWS IoT thing, it will not have any policies that authorize any AWS IoT operations, nor will it be associated with any AWS IoT thing object. This section describes how to add these relationships to a registered certificate.

**Important**  
To complete these procedures, you must have already created the thing or policy that you want to attach to the certificate.

The certificate authenticates a device with AWS IoT so that it can connect. Attaching the certificate to a thing resource establishes the relationship between the device (by way of the certificate) and the thing resource. To authorize the device to perform AWS IoT actions, such as to allow the device to connect and publish messages, an appropriate policy must be attached to the device's certificate. 

## Attach a thing to a client certificate (console)
<a name="attach-to-cert-thing-console"></a>

You will need the name of the thing object to complete this procedure.

**To attach a thing object to a registered certificate**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate to which you want to attach a policy, open the certificate's option menu by choosing the ellipsis icon, and choose **Attach thing**.

1. In the pop-up, locate the name of the thing you want to attach to the certificate, choose its check box, and choose **Attach**.

The thing object should now appear in the list of things on the certificate's details page.

## Attach a policy to a client certificate (console)
<a name="attach-to-cert-policy-console"></a>

You will need the name of the policy object to complete this procedure.

**To attach a policy object to a registered certificate**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate to which you want to attach a policy, open the certificate's option menu by choosing the ellipsis icon, and choose **Attach policy**. 

1. In the pop-up, locate the name of the policy you want to attach to the certificate, choose its check box, and choose **Attach**.

The policy object should now appear in the list of policies on the certificate's details page.

## Attach a thing to a client certificate (CLI)
<a name="attach-to-cert-thing-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-thing-principal.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-thing-principal.html) command to attach a thing object to a certificate.

```
aws iot attach-thing-principal \
    --principal certificateArn \
    --thing-name thingName
```

## Attach a policy to a client certificate (CLI)
<a name="attach-to-cert-policy-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-policy.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-policy.html) command to attach a policy object to a certificate.

```
aws iot attach-policy \
    --target certificateArn \
    --policy-name policyName
```

# Revoke a client certificate
<a name="revoke-ca-cert"></a>

If you detect suspicious activity on a registered client certificate, you can revoke it so that it can't be used again.

**Note**  
Once a certificate is revoked, it's status can't be changed. That is, the certificate status can't be changed to `Active` or any other status.

## Revoke a client certificate (console)
<a name="revoke-device-cert-console"></a>

**To revoke a client certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate that you want to revoke, and open the option menu by using the ellipsis icon.

1. In the option menu, choose **Revoke**.

If the certificate was successfully revoked, it will show as **Revoked** in the list of certificates.

## Revoke a client certificate (CLI)
<a name="revoke-device-cert-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to revoke a certificate.

```
aws iot update-certificate \
    --certificate-id certificateId \
    --new-status REVOKED
```

If the command was successful, the certificate's status will be `REVOKED`. Run [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html) to see the certificate's status.

```
aws iot describe-certificate \
    --certificate-id certificateId
```

# Transfer a certificate to another account
<a name="transfer-cert"></a>

X.509 certificates that belong to one AWS account can be transferred to another AWS account.

**To transfer an X.509 certificate from one AWS account to another**

1. [Begin a certificate transfer](#transfer-cert-init)

   The certificate must be deactivated and detached from all policies and things before initiating the transfer.

1. [Accept or reject a certificate transfer](#transfer-cert-accept)

   The receiving account must explicitly accept or reject the transferred certificate. After the receiving account accepts the certificate, the certificate must be activated before use.

1. [Cancel a certificate transfer](#transfer-cert-cancel)

   The originating account can cancel a transfer, if the certificate has not been accepted.

## Begin a certificate transfer
<a name="transfer-cert-init"></a>

You can begin to transfer a certificate to another AWS account by using the [AWS IoT console](https://console.aws.amazon.com/iot/home) or the AWS CLI.

### Begin a certificate transfer (console)
<a name="transfer-cert-init-console"></a>

To complete this procedure, you'll need the ID of the certificate that you want to transfer.

Do this procedure from the account with the certificate to transfer.

**To begin to transfer a certificate to another AWS account**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

   Choose the certificate with an **Active** or **Inactive** status that you want to transfer and open its details page.

1. On the certificate's **Details** page, in the **Actions** menu, if the **Deactivate** option is available, choose the **Deactivate** option to deactivate the certificate.

1. On the certificate's **Details** page, in the left menu, choose **Policies**.

1. On the certificate's **Policies** page, if there are any policies attached to the certificate, detach each one by opening the policy's options menu and choosing **Detach**.

   The certificate must not have any attached policies before you continue.

1. On the certificate's **Policies** page, in the left menu, choose **Things**.

1. On the certificate's **Things** page, if there are any things attached to the certificate, detach each one by opening the thing's options menu and choosing **Detach**.

   The certificate must not have any attached things before you continue.

1. On the certificate's **Things** page, in the left menu, choose **Details**.

1. On the certificate's **Details** page, in the **Actions** menu, choose **Start transfer** to open the **Start transfer** dialog box.

1. In the **Start transfer** dialog box, enter the AWS account number of the account to receive the certificate and an optional short message.

1. Choose **Start transfer** to transfer the certificate.

The console should display a message that indicates the success or failure of the transfer. If the transfer was started, the certificate's status is updated to **Transferred**.

### Begin a certificate transfer (CLI)
<a name="transfer-cert-init-cli"></a>

To complete this procedure, you'll need the *certificateId* and the *certificateArn* of the certificate that you want to transfer.

Do this procedure from the account with the certificate to transfer.

**To begin to transfer a certificate to another AWS account**

1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to deactivate the certificate.

   ```
   aws iot update-certificate --certificate-id certificateId --new-status INACTIVE
   ```

1. Detach all policies.

   1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-attached-policies.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-attached-policies.html) command to list the policies attached to the certificate.

      ```
      aws iot list-attached-policies --target certificateArn
      ```

   1. For each attached policy, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-policy.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-policy.html) command to detach the policy.

      ```
      aws iot detach-policy --target certificateArn --policy-name policy-name
      ```

1. Detach all things.

   1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-principal-things.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-principal-things.html) command to list the things attached to the certificate.

      ```
      aws iot list-principal-things --principal certificateArn
      ```

   1. For each attached thing, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-thing-principal.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-thing-principal.html) command to detach the thing.

      ```
      aws iot detach-thing-principal --principal certificateArn --thing-name thing-name
      ```

1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/transfer-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/transfer-certificate.html) command to start the certificate transfer.

   ```
   aws iot transfer-certificate --certificate-id certificateId --target-aws-account account-id
   ```

## Accept or reject a certificate transfer
<a name="transfer-cert-accept"></a>

You can accept or reject a certificate transferred to you AWS account from another AWS account by using the [AWS IoT console](https://console.aws.amazon.com/iot/home) or the AWS CLI.

### Accept or reject a certificate transfer (console)
<a name="transfer-cert-accept-console"></a>

To complete this procedure, you'll need the ID of the certificate that was transferred to your account.

Do this procedure from the account receiving the certificate that was transferred.

**To accept or reject a certificate that was transferred to your AWS account**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

   Choose the certificate with a status of **Pending transfer** that you want to accept or reject and open its details page.

1. On the certificate's **Details** page, in the **Actions** menu,
   + To accept the certificate, choose **Accept transfer**.
   + To not accept the certificate, choose **Reject transfer**.

### Accept or reject a certificate transfer (CLI)
<a name="transfer-cert-accept-cli"></a>

To complete this procedure, you'll need the *certificateId* of the certificate transfer that you want to accept or reject.

Do this procedure from the account receiving the certificate that was transferred.

**To accept or reject a certificate that was transferred to your AWS account**

1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/accept-certificate-transfer.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/accept-certificate-transfer.html) command to accept the certificate.

   ```
   aws iot accept-certificate-transfer --certificate-id certificateId
   ```

1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/reject-certificate-transfer.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/reject-certificate-transfer.html) command to reject the certificate.

   ```
   aws iot reject-certificate-transfer --certificate-id certificateId
   ```

## Cancel a certificate transfer
<a name="transfer-cert-cancel"></a>

You can cancel a certificate transfer before it has been accepted by using the [AWS IoT console](https://console.aws.amazon.com/iot/home) or the AWS CLI.

### Cancel a certificate transfer (console)
<a name="transfer-cert-cancel-console"></a>

To complete this procedure, you'll need the ID of the certificate transfer that you want to cancel.

Do this procedure from the account that initiated the certificate transfer.

**To cancel a certificate transfer**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

   Choose the certificate with **Transferred** status whose transfer you want to cancel and open its options menu.

1. On the certificate's options menu, choose the **Revoke transfer** option to cancel the certificate transfer.
**Important**  
Be careful not to mistake the **Revoke transfer** option with the **Revoke** option.  
The **Revoke transfer** option cancels the certificate transfer, while the **Revoke** option makes the certificate irreversibly unusable by AWS IoT. 

### Cancel a certificate transfer (CLI)
<a name="transfer-cert-cancel-cli"></a>

To complete this procedure, you'll need the *certificateId* of the certificate transfer that you want to cancel.

Do this procedure from the account that initiated the certificate transfer.

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/cancel-certificate-transfer.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/cancel-certificate-transfer.html) command to cancel the certificate transfer.

```
aws iot cancel-certificate-transfer --certificate-id certificateId
```

# Custom client certificate validation
<a name="customize-client-auth"></a>

AWS IoT Core supports custom client certificate validation for X.509 client certificates, which enhances client authentication management. This certificate validation method is also known as pre-authentication certificate checks, in which you evaluate client certificates based on your own criteria (defined in a Lambda function) and revoke client certificates or the certificates' signing certificate authority (CA) certificate to prevent clients to connect to AWS IoT Core. For example, you can create your own certificate revocation checks that validate the certificates' status against validation authorities that support [Online Certificate Status Protocol (OCSP)](https://en.wikipedia.org/wiki/Online_Certificate_Status_Protocol) or [Certificate Revocation Lists (CRL)](https://en.wikipedia.org/wiki/Certificate_revocation_list) endpoints, and prevent connections for clients with revoked certificates. The criteria used to evaluate client certificates are defined in a Lambda function (also known as pre-authentication Lambda). You must use the endpoints set in domain configurations and the[ authentication type](protocols.md#connection-protocol-auth-mode) must be X.509 certificate. In addition, clients must provide the [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) extension when connecting to AWS IoT Core.

**Note**  
This feature is not supported in the AWS GovCloud (US) Regions.

**Topics**
+ [Step 1: Register your X.509 client certificates with AWS IoT Core](#client-auth-cert-verification)
+ [Step 2: Create a Lambda function](#customize-client-auth-lambda)
+ [Step 3: Authorize AWS IoT to invoke your Lambda function](#customize-client-configuration-grant-permission)
+ [Step 4: Set authentication configuration for a domain](#customize-client-configuration)

## Step 1: Register your X.509 client certificates with AWS IoT Core
<a name="client-auth-cert-verification"></a>

If you haven't done this already, register and activate your [X.509 client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/x509-client-certs.html) with AWS IoT Core. Otherwise, skip to the next step.

To register and activate your client certificates with AWS IoT Core, follow the steps:

1. If you [create client certificates directly with AWS IoT](https://docs.aws.amazon.com//iot/latest/developerguide/device-certs-create.html). These client certificates will be automatically registered with AWS IoT Core.

1. If you [create your own client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/device-certs-your-own.html), follow [these instructions to register them with AWS IoT Core](https://docs.aws.amazon.com//iot/latest/developerguide/register-device-cert.html).

1. To activate your client certificates, follow [these instructions](https://docs.aws.amazon.com//iot/latest/developerguide/activate-or-deactivate-device-cert.html).

## Step 2: Create a Lambda function
<a name="customize-client-auth-lambda"></a>

You need to create a Lambda function that will perform certificate verification and be called for every client connect attempt for the configured endpoint. When creating this Lambda function, follow the general guidance from [Create your first Lambda function](https://docs.aws.amazon.com//lambda/latest/dg/getting-started.html). Additionally, ensure that the Lambda function adheres to the expected request and response formats as follows:

**Lambda function event example**

```
{
	"connectionMetadata": {
		"id": "string"
	},
	"principalId": "string",
	"serverName": "string",
	"clientCertificateChain": [
		"string",
		"string"
	]
}
```

`connectionMetadata`  
Metadata or additional information related to the client's connection to AWS IoT Core.

`principalId`  
The principal identifier associated with the client in the TLS connection.

`serverName`  
The [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) hostname string. AWS IoT Core requires devices to send the [SNI extension](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) to the Transport Layer Security (TLS) protocol and provide the complete endpoint address in the `host_name` field.

`clientCertificateChain`  
The array of strings that represents the client's X.509 certificate chain. 

**Lambda function response example**

```
{
	"isAuthenticated": "boolean"
}
```

`isAuthenticated`  
A Boolean value that indicates whether the request is authenticated.

**Note**  
In the Lambda response, `isAuthenticated` must be `true` to proceed to further authentication and authorization. Otherwise, the IoT client certificate can be disabled and custom authentication with X.509 client certificates can be blocked for further authentication and authorization.

## Step 3: Authorize AWS IoT to invoke your Lambda function
<a name="customize-client-configuration-grant-permission"></a>

After creating the Lambda function, you must grant permission for AWS IoT to invoke it, by using the [add-permission](https://docs.aws.amazon.com//cli/latest/reference/lambda/add-permission.html) CLI command. Note that this Lambda function will be invoked for every connect attempt to your configured endpoint. For more information, see [Authorizing AWS IoT to invoke your Lambda function](custom-auth-authorize.md).

## Step 4: Set authentication configuration for a domain
<a name="customize-client-configuration"></a>

The following section describes how to set authentication configuration for a custom domain using the AWS CLI.

### Set client certificate configuration for a domain (CLI)
<a name="customize-client-auth-cli"></a>

If you don't have a domain configuration, use the [https://docs.aws.amazon.com//cli/latest/reference/iot/create-domain-configuration.html](https://docs.aws.amazon.com//cli/latest/reference/iot/create-domain-configuration.html) CLI command to create one. If you already have a domain configuration, use the [https://docs.aws.amazon.com//cli/latest/reference/iot/update-domain-configuration.html](https://docs.aws.amazon.com//cli/latest/reference/iot/update-domain-configuration.html) CLI command to update the client certificate configuration for a domain. You must add the ARN of the Lambda function that you've created in the previous step.

```
aws iot create-domain-configuration \
    --domain-configuration-name domainConfigurationName \
    --authentication-type AWS_X509|CUSTOM_AUTH_X509 \
    --application-protocol SECURE_MQTT|HTTPS \
    --client-certificate-config 'clientCertificateCallbackArn":"arn:aws:lambda:us-east-2:123456789012:function:my-function:1"}'
```

```
aws iot update-domain-configuration \
    --domain-configuration-name domainConfigurationName \
    --authentication-type AWS_X509|CUSTOM_AUTH_X509 \
    --application-protocol SECURE_MQTT|HTTPS \
    --client-certificate-config '{"clientCertificateCallbackArn":"arn:aws:lambda:us-east-2:123456789012:function:my-function:1"}'
```

`domain-configuration-name`  
The name of the domain configuration.

`authentication-type`  
The authentication type of the domain configuration. For more information, see [choosing an authentication type](protocols.md#connection-protocol-auth-mode).

`application-protocol`  
The application protocol which devices use to communicate with AWS IoT Core. For more information, see [choosing an application protocol](protocols.md#protocol-selection).

`client-certificate-config`  
An object that specifies the client authentication configuration for a domain.

`clientCertificateCallbackArn`  
The Amazon Resource Name (ARN) of the Lambda function that AWS IoT invokes in TLS layer when new connection is being established. To customize client authentication to perform custom client certificate validation, you must add the ARN of the Lambda function that you've created in the previous step.

For more information, see [CreateDomainConfiguration](https://docs.aws.amazon.com//iot/latest/apireference/API_CreateDomainConfiguration.html) and [UpdateDomainConfiguration](https://docs.aws.amazon.com//iot/latest/apireference/API_UpdateDomainConfiguration.html) from the *AWS IoT API Reference*. For more information about domain configurations, see [Domain configurations](https://docs.aws.amazon.com//iot/latest/developerguide/iot-custom-endpoints-configurable.html).

# IAM users, groups, and roles
<a name="iam-users-groups-roles"></a>

IAM users, groups, and roles are the standard mechanisms for managing identity and authentication in AWS. You can use them to connect to AWS IoT HTTP interfaces using the AWS SDK and AWS CLI.

IAM roles also allow AWS IoT to access other AWS resources in your account on your behalf. For example, if you want to have a device publish its state to a DynamoDB table, IAM roles allow AWS IoT to interact with Amazon DynamoDB. For more information, see [IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html).

For message broker connections over HTTP, AWS IoT authenticates users, groups, and roles using the Signature Version 4 signing process. For information, see [Signing AWS API Requests](https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html).

When authenticating requests using query parameters with [temporary security credentials provided by AWS Security Token Service (AWS STS)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html), do not include `X-Amz-Security-Token` in the canonical query string when calculating the signature. Instead, append `X-Amz-Security-Token` as a query parameter after the signature has been computed. This differs from some other AWS services that require the security token to be part of the canonical request. For more information, see [ Signing requests with temporary security credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html#temporary-security-credentials).

**Note**  
The AWS IoT Device SDKs handle this signing behavior automatically. If you are implementing custom signing code, refer to the SDK source for reference:  
[AWS IoT Device SDK for Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2/blob/main/awsiot/mqtt_connection_builder.py) — see `websockets_with_default_aws_signing()`, which sets `omit_session_token=True`
[AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/sdk/src/main/java/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.java) — see `setOmitSessionToken(true)`

When using AWS Signature Version 4 with AWS IoT, clients must support the following in their TLS implementation:
+ TLS 1.2
+ SHA-256 RSA certificate signature validation
+ One of the cipher suites from the TLS cipher suite support section

For information, see [Identity and access management for AWS IoT](security-iam.md).

# Amazon Cognito identities
<a name="cognito-identities"></a>

Amazon Cognito Identity enables you to create temporary, limited privilege AWS credentials for use in mobile and web applications. When you use Amazon Cognito Identity, create identity pools that create unique identities for your users and authenticate them with identity providers like Login with Amazon, Facebook, and Google. You can also use Amazon Cognito identities with your own developer authenticated identities. For more information, see [ Amazon Cognito Identity](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html).

To use Amazon Cognito Identity, define an Amazon Cognito identity pool that is associated with an IAM role. The IAM role is associated with an IAM policy that grants identities from your identity pool permission to access AWS resources like calling AWS services.

Amazon Cognito Identity creates unauthenticated and authenticated identities. Unauthenticated identities are used for guest users in a mobile or web application who want to use the app without signing in. Unauthenticated users are granted only those permissions specified in the IAM policy associated with the identity pool.

When you use authenticated identities, in addition to the IAM policy attached to the identity pool, you must attach an AWS IoT policy to an Amazon Cognito Identity. To attach an AWS IoT policy, use the [ AttachPolicy](https://docs.aws.amazon.com/iot/latest/apireference/API_AttachPolicy.html) API and give permissions to an individual user of your AWS IoT application. You can use the AWS IoT policy to assign fine-grained permissions for specific customers and their devices.

Authenticated and unauthenticated users are different identity types. If you don't attach an AWS IoT policy to the Amazon Cognito Identity, an authenticated user fails authorization in AWS IoT and doesn't have access to AWS IoT resources and actions. For more information about creating policies for Amazon Cognito identities, see [Publish/Subscribe policy examples](pub-sub-policy.md) and [Authorization with Amazon Cognito identities](cog-iot-policies.md).

![\[Application accessing a device with Amazon Cognito Identity.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/device-cognito.png)


# Custom authentication and authorization
<a name="custom-authentication"></a>

 AWS IoT Core lets you define custom authorizers so that you can manage your own client authentication and authorization. This is useful when you need to use authentication mechanisms other than the ones that AWS IoT Core natively supports. (For more information about the natively supported mechanisms, see [Client authentication](client-authentication.md)).  

 For example, if you are migrating existing devices in the field to AWS IoT Core and these devices use a custom bearer token or MQTT user name and password to authenticate, you can migrate them to AWS IoT Core without having to provision new identities for them. You can use custom authentication with any of the communication protocols that AWS IoT Core supports. For more information about the protocols that AWS IoT Core supports, see [Device communication protocols](protocols.md). 

**Topics**
+ [Understanding the custom authentication workflow](custom-authorizer.md)
+ [Creating and managing custom authorizers (CLI)](config-custom-auth.md)
+ [Custom authentication with X.509 client certificates](custom-auth-509cert.md)
+ [Connecting to AWS IoT Core by using custom authentication](custom-auth.md)
+ [Troubleshooting your authorizers](custom-auth-troubleshooting.md)

# Understanding the custom authentication workflow
<a name="custom-authorizer"></a>

Custom authentication enables you to define how to authenticate and authorize clients by using [authorizer resources](https://docs.aws.amazon.com/iot/latest/apireference/API_AuthorizerDescription.html).  Each authorizer contains a reference to a customer-managed Lambda function, an optional public key for validating device credentials, and additional configuration information. The following diagram illustrates the authorization workflow for custom authentication in AWS IoT Core.

![\[Custom authorization workflow for custom authentication in AWS IoT Core.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/custom-authentication.png)


## AWS IoT Core custom authentication and authorization workflow
<a name="custom-authentication-workflow"></a>

The following list explains each step in the custom authentication and authorization workflow.

1. A device connects to a customer’s AWS IoT Core data endpoint by using one of the supported [Device communication protocols](protocols.md). The device passes credentials in either the request’s header fields or query parameters (for the HTTP Publish or MQTT over WebSockets protocols), or in the user name and password field of the MQTT CONNECT message (for the MQTT and MQTT over WebSockets protocols).

1. AWS IoT Core checks for one of two conditions:
   + The incoming request specifies an authorizer.
   + The AWS IoT Core data endpoint receiving the request has a default authorizer configured for it.

   If AWS IoT Core finds an authorizer in either of these ways, AWS IoT Core triggers the Lambda function associated with the authorizer.

1.  (Optional) If you've enabled token signing, AWS IoT Core validates the request signature by using the public key stored in the authorizer before triggering the Lambda function. If validation fails, AWS IoT Core stops the request without invoking the Lambda function.  

1. The Lambda function receives the credentials and connection metadata in the request and makes an authentication decision.

1. The Lambda function returns the results of the authentication decision and an AWS IoT Core policy document that specifies what actions are allowed in the connection. The Lambda function also returns information that specifies how often AWS IoT Core revalidates the credentials in the request by invoking the Lambda function.

1. AWS IoT Core evaluates activity on the connection against the policy it has received from the Lambda function.

1. After the connection is established and your custom authorizer Lambda is initially invoked, the next invocation can be delayed for up to 5 minutes on idle connections without any MQTT operations. After that, subsequent invocations will follow the refresh interval in your custom authorizer Lambda. This approach can prevent excessive invocations that could exceed the Lambda concurrency limit of your AWS account.

## Scaling considerations
<a name="custom-authentication-scaling"></a>

 Because a Lambda function handles authentication and authorization for your authorizer, the function is subject to Lambda pricing and service limits, such as concurrent execution rate. For more information about Lambda pricing, see [Lambda Pricing](https://aws.amazon.com/lambda/pricing/). You can manage the load on your Lambda function by adjusting the `refreshAfterInSeconds` and `disconnectAfterInSeconds` parameters in your Lambda function response. For more information about the contents of your Lambda function response, see [Defining your Lambda function](custom-auth-lambda.md).

**Note**  
If you leave signing enabled, you can prevent excessive triggering of your Lambda by unrecognized clients. Consider this before you disable signing in your authorizer.

**Note**  
The Lambda function timeout limit for custom authorizer is 5 seconds.

# Creating and managing custom authorizers (CLI)
<a name="config-custom-auth"></a>

AWS IoT Core implements custom authentication and authorization schemes by using custom authorizers. A custom authorizer is an AWS IoT Core resource that gives you the flexibility to define and implement the rules and policies based on your specific requirements. To create a custom authorizer with step-by-step instructions, see [Tutorial: Creating a custom authorizer for AWS IoT Core](https://docs.aws.amazon.com//iot/latest/developerguide/custom-auth-tutorial.html).

Each authorizer consists of the following components: 
+  *Name*: A unique user-defined string that identifies the authorizer.
+  *Lambda function ARN*: The Amazon Resource Name (ARN) of the Lambda function that implements the authorization and authentication logic.  
+  *Token key name*: The key name used to extract the token from the HTTP headers, query parameters, or MQTT CONNECT user name in order to perform signature validation. This value is required if signing is enabled in your authorizer. 
+  *Signing disabled flag (optional)*: A Boolean value that specifies whether to disable the signing requirement on credentials. This is useful for scenarios where signing the credentials doesn't make sense, such as authentication schemes that use MQTT user name and password. The default value is `false`, so signing is enabled by default. 
+  *Token signing public key*: The public key that AWS IoT Core uses to validate the token signature. Its minimum length is 2,048 bits. This value is required if signing is enabled in your authorizer.  

Lambda charges you for the number of times your Lambda function runs and for the amount of time it takes for the code in your function to execute. For more information about Lambda pricing, see [Lambda Pricing](https://aws.amazon.com/lambda/pricing/). For more information about creating Lambda functions, see the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/).

**Note**  
If you leave signing enabled, you can prevent excessive triggering of your Lambda by unrecognized clients. Consider this before you disable signing in your authorizer.

**Note**  
The Lambda function timeout limit for custom authorizer is 5 seconds.

**Topics**
+ [Defining your Lambda function](custom-auth-lambda.md)
+ [Creating an authorizer](custom-auth-create-authorizer.md)
+ [Authorizing AWS IoT to invoke your Lambda function](custom-auth-authorize.md)
+ [Testing your authorizers](custom-auth-testing.md)
+ [Managing custom authorizers](custom-auth-manage.md)

# Defining your Lambda function
<a name="custom-auth-lambda"></a>

 When AWS IoT Core invokes your authorizer, it triggers the associated Lambda associated with the authorizer with an event that contains the following JSON object. The example JSON object contains all of the possible fields. Any fields that aren't relevant to the connection request aren't included.

```
{
    "token" :"aToken",
    "signatureVerified": Boolean, // Indicates whether the device gateway has validated the signature.
    "protocols": ["tls", "http", "mqtt"], // Indicates which protocols to expect for the request.
    "protocolData": {
        "tls" : {
            "serverName": "serverName" // The server name indication (SNI) host_name string.
        },
        "http": {
            "headers": {
                "#{name}": "#{value}"
            },
            "queryString": "?#{name}=#{value}"
        },
        "mqtt": {
            "username": "myUserName",
            "password": "myPassword", // A base64-encoded string.
            "clientId": "myClientId" // Included in the event only when the device sends the value.
        }
    },
    "connectionMetadata": {
        "id": UUID // The connection ID. You can use this for logging.
    },
}
```

 The Lambda function should use this information to authenticate the incoming connection and decide what actions are permitted in the connection. The function should send a response that contains the following values. 
+  `isAuthenticated`: A Boolean value that indicates whether the request is authenticated.
+  `principalId`: An alphanumeric string that acts as an identifier for the token sent by the custom authorization request. The value must be an alphanumeric string with at least one, and no more than 128, characters and match this regular expression (regex) pattern: `([a-zA-Z0-9]){1,128}`. Special characters that are not alphanumeric are not allowed for use with the `principalId` in AWS IoT Core. Refer to the documentation for other AWS services if non-alphanumeric special characters are allowed for the `principalId`.
+  `policyDocuments`: A list of JSON-formatted AWS IoT Core policy documents For more information about creating AWS IoT Core policies, see [AWS IoT Core policies](iot-policies.md). The maximum number of policy documents is 10 policy documents. Each policy document can contain a maximum of 2,048 characters.
+  `disconnectAfterInSeconds`: An integer that specifies the maximum duration (in seconds) of the connection to the AWS IoT Core gateway. The minimum value is 300 seconds, and the maximum value is 86,400 seconds. The default value is 86,400.
**Note**  
The value of `disconnectAfterInSeconds` (returned by the Lambda function) is set when the connection establishes. This value cannot be modified during subsequent policy refresh Lambda invocations.
+  `refreshAfterInSeconds`: An integer that specifies the interval between policy refreshes. When this interval passes, AWS IoT Core invokes the Lambda function to allow for policy refreshes. The minimum value is 300 seconds, and the maximum value is 86,400 seconds. 

  The following JSON object contains an example of a response that your Lambda function can send. 

 **\$1 "isAuthenticated":true, //A Boolean that determines whether client can connect. "principalId": "xxxxxxxx",  //A string that identifies the connection in logs. "disconnectAfterInSeconds": 86400,  "refreshAfterInSeconds": 300,   "policyDocuments": [       \$1         "Version": "2012-10-17",         "Statement": [            \$1               "Action": "iot:Publish",               "Effect": "Allow",               "Resource": "arn:aws:iot:us-east-1:<your\$1aws\$1account\$1id>:topic/customauthtesting"             \$1          ]        \$1     ] \$1**

 The `policyDocument` value must contain a valid AWS IoT Core policy document. For more information about AWS IoT Core policies, see [AWS IoT Core policies](iot-policies.md).  In MQTT over TLS and MQTT over WebSockets connections, AWS IoT Core caches this policy for the interval specified in the value of the `refreshAfterInSeconds` field. In the case of HTTP connections the Lambda function is called for every authorization request unless your device is using HTTP persistent connections (also called HTTP keep-alive or HTTP connection reuse) you can choose to enable caching when configuring the authorizer. During this interval, AWS IoT Core authorizes actions in an established connection against this cached policy without triggering your Lambda function again. If failures occur during custom authentication, AWS IoT Core terminates the connection. AWS IoT Core also terminates the connection if it has been open for longer than the value specified in the `disconnectAfterInSeconds`parameter. 

 The following JavaScript contains a sample Node.js Lambda function that looks for a password in the MQTT Connect message with a value of `test` and returns a policy that grants permission to connect to AWS IoT Core with a client named `myClientName` and publish to a topic that contains the same client name. If it doesn't find the expected password, it returns a policy that denies those two actions. 

```
// A simple Lambda function for an authorizer. It demonstrates 
// how to parse an MQTT password and generate a response.

exports.handler = function(event, context, callback) { 
    var uname = event.protocolData.mqtt.username;
    var pwd = event.protocolData.mqtt.password;
    var buff = new Buffer(pwd, 'base64');
    var passwd = buff.toString('ascii');
    switch (passwd) { 
        case 'test': 
            callback(null, generateAuthResponse(passwd, 'Allow')); 
            break;
        default: 
            callback(null, generateAuthResponse(passwd, 'Deny'));  
    }
};

// Helper function to generate the authorization response.
var generateAuthResponse = function(token, effect) { 
    var authResponse = {}; 
    authResponse.isAuthenticated = true; 
    authResponse.principalId = 'TEST123'; 
    
    var policyDocument = {}; 
    policyDocument.Version = '2012-10-17';		 	 	 
    policyDocument.Statement = []; 
    var publishStatement = {}; 
    var connectStatement = {};
    connectStatement.Action = ["iot:Connect"];
    connectStatement.Effect = effect;
    connectStatement.Resource = ["arn:aws:iot:us-east-1:123456789012:client/myClientName"];
    publishStatement.Action = ["iot:Publish"]; 
    publishStatement.Effect = effect; 
    publishStatement.Resource = ["arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"]; 
    policyDocument.Statement[0] = connectStatement;
    policyDocument.Statement[1] = publishStatement; 
    authResponse.policyDocuments = [policyDocument]; 
    authResponse.disconnectAfterInSeconds = 3600; 
    authResponse.refreshAfterInSeconds = 300;
    
    return authResponse; 
}
```

 The preceding Lambda function returns the following JSON when it receives the expected password of `test` in the MQTT Connect message. The values of the `password` and `principalId` properties will be the values from the MQTT Connect message.

```
{
  "password": "password",
  "isAuthenticated": true,
  "principalId": "principalId",
  "policyDocuments": [
    {
      "Version": "2012-10-17",		 	 	 
      "Statement": [
        {
          "Action": "iot:Connect",
          "Effect": "Allow",
          "Resource": "*"
        },
        {
          "Action": "iot:Publish",
          "Effect": "Allow",
          "Resource": "arn:aws:iot:region:accountId:topic/telemetry/${iot:ClientId}"
        },
        {
          "Action": "iot:Subscribe",
          "Effect": "Allow",
          "Resource": "arn:aws:iot:region:accountId:topicfilter/telemetry/${iot:ClientId}"
        },
        {
          "Action": "iot:Receive",
          "Effect": "Allow",
          "Resource": "arn:aws:iot:region:accountId:topic/telemetry/${iot:ClientId}"
        }
      ]
    }
  ],
  "disconnectAfterInSeconds": 3600,
  "refreshAfterInSeconds": 300
}
```

# Creating an authorizer
<a name="custom-auth-create-authorizer"></a>

 You can create an authorizer by using the [CreateAuthorizer API](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateAuthorizer.html). The following example describes the command. 

```
aws iot create-authorizer
--authorizer-name MyAuthorizer
--authorizer-function-arn arn:aws:lambda:us-west-2:<account_id>:function:MyAuthorizerFunction  //The ARN of the Lambda function.
[--token-key-name MyAuthorizerToken //The key used to extract the token from headers.
[--token-signing-public-keys FirstKey=
 "-----BEGIN PUBLIC KEY-----
  [...insert your public key here...] 
  -----END PUBLIC KEY-----"
[--status ACTIVE]
[--tags <value>]
[--signing-disabled | --no-signing-disabled]
```

You can use the `signing-disabled` parameter to opt out of signature validation for each invocation of your authorizer. We strongly recommend that you do not disable signing unless you have to. Signature validation protects you against excessive invocations of your Lambda function from unknown devices. You can't update the `signing-disabled` status of an authorizer after you create it. To change this behavior, you must create another custom authorizer with a different value for the `signing-disabled` parameter. 

Values for the `tokenKeyName` and `tokenSigningPublicKeys` parameters are optional if you have disabled signing. They are required values if signing is enabled. 

After you create your Lambda function and the custom authorizer, you must explicitly grant the AWS IoT Core service permission to invoke the function on your behalf. You can do this with the following command. 

**Note**  
The default IoT endpoint might not support using custom authorizers with Lambda functions. Instead, you can use domain configurations to define a new endpoint and then specify that endpoint for the custom authorizer.

```
aws lambda add-permission --function-name <lambda_function_name>
--principal iot.amazonaws.com --source-arn <authorizer_arn>
--statement-id Id-123 --action "lambda:InvokeFunction"
```

# Authorizing AWS IoT to invoke your Lambda function
<a name="custom-auth-authorize"></a>

In this section, you'll grant the permission of the custom authorizer resource that you just created to run the Lambda function. To grant the permission, you can use the [add-permission](https://docs.aws.amazon.com//cli/latest/reference/lambda/add-permission.html) CLI command.

**Grant permission to your Lambda function using the AWS CLI**

1. After inserting your values, enter the following command. Note that the `statement-id` value must be unique. Replace `Id-1234` with the exact value you have, otherwise, you might get a `ResourceConflictException` error.

   ```
   aws lambda add-permission  \
   --function-name "custom-auth-function" \
   --principal "iot.amazonaws.com" \
   --action "lambda:InvokeFunction" \
   --statement-id "Id-1234" \
   --source-arn authorizerArn
   ```

1. If the command succeeds, it returns a permission statement, such as this example. You can continue to the next section to test the custom authorizer.

   ```
   {
       "Statement": "{\"Sid\":\"Id-1234\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"iot.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:Region:57EXAMPLE833:function:custom-auth-function\",\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:lambda:Region:57EXAMPLE833:function:custom-auth-function\"}}}"
   }
   ```

   If the command doesn't succeed, it returns an error, such as this example. You'll need to review and correct the error before you continue.

   ```
   An error occurred (AccessDeniedException) when calling the AddPermission operation: User: arn:aws:iam::57EXAMPLE833:user/EXAMPLE-1 is not authorized to perform: lambda:AddPer
   mission on resource: arn:aws:lambda:Region:57EXAMPLE833:function:custom-auth-function
   ```

# Testing your authorizers
<a name="custom-auth-testing"></a>

 You can use the [TestInvokeAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_TestInvokeAuthorizer.html) API to test the invocation and return values of your authorizer. This API enables you to specify protocol metadata and test the signature validation in your authorizer.

The following tabs show how to use the AWS CLI to test your authorizer.

------
#### [ Unix-like ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER \
--token TOKEN_VALUE --token-signature TOKEN_SIGNATURE
```

------
#### [ Windows CMD ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER ^
--token TOKEN_VALUE --token-signature TOKEN_SIGNATURE
```

------
#### [ Windows PowerShell ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER `
--token TOKEN_VALUE --token-signature TOKEN_SIGNATURE
```

------

The value of the `token-signature` parameter is the signed token. To learn how to obtain this value, see [Signing the token](custom-auth.md#custom-auth-token-signature).

If your authorizer takes a user name and password, you can pass this information by using the `--mqtt-context` parameter. The following tabs show how to use the `TestInvokeAuthorizer` API to send a JSON object that contains a user name, password, and client name to your custom authorizer.

------
#### [ Unix-like ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER  \
--mqtt-context '{"username": "USER_NAME", "password": "dGVzdA==", "clientId":"CLIENT_NAME"}'
```

------
#### [ Windows CMD ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER  ^
--mqtt-context '{"username": "USER_NAME", "password": "dGVzdA==", "clientId":"CLIENT_NAME"}'
```

------
#### [ Windows PowerShell ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER  `
--mqtt-context '{"username": "USER_NAME", "password": "dGVzdA==", "clientId":"CLIENT_NAME"}'
```

------

The password must be base64-encoded. The following example shows how to encode a password in a Unix-like environment.

```
echo -n PASSWORD | base64
```

# Managing custom authorizers
<a name="custom-auth-manage"></a>

 You can manage your authorizers by using the following APIs. 
+ [ListAuthorizers](https://docs.aws.amazon.com/iot/latest/apireference/API_ListAuthorizers.html): Show all authorizers in your account.
+  [DescribeAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuthorizer.html): Displays properties of the specified authorizer. These values include creation date, last modified date, and other attributes.
+ [SetDefaultAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_SetDefaultAuthorizer.html): Specifies the default authorizer for your AWS IoT Core data endpoints. AWS IoT Core uses this authorizer if a device doesn't pass AWS IoT Core credentials and doesn't specify an authorizer. For more information about using AWS IoT Core credentials, see [Client authentication](client-authentication.md).
+ [UpdateAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateAuthorizer.html):  Changes the status, token key name, or public keys for the specified authorizer.
+  [DeleteAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteAuthorizer.html): Deletes the specified authorizer. 

**Note**  
 You can't update an authorizer's signing requirement. This means that you can't disable signing in an existing authorizer that requires it. You also can't require signing in an existing authorizer that doesn't require it. 

# Custom authentication with X.509 client certificates
<a name="custom-auth-509cert"></a>

When connecting devices to AWS IoT Core, you have multiple [authentication types](protocols.md#connection-protocol-auth-mode) available. You can use [X.509 client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/x509-client-certs.html) that can be used to authenticate client and device connections, or define [custom authorizers](https://docs.aws.amazon.com//iot/latest/developerguide/custom-authentication.html) to manage your own client authentication and authorization logic. This topic covers how to use custom authentication with X.509 client certificates.

Using custom authentication with X.509 certificates can be helpful if you've already authenticated your devices using X.509 certificates and want to perform additional validation and custom authorization. For example, if you store your devices' data such as their serial numbers in the X.509 client certificate, after AWS IoT Core authenticated the X.509 client certificate, you can use a custom authorizer to identify specific devices based on the information stored in the certificate's CommonName field. Using custom authentication with X.509 certificates can enhance your device security management when connecting devices to AWS IoT Core and provides more flexibility to manage the authentication and authorization logic. AWS IoT Core supports custom authentication with X.509 certificates using the X.509 certificate and custom authorizer authentication type, which works with both the [MQTT](https://docs.aws.amazon.com//iot/latest/developerguide/mqtt.html) protocol and the [HTTPS](https://docs.aws.amazon.com//iot/latest/developerguide/http.html) protocol. For more information about the authentication types and application protocols that AWS IoT Core device endpoints support, see [Device communication protocols](https://docs.aws.amazon.com//iot/latest/developerguide/protocols.html).

**Note**  
Custom authentication with X.509 client certificates is not supported in the AWS GovCloud (US) Regions.

**Important**  
You must use an endpoint created using [domain configurations](iot-custom-endpoints-configurable.md). In addition, clients must provide the [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) extension when connecting to AWS IoT Core.

**Topics**
+ [Step 1: Register your X.509 client certificates with AWS IoT Core](#custom-auth-509cert-client)
+ [Step 2: Create a Lambda function](#custom-auth-509cert-lambda)
+ [Step 3: Create a custom authorizer](#custom-auth-509cert-authorizer)
+ [Step 4: Set authentication type and application protocol in a domain configuration](#custom-auth-509cert-domainconfig)

## Step 1: Register your X.509 client certificates with AWS IoT Core
<a name="custom-auth-509cert-client"></a>

If you haven't done this already, register and activate your [X.509 client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/x509-client-certs.html) with AWS IoT Core. Otherwise, skip to the next step.

To register and activate your client certificates with AWS IoT Core, follow the steps:

1. If you [create client certificates directly with AWS IoT](https://docs.aws.amazon.com//iot/latest/developerguide/device-certs-create.html). These client certificates will be automatically registered with AWS IoT Core.

1. If you [create your own client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/device-certs-your-own.html), follow [these instructions to register them with AWS IoT Core](https://docs.aws.amazon.com//iot/latest/developerguide/register-device-cert.html).

1. To activate your client certificates, follow [these instructions](https://docs.aws.amazon.com//iot/latest/developerguide/activate-or-deactivate-device-cert.html).

## Step 2: Create a Lambda function
<a name="custom-auth-509cert-lambda"></a>

AWS IoT Core uses custom authorizers to implement custom authentication and authorization schemes. A custom authorizer is associated with a Lambda function that determines whether a device is authenticated and what operations the device is allowed to perform. When a device connects to AWS IoT Core, AWS IoT Core retrieves the authorizer details including authorizer name and associated Lambda function, and invokes the Lambda function. The Lambda function receives an event that contains a JSON object with the device's X.509 client certificate data. Your Lambda function uses this event JSON object to evaluate the authentication request, decide the actions to take, and send a response back.

### Lambda function event example
<a name="custom-auth-509cert-event"></a>

The following example JSON object contains all possible fields that can be included. The actual JSON object will only contain fields relevant to the specific connection request.

```
{
	"token": "aToken",
	"signatureVerified": true,
	"protocols": [
		"tls",
		"mqtt"
	],
	"protocolData": {
		"tls": {
			"serverName": "serverName",
			"x509CertificatePem": "x509CertificatePem",
			"principalId": "principalId"
		},
		"mqtt": {
			"clientId": "myClientId",
                     "username": "myUserName",
                     "password": "myPassword"
		}
	},
	"connectionMetadata": {
		"id": "UUID"
	}
}
```

`signatureVerified`  
A Boolean value that indicates whether the token signature configured in the authorizer is verified or not before invoking the authorizer's Lambda function. If the authorizer is configured to disable token signing, this field will be false. 

`protocols`  
An array that contains the protocols to expect for the request.

`protocolData`  
An object that contains information of the protocols used in the connection. It provides protocol-specific details that can be useful for authentication, authorization, and more.  
`tls` - This object holds information related to the TLS (Transport Layer Security) protocol.   
+ `serverName` - The [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) hostname string. AWS IoT Core requires devices to send the [SNI extension](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) to the Transport Layer Security (TLS) protocol and provide the complete endpoint address in the `host_name` field.
+ `x509CertificatePem` - The X.509 certificate in PEM format, which is used for client authentication in the TLS connection.
+ `principalId` - The principal identifier associated with the client in the TLS connection.
`mqtt` - This object holds information related to the MQTT protocol.  
+ `clientId` - A string only needs to be included in the event that the device sends this value.
+ `username` - The user name provided in the MQTT Connect packet.
+ `password` - The password provided in the MQTT Connect packet.

`connectionMetadata`  
Metadata of the connection.  
`id` - The connection ID, which you can use for logging and troubleshooting.

**Note**  
In this event JSON object, `x509CertificatePem` and `principalId` are two new fields in the request. The value of `principalId` is the same as the value of `certificateId`. For more information, see [Certificate](https://docs.aws.amazon.com//iot/latest/apireference/API_Certificate.html).

### Lambda function response example
<a name="custom-auth-509cert-response"></a>

The Lambda function should use information from the event JSON object to authenticate the incoming connection and decide what actions are permitted in the connection.

The following JSON object contains an example response that your Lambda function can send.

```
{
	"isAuthenticated": true,
	"principalId": "xxxxxxxx",
	"disconnectAfterInSeconds": 86400,
	"refreshAfterInSeconds": 300,
	"policyDocuments": [
		{
			"Version": "2012-10-17",		 	 	 
			"Statement": [
				{
					"Effect": "Allow",
					"Action": "iot:Publish",
					"Resource": "arn:aws:iot:us-east-1:123456789012:topic/customauthtesting"
				}
			]
		}
	]
}
```

In this example, this function should send a response that contains the following values.

`isAuthenticated`  
A Boolean value that indicates whether the request is authenticated.

`principalId`  
An alphanumeric string that acts as an identifier for the token sent by the custom authorization request. The value must be an alphanumeric string with at least one, and no more than 128, characters. It identifies the connection in logs. The value of `principalId` must be the same as the value of `principalId` in the event JSON object (i.e. certificateId of the X.509 certificate).

`policyDocuments`  
A list of JSON-formatted AWS IoT Core policy documents. The value is optional and supports [thing policy variables](https://docs.aws.amazon.com//iot/latest/developerguide/thing-policy-variables.html) and [certificate policy variables](https://docs.aws.amazon.com//iot/latest/developerguide/cert-policy-variables.html). The maximum number of policy documents is 10. Each policy document can contain a maximum of 2,048 characters. If you have multiple policies attached to your client certificate and the Lambda function, the permission is a collection of all policies. For more information about creating AWS IoT Core policies, see [Policies](https://docs.aws.amazon.com//iot/latest/developerguide/iot-policies.html).

`disconnectAfterInSeconds`  
An integer that specifies the maximum duration (in seconds) of the connection to the AWS IoT Core gateway. The minimum value is 300 seconds, and the maximum value is 86,400 seconds. `disconnectAfterInSeconds` is for the lifetime of a connection and doesn't get refreshed on consecutive policy refreshes.

`refreshAfterInSeconds`  
An integer that specifies the interval between policy refreshes. When this interval passes, AWS IoT Core invokes the Lambda function to allow for policy refreshes. The minimum value is 300 seconds, and the maximum value is 86,400 seconds.

### Example Lambda function
<a name="custom-auth-509cert-js-example"></a>

The following is a sample Node.js Lambda function. The function examines the client's X.509 certificate and extracts relevant information such as the serial number, fingerprint, and subject name. If the extracted information matches the expected values, the client is granted access to connect. This mechanism ensures that only authorized clients with valid certificates can establish a connection.

```
const crypto = require('crypto');

exports.handler = async (event) => {
    
    // Extract the certificate PEM from the event
    const certPem = event.protocolData.tls.x509CertificatePem;
    
    // Parse the certificate using Node's crypto module
    const cert = new crypto.X509Certificate(certPem);
    
    var effect = "Deny";
    // Allow permissions only for a particular certificate serial, fingerprint, and subject
    if (cert.serialNumber === "7F8D2E4B9C1A5036DE8F7C4B2A91E5D80463BC9A1257" // This is a random serial
       && cert.fingerprint === "F2:9A:C4:1D:B5:E7:08:3F:6B:D0:4E:92:A7:C1:5B:8D:16:0F:E3:7A" // This is a random fingerprint
       && cert.subject === "allow.example.com") {
      effect = "Allow";
    }
    
    return generateAuthResponse(event.protocolData.tls.principalId, effect);
};


// Helper function to generate the authorization response.
function generateAuthResponse(principalId, effect) {
    const authResponse = {
        isAuthenticated: true,
        principalId,
        disconnectAfterInSeconds: 3600,
        refreshAfterInSeconds: 300,
        policyDocuments: [
          {
            Version: "2012-10-17",		 	 	 
            Statement: [
              {
                Action: ["iot:Connect"],
                Effect: effect,
                Resource: [
                  "arn:aws:iot:us-east-1:123456789012:client/myClientName"
                ]
              },
              {
                Action: ["iot:Publish"],
                Effect: effect,
                Resource: [
                  "arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"
                ]
              },
              {
                Action: ["iot:Subscribe"],
                Effect: effect,
                Resource: [
                   "arn:aws:iot:us-east-1:123456789012:topicfilter/telemetry/myClientName"
                ]
              },
              {
                Action: ["iot:Receive"],
                Effect: effect,
                Resource: [
                   "arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"
                ]
              }
            ]
          }
        ]
      };

  return authResponse;
}
```

The preceding Lambda function returns the following JSON when it receives a certificate with the expected serial, fingerprint, and subject. The value of `x509CertificatePem` will be the client certificate provided in the TLS handshake. For more information, see [Defining your Lambda function](https://docs.aws.amazon.com//iot/latest/developerguide/config-custom-auth.html#custom-auth-lambda).

```
{
	"isAuthenticated": true,
	"principalId": "principalId in the event JSON object",
	"policyDocuments": [
		{
			"Version": "2012-10-17",		 	 	 
			"Statement": [
				{
					"Action": "iot:Connect",
					"Effect": "Allow",
					"Resource": "arn:aws:iot:us-east-1:123456789012:client/myClientName"
				},
				{
					"Action": "iot:Publish",
					"Effect": "Allow",
					"Resource": "arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"
				},
				{
					"Action": "iot:Subscribe",
					"Effect": "Allow",
					"Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/telemetry/myClientName"
				},
				{
					"Action": "iot:Receive",
					"Effect": "Allow",
					"Resource": "arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"
				}
			]
		}
	],
	"disconnectAfterInSeconds": 3600,
	"refreshAfterInSeconds": 300
}
```

## Step 3: Create a custom authorizer
<a name="custom-auth-509cert-authorizer"></a>

After [you define the Lambda function](#custom-auth-509cert-lambda), create a custom authorizer to manage your own client authentication and authorization logic. You can follow the detailed instructions in [Step 3: Create a customer authorizer resource and its authorization](https://docs.aws.amazon.com//iot/latest/developerguide/custom-auth-tutorial.html#custom-auth-tutorial-authorizer). For more information, see [Creating an authorizer](https://docs.aws.amazon.com//iot/latest/developerguide/config-custom-auth.html). 

In the process of creating the custom authorizer, you must grant AWS IoT permission to invoke the Lambda function after it's created. For detailed instructions, see [Authorizing AWS IoT to invoke your Lambda function](custom-auth-authorize.md).

## Step 4: Set authentication type and application protocol in a domain configuration
<a name="custom-auth-509cert-domainconfig"></a>

To authenticate devices using custom authentication with X.509 client certificates, you must set the authentication type and application protocol in a domain configuration, and you must send the SNI extension. The value of `authenticationType` must be `CUSTOM_AUTH_X509`, and the value of `applicationProtocol` can either be `SECURE_MQTT` or `HTTPS`.

### Set authentication type and application protocol in domain configuration (CLI)
<a name="custom-auth-509cert-cli"></a>

If you don't have a domain configuration, use the [https://docs.aws.amazon.com//cli/latest/reference/iot/create-domain-configuration.html](https://docs.aws.amazon.com//cli/latest/reference/iot/create-domain-configuration.html) command to create one. The value of `authenticationType` must be `CUSTOM_AUTH_X509`, and the value of `applicationProtocol` can either be `SECURE_MQTT` or `HTTPS`.

```
aws iot create-domain-configuration \
    --domain-configuration-name domainConfigurationName \
    --authentication-type CUSTOM_AUTH_X509 \  
    --application-protocol SECURE_MQTT \ 
    --authorizer-config '{
        "defaultAuthorizerName": my-custom-authorizer
    }'
```

If you already have a domain configuration, use the [https://docs.aws.amazon.com//cli/latest/reference/iot/update-domain-configuration.html](https://docs.aws.amazon.com//cli/latest/reference/iot/update-domain-configuration.html) command update `authenticationType` and `applicationProtocol` if needed. Note that you can't change the authentication type or protocol on the default endpoint (`iot:Data-ATS`).

```
aws iot update-domain-configuration \
    --domain-configuration-name domainConfigurationName \
    --authentication-type CUSTOM_AUTH_X509 \  
    --application-protocol SECURE_MQTT \
    --authorizer-config '{
        "defaultAuthorizerName": my-custom-authorizer
    }'
```

`domain-configuration-name`  
The name of the domain configuration.

`authentication-type`  
The authentication type of the domain configuration. For more information, see [choosing an authentication type](protocols.md#connection-protocol-auth-mode).

`application-protocol`  
The application protocol which devices use to communicate with AWS IoT Core. For more information, see [choosing an application protocol](protocols.md#protocol-selection).

`--authorizer-config`  
An object that specifies the authorizer configuration in a domain configuration.

`defaultAuthorizerName`  
The name of the authorizer for a domain configuration.

For more information, see [CreateDomainConfiguration](https://docs.aws.amazon.com//iot/latest/apireference/API_CreateDomainConfiguration.html) and [UpdateDomainConfiguration](https://docs.aws.amazon.com//iot/latest/apireference/API_UpdateDomainConfiguration.html) from the *AWS IoT API Reference*. For more information about domain configuration, see [Domain configurations](https://docs.aws.amazon.com//iot/latest/developerguide/iot-custom-endpoints-configurable.html).

# Connecting to AWS IoT Core by using custom authentication
<a name="custom-auth"></a>

 Devices can connect to AWS IoT Core by using custom authentication with any protocol that AWS IoT Core supports for device messaging. For more information about supported communication protocols, see [Device communication protocols](protocols.md).  The connection data that you pass to your authorizer Lambda function depends on the protocol you use. For more information about creating your authorizer Lambda function, see [Defining your Lambda function](custom-auth-lambda.md). The following sections explain how to connect to authenticate by using each supported protocol.

## HTTPS
<a name="custom-auth-http"></a>

Devices sending data to AWS IoT Core by using the [HTTP Publish API](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdata_Publish.html) can pass credentials either through request headers or query parameters in their HTTP POST requests. Devices can specify an authorizer to invoke by using the `x-amz-customauthorizer-name` header or query parameter. If you have token signing enabled in your authorizer, you must pass the `token-key-name` and `x-amz-customauthorizer-signature` in either request headers or query parameters. Note that the `token-signature` value must be URL-encoded when using JavaScript from within the browser.

**Note**  
The customer authorizer for the HTTPS protocol only supports publish operations. For more information about the HTTPS protocol, see [Device communication protocols](protocols.md).

The following example requests show how you pass these parameters in both request headers and query parameters. 

```
//Passing credentials via headers
POST /topics/topic?qos=qos HTTP/1.1
Host: your-endpoint 
x-amz-customauthorizer-signature: token-signature
token-key-name: token-value 
x-amz-customauthorizer-name: authorizer-name

//Passing credentials via query parameters
POST /topics/topic?qos=qos&x-amz-customauthorizer-signature=token-signature&token-key-name=token-value HTTP/1.1
```

## MQTT
<a name="custom-auth-mqtt"></a>

 Devices connecting to AWS IoT Core by using an MQTT connection can pass credentials through the `username` and `password` fields of MQTT messages. The `username` value can also optionally contain a query string that passes additional values (including a token, signature, and authorizer name) to your authorizer. You can use this query string if you want to use a token-based authentication scheme instead of `username` and `password` values.  

**Note**  
 Data in the password field is base64-encoded by AWS IoT Core. Your Lambda function must decode it. 

 The following example contains a `username` string that contains extra parameters that specify a token and signature.  

```
username?x-amz-customauthorizer-name=authorizer-name&x-amz-customauthorizer-signature=token-signature&token-key-name=token-value
```

To invoke an authorizer, devices connecting to AWS IoT Core by using MQTT and custom authentication must connect on port 443. They also must pass the Application Layer Protocol Negotiation (ALPN) TLS extension with a value of `mqtt` and the Server Name Indication (SNI) extension with the host name of their AWS IoT Core data endpoint. To avoid potential errors, the value for `x-amz-customauthorizer-signature` should be URL encoded. We also highly recommend that the values of `x-amz-customauthorizer-name` and `token-key-name` be URL encoded. For more information about these values, see [Device communication protocols](protocols.md). The V2 [AWS IoT Device SDKs, Mobile SDKs, and AWS IoT Device Client](iot-sdks.md) can configure both of these extensions. 

## MQTT over WebSockets
<a name="custom-auth-websockets"></a>

 Devices connecting to AWS IoT Core by using MQTT over WebSockets can pass credentials in one of the two following ways. 
+ Through request headers or query parameters in the HTTP UPGRADE request to establish the WebSockets connection.
+ Through the `username` and `password` fields in the MQTT CONNECT message.

 If you pass credentials through the MQTT connect message, the ALPN and SNI TLS extensions are required. For more information about these extensions, see [MQTT](#custom-auth-mqtt).   The following example demonstrates how to pass credentials through the HTTP Upgrade request. 

```
GET /mqtt HTTP/1.1
Host: your-endpoint 
Upgrade: WebSocket 
Connection: Upgrade 
x-amz-customauthorizer-signature: token-signature
token-key-name: token-value 
sec-WebSocket-Key: any random base64 value 
sec-websocket-protocol: mqtt 
sec-WebSocket-Version: websocket version
```

## Signing the token
<a name="custom-auth-token-signature"></a>

You must sign the token with the private key of the public-private key pair that you used in the `create-authorizer` call. The following examples show how to create the token signature by using a UNIX-like command and JavaScript. They use the SHA-256 hash algorithm to encode the signature.

------
#### [ Command line ]

```
echo -n TOKEN_VALUE | openssl dgst -sha256 -sign PEM encoded RSA private key | openssl base64
```

------
#### [ JavaScript ]

```
const crypto = require('crypto')

const key = "PEM encoded RSA private key"

const k = crypto.createPrivateKey(key)
let sign = crypto.createSign('SHA256')
sign.write(t)
sign.end()
const s = sign.sign(k, 'base64')
```

------

# Troubleshooting your authorizers
<a name="custom-auth-troubleshooting"></a>

 This topic walks through common issues that can cause problems in custom authentication workflows and steps for resolving them. To troubleshoot issues most effectively, enable CloudWatch logs for AWS IoT Core and set the log level to **DEBUG**. You can enable CloudWatch logs in the AWS IoT Core console ([https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/)). For more information about enabling and configuring logs for AWS IoT Core, see [Configure AWS IoT logging](configure-logging.md). 

**Note**  
If you leave the log level at **DEBUG** for long periods of time, CloudWatch might store large amounts of logging data. This can increase your CloudWatch charges. Consider using resource-based logging to increase the verbosity for only devices in a particular thing group. For more information about resource-based logging, see [Configure AWS IoT logging](configure-logging.md). Also, when you're done troubleshooting, reduce the log level to a less verbose level.

Before you start troubleshooting, review [Understanding the custom authentication workflow](custom-authorizer.md) for a high-level view of the custom authentication process. This helps you understand where to look for the source of a problem.

This topic discusses the following two areas for you to investigate.
+ Issues related to your authorizer's Lambda function.
+ Issues related to your device.

## Check for issues in your authorizer’s Lambda function
<a name="custom-auth-troubleshooting-lambda"></a>

Perform the following steps to make sure that your devices’ connection attempts are invoking your Lambda function.

1. Verify which Lambda function is associated with your authorizer.

   You can do this by calling the [DescribeAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuthorizer.html) API or by clicking on the desired authorizer in the **Secure** section of the AWS IoT Core console.

1. Check the invocation metrics for the Lambda function. Perform the following steps to do this.

   1. Open the AWS Lambda console ([https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/)) and select the function that is associated with your authorizer.

   1. Choose the **Monitor** tab and view metrics for the time frame that is relevant to your problem.

1. If you see no invocations, verify that AWS IoT Core has permission to invoke your Lambda function. If you see invocations, skip to the next step. Perform the following steps to verify that your Lambda function has the required permissions.

   1. Choose the **Permissions** tab for your function in the AWS Lambda console.

   1. Find the **Resource-based Policy** section at the bottom of the page. If your Lambda function has the required permissions, the policy looks like the following example.  
****  

      ```
      {
        "Version":"2012-10-17",		 	 	 
        "Id": "default",
        "Statement": [
          {
            "Sid": "Id123",
            "Effect": "Allow",
            "Principal": {
              "Service": "iot.amazonaws.com"
            },
            "Action": "lambda:InvokeFunction",
            "Resource": "arn:aws:lambda:us-east-1:111111111111:function:FunctionName",
            "Condition": {
              "ArnLike": {
                "AWS:SourceArn": "arn:aws:iot:us-east-1:111111111111:authorizer/AuthorizerName"
              },
              "StringEquals": {
                "AWS:SourceAccount": "111111111111"
              }
            }
          }
        ]
      }
      ```

   1. This policy grants the `InvokeFunction` permission on your function to the AWS IoT Core principal. If you don't see it, you'll have to add it by using the [AddPermission](https://docs.aws.amazon.com/lambda/latest/dg/API_AddPermission.html) API. The following example shows you how to do this by using the AWS CLI.

      ```
      aws lambda add-permission --function-name FunctionName --principal iot.amazonaws.com --source-arn AuthorizerARn --statement-id Id-123 --action "lambda:InvokeFunction"
      ```

1. If you see invocations, verify that there are no errors. An error might indicate that the Lambda function isn't properly handling the connection event that AWS IoT Core sends to it.

   For information about handling the event in your Lambda function, see [Defining your Lambda function](custom-auth-lambda.md). You can use the test feature in the AWS Lambda console ([https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/)) to hard-code test values in the function to make sure that the function is handling events correctly.

1. If you see invocations with no errors, but your devices are not able to connect (or publish, subscribe, and receive messages), the issue might be that the policy that your Lambda function returns doesn't give permissions for the actions that your devices are trying to take. Perform the following steps to determine whether anything is wrong with the policy that the function returns.

   1. Use an Amazon CloudWatch Logs Insights query to scan logs over a short period of time to check for failures. The following example query sorts events by timestamp and looks for failures.

      ```
      display clientId, eventType, status, @timestamp | sort @timestamp desc | filter status = "Failure"    
      ```

   1. Update your Lambda function to log the data that it's returning to AWS IoT Core and the event that triggers the function. You can use these logs to inspect the policy that the function creates.

1. If you see invocations with no errors, but your devices are not able to connect (or publish, subscribe, and receive messages), another reason can be that your Lambda function exceeds the timeout limit. The Lambda function timeout limit for custom authorizer is 5 seconds. You can check the function duration in CloudWatch logs or metrics. 

## Investigating device issues
<a name="custom-auth-troubleshooting-investigate"></a>

If you find no issues with invoking your Lambda function or with the policy that the function returns, look for problems with your devices' connection attempts. Malformed connection requests can cause AWS IoT Core not to trigger your authorizer. Connection problems can occur at both the TLS and application layers.

**Possible TLS layer issues:**
+ Customers must pass either a hostname header (HTTP, MQTT over WebSockets) or the Server Name Indication TLS extension (HTTP, MQTT over WebSockets, MQTT) in all custom authentication requests. In both cases, the value passed must match one of your account’s AWS IoT Core data endpoints. These are the endpoints that are returned when you perform the following CLI commands.
  + `aws iot describe-endpoint --endpoint-type iot:Data-ATS`
  + `aws iot describe-endpoint --endpoint-type iot:Data` (for legacy VeriSign endpoints)
+ Devices that use custom authentication for MQTT connections must also pass the Application Layer Protocol Negotiation (ALPN) TLS extension with a value of `mqtt`.
+ Custom authentication is currently available only on port 443.

**Possible application layer issues:**
+ If signing is enabled (the `signingDisabled` field is false in your authorizer), look for the following signature issues.
  + Make sure that you're passing the token signature in either the `x-amz-customauthorizer-signature`header or in a query string parameter.
  + Make sure that the service isn't signing a value other than the token.
  + Make sure that you pass the token in the header or query parameter that you specified in the `token-key-name` field in your authorizer.
+ Make sure that the authorizer name you pass in the `x-amz-customauthorizer-name` header or query string parameter is valid or that you have a default authorizer defined for your account.

# Authorization
<a name="iot-authorization"></a>

Authorization is the process of granting permissions to an authenticated identity. You grant permissions in AWS IoT Core using AWS IoT Core and IAM policies. This topic covers AWS IoT Core policies. For more information about IAM policies, see [Identity and access management for AWS IoT](security-iam.md) and [How AWS IoT works with IAM](security_iam_service-with-iam.md).

AWS IoT Core policies determine what an authenticated identity can do. An authenticated identity is used by devices, mobile applications, web applications, and desktop applications. An authenticated identity can even be a user typing AWS IoT Core CLI commands. An identity can execute AWS IoT Core operations only if it has a policy that grants it permission for those operations.

Both AWS IoT Core policies and IAM policies are used with AWS IoT Core to control the operations an identity (also called a *principal*) can perform. The policy type you use depends on the type of identity you are using to authenticate with AWS IoT Core. 

AWS IoT Core operations are divided into two groups: 
+ Control plane API allows you to perform administrative tasks like creating or updating certificates, things, rules, and so on.
+ Data plane API allows you send data to and receive data from AWS IoT Core. 

The type of policy you use depends on whether you are using control plane or data plane API.

The following table shows the identity types, the protocols they use, and the policy types that can be used for authorization.


**AWS IoT Core data plane API and policy types**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/iot-authorization.html)


**AWS IoT Core control plane API and policy types**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/iot-authorization.html)

AWS IoT Core policies are attached to X.509 certificates, Amazon Cognito identities, or thing groups. IAM policies are attached to an IAM user, group, or role. If you use the AWS IoT console or the AWS IoT Core CLI to attach the policy (to a certificate, Amazon Cognito Identity, or thing group), you use an AWS IoT Core policy. Otherwise, you use an IAM policy. AWS IoT Core policies attached to a thing group applies to any thing within that thing group. For the AWS IoT Core policy to take effect, the `clientId` and the thing name must match.

Policy-based authorization is a powerful tool. It gives you complete control over what a device, user, or application can do in AWS IoT Core. For example, consider a device connecting to AWS IoT Core with a certificate. You can allow the device to access all MQTT topics, or you can restrict its access to a single topic. In another example, consider a user typing CLI commands at the command line. By using a policy, you can allow or deny access to any command or AWS IoT Core resource for the user. You can also control an application's access to AWS IoT Core resources.

Changes made to a policy can take a few minutes to become effective because of how AWS IoT caches the policy documents. That is, it may take a few minutes to access a resource that has recently been granted access, and a resource may be accessible for several minutes after its access has been revoked.

## AWS training and certification
<a name="iot-authorization-training"></a>

For information about authorization in AWS IoT Core, take the [Deep Dive into AWS IoT Core Authentication and Authorization](https://www.aws.training/Details/Curriculum?id=42335) course on the AWS Training and Certification website.

# AWS IoT Core policies
<a name="iot-policies"></a>

AWS IoT Core policies are JSON documents. They follow the same conventions as IAM policies. AWS IoT Core supports named policies so many identities can reference the same policy document. Named policies are versioned so they can be easily rolled back.

AWS IoT Core policies allow you to control access to the AWS IoT Core data plane. The AWS IoT Core data plane consists of operations that allow you to connect to the AWS IoT Core message broker, send and receive MQTT messages, and get or update a thing's Device Shadow.

An AWS IoT Core policy is a JSON document that contains one or more policy statements. Each statement contains:
+ `Effect`, which specifies whether the action is allowed or denied.
+ `Action`, which specifies the action the policy is allowing or denying.
+ `Resource`, which specifies the resource or resources on which the action is allowed or denied.

Changes made to a policy can take anywhere between 6 and 8 minutes to become effective because of how AWS IoT caches the policy documents. That is, it may take a few minutes to access a resource that has recently been granted access, and a resource may be accessible for several minutes after its access has been revoked.

AWS IoT Core policies can be attached to X.509 certificates, Amazon Cognito identities, and thing groups. The policies attached to a thing group apply to any thing within that group. For the policy to take effect, the `clientId` and the thing name must match. AWS IoT Core policies follow the same policy evaluation logic as IAM policies. By default, all policies are implicitly denied. An explicit allow in any identity-based or resource-based policy overrides the default behavior. An explicit deny in any policy overrides any allows. For more information, see [Policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow) in the *AWS Identity and Access Management User Guide*.

**Topics**
+ [AWS IoT Core policy actions](iot-policy-actions.md)
+ [AWS IoT Core action resources](iot-action-resources.md)
+ [AWS IoT Core policy variables](iot-policy-variables.md)
+ [Cross-service confused deputy prevention](cross-service-confused-deputy-prevention.md)
+ [AWS IoT Core policy examples](example-iot-policies.md)
+ [Authorization with Amazon Cognito identities](cog-iot-policies.md)

# AWS IoT Core policy actions
<a name="iot-policy-actions"></a>

The following policy actions are defined by AWS IoT Core:MQTT Policy Actions

`iot:Connect`  
Represents the permission to connect to the AWS IoT Core message broker. The `iot:Connect` permission is checked every time a `CONNECT` request is sent to the broker. The message broker doesn't allow two clients with the same client ID to stay connected at the same time. After the second client connects, the broker closes the existing connection. Use the `iot:Connect` permission to ensure only authorized clients using a specific client ID can connect.

`iot:DeleteConnection`  
Represents the permission to disconnect a connected MQTT client from AWS IoT Core. The `iot:DeleteConnection` permission is checked every time a request is made to forcibly disconnect a client. When you disconnect a client, AWS IoT Core closes the client's network connection and optionally cleans the session state.

`iot:GetRetainedMessage`  
Represents the permission to get the contents of a single retained message. Retained messages are the messages that were published with the RETAIN flag set and stored by AWS IoT Core. For permission to get a list of all the account's retained messages, see [iot:ListRetainedMessages](#action_listretainedmessages).

`iot:ListRetainedMessages`  
Represents the permission to retrieve summary information about the account's retained messages, but not the contents of the messages. Retained messages are the messages that were published with the RETAIN flag set and stored by AWS IoT Core. The resource ARN specified for this action must be `*`. For permission to get the contents of a single retained message, see [iot:GetRetainedMessage](#action_getretainpublish).

`iot:Publish`  
Represents the permission to publish an MQTT topic. This permission is checked every time a PUBLISH request is sent to the broker. You can use this to allow clients to publish to specific topic patterns.  
To grant `iot:Publish` permission, you must also grant `iot:Connect` permission.

`iot:Receive`  
Represents the permission to receive a message from AWS IoT Core. The `iot:Receive` permission is confirmed every time a message is delivered to a client. Because this permission is checked on every delivery, you can use it to revoke permissions to clients that are currently subscribed to a topic.

`iot:RetainPublish`  
Represents the permission to publish an MQTT message with the RETAIN flag set.  
To grant `iot:RetainPublish` permission, you must also grant `iot:Publish` permission.

`iot:Subscribe`  
Represents the permission to subscribe to a topic filter. This permission is checked every time a SUBSCRIBE request is sent to the broker. Use it to allow clients to subscribe to topics that match specific topic patterns.  
To grant `iot:Subscribe` permission, you must also grant `iot:Connect` permission.Device Shadow Policy Actions

`iot:DeleteThingShadow`  
Represents the permission to delete a thing's Device Shadow. The `iot:DeleteThingShadow` permission is checked every time a request is made to delete a thing's Device Shadow contents.

`iot:GetThingShadow`  
Represents the permission to retrieve a thing's Device Shadow. The `iot:GetThingShadow` permission is checked every time a request is made to retrieve a thing's Device Shadow contents.

`iot:ListNamedShadowsForThing`  
Represents the permission to list a thing's named Shadows. The `iot:ListNamedShadowsForThing` permission is checked every time a request is made to list a thing's named Shadows.

`iot:UpdateThingShadow`  
Represents the permission to update a device's shadow. The `iot:UpdateThingShadow` permission is checked every time a request is made to update a thing's Device Shadow contents.

**Note**  
The job execution policy actions apply only for the HTTP TLS endpoint. If you use the MQTT endpoint, you must use MQTT policy actions defined in this topic.  
For an example of a job execution policy that demonstrates this, see [Basic job policy example](basic-jobs-example.md) that works with the MQTT protocol.Job Executions AWS IoT Core Policy Actions

`iotjobsdata:DescribeJobExecution`  
Represents the permission to retrieve a job execution for a given thing. The `iotjobsdata:DescribeJobExecution` permission is checked every time a request is made to get a job execution.

`iotjobsdata:GetPendingJobExecutions`  
Represents the permission to retrieve the list of jobs that are not in a terminal status for a thing. The `iotjobsdata:GetPendingJobExecutions` permission is checked every time a request is made to retrieve the list. 

`iotjobsdata:UpdateJobExecution`  
Represents the permission to update a job execution. The `iotjobsdata:UpdateJobExecution` permission is checked every time a request is made to update the state of a job execution.

`iotjobsdata:StartNextPendingJobExecution`  
Represents the permission to get and start the next pending job execution for a thing. (That is, to update a job execution with status QUEUED to IN\$1PROGRESS.) The `iotjobsdata:StartNextPendingJobExecution` permission is checked every time a request is made to start the next pending job execution.AWS IoT Core Credential Provider Policy Action

`iot:AssumeRoleWithCertificate`  
Represents the permission to call AWS IoT Core credential provider to assume an IAM role with certificate-based authentication. The `iot:AssumeRoleWithCertificate` permission is checked every time a request is made to AWS IoT Core credential provider to assume a role.

# AWS IoT Core action resources
<a name="iot-action-resources"></a>

To specify a resource for an AWS IoT Core policy action, use the Amazon Resource Name (ARN) of the resource. All resource ARNs follow the following format:

```
arn:partition:iot:region:AWS-account-ID:Resource-type/Resource-name
```

The following table shows the resource to specify for each action type. The ARN examples are for the account ID `123456789012`, in the partition `aws`, and specific to the region `us-east-1`. For more information about the formats for ARNs, see [Amazon Resource Names (ARNs)](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference-arns.html) from the AWS Identity and Access Management User Guide.


| Action | Resource type | Resource name | ARN example | 
| --- | --- | --- | --- | 
| iot:Connect | client |  The client's client ID  | arn:aws:iot:us-east-1:123456789012:client/myClientId | 
| iot:DeleteConnection | client |  The client's client ID  | arn:aws:iot:us-east-1:123456789012:client/myClientId | 
| iot:DeleteThingShadow | thing |  The thing's name, and the shadow's name, if applicable  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne arn:aws:iot:us-east-1:123456789012:thing/thingOne/shadowOne  | 
| iotjobsdata:DescribeJobExecution | thing |  The thing's name  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne  | 
| iotjobsdata:GetPendingJobExecutions | thing |  The thing's name  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne  | 
| iot:GetRetainedMessage | topic |  A retained message topic  |  arn:aws:iot:us-east-1:123456789012:topic/myTopicName  | 
| iot:GetThingShadow | thing |  The thing's name, and the shadow's name, if applicable  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne arn:aws:iot:us-east-1:123456789012:thing/thingOne/shadowOne  | 
| iot:ListNamedShadowsForThing | All | All |  \$1 | 
| iot:ListRetainedMessages | All | All |  \$1 | 
| iot:Publish | topic |  A topic string  | arn:aws:iot:us-east-1:123456789012:topic/myTopicName | 
| iot:Receive | topic |  A topic string  | arn:aws:iot:us-east-1:123456789012:topic/myTopicName | 
| iot:RetainPublish | topic |  A topic to publish with the RETAIN flag set  |  arn:aws:iot:us-east-1:123456789012:topic/myTopicName  | 
| iotjobsdata:StartNextPendingJobExecution | thing |  The thing's name  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne  | 
| iot:Subscribe | topicfilter | A topic filter string | arn:aws:iot:us-east-1:123456789012:topicfilter/myTopicFilter | 
| iotjobsdata:UpdateJobExecution | thing |  The thing's name  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne  | 
| iot:UpdateThingShadow | thing |  The thing's name, and the shadow's name, if applicable  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne arn:aws:iot:us-east-1:123456789012:thing/thingOne/shadowOne  | 
| iot:AssumeRoleWithCertificate | rolealias |  A role alias that points to a role ARN  |  arn:aws:iot:us-east-1:123456789012:rolealias/CredentialProviderRole\$1alias | 

# AWS IoT Core policy variables
<a name="iot-policy-variables"></a>

AWS IoT Core defines policy variables that can be used in AWS IoT Core policies in the `Resource` or `Condition` block. When a policy is evaluated, the policy variables are replaced by actual values. For example, if a device is connected to the AWS IoT Core message broker with a client ID of 100-234-3456, the `iot:ClientId` policy variable is replaced in the policy document by 100-234-3456.

AWS IoT Core policies can use wildcard characters and follow a similar convention to IAM policies. Inserting an `*` (asterik) in the string can be treated as a wildcard, matching any characters. For example, you can use `*` to describe multiple MQTT topic names in the `Resource` attribute of a policy. The characters `+` and `#` are treated as literal strings in a policy. For an example policy that shows how to use wildcards, see [Using wildcard characters in MQTT and AWS IoT Core policies](pub-sub-policy.md#pub-sub-policy-cert).

You can also use predefined policy variables with fixed values to represent characters that otherwise have special meaning. These special characters include `$(*)`, `$(?)`, and `$($)`. For more information about policy variables and the special characters, see [IAM Policy elements: Variables and tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html) and [Creating a condition with multiple keys or values](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_multi-value-conditions.html).

**Topics**
+ [Basic AWS IoT Core policy variables](basic-policy-variables.md)
+ [Thing policy variables](thing-policy-variables.md)
+ [X.509 Certificate AWS IoT Core policy variables](cert-policy-variables.md)

# Basic AWS IoT Core policy variables
<a name="basic-policy-variables"></a>

AWS IoT Core defines the following basic policy variables:
+ `aws:SourceIp`: The IP address of the client connected to the AWS IoT Core message broker.
+ `iot:ClientId`: The client ID used to connect to the AWS IoT Core message broker.
+ `iot:DomainName`: The domain name of the client connected to AWS IoT Core.

**Topics**
+ [Examples of `ClientId` and `SourceIp` policy variables](#basic-policy-variables-example)
+ [Examples of `iot:DomainName` policy variable](#basic-policy-variables-example-domain)

## Examples of `ClientId` and `SourceIp` policy variables
<a name="basic-policy-variables-example"></a>

The following AWS IoT Core policy shows a policy that uses policy variables. `aws:SourceIp` can be used in the Condition element of your policy to allow principals to make API requests only within a specific address range. For examples, see [Authorizing users and cloud services to use AWS IoT Jobs](iam-policy-users-jobs.md).

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/clientid1"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/my/topic/${iot:ClientId}"
			],
			"Condition": {
				"IpAddress": {
					"aws:SourceIp": "123.45.167.89"
				}
			}
		}
	]
}
```

In these examples, `${iot:ClientId}` is replaced by the ID of the client connected to the AWS IoT Core message broker when the policy is evaluated. When you use policy variables like `${iot:ClientId}`, you can inadvertently open access to unintended topics. For example, if you use a policy that uses `${iot:ClientId}` to specify a topic filter:

```
{
	"Effect": "Allow",
	"Action": [
		"iot:Subscribe"
	],
	"Resource": [
		"arn:aws:iot:us-east-1:123456789012:topicfilter/my/${iot:ClientId}/topic"
	]
}
```

A client can connect using `+` as the client ID. This would allow the user to subscribe to any topic that matches the topic filter `my/+/topic`. To protect against such security gaps, use the `iot:Connect` policy action to control which client IDs can connect. For example, this policy allows only those clients whose client ID is `clientid1` to connect:

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/clientid"
			]
		}
	]
}
```

**Note**  
Using the policy variable `${iot:ClientId}` with `Connect` is not recommended. There is no check on the value of `ClientId`, so an attacher with a different client's ID can pass the validation but cause disconnection. Because any `ClientId` is allowed, setting a random client ID can bypass thing group policies.

## Examples of `iot:DomainName` policy variable
<a name="basic-policy-variables-example-domain"></a>

You can add the `iot:DomainName` policy variable to restrict which domains are allowed to use. Adding the `iot:DomainName` policy variable allows devices to connect to only specific configured endpoints.

The following policy allows devices to connect to the specified domain.

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": {
		"Sid": "AllowConnectionsToSpecifiedDomain",
		"Effect": "Allow",
		"Action": [
			"iot:Connect"
		],
		"Resource": "arn:aws:iot:us-east-1:123456789012:client/clientid",
		"Condition": {
			"StringEquals": {
				"iot:DomainName": "d1234567890abcdefghij-ats.iot.us-east-1.amazonaws.com"
			}
		}
	}
}
```

The following policy denies devices to connect to the specified domain.

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": {
		"Sid": "DenyConnectionsToSpecifiedDomain",
		"Effect": "Deny",
		"Action": [
			"iot:Connect"
		],
		"Resource": "arn:aws:iot:us-east-1:123456789012:client/clientid",
		"Condition": {
			"StringEquals": {
				"iot:DomainName": "d1234567890abcdefghij-ats.iot.us-east-1.amazonaws.com"
			}
		}
	}
}
```

For more information about policy conditional operator, see [IAM JSON policy elements: Condition operators](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_elements_condition_operators.html). For more information about domain configurations, see [What is a domain configuration?](https://docs.aws.amazon.com//iot/latest/developerguide/iot-custom-endpoints-configurable.html).

# Thing policy variables
<a name="thing-policy-variables"></a>

Thing policy variables allow you to write AWS IoT Core policies that grant or deny permissions based on thing properties like thing names, thing types, and thing attribute values. You can use thing policy variables to apply the same policy to control many AWS IoT Core devices. For more information about device provisioning, see [Device Provisioning](iot-provision.html).

If you use non-exclusive thing association, the same certificate can be attached to multiple things. To maintain a clear association and to avoid potential conflicts, you must match your client ID with the thing name. In this case, you obtain the thing name from the client ID in the MQTT `Connect` message sent when a thing connects to AWS IoT Core.

Keep the following in mind when using thing policy variables in AWS IoT Core policies.
+ Use the [AttachThingPrincipal](https://docs.aws.amazon.com/iot/latest/apireference/API_AttachThingPrincipal.html) API to attach certificates or principals (authenticated Amazon Cognito identities) to a thing.
+ If non-exclusive thing association is in place, when you're replacing thing names with thing policy variables, the value of `clientId` in the MQTT connect message or the TLS connection must exactly match the thing name.

The following thing policy variables are available:
+ `iot:Connection.Thing.ThingName`

  This resolves to the name of the thing in the AWS IoT Core registry for which the policy is being evaluated. AWS IoT Core uses the certificate the device presents when it authenticates to determine which thing to use to verify the connection. This policy variable is only available when a device connects over MQTT or MQTT over the WebSocket protocol.
+ `iot:Connection.Thing.ThingTypeName`

  This resolves to the thing type associated with the thing for which the policy is being evaluated. The client ID of the MQTT/WebSocket connection must be the same as the thing name. This policy variable is available only when connecting over MQTT or MQTT over the WebSocket protocol.
+ `iot:Connection.Thing.Attributes[attributeName]`

  This resolves to the value of the specified attribute associated with the thing for which the policy is being evaluated. A thing can have up to 50 attributes. Each attribute is available as a policy variable: `iot:Connection.Thing.Attributes[attributeName]` where *attributeName* is the name of the attribute. The client ID of the MQTT/WebSocket connection must be the same as the thing name. This policy variable is only available when connecting over MQTT or MQTT over the WebSocket protocol.
+ `iot:Connection.Thing.IsAttached`

  `iot:Connection.Thing.IsAttached: ["true"]` enforces that only the devices that are both registered in AWS IoT and attached to principal can access the permissions inside the policy. You can use this variable to prevent a device from connecting to AWS IoT Core if it presents a certificate that is not attached to an IoT thing in the AWS IoT Core registry.This variable has values `true` or `false` indicating that the connecting thing is attached to the certificate or Amazon Cognito identity in the registry using [AttachThingPrincipal](https://docs.aws.amazon.com/iot/latest/apireference/API_AttachThingPrincipal.html) API. Thing name is taken as client Id. 

If your client ID matches your thing name, or if you attach your certificate to a thing exclusively, using policy variables in the policy definition can simplify policy management. Instead of creating individual policies for each IoT thing, you can define a single policy using the thing policy variables. This policy can be applied to all devices dynamically. The following is an example policy to show how it works. For more information, see [Associating an AWS IoT thing to an MQTT client connection](exclusive-thing.md).

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Condition": {
				"StringLike": {
					"iot:ClientId": "*${iot:Connection.Thing.Attributes[envType]}"
				}
			},
			"Effect": "Allow",
			"Action": "iot:Connect",
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/*"
		}
	]
}
```

This policy example allows things to connect to AWS IoT Core if their client ID ends with the value of their `envType` attribute. Only things with a matching client ID pattern will be allowed to connect.

# X.509 Certificate AWS IoT Core policy variables
<a name="cert-policy-variables"></a>

X.509 certificate policy variables assist with writing AWS IoT Core policies. These policies grant permissions based on X.509 certificate attributes. The following sections describe how to use these certificate policy variables.

**Important**  
If your X.509 certificate doesn't include a particular certificate attribute but the corresponding certificate policy variable is used in your policy document, the policy evaluation might lead to unexpected behavior.

## CertificateId
<a name="cert-policy-variables-certid"></a>

In the [RegisterCertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCertificate.html) API, the `certificateId` appears in the response body. To get information about your certificate, use the `certificateId` in [DescribeCertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeCertificate.html).

## Issuer attributes
<a name="issuer-attributes"></a>

The following AWS IoT Core policy variables support the allowing or denying of permissions, based on certificate attributes set by the certificate issuer.
+ `iot:Certificate.Issuer.DistinguishedNameQualifier`
+ `iot:Certificate.Issuer.Country`
+ `iot:Certificate.Issuer.Organization`
+ `iot:Certificate.Issuer.OrganizationalUnit`
+ `iot:Certificate.Issuer.State`
+ `iot:Certificate.Issuer.CommonName`
+ `iot:Certificate.Issuer.SerialNumber`
+ `iot:Certificate.Issuer.Title`
+ `iot:Certificate.Issuer.Surname`
+ `iot:Certificate.Issuer.GivenName`
+ `iot:Certificate.Issuer.Initials`
+ `iot:Certificate.Issuer.Pseudonym`
+ `iot:Certificate.Issuer.GenerationQualifier` 

## Subject attributes
<a name="subject-attributes"></a>

The following AWS IoT Core policy variables support the granting or denying of permissions, based on certificate subject attributes set by the certificate issuer.
+ `iot:Certificate.Subject.DistinguishedNameQualifier`
+ `iot:Certificate.Subject.Country`
+ `iot:Certificate.Subject.Organization`
+ `iot:Certificate.Subject.OrganizationalUnit`
+ `iot:Certificate.Subject.State`
+ `iot:Certificate.Subject.CommonName`
+ `iot:Certificate.Subject.SerialNumber`
+ `iot:Certificate.Subject.Title`
+ `iot:Certificate.Subject.Surname`
+ `iot:Certificate.Subject.GivenName`
+ `iot:Certificate.Subject.Initials`
+ `iot:Certificate.Subject.Pseudonym`
+ `iot:Certificate.Subject.GenerationQualifier` 

X.509 certificates provide these attributes with the option to contain one or more values. By default, the policy variables for each multi-value attribute return the first value. For example, the `Certificate.Subject.Country` attribute might contain a list of country names, but when evaluated in a policy, `iot:Certificate.Subject.Country` is replaced by the first country name.

You can request a specific attribute value other than the first value by using a one-based index. For example, `iot:Certificate.Subject.Country.1` is replaced by the second country name in the `Certificate.Subject.Country` attribute. If you specify an index value that does not exist (for example, if you ask for a third value when there are only two values assigned to the attribute), no substitution is made and authorization fails. You can use the `.List` suffix on the policy variable name to specify all values of the attribute.

## Issuer alternate name attributes
<a name="issuer-alternate-name-attributes"></a>

The following AWS IoT Core policy variables support the granting or denying of permissions, based on issuer alternate name attributes set by the certificate issuer.
+ `iot:Certificate.Issuer.AlternativeName.RFC822Name`
+ `iot:Certificate.Issuer.AlternativeName.DNSName`
+ `iot:Certificate.Issuer.AlternativeName.DirectoryName`
+ `iot:Certificate.Issuer.AlternativeName.UniformResourceIdentifier`
+ `iot:Certificate.Issuer.AlternativeName.IPAddress`

## Subject alternate name attributes
<a name="subject-alternate-name-attributes"></a>

The following AWS IoT Core policy variables support the granting or denying of permissions, based on subject alternate name attributes set by the certificate issuer.
+ `iot:Certificate.Subject.AlternativeName.RFC822Name`
+ `iot:Certificate.Subject.AlternativeName.DNSName`
+ `iot:Certificate.Subject.AlternativeName.DirectoryName`
+ `iot:Certificate.Subject.AlternativeName.UniformResourceIdentifier`
+ `iot:Certificate.Subject.AlternativeName.IPAddress`

## Other attributes
<a name="other-attributes"></a>

You can use `iot:Certificate.SerialNumber` to allow or deny access to AWS IoT Core resources, based on the serial number of a certificate. The `iot:Certificate.AvailableKeys` policy variable contains the name of all certificate policy variables that contain values.

# Using X.509 certificate policy variables
<a name="use-policy-variables"></a>

This topic provides details of how to use certificate policy variables. X.509 certificate policy variables are essential when you create AWS IoT Core policies that give permissions based on X.509 certificate attributes. If your X.509 certificate doesn't include a particular certificate attribute but the corresponding certificate policy variable is used in your policy document, the policy evaluation might lead to unexpected behavior. This is because the missing policy variable doesn't get evaluated in the policy statement.

**Topics**
+ [X.509 certificate example](#certificate-example)
+ [Using certificate issuer attributes as certificate policy variables](#issuer-attributes-policy)
+ [Using certificate subject attributes as certificate policy variables](#subject-attributes-policy)
+ [Using certificate Issuer alternate name attributes as certificate policy variables](#issuer-alternate-name-attributes-policy)
+ [Using certificate subject alternate name attributes as certificate policy variables](#subject-alternate-name-attributes-policy)
+ [Using other certificate attribute as a certificate policy variable](#other-attributes-policy)
+ [X.509 Certificate policy variable limitations](#policy-limits)
+ [Example policies using certificate policy variables](#example-attributes-policy)

## X.509 certificate example
<a name="certificate-example"></a>

A typical X.509 certificate might appear as follows. This example certificate includes certificate attributes. During the evaluation of AWS IoT Core policies, the following certificate attributes will be populated as certificate policy variables: `Serial Number`, `Issuer`, `Subject`, `X509v3 Issuer Alternative Name`, and `X509v3 Subject Alternative Name`.

```
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            92:12:85:cb:b7:a5:e0:86
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, O=IoT Devices, OU=SmartHome, ST=WA, CN=IoT Devices Primary CA, 
				GN=Primary CA1/initials=XY/dnQualifier=Example corp,
				SN=SmartHome/ title=CA1/pseudonym=Primary_CA/generationQualifier=2/serialNumber=987		
        Validity
            Not Before: Mar 26 03:25:40 2024 GMT
            Not After : Apr 28 03:25:40 2025 GMT
        Subject: C=US, O=IoT Devices, OU=LightBulb, ST=NY, CN=LightBulb Device Cert, 
				GN=Bulb/initials=ZZ/dnQualifier=Bulb001, 
				SN=Multi Color/title=RGB/pseudonym=RGB Device/generationQualifier=4/serialNumber=123
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                RSA Public-Key: (2048 bit)
                Modulus:
                    << REDACTED >>
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            X509v3 Key Usage: 
                Digital Signature, Non Repudiation, Key Encipherment
            X509v3 Subject Alternative Name: 
                DNS:example.com, IP Address:1.2.3.4, URI:ResourceIdentifier001, email:device1@example.com, DirName:/C=US/O=IoT/OU=SmartHome/CN=LightBulbCert
            X509v3 Issuer Alternative Name: 
                DNS:issuer.com, IP Address:5.6.7.8, URI:PrimarySignerCA, email:primary@issuer.com, DirName:/C=US/O=Issuer/OU=IoT Devices/CN=Primary Issuer CA
    Signature Algorithm: sha256WithRSAEncryption
         << REDACTED >>
```

## Using certificate issuer attributes as certificate policy variables
<a name="issuer-attributes-policy"></a>

The following table provides details of how certificate issuer attributes will be populated in an AWS IoT Core policy.


**Issuer attributes to be populated in a policy**  

| Certificate issuer attributes | Certificate policy variables | 
| --- | --- | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/use-policy-variables.html)  | 

## Using certificate subject attributes as certificate policy variables
<a name="subject-attributes-policy"></a>

The following table provides details of how certificate subject attributes will be populated in an AWS IoT Core policy.


**Subject attributes to be populated in a policy**  

| Certificate subject attributes | Certificate policy variables | 
| --- | --- | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/use-policy-variables.html)  | 

## Using certificate Issuer alternate name attributes as certificate policy variables
<a name="issuer-alternate-name-attributes-policy"></a>

The following table provides details of how certificate issuer alternate name attributes will be populated in an AWS IoT Core policy.


**Issuer alternate name attributes to be populated in a policy**  

| X509v3 Issuer Alternative Name | Attribute in a policy | 
| --- | --- | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/use-policy-variables.html)  | 

## Using certificate subject alternate name attributes as certificate policy variables
<a name="subject-alternate-name-attributes-policy"></a>

The following table provides details of how certificate subject alternate name attributes will be populated in an AWS IoT Core policy.


**Subject alternate name attributes to be populated in a policy**  

| X509v3 Subject Alternative Name | Attribute in a policy | 
| --- | --- | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/use-policy-variables.html)  | 

## Using other certificate attribute as a certificate policy variable
<a name="other-attributes-policy"></a>

The following table provides details of how other certificate attributes will be populated in an AWS IoT Core policy.


**Other attributes to be populated in a policy**  

| Other certificate attribute | Certificate policy variable | 
| --- | --- | 
|  `Serial Number: 92:12:85:cb:b7:a5:e0:86`  |  `iot:Certificate.SerialNumber = 10525622389124227206`  | 

## X.509 Certificate policy variable limitations
<a name="policy-limits"></a>

The following limitations apply to X.509 certificate policy variables:

Missing policy variables  
If your X.509 certificate doesn't include a particular certificate attribute but the corresponding certificate policy variable is used in your policy document, the policy evaluation might lead to unexpected behavior. This is because the missing policy variable doesn't get evaluated in the policy statement.

Certificate SerialNumber format  
AWS IoT Core treats the certificate serial number as the string representation of a decimal integer. For example, if a policy only allows connections with Client ID matching the certificate serial number, the client ID must be the serial number in decimal format.

Wildcards  
If wildcard characters are present in certificate attributes, the policy variable is not replaced by the certificate attribute value. This will leave the `${policy-variable}` text in the policy document. This might cause authorization failure. The following wildcard characters can be used: `*`, `$`, `+`, `?`, and `#`.

Array fields  
Certificate attributes that contain arrays are limited to five items. Additional items are ignored.

String length  
All string values are limited to 1024 characters. If a certificate attribute contains a string longer than 1024 characters, the policy variable is not replaced by the certificate attribute value. This will leave the `${policy-variable}` in the policy document. This might cause authorization failure.

Special Characters  
Any special character, such as `,`, `"`, `\`, `+`, `=`, `<`, `>` and `;` must be prefixed with a backslash (`\`) when used in a policy variable. For example, `Amazon Web Services O=Amazon.com Inc. L=Seattle ST=Washington C=US` becomes `Amazon Web Service O\=Amazon.com Inc. L\=Seattle ST\=Washington C\=US`.

## Example policies using certificate policy variables
<a name="example-attributes-policy"></a>

The following policy document allows connections with client ID that matches the certificate serial number and publishing to the topic that matches the pattern: `${iot:Certificate.Subject.Organization}/device-stats/${iot:ClientId}/*`. 

**Important**  
If your X.509 certificate doesn't include a particular certificate attribute but the corresponding certificate policy variable is used in your policy document, the policy evaluation might lead to unexpected behavior. This is because the missing policy variable doesn't get evaluated in the policy statement. For example, if you attach the following policy document to a certificate that doesn't contain the `iot:Certificate.Subject.Organization` attribute, the `iot:Certificate.Subject.Organization` certificate policy variables won't be populated during the policy evaluation.

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Certificate.SerialNumber}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/${iot:Certificate.Subject.Organization}/device-stats/${iot:ClientId}/*"
			]
		}
	]
}
```

You can also use the [Null condition operator](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Null) to ensure that the certificate policy variables used in a policy are populated during policy evaluation. The following policy document allows `iot:Connect` with certificates only when the Certificate Serial Number and Certificate Subject Common name attributes are present.

All of the certificate policy variables have String values, so all of the [String condition operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String) are supported.

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/*"
			],
			"Condition": {
				"Null": {
					"iot:Certificate.SerialNumber": "false",
					"iot:Certificate.Subject.CommonName": "false"
				}
			}
		}
	]
}
```

# Cross-service confused deputy prevention
<a name="cross-service-confused-deputy-prevention"></a>

The *confused deputy problem* is a security issue where an entity that doesn't have permission to perform an action can coerce a more-privileged entity to perform the action. In AWS, cross-service impersonation can result in the confused deputy problem. Cross-service impersonation can occur when one service (the *calling service*) calls another service (the *called service*). The calling service can be manipulated to use its permissions to act on another customer's resources in a way it shouldn't otherwise have permission to access. To prevent this, AWS provides tools that help you protect your data for all services with service principals that have been given access to resources in your account. 

To limit the permissions that AWS IoT gives another service to the resource, we recommend using the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn) and [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount) global condition context keys in resource policies. If you use both global condition context keys, the `aws:SourceAccount` value and the account in the `aws:SourceArn` value must use the same account ID when used in the same policy statement.

The most effective way to protect against the confused deputy problem is to use the `aws:SourceArn` global condition context key with the full Amazon Resource Name (ARN) of the resource. For AWS IoT, your `aws:SourceArn` must comply with the format: `arn:aws:iot:region:account-id:resource-type/resource-id` for resource specific permissions or `arn:aws:iot:region:account-id:*`. The resource-id can be the name or ID of the permitted resource, or a wildcard statement of the permitted resource IDs. Make sure that the *region* matches your AWS IoT Region and the *account-id* matches your customer account ID. 

The following example shows how to prevent the confused deputy problem by using the `aws:SourceArn` and `aws:SourceAccount` global condition context keys in the AWS IoT role trust policy. For more examples, see [Detailed examples of confused deputy prevention](#cross-service-confused-deputy-prevention-examples).

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Service":"iot.amazonaws.com"
         },
         "Action":"sts:AssumeRole",
         "Condition":{
            "StringEquals":{
               "aws:SourceAccount":"123456789012"
        },
            "ArnLike":{
               "aws:SourceArn":"arn:aws:iot:us-east-1:123456789012:*"
        }
         }
      }
   ]
}
```

**Note**  
If you get access deny errors, it can be because the service integration with AWS Security Token Service (STS) doesn't support the `aws:SourceArn` and `aws:SourceAccount` context keys.

## Detailed examples of confused deputy prevention
<a name="cross-service-confused-deputy-prevention-examples"></a>

**This section provides detailed examples of how to prevent the confused deputy problem by using the `aws:SourceArn` and `aws:SourceAccount` global condition context keys in the AWS IoT role trust policy.**
+ [Fleet provisioning](#cross-service-confused-deputy-prevention-fleet-provision)
+ [JITP](#cross-service-confused-deputy-prevention-JITP)
+ [Credential provider](#cross-service-confused-deputy-prevention-credential-provider)

### Fleet provisioning
<a name="cross-service-confused-deputy-prevention-fleet-provision"></a>

You can configure [fleet provisioning](https://docs.aws.amazon.com/iot/latest/developerguide/iot-provision.html) using a provisioning template resource. When a provisioning template references a provisioning role, that role's trust policy can include the `aws:SourceArn` and `aws:SourceAccount` condition keys. These keys limit the resources for which the configuration can invoke the `sts:AssumeRole` request.

The role with the following trust policy can only be assumed by the IoT principal (`iot.amazonaws.com`) for the provisioning template specified in the `SourceArn`.

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Service":"iot.amazonaws.com"
         },
         "Action":"sts:AssumeRole",
         "Condition":{
            "StringEquals":{
               "aws:SourceAccount":"123456789012"
        },
            "ArnLike":{
               "aws:SourceArn":"arn:aws:iot:us-east-1:123456789012:provisioningtemplate/example_template"
        }
         }
      }
   ]
}
```

### JITP
<a name="cross-service-confused-deputy-prevention-JITP"></a>

In [just-in-time provisioning (JITP)](https://docs.aws.amazon.com//iot/latest/developerguide/jit-provisioning.html), you can either use provisioning template as a resource separate from the CA or define the template body and the role as part of the CA certificate configuration. The value of `aws:SourceArn` in the AWS IoT role trust policy depends on how you define the provisioning template.

#### Defining provisioning template as a separate resource
<a name="cross-service-confused-deputy-prevention-JITP-template"></a>

If you define your provisioning template as a separate resource, the value of `aws:SourceArn` can be `"arn:aws:iot:region:account-id:provisioningtemplate/example_template"`. You can use the same policy example in [Fleet provisioning](#cross-service-confused-deputy-prevention-fleet-provision).

#### Defining provisioning template in a CA certificate
<a name="cross-service-confused-deputy-prevention-JITP-CA"></a>

If you define your provisioning template within a CA certificate resource, the value of `aws:SourceArn` can be `"arn:aws:iot:region:account-id:cacert/cert_id"` or `"arn:aws:iot:region:account-id:cacert/*"`. You can use a wildcard when the resource identifier, such as the ID of a CA certificate, is unknown at the time of creation.

The role with the following trust policy can only be assumed by the IoT principal (`iot.amazonaws.com`) for the CA certificate specified in the `SourceArn`.

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Service":"iot.amazonaws.com"
         },
         "Action":"sts:AssumeRole",
         "Condition":{
            "StringEquals":{
               "aws:SourceAccount":"123456789012"
        },
            "ArnLike":{
               "aws:SourceArn":"arn:aws:iot:us-east-1:123456789012:cacert/8ecde6884f3d87b1125ba31ac3fcb13d7016de7f57cc904fe1cb97c6ae98196e"
        }
         }
      }
   ]
}
```

When creating a CA certificate, you can reference a provisioning role in the registration configuration. The trust policy of the provisioning role can use `aws:SourceArn` to restrict what resources the role can be assumed for. However, during the initial [RegisterCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCACertificate.html) call to register the CA certificate, you would not have the ARN of the CA certificate to specify in the `aws:SourceArn` condition.

To work around this, i.e., to specify the provisioning role trust policy to the specific CA certificate that's registered with AWS IoT Core, you can do the following:
+ First, call [RegisterCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCACertificate.html) without providing the `RegistrationConfig` parameter.
+ After the CA certificate is registered with AWS IoT Core, call [UpdateCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateCACertificate.html) on it.

  In the UpdateCACertificate call, provide a `RegistrationConfig` that includes the provisioning role trust policy with `aws:SourceArn` set to the ARN of the newly registered CA certificate.

### Credential provider
<a name="cross-service-confused-deputy-prevention-credential-provider"></a>

For [AWS IoT Core credential provider](https://docs.aws.amazon.com//iot/latest/developerguide/authorizing-direct-aws.html), use the same AWS account you use to create the role alias in `aws:SourceAccount`, and specify a statement that matches the resource ARN of the rolealias resource type in `aws:SourceArn`. When creating an IAM role for use with AWS IoT Core credential provider, you must include in the `aws:SourceArn` condition the ARNs of any role aliases that might need to assume the role, thereby authorizing the cross-service `sts:AssumeRole` request.

The role with the following trust policy can only be assumed by the principal of AWS IoT Core credential provider (`credentials.iot.amazonaws.com`) for the roleAlias specified in the `SourceArn`. If a principal attempts to retrieve credentials for a role alias other than what's specified in the `aws:SourceArn` condition, the request will be denied, even if that other role alias references the same IAM role.

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "credentials.iot.amazonaws.com"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "aws:SourceAccount": "123456789012"
        },
        "ArnLike": {
          "aws:SourceArn": "arn:aws:iot:us-east-1:123456789012:rolealias/example_rolealias"
        }
      }
    }
  ]
}
```

# AWS IoT Core policy examples
<a name="example-iot-policies"></a>

The example policies in this section illustrate the policy documents used to complete common tasks in AWS IoT Core. You can use them as examples to start from when creating the policies for your solutions.<a name="example-iot-policies-elements"></a>

The examples in this section use these policy elements:
+ [AWS IoT Core policy actions](iot-policy-actions.md)
+ [AWS IoT Core action resources](iot-action-resources.md)
+ [AWS IoT identity-based policy examples](security_iam_id-based-policy-examples.md)
+ [Basic AWS IoT Core policy variables](basic-policy-variables.md)
+ [X.509 Certificate AWS IoT Core policy variables](cert-policy-variables.md)

**Topics**
+ [Connect policy examples](connect-policy.md)
+ [Publish/Subscribe policy examples](pub-sub-policy.md)
+ [Connect and publish policy examples](connect-and-pub.md)
+ [Retained message policy examples](retained-message-policy-examples.md)
+ [Certificate policy examples](certificate-policy-examples.md)
+ [Thing policy examples](thing-policy-examples.md)
+ [Basic job policy example](basic-jobs-example.md)

# Connect policy examples
<a name="connect-policy"></a>

The following policy denies permission to client IDs `client1` and `client2` to connect to AWS IoT Core, while allowing devices to connect using a client ID. The client ID matches the name of a thing that's registered in the AWS IoT Core registry and attached to the principal that's used for connection:

**Note**  
For registered devices, we recommend that you use [thing policy variables](thing-policy-variables.md) for `Connect` actions and attach the thing to the principal that's used for the connection.

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Deny",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/client1",
				"arn:aws:iot:us-east-1:123456789012:client/client2"
			]
		},
		{
			"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"
				}
			}
		}
	]
}
```

The following policy grants permission to connect to AWS IoT Core with client ID `client1`. This policy example is for unregistered devices.

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/client1"
			]
		}
	]
}
```

## MQTT persistent sessions policy examples
<a name="persistent-sessions-examples"></a>

`connectAttributes` allow you to specify what attributes you want to use in your connect message in your IAM policies such as `PersistentConnect` and `LastWill`. For more information, see [Using connectAttributes](mqtt.md#connect-attribute).

The following policy allows connect with `PersistentConnect` feature:

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect"
					]
				}
			}
		}
	]
}
```

The following policy disallows `PersistentConnect`, other features are allowed:

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringNotEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect"
					]
				}
			}
		}
	]
}
```

The above policy can also be expressed using `StringEquals`, any other feature including new feature is allowed:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1"
        },
        {
            "Effect": "Deny",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "*",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:ConnectAttributes": [
                        "PersistentConnect"
                    ]
            }
        }
        }
    ]
}
```

The following policy allows connect by both `PersistentConnect` and `LastWill`, any other new feature is not allowed:

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect",
						"LastWill"
					]
				}
			}
		}
	]
}
```

The following policy allows clean connect by clients with or without `LastWill`, no other features will be allowed:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
        "Effect": "Allow",
        "Action": [
            "iot:Connect"
        ],
        "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
        "Condition": {
            "StringEquals": {
                "iot:ConnectAttributes": "LastWill"
        }
        }
    }]
}
```

The following policy only allows connect using default features:

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": []
				}
			}
		}
	]
}
```

The following policy allows connect only with `PersistentConnect`, any new feature is allowed as long as the connection uses `PersistentConnect`:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:ConnectAttributes": [
                        "PersistentConnect"
                    ]
            }
        }
        }
    ]
}
```

The following policy states the connect must have both `PersistentConnect` and `LastWill` usage, no new feature is allowed:

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect",
						"LastWill"
					]
				}
			}
		},
		{
			"Effect": "Deny",
			"Action": [
				"iot:Connect"
			],
			"Resource": "*",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect"
					]
				}
			}
		},
		{
			"Effect": "Deny",
			"Action": [
				"iot:Connect"
			],
			"Resource": "*",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"LastWill"
					]
				}
			}
		},
		{
			"Effect": "Deny",
			"Action": [
				"iot:Connect"
			],
			"Resource": "*",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": []
				}
			}
		}
	]
}
```

The following policy must not have `PersistentConnect` but can have `LastWill`, any other new feature is not allowed:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "*",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:ConnectAttributes": [
                        "PersistentConnect"
                    ]
            }
        }
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
            "Condition": {
                "ForAllValues:StringEquals": {
                    "iot:ConnectAttributes": [
                        "LastWill"
                    ]
            }
        }
        }
    ]
}
```

The following policy allows connect only by clients that have a `LastWill` with topic `"my/lastwill/topicName"`, any feature is allowed as long as it uses the `LastWill` topic:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
            "Condition": {
                "ArnEquals": {
                "iot:LastWillTopic": "arn:aws:iot:us-east-1:123456789012:topic/my/lastwill/topicName"
            }
        }
        }
    ]
}
```

The following policy only allows clean connect using a specific `LastWillTopic`, any feature is allowed as long as it uses the `LastWillTopic`:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
            "Condition": {
                "ArnEquals": {
                "iot:LastWillTopic": "arn:aws:iot:us-east-1:123456789012:topic/my/lastwill/topicName"
            }
        }
        },
        {
            "Effect": "Deny",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "*",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:ConnectAttributes": [
                        "PersistentConnect"
                    ]
            }
        }
        }
    ]
}
```

# Publish/Subscribe policy examples
<a name="pub-sub-policy"></a>

The policy you use depends on how you're connecting to AWS IoT Core. You can connect to AWS IoT Core by using an MQTT client, HTTP, or WebSocket. When you connect with an MQTT client, you're authenticating with an X.509 certificate. When you connect over HTTP or the WebSocket protocol, you're authenticating with Signature Version 4 and Amazon Cognito. 

**Note**  
For registered devices, we recommend that you use [thing policy variables](thing-policy-variables.md) for `Connect` actions and attach the thing to the principal that's used for the connection. 

**Topics**
+ [Using wildcard characters in MQTT and AWS IoT Core policies](#pub-sub-policy-cert)
+ [Policies to publish, subscribe and receive messages to/from specific topics](#pub-sub-specific-topic)
+ [Policies to publish, subscribe and receive messages to/from topics with a specific prefix](#pub-sub-policy-specific-topic-prefix)
+ [Policies to publish, subscribe and receive messages to/from topics specific to each device](#pub-sub-specific-topic-device)
+ [Policies to publish, subscribe and receive messages to/from topics with thing attribute in topic name](#pub-sub-topic-attribute)
+ [Policies to deny publishing messages to subtopics of a topic name](#pub-sub-deny-publish)
+ [Policies to deny receiving messages from subtopics of a topic name](#pub-sub-deny-receive)
+ [Policies to subscribe to topics using MQTT wildcard characters](#pub-sub-topic-wildcard)
+ [Policies for HTTP and WebSocket clients](#pub-sub-policy-cognito)

## Using wildcard characters in MQTT and AWS IoT Core policies
<a name="pub-sub-policy-cert"></a>

MQTT and AWS IoT Core policies have different wildcard characters and you should choose them after careful consideration. In MQTT, the wildcard characters `+` and `#` are used in [MQTT topic filters](https://docs.aws.amazon.com/iot/latest/developerguide/topics.html#topicfilters) to subscribe to multiple topic names. AWS IoT Core policies use `*` and `?` as wildcard characters and follow the conventions of [IAM policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_grammar.html#policies-grammar-json). In a policy document, the `*` represents any combination of characters and a question mark `?` represents any single character. In policy documents, the MQTT wildcard characters, `+` and `#` are treated as those characters with no special meaning. To describe multiple topic names and topic filters in the `resource` attribute of a policy, use the `*` and `?` wildcard characters in place of the MQTT wildcard characters.

When you choose the wildcard characters to use in a policy document, consider that the `*` character is not confined to a single topic level. The `+` character is confined to a single topic level in an MQTT topic filter. To help constrain a wildcard specification to a single MQTT topic filter level, consider using multiple `?` characters. For more information about using wildcard characters in a policy resource and more examples of what they match, see [Using wildcards in resource ARNs](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_elements_resource.html#reference_policies_elements_resource_wildcards).

The table below shows the different wildcard characters used in MQTT and AWS IoT Core policies for MQTT clients.


| Wildcard character | Is MQTT wildcard character | Example in MQTT | Is AWS IoT Core policy wildcard character | Example in AWS IoT Core policies for MQTT clients | 
| --- | --- | --- | --- | --- | 
| \$1 | Yes | some/\$1 | No | N/A | 
| \$1 | Yes | some/\$1/topic | No | N/A | 
| \$1 | No | N/A | Yes | `topicfilter/some/*/topic` `topicfilter/some/sensor*/topic`  | 
| ? | No | N/A | Yes |  `topic/some/?????/topic` `topicfilter/some/sensor???/topic`  | 

## Policies to publish, subscribe and receive messages to/from specific topics
<a name="pub-sub-specific-topic"></a>

The following shows examples for registered and unregistered devices to publish, subscribe and receive messages to/from the topic named "some\$1specific\$1topic". The examples also highlight that `Publish` and `Receive` use "topic" as the resource, and `Subscribe` uses "topicfilter" as the resource.

------
#### [ Registered devices ]

For devices registered in AWS IoT Core registry, the following policy allows devices to connect with clientId that matches the name of a thing in the registry. It also provides `Publish`, `Subscribe` and `Receive` permissions for the topic named "some\$1specific\$1topic".

****  

```
{
	"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:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/some_specific_topic"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Subscribe"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topicfilter/some_specific_topic"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Receive"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/some_specific_topic"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

For devices not registered in AWS IoT Core registry, the following policy allows devices to connect using either clientId1, clientId2 or clientId3. It also provides `Publish`, `Subscribe` and `Receive` permissions for the topic named "some\$1specific\$1topic".

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/some_specific_topic"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Subscribe"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topicfilter/some_specific_topic"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/some_specific_topic"
            ]
        }
    ]
}
```

------

## Policies to publish, subscribe and receive messages to/from topics with a specific prefix
<a name="pub-sub-policy-specific-topic-prefix"></a>

The following shows examples for registered and unregistered devices to publish, subscribe and receive messages to/from topics prefixed with "topic\$1prefix".

**Note**  
Note the use of the wildcard character `*` in this example. Although `*` is useful to provide permissions for multiple topic names in a single statement, it can lead to unintended consequences by providing more privileges to devices than required. So we recommend that you only use the wildcard character `*` after careful consideration.

------
#### [ Registered devices ]

For devices registered in AWS IoT Core registry, the following policy allows devices to connect with clientId that matches the name of a thing in the registry. It also provides `Publish`, `Subscribe` and `Receive` permissions for topics prefixed with "topic\$1prefix".

****  

```
{
	"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:Publish",
				"iot:Receive"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/topic_prefix*"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Subscribe"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topicfilter/topic_prefix*"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

For devices not registered in AWS IoT Core registry, the following policy allows devices to connect using either clientId1, clientId2 or clientId3. It also provides `Publish`, `Subscribe` and `Receive` permissions for topics prefixed with "topic\$1prefix".

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish",
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/topic_prefix*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Subscribe"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topicfilter/topic_prefix*"
            ]
        }
    ]
}
```

------

## Policies to publish, subscribe and receive messages to/from topics specific to each device
<a name="pub-sub-specific-topic-device"></a>

The following shows examples for registered and unregistered devices to publish, subscribe and receive messages to/from topics that are specific to the given device.

------
#### [ Registered devices ]

For devices registered in AWS IoT Core registry, the following policy allows devices to connect with clientId that matches the name of a thing in the registry. It provides permission to publish to the thing-specific topic (`sensor/device/${iot:Connection.Thing.ThingName}`) and also subscribe to and receive from the thing-specific topic (`command/device/${iot:Connection.Thing.ThingName}`). If the thing name in the registry is "thing1", the device will be able to publish to the topic "sensor/device/thing1". The device will also be able to subscribe to and receive from the topic "command/device/thing1".

****  

```
{
	"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:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/sensor/device/${iot:Connection.Thing.ThingName}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Subscribe"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topicfilter/command/device/${iot:Connection.Thing.ThingName}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Receive"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/command/device/${iot:Connection.Thing.ThingName}"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

For devices not registered in AWS IoT Core registry, the following policy allows devices to connect using either clientId1, clientId2 or clientId3. It provides permission to publish to the client-specific topic (`sensor/device/${iot:ClientId}`), and also subscribe to and receive from the client-specific topic (`command/device/${iot:ClientId}`). If the device connects with clientId as clientId1, it will be able to publish to the topic "sensor/device/clientId1". The device will also be able to subscribe to and receive from the topic `device/clientId1/command`.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/sensor/device/${iot:Connection.Thing.ThingName}"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Subscribe"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topicfilter/command/device/${iot:Connection.Thing.ThingName}"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/command/device/${iot:Connection.Thing.ThingName}"
            ]
        }
    ]
}
```

------

## Policies to publish, subscribe and receive messages to/from topics with thing attribute in topic name
<a name="pub-sub-topic-attribute"></a>

The following shows an example for registered devices to publish, subscribe and receive messages to/from topics whose names include thing attributes.

**Note**  
Thing attributes only exist for devices registered in AWS IoT Core Registry. There is no corresponding example for unregistered devices.

------
#### [ Registered devices ]

For devices registered in AWS IoT Core registry, the following policy allows devices to connect with clientId that matches the name of a thing in the registry. It provides permission to publish to the topic (`sensor/${iot:Connection.Thing.Attributes[version]}`), and subscribe to and receive from the topic (`command/${iot:Connection.Thing.Attributes[location]}`) where the topic name includes thing attributes. If the thing name in the registry has `version=v1` and `location=Seattle`, the device will be able to publish to the topic "sensor/v1", and subscribe to and receive from the topic "command/Seattle".

****  

```
{
	"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:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/sensor/${iot:Connection.Thing.Attributes[version]}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Subscribe"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topicfilter/command/${iot:Connection.Thing.Attributes[location]}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Receive"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/command/${iot:Connection.Thing.Attributes[location]}"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

Because thing attributes only exist for devices registered in AWS IoT Core registry, there is no corresponding example for unregistered things.

------

## Policies to deny publishing messages to subtopics of a topic name
<a name="pub-sub-deny-publish"></a>

The following shows examples for registered and unregistered devices to publish messages to all topics except certain subtopics.

------
#### [ Registered devices ]

For devices registered in AWS IoT Core registry, the following policy allows devices to connect with clientId that matches the name of a thing in the registry. It provides permission to publish to all topics prefixed with "department/" but not to the "department/admins" subtopic.

****  

```
{
	"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:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/department/*"
			]
		},
		{
			"Effect": "Deny",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/department/admins"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

For devices not registered in AWS IoT Core registry, the following policy allows devices to connect using either clientId1, clientId2 or clientId3. It provides permission to publish to all topics prefixed with "department/" but not to the "department/admins" subtopic.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/department/*"
            ]
        },
        {
            "Effect": "Deny",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/department/admins"
            ]
        }
    ]
}
```

------

## Policies to deny receiving messages from subtopics of a topic name
<a name="pub-sub-deny-receive"></a>

The following shows examples for registered and unregistered devices to subscribe to and receive messages from topics with specific prefixes except certain subtopics.

------
#### [ Registered devices ]

For devices registered in AWS IoT Core registry, the following policy allows devices to connect with clientId that matches the name of a thing in the registry. The policy allows devices to subscribe to any topic prefixed with "topic\$1prefix". By using `NotResource` in the statement for `iot:Receive`, we allow the device to receive messages from all topics that the device has subscribed to, except the topics prefixed with "topic\$1prefix/restricted". For example, with this policy, devices can subscribe to "topic\$1prefix/topic1" and even "topic\$1prefix/restricted", however, they will only receive messages from the topic "topic\$1prefix/topic1" and no messages from the topic "topic\$1prefix/restricted".

****  

```
{
	"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/topic_prefix/*"
		},
		{
			"Effect": "Allow",
			"Action": "iot:Receive",
			"NotResource": "arn:aws:iot:us-east-1:123456789012:topic/topic_prefix/restricted/*"
		}
	]
}
```

------
#### [ Unregistered devices ]

For devices not registered in AWS IoT Core registry, the following policy allows devices to connect using either clientId1, clientId2 or clientId3. The policy allows devices to subscribe to any topic prefixed with "topic\$1prefix". By using `NotResource` in the statement for `iot:Receive`, we allow the device to receive messages from all topics that the device has subscribed to, except topics prefixed with "topic\$1prefix/restricted". For example, with this policy, devices can subscribe to "topic\$1prefix/topic1" and even "topic\$1prefix/restricted". However, they will only receive messages from the topic "topic\$1prefix/topic1" and no messages from the topic "topic\$1prefix/restricted".

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "iot:Subscribe",
            "Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/topic_prefix/*"
        },
        {
            "Effect": "Allow",
            "Action": "iot:Receive",
            "NotResource": "arn:aws:iot:us-east-1:123456789012:topic/topic_prefix/restricted/*"
        }
    ]
}
```

------

## Policies to subscribe to topics using MQTT wildcard characters
<a name="pub-sub-topic-wildcard"></a>

MQTT wildcard characters \$1 and \$1 are treated as literal strings, but they are not treated as wildcards when used in AWS IoT Core policies. In MQTT, \$1 and \$1 are treated as wildcards only when subscribing to a topic filter but as a literal string in all other contexts. We recommend that you only use these MQTT wildcards as part of AWS IoT Core policies after careful consideration.

The following shows examples for registered and unregistered things using MQTT wildcards in AWS IoT Core policies. These wildcards are treated as literal strings.

------
#### [ Registered devices ]

For devices registered in AWS IoT Core registry, the following policy allows devices to connect with clientId that matches the name of a thing in the registry. The policy allows devices to subscribe to the topics "department/\$1/employees" and "location/\$1". Because \$1 and \$1 are treated as literal strings in AWS IoT Core policies, devices can subscribe to the topic "department/\$1/employees" but not to the topic "department/engineering/employees". Similarly, devices can subscribe to the topic "location/\$1" but not to the topic "location/Seattle". However, once the device subscribes to the topic "department/\$1/employees", the policy will allow them to receive messages from the topic "department/engineering/employees". Similarly, once the device subscribes to the topic "location/\$1", they will receive messages from the topic "location/Seattle" as well.

****  

```
{
	"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/department/+/employees"
		},
		{
			"Effect": "Allow",
			"Action": "iot:Subscribe",
			"Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/location/#"
		},
		{
			"Effect": "Allow",
			"Action": "iot:Receive",
			"Resource": "arn:aws:iot:us-east-1:123456789012:topic/*"
		}
	]
}
```

------
#### [ Unregistered devices ]

For devices not registered in AWS IoT Core registry, the following policy allows devices to connect using either clientId1, clientId2 or clientId3. The policy allows devices to subscribe to the topics of "department/\$1/employees" and "location/\$1". Because \$1 and \$1 are treated as literal strings in AWS IoT Core policies, devices can subscribe to the topic "department/\$1/employees" but not to the topic "department/engineering/employees". Similarly, devices can subscribe to the topic "location/\$1" but not "location/Seattle". However, once the device subscribes to the topic "department/\$1/employees", the policy will allow them to receive messages from the topic "department/engineering/employees". Similarly, once the device subscribes to the topic "location/\$1", they will receive messages from the topic "location/Seattle" as well.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "iot:Subscribe",
            "Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/department/+/employees"
        },
        {
            "Effect": "Allow",
            "Action": "iot:Subscribe",
            "Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/location/#"
        },
        {
            "Effect": "Allow",
            "Action": "iot:Receive",
            "Resource": "arn:aws:iot:us-east-1:123456789012:topic/*"
        }
    ]
}
```

------

## Policies for HTTP and WebSocket clients
<a name="pub-sub-policy-cognito"></a>

When you connect over HTTP or the WebSocket protocol, you're authenticating with Signature Version 4 and Amazon Cognito. Amazon Cognito identities can be authenticated or unauthenticated. Authenticated identities belong to users who are authenticated by any supported identity provider. Unauthenticated identities typically belong to guest users who do not authenticate with an identity provider. Amazon Cognito provides a unique identifier and AWS credentials to support unauthenticated identities. For more information, see [Authorization with Amazon Cognito identities](cog-iot-policies.md).

For the following operations, AWS IoT Core uses AWS IoT Core policies attached to Amazon Cognito identities through the `AttachPolicy` API. This scopes down the permissions attached to the Amazon Cognito Identity pool with authenticated identities.
+ `iot:Connect`
+ `iot:Publish`
+ `iot:Subscribe`
+ `iot:Receive`
+ `iot:GetThingShadow`
+ `iot:UpdateThingShadow`
+ `iot:DeleteThingShadow`

That means an Amazon Cognito Identity needs permission from the IAM role policy and the AWS IoT Core policy. You attach the IAM role policy to the pool and the AWS IoT Core policy to the Amazon Cognito Identity through the AWS IoT Core `AttachPolicy` API.

Authenticated and unauthenticated users are different identity types. If you don't attach an AWS IoT policy to the Amazon Cognito Identity, an authenticated user fails authorization in AWS IoT and doesn't have access to AWS IoT resources and actions.

**Note**  
For other AWS IoT Core operations or for unauthenticated identities, AWS IoT Core does not scope down the permissions attached to the Amazon Cognito identity pool role. For both authenticated and unauthenticated identities, this is the most permissive policy that we recommend you attach to the Amazon Cognito pool role.

**HTTP**

To allow unauthenticated Amazon Cognito identities to publish messages over HTTP on a topic specific to the Amazon Cognito Identity, attach the following IAM policy to the Amazon Cognito Identity pool role:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/${cognito-identity.amazonaws.com:sub}"
            ]
        }
    ]
}
```

To allow authenticated users, attach the preceding policy to the Amazon Cognito Identity pool role and to the Amazon Cognito Identity using the AWS IoT Core [AttachPolicy](https://docs.aws.amazon.com//iot/latest/apireference/API_AttachPolicy.html) API.

**Note**  
When authorizing Amazon Cognito identities, AWS IoT Core considers both policies and grants the least privileges specified. An action is allowed only if both policies allow the requested action. If either policy disallows an action, that action is unauthorized.

**MQTT**

To allow unauthenticated Amazon Cognito identities to publish MQTT messages over WebSocket on a topic specific to the Amazon Cognito Identity in your account, attach the following IAM policy to the Amazon Cognito Identity pool role:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${cognito-identity.amazonaws.com:sub}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${cognito-identity.amazonaws.com:sub}"]
        }
    ]
}
```

To allow authenticated users, attach the preceding policy to the Amazon Cognito Identity pool role and to the Amazon Cognito Identity using the AWS IoT Core [AttachPolicy](https://docs.aws.amazon.com//iot/latest/apireference/API_AttachPolicy.html) API.

**Note**  
When authorizing Amazon Cognito identities, AWS IoT Core considers both and grants the least privileges specified. An action is allowed only if both policies allow the requested action. If either policy disallows an action, that action is unauthorized.

# Connect and publish policy examples
<a name="connect-and-pub"></a>

For devices registered as things in the AWS IoT Core registry, the following policy grants permission to connect to AWS IoT Core with a client ID that matches the thing name and restricts the device to publishing on a client-ID or thing name-specific MQTT topic. For a connection to be successful, the thing name must be registered in the AWS IoT Core registry and be authenticated using an identity or principal attached to the thing:

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:topic/${iot:Connection.Thing.ThingName}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
      ]
    }
  ]
}
```

For devices not registered as things in the AWS IoT Core registry, the following policy grants permission to connect to AWS IoT Core with client ID `client1` and restricts the device to publishing on a clientID-specific MQTT topic:

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:topic/${iot:ClientId}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:client/client1"
      ]
    }
  ]
}
```

# Retained message policy examples
<a name="retained-message-policy-examples"></a>

Using [retained messages](mqtt.md#mqtt-retain) requires specific policies. Retained messages are MQTT messages published with the RETAIN flag set and stored by AWS IoT Core. This section presents examples of policies that allow common uses of retained messages.

**Topics**
+ [Policy to connect and publish retained messages](#retained-message-policy-examples-publish)
+ [Policy to connect and publish retained Will messages](#retained-message-policy-examples-publish-lwt)
+ [Policy to list and get retained messages](#retained-message-policy-examples-list-get)

## Policy to connect and publish retained messages
<a name="retained-message-policy-examples-publish"></a>

For a device to publish retained messages, the device must be able to connect, publish (any MQTT message), and publish MQTT retained messages. The following policy grants these permissions for the topic: `device/sample/configuration` to client **device1**. For another example that grants permission to connect, see [Connect and publish policy examples](connect-and-pub.md).

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/device1"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish",
				"iot:RetainPublish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/device/sample/configuration"
			]
		}
	]
}
```

## Policy to connect and publish retained Will messages
<a name="retained-message-policy-examples-publish-lwt"></a>

Clients can configure a message that AWS IoT Core will publish when the client disconnects unexpectedly. MQTT calls such a message a [*Will* message](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/errata01/os/mqtt-v3.1.1-errata01-os-complete.html#_Will_Flag). A client must have an additional condition added to its connect permission to include them. 

The following policy document grants all clients permission to connect and publish a Will message, identified by its topic, `will`, that AWS IoT Core will also retain.

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/device1"
			],
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"LastWill"
					]
				}
			}
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish",
				"iot:RetainPublish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/will"
			]
		}
	]
}
```

## Policy to list and get retained messages
<a name="retained-message-policy-examples-list-get"></a>

Services and applications can access retained messages without the need to support an MQTT client by calling [https://docs.aws.amazon.com//iot/latest/apireference/API_iotdata_ListRetainedMessages.html](https://docs.aws.amazon.com//iot/latest/apireference/API_iotdata_ListRetainedMessages.html) and [https://docs.aws.amazon.com//iot/latest/apireference/API_iotdata_GetRetainedMessage.html](https://docs.aws.amazon.com//iot/latest/apireference/API_iotdata_GetRetainedMessage.html). The services and applications that call these actions must be authorized by using a policy such as the following example.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:ListRetainedMessages"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/device1"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:GetRetainedMessage"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/foo"
            ]
        }
    ]
}
```

# Certificate policy examples
<a name="certificate-policy-examples"></a>

For devices registered in AWS IoT Core registry, the following policy grants permission to connect to AWS IoT Core with a client ID that matches a thing name, and to publish to a topic whose name is equal to the `certificateId` of the certificate the device used to authenticate itself:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:CertificateId}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"]
        }
    ]
}
```

For devices not registered in the AWS IoT Core registry, the following policy grants permission to connect to AWS IoT Core with client IDs, `client1`, `client2`, and `client3` and to publish to a topic whose name is equal to the `certificateId` of the certificate the device used to authenticate itself:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:CertificateId}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1",
                "arn:aws:iot:us-east-1:123456789012:client/client2",
                "arn:aws:iot:us-east-1:123456789012:client/client3"
            ]
        }
    ]
}
```

For devices registered in AWS IoT Core registry, the following policy grants permission to connect to AWS IoT Core with a client ID that matches the thing name, and to publish to a topic whose name is equal to the subject's `CommonName` field of the certificate the device used to authenticate itself:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:Certificate.Subject.CommonName}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"]
        }
    ]
}
```

**Note**  
In this example, the certificate's subject common name is used as the topic identifier, with the assumption that the subject common name is unique for each registered certificate. If the certificates are shared across multiple devices, the subject common name is the same for all the devices that share this certificate, thereby allowing publish privileges to the same topic from multiple devices (not recommended).

For devices not registered in AWS IoT Core registry, the following policy grants permission to connect to AWS IoT Core with client IDs, `client1`, `client2`, and `client3` and to publish to a topic whose name is equal to the subject's `CommonName` field of the certificate the device used to authenticate itself:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:Certificate.Subject.CommonName}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1",
                "arn:aws:iot:us-east-1:123456789012:client/client2",
                "arn:aws:iot:us-east-1:123456789012:client/client3"
            ]
        }
    ]
}
```

**Note**  
In this example, the certificate's subject common name is used as the topic identifier, with the assumption that the subject common name is unique for each registered certificate. If the certificates are shared across multiple devices, the subject common name is the same for all the devices that share this certificate, thereby allowing publish privileges to the same topic from multiple devices (not recommended).

For devices registered in the AWS IoT Core registry, the following policy grants permission to connect to AWS IoT Core with a client ID that matches the thing name, and to publish to a topic whose name is prefixed with `admin/` when the certificate used to authenticate the device has its `Subject.CommonName.2` field set to `Administrator`:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin/*"],
            "Condition": {
                "StringEquals": {
                    "iot:Certificate.Subject.CommonName.2": "Administrator"
            }
        }
        }
    ]
}
```

For devices not registered in AWS IoT Core registry, the following policy grants permission to connect to AWS IoT Core with client IDs `client1`, `client2`, and `client3` and to publish to a topic whose name is prefixed with `admin/` when the certificate used to authenticate the device has its `Subject.CommonName.2` field set to `Administrator`:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1",
                "arn:aws:iot:us-east-1:123456789012:client/client2",
                "arn:aws:iot:us-east-1:123456789012:client/client3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin/*"],
            "Condition": {
                "StringEquals": {
                    "iot:Certificate.Subject.CommonName.2": "Administrator"
            }
        }
        }
    ]
}
```

For devices registered in AWS IoT Core registry, the following policy allows a device to use its thing name to publish on a specific topic that consists of `admin/` followed by the `ThingName` when the certificate used to authenticate the device has any one of its `Subject.CommonName` fields set to `Administrator`:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin/${iot:Connection.Thing.ThingName}"],
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:Certificate.Subject.CommonName.List": "Administrator"
            }
        }
        }
    ]
}
```

For devices not registered in AWS IoT Core registry, the following policy grants permission to connect to AWS IoT Core with client IDs `client1`, `client2`, and `client3` and to publish to the topic `admin` when the certificate used to authenticate the device has any one of its `Subject.CommonName` fields set to `Administrator`:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1",
                "arn:aws:iot:us-east-1:123456789012:client/client2",
                "arn:aws:iot:us-east-1:123456789012:client/client3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin"],
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:Certificate.Subject.CommonName.List": "Administrator"
            }
        }
        }
    ]
}
```

# Thing policy examples
<a name="thing-policy-examples"></a>

The following policy allows a device to connect if the certificate used to authenticate with AWS IoT Core is attached to the thing for which the policy is being evaluated:

****  

```
{  
    "Version":"2012-10-17",		 	 	 
    "Statement":[
        {  
            "Effect":"Allow",
            "Action":["iot:Connect"],
            "Resource":[ "*" ],
            "Condition": {
                "Bool": {
                    "iot:Connection.Thing.IsAttached": ["true"]
            }
        }
        }
    ]
}
```

The following policy allows a device to publish if the certificate is attached to a thing with a particular thing type and if the thing has an attribute of `attributeName` with value `attributeValue`. For more information about thing policy variables, see [Thing policy variables](thing-policy-variables.md).

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": "arn:aws:iot:us-east-1:123456789012:topic/device/stats",
      "Condition": {
        "StringEquals": {
          "iot:Connection.Thing.Attributes[attributeName]": "attributeValue",
          "iot:Connection.Thing.ThingTypeName": "Thing_Type_Name"
        },
        "Bool": {
          "iot:Connection.Thing.IsAttached": "true"
        }
      }
    }
  ]
}
```

The following policy allows a device to publish to a topic that starts with an attribute of the thing. If the device certificate is not associated with the thing, this variable won't be resolved and will result in an access denied error. For more information about thing policy variables, see [Thing policy variables](thing-policy-variables.md).

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": "arn:aws:iot:us-east-1:123456789012:topic/${iot:Connection.Thing.Attributes[attributeName]}/*"
    }
  ]
}
```

# Basic job policy example
<a name="basic-jobs-example"></a>

This sample shows the policy statments required for a job target that's a single device to receive a job request and communicate job execution status with AWS IoT.

Replace *us-west-2:57EXAMPLE833* with your AWS Region, a colon character (:), and your 12-digit AWS account number, and then replace *uniqueThingName* with the name of the thing resource that represents the device in AWS IoT.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:client/uniqueThingName"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topic/test/dc/pubtopic",
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/events/job/*",
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/events/jobExecution/*",
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/things/uniqueThingName/jobs/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Subscribe"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topicfilter/test/dc/subtopic",
                "arn:aws:iot:us-west-2:123456789012:topicfilter/$aws/events/jobExecution/*",
                "arn:aws:iot:us-west-2:123456789012:topicfilter/$aws/things/uniqueThingName/jobs/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topic/test/dc/subtopic",
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/things/uniqueThingName/jobs/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iotjobsdata:DescribeJobExecution",
                "iotjobsdata:GetPendingJobExecutions",
                "iotjobsdata:StartNextPendingJobExecution",
                "iotjobsdata:UpdateJobExecution"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/things/uniqueThingName"
            ]
        }
    ]
}
```

# Authorization with Amazon Cognito identities
<a name="cog-iot-policies"></a>

There are two types of Amazon Cognito identities: unauthenticated and authenticated. If your app supports unauthenticated Amazon Cognito identities, no authentication is performed, so you don't know who the user is. 

**Unauthenticated Identities:** For unauthenticated Amazon Cognito identities, you grant permissions by attaching an IAM role to an unauthenticated identity pool. We recommend that you only grant access to those resources you want available to unknown users.

**Important**  
For unauthenticated Amazon Cognito users connecting to AWS IoT Core, we recommend that you give access to very limited resources in IAM policies.

**Authenticated Identities:** For authenticated Amazon Cognito identities, you need to specify permissions in two places: 
+ Attach an IAM policy to the authenticated Amazon Cognito Identity pool and
+ Attach an AWS IoT Core policy to the Amazon Cognito Identity (authenticated user).

## Policy examples for unauthenticated and authenticated Amazon Cognito users connecting to AWS IoT Core
<a name="cog-iot-policies-auth-unauth-examples"></a>

The following example shows permissions in both the IAM policy and the IoT policy of an Amazon Cognito identity. The authenticated user wants to publish to a device specific topic (e.g. device/DEVICE\$1ID/status).

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/Client_ID"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/device/Device_ID/status"
            ]
        }
    ]
}
```

The following example shows the permissions in an IAM policy of an Amazon Cognito unauthenticated role. The unauthenticated user wants to publish to non-device specific topics that do not require authentication.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/non_device_specific_topic"
            ]
        }
    ]
}
```

## GitHub examples
<a name="cog-iot-policies-github"></a>

The following example web applications on GitHub show how to incorporate policy attachment to authenticated users into the user signup and authentication process.
+ [MQTT publish/subscribe React web application using AWS Amplify and the AWS IoT Device SDK for JavaScript](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-cp)
+ [MQTT publish/subscribe React web application using AWS Amplify, the AWS IoT Device SDK for JavaScript, and a Lambda function](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-lambda)

Amplify is a set of tools and services that helps you build web and mobile applications that integrate with AWS services. For more information about Amplify, see [Amplify Framework Documentation,](https://docs.amplify.aws/).

Both examples perform the following steps.

1. When a user signs up for an account, the application creates an Amazon Cognito user pool and identity.

1. When a user authenticates, the application creates and attaches a policy to the identity. This gives the user publish and subscribe permissions.

1. The user can use the application to publish and subscribe to MQTT topics.

The first example uses the `AttachPolicy` API operation directly inside the authentication operation. The following example demonstrates how to implement this API call inside a React web application that uses Amplify and the AWS IoT Device SDK for JavaScript.

```
function attachPolicy(id, policyName) {
    var Iot = new AWS.Iot({region: AWSConfiguration.region, apiVersion: AWSConfiguration.apiVersion, endpoint: AWSConfiguration.endpoint});
    var params = {policyName: policyName, target: id};

    console.log("Attach IoT Policy: " + policyName + " with cognito identity id: " + id);
    Iot.attachPolicy(params, function(err, data) {
         if (err) {
               if (err.code !== 'ResourceAlreadyExistsException') {
                  console.log(err);
               }
          }
         else  {
            console.log("Successfully attached policy with the identity", data);
         }
     });
}
```

This code appears in the [AuthDisplay.js](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-cp/blob/d1c307b36357be934db9dda020140fa337709cd9/src/AuthDisplay.js#L45) file.

The second example implements the `AttachPolicy` API operation in a Lambda function. The following example shows how the Lambda uses this API call.

```
iot.attachPolicy(params, function(err, data) {
     if (err) {
           if (err.code !== 'ResourceAlreadyExistsException') {
              console.log(err);
              res.json({error: err, url: req.url, body: req.body});
           }
      }
     else  {
        console.log(data);
        res.json({success: 'Create and attach policy call succeed!', url: req.url, body: req.body});
     }
 });
```

This code appears inside the `iot.GetPolicy` function in the [app.js](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-lambda/blob/e493039581d2aff0faa3949086deead20a2c5385/amplify/backend/function/amplifyiotlambda/src/app.js#L50) file.

**Note**  
When you call the function with AWS credentials that you obtain through Amazon Cognito Identity pools, the context object in your Lambda function contains a value for `context.cognito_identity_id`. For more information, see the following.   
[AWS Lambda context object in Node.js](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html)
[AWS Lambda context object in Python](https://docs.aws.amazon.com/lambda/latest/dg/python-context.html)
[AWS Lambda context object in Ruby](https://docs.aws.amazon.com/lambda/latest/dg/ruby-context.html)
[AWS Lambda context object in Java](https://docs.aws.amazon.com/lambda/latest/dg/java-context.html)
[AWS Lambda context object in Go](https://docs.aws.amazon.com/lambda/latest/dg/golang-context.html)
[AWS Lambda context object in C\$1](https://docs.aws.amazon.com/lambda/latest/dg/csharp-context.html)
[AWS Lambda context object in PowerShell](https://docs.aws.amazon.com/lambda/latest/dg/powershell-context.html)

# Authorizing direct calls to AWS services using AWS IoT Core credential provider
<a name="authorizing-direct-aws"></a>

Devices can use X.509 certificates to connect to AWS IoT Core using TLS mutual authentication protocols. Other AWS services do not support certificate-based authentication, but they can be called using AWS credentials in [AWS Signature Version 4 format](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). The [Signature Version 4 algorithm](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html) normally requires the caller to have an access key ID and a secret access key. AWS IoT Core has a credentials provider that allows you to use the built-in [X.509 certificate](x509-client-certs.html) as the unique device identity to authenticate AWS requests. This eliminates the need to store an access key ID and a secret access key on your device.

The credentials provider authenticates a caller using an X.509 certificate and issues a temporary, limited-privilege security token. The token can be used to sign and authenticate any AWS request. This way of authenticating your AWS requests requires you to create and configure an [AWS Identity and Access Management (IAM) role](https://docs.aws.amazon.com/service-authorization/latest/reference/id_roles.html) and attach appropriate IAM policies to the role so that the credentials provider can assume the role on your behalf. For more information about AWS IoT Core and IAM, see [Identity and access management for AWS IoT](security-iam.md).

 AWS IoT requires devices to send the [Server Name Indication (SNI) extension](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) to the Transport Layer Security (TLS) protocol and provide the complete endpoint address in the `host_name` field. The `host_name` field must contain the endpoint you are calling, and it must be:
+ The `endpointAddress` returned by `aws iot [describe-endpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-endpoint.html) --endpoint-type iot:CredentialProvider`.

Connections attempted by devices without the correct `host_name` value will fail.

The following diagram illustrates the credentials provider workflow.

![\[AWS IoT Core credentials provider workflow.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/credentials-provider-diagram.png)


1. The AWS IoT Core device makes an HTTPS request to the credentials provider for a security token. The request includes the device X.509 certificate for authentication.

1. The credentials provider forwards the request to the AWS IoT Core authentication and authorization module to validate the certificate and verify that the device has permission to request the security token.

1. If the certificate is valid and has permission to request a security token, the AWS IoT Core authentication and authorization module returns success. Otherwise, it sends an exception to the device.

1. After successfully validating the certificate, the credentials provider invokes the [AWS Security Token Service (AWS STS)](https://docs.aws.amazon.com/STS/latest/APIReference/Welcome.html) to assume the IAM role that you created for it.

1. AWS STS returns a temporary, limited-privilege security token to the credentials provider.

1. The credentials provider returns the security token to the device.

1. The device uses the security token to sign an AWS request with AWS Signature Version 4.

1. The requested service invokes IAM to validate the signature and authorize the request against access policies attached to the IAM role that you created for the credentials provider.

1. If IAM validates the signature successfully and authorizes the request, the request is successful. Otherwise, IAM sends an exception.

The following section describes how to use a certificate to get a security token. It is written with the assumption that you have already [registered a device](register-device.html) and [created and activated your own certificate](device-certs-your-own.html) for it.

## How to use a certificate to get a security token
<a name="authorizing-direct-aws.walkthrough"></a>

1. Configure the IAM role that the credentials provider assumes on behalf of your device. Attach the following trust policy to the role.   
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Principal": {"Service": "credentials.iot.amazonaws.com"},
           "Action": "sts:AssumeRole"
       }
   }
   ```

   For each AWS service that you want to call, attach an access policy to the role. The credentials provider supports the following policy variables:
   + `credentials-iot:ThingName`
   + `credentials-iot:ThingTypeName`
   + `credentials-iot:AwsCertificateId`

   When the device provides the thing name in its request to an AWS service, the credentials provider adds `credentials-iot:ThingName` and `credentials-iot:ThingTypeName` as context variables to the security token. The credentials provider provides `credentials-iot:AwsCertificateId` as a context variable even if the device doesn't provide the thing name in the request. You pass the thing name as the value of the `x-amzn-iot-thingname` HTTP request header.

   These three variables work for IAM policies only, not AWS IoT Core policies.

1. Make sure that the user who performs the next step (creating a role alias) has permission to pass the newly created role to AWS IoT Core. The following policy gives both `iam:GetRole` and `iam:PassRole` permissions to an AWS user. The `iam:GetRole` permission allows the user to get information about the role that you've just created. The `iam:PassRole` permission allows the user to pass the role to another AWS service.  
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Action": [
               "iam:GetRole",
               "iam:PassRole"
           ],
           "Resource": "arn:aws:iam::123456789012:role/your role name"
       }
   }
   ```

1. Create an AWS IoT Core role alias. The device that is going to make direct calls to AWS services must know which role ARN to use when connecting to AWS IoT Core. Hard-coding the role ARN is not a good solution because it requires you to update the device whenever the role ARN changes. A better solution is to use the `CreateRoleAlias` API to create a role alias that points to the role ARN. If the role ARN changes, you simply update the role alias. No change is required on the device. This API takes the following parameters:  
`roleAlias`  
Required. An arbitrary string that identifies the role alias. It serves as the primary key in the role alias data model. It contains 1-128 characters and must include only alphanumeric characters and the =, @, and - symbols. Uppercase and lowercase alphabetic characters are allowed. Role alias names are case sensitive.  
`roleArn`  
Required. The ARN of the role to which the role alias refers.  
`credentialDurationSeconds`  
Optional. How long (in seconds) the credential is valid. The minimum value is 900 seconds (15 minutes). The maximum value is 43,200 seconds (12 hours). The default value is 3,600 seconds (1 hour).   
The AWS IoT Core Credential Provider can issue a credential with a maximum lifetime is 43,200 seconds (12 hours). Having the credential be valid for up to 12 hours can help reduce the number of calls to the credential provider by caching the credential longer.  
The `credentialDurationSeconds` value must be less than or equal to the maximum session duration of the IAM role that the role alias references. For more information, see [ Modifying a role maximum session duration (AWS API)](https://docs.aws.amazon.com//IAM/latest/UserGuide/roles-managingrole-editing-api.html#roles-modify_max-session-duration-api) from the AWS Identity and Access Management User Guide.

   For more information about this API, see [CreateRoleAlias](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateRoleAlias.html). 

1. Attach a policy to the device certificate. The policy attached to the device certificate must grant the device permission to assume the role. You do this by granting permission for the `iot:AssumeRoleWithCertificate` action to the role alias, as in the following example.  
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iot:AssumeRoleWithCertificate",
               "Resource": "arn:aws:iot:us-east-1:123456789012:rolealias/your role alias"
           }
       ]
   }
   ```

1. Make an HTTPS request to the credentials provider to get a security token. Supply the following information:
   + *Certificate*: Because this is an HTTP request over TLS mutual authentication, you must provide the certificate and the private key to your client while making the request. Use the same certificate and private key you used when you registered your certificate with AWS IoT Core.

     To make sure your device is communicating with AWS IoT Core (and not a service impersonating it), see [Server Authentication](x509-client-certs.html#server-authentication), follow the links to download the appropriate CA certificates, and then copy them to your device.
   + *RoleAlias*: The name of the role alias that you created for the credentials provider. Role alias names are case sensitive and must match the role alias created in AWS IoT Core.
   + *ThingName*: The thing name that you created when you registered your AWS IoT Core thing. This is passed as the value of the `x-amzn-iot-thingname` HTTP header. This value is required only if you are using thing attributes as policy variables in AWS IoT Core or IAM policies.
**Note**  
The *ThingName* that you provide in `x-amzn-iot-thingname` must match the name of the AWS IoT Thing resource assigned to a cert. If it doesn't match, a 403 error is returned.

   Run the following command in the AWS CLI to obtain the credentials provider endpoint for your AWS account. For more information about this API, see [DescribeEndpoint](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeEndpoint.html). For FIPS-enabled endpoints, see [AWS IoT Core - credential provider endpoints](iot-connect-fips.md#iot-connect-fips-credential).

   ```
   aws iot describe-endpoint --endpoint-type iot:CredentialProvider
   ```

   The following JSON object is sample output of the **describe-endpoint** command. It contains the `endpointAddress` that you use to request a security token.

   ```
   {
       "endpointAddress": "your_aws_account_specific_prefix.credentials.iot.your region.amazonaws.com"
   }
   ```

   Use the endpoint to make an HTTPS request to the credentials provider to return a security token. The following example command uses `curl`, but you can use any HTTP client.
**Note**  
The *roleAlias* name is case sensitive and must match the role alias created in AWS IoT.

   ```
   curl --cert your certificate --key your private key -H "x-amzn-iot-thingname: your thing name" --cacert AmazonRootCA1.pem https://your endpoint /role-aliases/your role alias/credentials
   ```

   This command returns a security token object that contains an `accessKeyId`, a `secretAccessKey`, a `sessionToken`, and an expiration. The following JSON object is sample output of the `curl` command.

   ```
       {"credentials":{"accessKeyId":"access key","secretAccessKey":"secret access key","sessionToken":"session token","expiration":"2018-01-18T09:18:06Z"}}
   ```

   You can then use the `accessKeyId`, `secretAccessKey`, and `sessionToken` values to sign requests to AWS services. For an end-to-end demonstration, see [How to Eliminate the Need for Hard-Coded AWS Credentials in Devices by Using the AWS IoT Credential Provider](https://aws.amazon.com/blogs/security/how-to-eliminate-the-need-for-hardcoded-aws-credentials-in-devices-by-using-the-aws-iot-credentials-provider/) blog post on the *AWS Security Blog*.

# Cross account access with IAM
<a name="cross-account-access"></a>

AWS IoT Core allows you to enable a principal to publish or subscribe to a topic that is defined in an AWS account not owned by the principal. You configure cross account access by creating an IAM policy and IAM role and then attaching the policy to the role.

First, create a customer managed IAM policy as described in [Creating IAM Policies](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies_create.html), just like you would for other users and certificates in your AWS account. 

For devices registered in AWS IoT Core registry, the following policy grants permission to devices connect to AWS IoT Core using a client ID that matches the device's thing name and to publish to the `my/topic/thing-name ` where *thing-name* is the device's thing name:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/my/topic/${iot:Connection.Thing.ThingName}"
            ]
        }
    ]
}
```

For devices not registered in AWS IoT Core registry, the following policy grants permission to a device to use the thing name `client1` registered in your account's (123456789012) AWS IoT Core registry to connect to AWS IoT Core and to publish to a client ID-specific topic whose name is prefixed with `my/topic/`:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/my/topic/${iot:ClientId}"
            ]
        }
    ]
}
```

Next, follow the steps in [Creating a role to delegate permissions to an IAM user](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-user.html). Enter the account ID of the AWS account with which you want to share access. Then, in the final step, attach the policy you just created to the role. If, at a later time, you need to modify the AWS account ID to which you are granting access, you can use the following trust policy format to do so: 

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": { 
                "AWS": "arn:aws:iam::567890123456:user/MyUser"
        },
            "Action": "sts:AssumeRole"
        }
    ]
}
```

# Data protection in AWS IoT Core
<a name="data-protection"></a>

The AWS [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) applies to data protection in AWS IoT Core. As described in this model, AWS is responsible for protecting the global infrastructure that runs all of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. You are also responsible for the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the [Data Privacy FAQ](https://aws.amazon.com/compliance/data-privacy-faq/). For information about data protection in Europe, see the [AWS Shared Responsibility Model and GDPR](https://aws.amazon.com/blogs/security/the-aws-shared-responsibility-model-and-gdpr/) blog post on the *AWS Security Blog*.

For data protection purposes, we recommend that you protect AWS account credentials and set up individual users with AWS IAM Identity Center or AWS Identity and Access Management (IAM). That way, each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways:
+ Use multi-factor authentication (MFA) with each account.
+ Use SSL/TLS to communicate with AWS resources. We require TLS 1.2 and recommend TLS 1.3.
+ Set up API and user activity logging with AWS CloudTrail. For information about using CloudTrail trails to capture AWS activities, see [Working with CloudTrail trails](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-trails.html) in the *AWS CloudTrail User Guide*.
+ Use AWS encryption solutions, along with all default security controls within AWS services.
+ Use advanced managed security services such as Amazon Macie, which assists in discovering and securing sensitive data that is stored in Amazon S3.
+ If you require FIPS 140-3 validated cryptographic modules when accessing AWS through a command line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints, see [Federal Information Processing Standard (FIPS) 140-3](https://aws.amazon.com/compliance/fips/).

We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into tags or free-form text fields such as a **Name** field. This includes when you work with AWS IoT or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into tags or free-form text fields used for names may be used for billing or diagnostic logs. If you provide a URL to an external server, we strongly recommend that you do not include credentials information in the URL to validate your request to that server.

For more information about data protection, see the [AWS Shared Responsibility Model and GDPR](https://aws.amazon.com/blogs/security/the-aws-shared-responsibility-model-and-gdpr/) blog post on the *AWS Security Blog*.

AWS IoT devices gather data, perform some manipulation on that data, and then send that data to another web service. You might choose to store some data on your device for a short period of time. You're responsible for providing any data protection on that data at rest. When your device sends data to AWS IoT, it does so over a TLS connection as discussed later in this section. AWS IoT devices can send data to any AWS service. For more information about each service's data security, see the documentation for that service. AWS IoT can be configured to write logs to CloudWatch Logs and log AWS IoT API calls to AWS CloudTrail. For more information about data security for these services, see [ Authentication and Access Control for Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/auth-and-access-control-cw.html) and [Encrypting CloudTrail Log Files with AWS KMS managed keys](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/encrypting-cloudtrail-log-files-with-aws-kms.html).

## Data encryption in AWS IoT
<a name="data-protection-encrypt"></a>

By default, all AWS IoT data in transit and at rest is encrypted. [Data in transit is encrypted using TLS](transport-security.md), and data at rest is encrypted using AWS owned keys. AWS IoT supports customer managed AWS KMS keys (KMS keys) from AWS Key Management Service (AWS KMS). However, Device Advisor and AWS IoT Wireless use only an AWS owned key to encrypt customer data.

 

# Transport security in AWS IoT Core
<a name="transport-security"></a>

TLS (Transport Layer Security) is a cryptographic protocol that is designed for secure communication over a computer network. The AWS IoT Core Device Gateway requires customers to encrypt all communication while in-transit by using TLS for connections from devices to the Gateway. TLS is used to achieve confidentiality of the application protocols (MQTT, HTTP, and WebSocket) supported by AWS IoT Core. TLS support is available in a number of programming languages and operating systems. Data within AWS is encrypted by the specific AWS service. For more information about data encryption on other AWS services, see the security documentation for that service.

**Topics**
+ [TLS protocols](#tls-ssl-policy)
+ [Security policies](#tls-policy-table)
+ [Important notes for transport security in AWS IoT Core](#tls-ssl-core)
+ [Transport security for LoRaWAN wireless devices](#tls-lorawan)

## TLS protocols
<a name="tls-ssl-policy"></a>

AWS IoT Core supports the following versions of the TLS protocol:
+ TLS 1.3 
+ TLS 1.2

With AWS IoT Core, you can configure the TLS settings (for [TLS 1.2](https://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_1.2) and [TLS 1.3](https://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_1.3)) in domain configurations. For more information, see [Configuring TLS settings in domain configurations](iot-endpoints-tls-config.md).

## Security policies
<a name="tls-policy-table"></a>

A security policy is a combination of TLS protocols and their ciphers that determine which protocols and ciphers are supported during TLS negotiations between a client and a server. You can configure your devices to use predefined security policies based on your needs. Note that AWS IoT Core doesn't support custom security policies.

You can choose one of the predefined security policies for your devices when connecting them to AWS IoT Core. The names of the most recent predefined security policies in AWS IoT Core include version information based on the year and month that they were released. The default predefined security policy is `IoTSecurityPolicy_TLS13_1_2_2022_10`. To specify a security policy, you can use the AWS IoT console or the AWS CLI. For more information, see [Configuring TLS settings in domain configurations](iot-endpoints-tls-config.md).

The following table describes the most recent predefined security policies that AWS IoT Core supports. The `IotSecurityPolicy_` has been removed from policy names in the heading row so that they fit.


| **Security policy** | TLS13\$11\$13\$12022\$110 | TLS13\$11\$12\$12022\$110 | TLS12\$11\$12\$12022\$110 | TLS12\$11\$10\$12016\$101\$1 | TLS12\$11\$10\$12015\$101\$1 | 
| --- | --- | --- | --- | --- | --- | 
| TCP Port |  443/8443/8883  |  443/8443/8883  |  443/8443/8883  | 443 | 8443/8883 | 443 | 8443/8883 | 
| TLS Protocols | 
| TLS 1.2 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| TLS 1.3 | ✓ | ✓ |  |  |  |  |  | 
| TLS Ciphers | 
| TLS\$1AES\$1128\$1GCM\$1SHA256 | ✓ | ✓ |  |  |  |  |  | 
| TLS\$1AES\$1256\$1GCM\$1SHA384 | ✓ | ✓ |  |  |  |  |  | 
| TLS\$1CHACHA20\$1POLY1305\$1SHA256 | ✓ | ✓ |  |  |  |  |  | 
| ECDHE-RSA-AES128-GCM-SHA256 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-RSA-AES128-SHA256 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-RSA-AES128-SHA |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-RSA-AES256-GCM-SHA384 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-RSA-AES256-SHA384 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-RSA-AES256-SHA |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| AES128-GCM-SHA256 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| AES128-SHA256 |  | ✓ | ✓ | ✓ |  | ✓ | ✓ | 
| AES128-SHA |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| AES256-GCM-SHA384 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| AES256-SHA256 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| AES256-SHA |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| DHE-RSA-AES256-SHA |  |  |  |  |  | ✓ | ✓ | 
| ECDHE-ECDSA-AES128-GCM-SHA256 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-ECDSA-AES128-SHA256 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-ECDSA-AES128-SHA |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-ECDSA-AES256-GCM-SHA384 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-ECDSA-AES256-SHA384 |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 
| ECDHE-ECDSA-AES256-SHA |  | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 

**Note**  
`TLS12_1_0_2016_01` is only available in the following AWS Regions: ap-east-1, ap-northeast-2, ap-south-1, ap-southeast-2, ca-central-1, cn-north-1, cn-northwest-1, eu-north-1, eu-west-2, eu-west-3, me-south-1, sa-east-1, us-east-2, us-gov-west-1, us-gov-west-2, us-west-1.  
`TLS12_1_0_2015_01` is only available in the following AWS Regions: ap-northeast-1, ap-southeast-1, eu-central-1, eu-west-1, us-east-1, us-west-2.

## Important notes for transport security in AWS IoT Core
<a name="tls-ssl-core"></a>

For devices that connect to AWS IoT Core using [MQTT](https://docs.aws.amazon.com//iot/latest/developerguide/mqtt.html), TLS encrypts the connection between the devices and the broker, and AWS IoT Core uses TLS client authentication to identify devices. For more information, see [Client authentication](https://docs.aws.amazon.com//iot/latest/developerguide/client-authentication.html). For devices that connect to AWS IoT Core using [HTTP](https://docs.aws.amazon.com//iot/latest/developerguide/http.html), TLS encrypts the connection between the devices and the broker, and authentication is delegated to AWS Signature Version 4. For more information, see [Signing requests with Signature Version 4](https://docs.aws.amazon.com//general/latest/gr/create-signed-request.html) in the *AWS General Reference*.

When you connect devices to AWS IoT Core, sending the [Server Name Indication (SNI) extension](https://tools.ietf.org/html/rfc3546#section-3.1) is not required but highly recommended. To use features such as [multi-account registration](https://docs.aws.amazon.com//iot/latest/developerguide/x509-client-certs.html#multiple-account-cert), [custom domains](https://docs.aws.amazon.com//iot/latest/developerguide/iot-custom-endpoints-configurable-custom.html), [VPC endpoints](https://docs.aws.amazon.com//iot/latest/developerguide/IoTCore-VPC.html), and [configured TLS policies](https://docs.aws.amazon.com//iot/latest/developerguide/iot-endpoints-tls-config.html), you must use the SNI extension and provide the complete endpoint address in the `host_name` field. The `host_name` field must contain the endpoint you are calling. That endpoint must be one of the following:
+ The `endpointAddress` returned by `aws iot [describe-endpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-endpoint.html) --endpoint-type iot:Data-ATS`
+ The `domainName` returned by `aws iot [describe-domain-configuration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-domain-configuration.html) –-domain-configuration-name "domain_configuration_name"`

Connections attempted by devices with the incorrect or invalid `host_name` value will fail. AWS IoT Core will log failures to CloudWatch for the authentication type of [Custom Authentication](https://docs.aws.amazon.com//iot/latest/developerguide/custom-authentication.html).

AWS IoT Core doesn't support the [SessionTicket TLS extension](https://www.ietf.org/rfc/rfc5077.txt).

## Transport security for LoRaWAN wireless devices
<a name="tls-lorawan"></a>

LoRaWAN devices follow the security practices described in [LoRaWAN ™ SECURITY: A White Paper Prepared for the LoRa Alliance™ by Gemalto, Actility, and Semtech](https://lora-alliance.org/sites/default/files/2019-05/lorawan_security_whitepaper.pdf). 

For more information about transport security with LoRaWAN devices, see [LoRaWAN data and transport security](https://docs.aws.amazon.com/iot-wireless/latest/developerguide/iot-lorawan-security.html).

# Data encryption in AWS IoT
<a name="data-encryption"></a>

Data protection refers to protecting data while in-transit (as it travels to and from AWS IoT Core) and at rest (while it is stored on devices or by other AWS services). All data sent to AWS IoT Core is sent over an TLS connection using MQTT, HTTPS, and WebSocket protocols, making it secure by default while in transit. AWS IoT Core collects data from devices and then sends it to other AWS services for further processing. For more information about data encryption on other AWS services, see the security documentation for that service. For more information, see [Data encryption at rest](encryption-at-rest.md).

FreeRTOS provides a PKCS\$111 library that abstracts key storage, accessing cryptographic objects and managing sessions. It is your responsibility to use this library to encrypt data at rest on your devices. For more information, see [ FreeRTOS Public Key Cryptography Standard (PKCS) \$111 Library](https://docs.aws.amazon.com/freertos/latest/userguide/security-pkcs.html).

# Data encryption at rest in AWS IoT Core
<a name="encryption-at-rest"></a>

By default, all AWS IoT Core data at rest is encrypted using AWS owned keys. AWS IoT Core also supports symmetric customer managed keys from AWS Key Management Service (AWS KMS). With customer managed keys, you can create, own, and manage the AWS KMS keys in your AWS account. AWS IoT Core will use your KMS keys to encrypt your data at rest. You have full control over these KMS keys, including creating and maintaining their key policies. You can also configure IAM policies for the roles that access AWS KMS to control permissions for these keys.

## AWS owned keys
<a name="aws-owned-keys"></a>

AWS owned keys are a collection of KMS keys that an AWS service owns and manages for use in multiple AWS accounts. AWS services can use AWS owned keys to protect your data. By default, AWS IoT Core encrypts data at rest using AWS owned keys. These keys are managed by the service. You can't view, manage, or use AWS owned keys. However, you don't need to take any actions to protect these keys.

For more information about AWS owned keys, see [AWS owned keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#aws-owned-key) in the *AWS Key Management Service Developer Guide*.

## Customer managed keys
<a name="customer-managed-keys"></a>

Customer managed keys are KMS keys in your AWS account that you create, own, and manage. You have full control over these AWS KMS keys, including creating and maintaining their key policies. You can also configure IAM policies for the roles that access AWS KMS to control permissions for these keys. You can configure AWS IoT Core to use customer managed KMS keys to encrypt your data.

For more information about customer managed keys, see [Customer managed keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#customer-cmk) in the *AWS Key Management Service Developer Guide*.

To opt in to customer managed keys in AWS IoT Core, follow these steps:

**Topics**
+ [Step 1: Create a customer managed key](#encryption-at-rest-cmk-create)
+ [Step 2: Create an IAM role to grant AWS IoT Core permissions to use the KMS key](#create-an-iam-role)
+ [Step 3: Opt in to customer managed keys in AWS IoT Core](#opt-in-customer-managed-keys)
+ [Step 4: Additional permissions required for AWS IoT Core control plane operations](#cmk-control-plane-permissions)
+ [Step 5: Managing keys](#understanding-key-health)
+ [Step 6: Monitoring key health](#health-status-monitoring)

### Step 1: Create a customer managed key
<a name="encryption-at-rest-cmk-create"></a>

You can create a symmetric customer managed key by using the AWS KMS console or the AWS KMS CLI commands. The `keySpec` must be `SYMMETRIC_DEFAULT` and the `keyUsage` must be `ENCRYPT_DECRYPT`.

**Note**  
AWS IoT Core only supports AWS KMS keys with `SYMMETRIC_DEFAULT` key spec and `ENCRYPT_DECRYPT` key usage for customer managed keys.

The following is an example AWS CLI command to create a KMS key which can be used with AWS IoT Core for customer managed keys.

```
aws kms create-key --key-spec SYMMETRIC_DEFAULT --key-usage ENCRYPT_DECRYPT --region us-west-2
```

The following is an example output of the command.

```
{
    "KeyMetadata": {
        "AWSAccountId": "111122223333",
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "Arn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "CreationDate": "2024-09-19T11:45:23.982000-07:00",
        "Enabled": true,
        "Description": "",
        "KeyUsage": "ENCRYPT_DECRYPT",
        "KeyState": "Enabled",
        "Origin": "AWS_KMS",
        "KeyManager": "CUSTOMER",
        "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",
        "KeySpec": "SYMMETRIC_DEFAULT",
        "EncryptionAlgorithms": [
            "SYMMETRIC_DEFAULT"
        ],
        "MultiRegion": false
    }
}
```

For more information, see [Creating a symmetric customer managed key](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html#create-symmetric-cmk) in the *AWS Key Management Service Developer Guide*.

#### Key policy
<a name="key-policy"></a>

When creating a customer managed key, you can specify a key policy. Key policies control access to your customer managed key. Every customer managed key must have exactly one key policy, which contains statements that determine who can use the key and how they can use it. For more information, see [Key policies](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html) in the *AWS Key Management Service Developer Guide*.

AWS IoT Core uses an IAM role in your account to access your customer managed key. If you're using a custom key policy, make sure the IAM role created on this key has the following permissions:
+ `kms:DescribeKey`
+ `kms:Decrypt`
+ `kms:Encrypt`
+ `kms:GenerateDataKeyWithoutPlaintext`
+ `kms:ReEncryptTo`
+ `kms:ReEncryptFrom`

### Step 2: Create an IAM role to grant AWS IoT Core permissions to use the KMS key
<a name="create-an-iam-role"></a>

For AWS IoT Core to use the KMS key you created to encrypt your data at rest, you also need to create an IAM role in your account, which AWS IoT Core can assume to access the KMS key.

The role must have the following trust policy to allow AWS IoT Core to assume the role.

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Principal": {
            "Service": "iot.amazonaws.com"
        },
        "Action": "sts:AssumeRole",
        "Condition": {
            "StringEquals": {
                "aws:SourceAccount": "111122223333"
            },
            "ArnLike": {
                "aws:SourceArn": "arn:aws:iot:us-west-2:111122223333:*"
            }
        }
    }
}
```

Ensure the IAM policies attached to the IAM role have the following permissions on the KMS key:
+ `kms:DescribeKey`
+ `kms:Decrypt`
+ `kms:Encrypt`
+ `kms:GenerateDataKeyWithoutPlaintext`
+ `kms:ReEncryptTo`
+ `kms:ReEncryptFrom`

The following is an example IAM policy with the required permissions for customer managed keys.

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowIoTToAccessKMSResource",
            "Effect": "Allow",
            "Action": [
                "kms:DescribeKey",
                "kms:Decrypt",
                "kms:Encrypt",
                "kms:ReEncryptTo",
                "kms:ReEncryptFrom",
                "kms:GenerateDataKeyWithoutPlaintext"
            ],
            "Resource": [
                "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
            ],
            "Condition": {
                "StringEquals": {
                    "kms:EncryptionContext:aws-crypto-ec:vendor": "iot.amazonaws.com"
                }
            }
        }
    ]
}
```

For more information, see [Create a role to delegate permissions to an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html) in the *AWS Identity and Access Management User Guide*.

### Step 3: Opt in to customer managed keys in AWS IoT Core
<a name="opt-in-customer-managed-keys"></a>

After you complete all the previous steps, run the `update-encryption-configuration` CLI command to opt in using customer managed keys in AWS IoT Core. When you opt in to customer managed keys, all AWS IoT Core resources in your AWS account will be encrypted using the specified AWS KMS key.

1. To opt in to customer managed keys in AWS IoT Core using AWS CLI, run the `update-encryption-configuration` CLI command.

   ```
   aws iot update-encryption-configuration --encryption-type "CUSTOMER_MANAGED_KMS_KEY" \
   --kms-access-role-arn "arn:aws:iam::111122223333:role/myrole" \
   --kms-key-arn "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" --region us-west-2
   ```

1. To verify customer managed keys in AWS IoT Core using AWS CLI, run the `describe-encryption-configuration` CLI command:

   ```
   aws iot describe-encryption-configuration --region us-west-2
   ```

   If you have enabled customer managed keys in AWS IoT Core, the output can look like the following:

   ```
   {
       "encryptionType": "CUSTOMER_MANAGED_KMS_KEY",
       "kmsKeyArn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
       "kmsAccessRoleArn": "arn:aws:iam::111122223333:role/myrole",
       "configurationDetails": {
           "configurationStatus": "HEALTHY"
       },
       "lastModifiedDate": "2024-09-26T22:01:02.365000-07:00"
   }
   ```

   The `lastModifiedDate` field indicates the date when the encryption configuration was last updated.

   If you haven't enabled customer managed keys, the output can look like the following:

   ```
   {
       "encryptionType": "AWS_OWNED_KMS_KEY",
       "lastModifiedDate": "2024-09-26T22:01:02.365000-07:00"
   }
   ```

### Step 4: Additional permissions required for AWS IoT Core control plane operations
<a name="cmk-control-plane-permissions"></a>

After you opt in to customer managed keys, all the AWS IoT Core resources belonging to your AWS account are encrypted with the provided KMS key. All control plane operations now require the caller to have `kms:Decrypt` permissions on the KMS key in addition to the permissions required for the specific operation on the AWS IoT Core resource. If the caller does not have `kms:Decrypt` permission and they make an API call that requires encryption or decryption of data (for example, `GetPolicy`), they will receive an `UnauthorizedException`.

For example, when you call `GetPolicy`, you need both `iot:GetPolicy` and `kms:Decrypt` permissions on your customer managed KMS key for the API call to succeed.

**Note**  
When updating IAM users or roles to grant AWS KMS permissions on the key used for your encryption configuration, ensure the KMS key policy also grants the required permissions to the respective IAM users or roles.

#### AWS KMS permissions for `UpdateEncryptionConfiguration`
<a name="kms-permissions-update-encryption-configuration"></a>

The `UpdateEncryptionConfiguration` API call needs the following AWS KMS permissions on the KMS key to be able to opt in to customer managed keys or to modify the key configuration:
+ `kms:DescribeKey`
+ `kms:Decrypt`
+ `kms:Encrypt`
+ `kms:GenerateDataKeyWithoutPlaintext`
+ `kms:ReEncryptTo`
+ `kms:ReEncryptFrom`

#### AWS KMS permissions for all other control plane APIs
<a name="kms-permissions-control-plane-apis"></a>

Most control plane APIs require `kms:Decrypt` permissions when customer managed keys are enabled. However, certain APIs do not require these additional permissions:

APIs that do not require AWS KMS permissions  
The `List*` and `Delete*` APIs do not fall into this bucket. Customers can always invoke any `List*` or `Delete*` control plane API and those API calls would succeed even if the caller does not have `kms:Decrypt` permission. These API calls will succeed even if your customer managed key is unhealthy as `List*` and `Delete*` APIs do not do any decryption.  
+ **List\$1 APIs** – All listing operations (for example, `ListThings`, `ListPolicies`, `ListCertificates`)
+ **Delete\$1 APIs** – All deletion operations (for example, `DeleteThing`, `DeletePolicy`, `DeleteCertificate`)

### Step 5: Managing keys
<a name="understanding-key-health"></a>

AWS IoT Core runs periodic checks on your customer managed key configuration to ensure encrypt and decrypt operations are not impacted. These health checks run once every minute and verify AWS IoT Core's ability to access and use both the AWS KMS key and the associated IAM role for encrypt and decrypt operations.

HEALTHY  
AWS IoT Core can successfully access the AWS KMS key through the specified IAM role and perform encryption/decryption operations. All components function correctly.

UNHEALTHY  
AWS IoT Core can't access or use the AWS KMS key. This prevents new encryption operations and may impact service functionality. The `errorCode` field indicates whether the issue is with the key or the IAM role.

#### Customer actions that can impact key health
<a name="customer-actions-affecting-health"></a>

Several customer actions can cause the key health status to change from `HEALTHY` to `UNHEALTHY`:

Key-related actions  
+ **Deleting an AWS KMS key** – When you schedule a key deletion, it's in a `Pending deletion` status and can't be used
+ **Disabling an AWS KMS key** – When you disable a KMS key, it can no longer be used for encrypt / decrypt operations
+ **Scheduling key for deletion** – Key becomes unusable when deletion completes
+ **Modifying key policy** – Removing necessary permissions for AWS IoT Core access
+ **Changing key usage permissions** – Restricting required AWS KMS actions

IAM role-related actions  
+ **Deleting the IAM role** – AWS IoT Core can't assume the role to access the key
+ **Modifying role permissions** – Removing required AWS KMS permissions from the role policy
+ **Changing trust policy** – Preventing AWS IoT Core service from assuming the role
+ **Adding restrictive conditions** – Conditions that prevent AWS IoT Core from using the role

Account-level actions  
+ **Cross-account key access changes** – Modifying permissions for keys in different accounts
+ **Service Control Policies (SCPs)** – Organization-level policies that restrict AWS KMS access
+ **Account-level IAM policies** – Policies that override or conflict with key access

**Important**  
Any changes to AWS KMS keys, IAM roles, or policies used by AWS IoT Core should be tested in development environments first. Monitor the key health status closely after making any changes to ensure AWS IoT Core functionality is not impacted.

#### Updating encryption configuration
<a name="key-transition"></a>

Update your encryption configuration in AWS IoT Core to change from one customer managed key to another, or between AWS owned keys and customer managed keys.

To change the configuration to a different customer managed key:

1. Create a new customer managed key following the steps in [Step 1: Create a customer managed key](#encryption-at-rest-cmk-create).

1. Update your IAM role policy to include permissions for both the old and new keys during the update period.

1. Update your encryption configuration to use the new key:

   ```
   aws iot update-encryption-configuration --encryption-type "CUSTOMER_MANAGED_KMS_KEY" \
   --kms-access-role-arn "arn:aws:iam::111122223333:role/myrole" \
   --kms-key-arn "arn:aws:kms:us-west-2:111122223333:key/new-key-id"
   ```

To change the configuration from customer managed keys back to AWS owned keys:

```
aws iot update-encryption-configuration --encryption-type "AWS_OWNED_KMS_KEY"
```

**Note**  
When updating the encryption configuration for new customer managed keys, ensure both the old and new keys remain accessible for the operation to succeed.

##### Common failure scenarios and impacts
<a name="failure-scenarios"></a>

The following table describes common failure scenarios when keys are deleted or deactivated:


| Scenario | Immediate Impact | Long-term Consequences | 
| --- | --- | --- | 
|  Key disabled  |  All new encryption/decryption operations fail immediately  |  Service disruption until the key is re-enabled or replaced  | 
|  Key scheduled for deletion  |  Key status is changed to pending deletion and all encryption/decryption operations will fail  |  Automatic service failure when deletion completes  | 
|  Key permanently deleted  |  Immediate and permanent failure of all operations  |  Permanent data loss and inability to recover encrypted data  | 
|  Key policy modified incorrectly  |  AWS IoT Core loses access permissions to the key  |  Service failures until policy is corrected  | 
|  IAM role deleted  |  AWS IoT Core can't assume role to access key  |  Complete encryption service failure  | 
|  IAM role is modified incorrectly  |  AWS IoT Core can't assume role or use role to access key  |   Service failures until IAM role is corrected  | 

##### Prevention and best practices
<a name="prevention-best-practices"></a>

To prevent accidental key deletion or deactivation and minimize the risk of service failures:

Implement key lifecycle policies  
Establish clear procedures for key creation, rotation, and retirement. Document which keys are used by which AWS IoT Core resources and maintain an inventory of active keys.

Use IAM policies to restrict key deletion  
Create IAM policies that prevent unauthorized users from deleting or disabling critical encryption keys. Use conditions to require additional approval for key deletion operations.

Enable CloudTrail logging  
Monitor all AWS KMS key operations through CloudTrail to detect unauthorized or accidental key management activities. Set up alerts for key deletion, disabling, or policy changes.

Test key replacement procedures  
Regularly test your key replacement procedures in non-production environments to ensure you can quickly recover from key-related failures.

Maintain key backups  
While you can't export AWS KMS key material, maintain detailed records of key ARNs, policies, and associated AWS IoT Core configurations to facilitate rapid key replacement if needed.

Monitor key health  
Continuously monitor the `CMK.Health` metric and set up automated alerts for key health status changes. Implement automated responses to quickly address key-related issues.

**Important**  
Always test key update procedures in development environments before implementing them in production. Have a documented rollback plan and ensure that key replacement procedures can be executed quickly in case of emergencies.

### Step 6: Monitoring key health
<a name="health-status-monitoring"></a>

As part of the periodic checks AWS IoT Core runs, CloudWatch metrics and logs are emitted to provide visibility on the health status of your customer managed key configuration

AWS IoT Core emits the `CMK.Health` metric to CloudWatch at least once every minute. The metric provides information about the health status of the customer managed keys used by AWS IoT Core for encrypting and decrypting your data.

The `CMK.Health` metric can have the following values:
+ The value is `1`: AWS IoT Core is able to use the encryption keys successfully for encrypting and decrypting your data.
+ The value is `0`: AWS IoT Core is unable to use the encryption keys for encrypting and decrypting your data.

AWS IoT Core also emits AWS IoT V2 logs when the health status of the encryption keys changes. These logs provide additional details about the health status update. To view these logs, you must enable AWS IoT V2 logs. The `HEALTHY` logs are emitted at `INFO` level, and the `UNHEALTHY` logs are emitted at `ERROR` level. For more information about the log levels, see [Log levels](https://docs.aws.amazon.com/iot/latest/developerguide/configure-logging.html#log-level).

The following examples are CloudWatch log entries emitted by AWS IoT Core to indicate the health status update of the customer managed keys.

To effectively monitor and respond to key health status changes:

1. **Set up CloudWatch alarms** for the `CMK.Health` metric:

   ```
   aws cloudwatch put-metric-alarm --region us-west-2 \
     --alarm-name "IoTCore-CMK-Health-Alert" \
     --alarm-description "Alert when IoT Core CMK health is unhealthy" \
     --metric-name "CMK.Health" \
     --namespace "AWS/IoT" \
     --statistic "Minimum" \
     --period 300 \
     --evaluation-periods 1 \
     --threshold 1 \
     --comparison-operator "LessThanThreshold" \
     --alarm-actions "arn:aws:sns:us-west-2:111122223333:iot-alerts"
   ```

1. **Enable AWS IoT V2 logging** to capture detailed health status change events with error codes and messages.

1. **Check configuration status** for troubleshooting:

   ```
   aws iot describe-encryption-configuration --region us-west-2
   ```

1. **Investigate UNHEALTHY status** by examining the `errorCode` field:
   + `KMS_KEY_VALIDATION_ERROR` – Issue with the AWS KMS key (disabled, deleted, or policy problems)
   + `ROLE_VALIDATION_ERROR` – Issue with the IAM role (deleted, policy problems, or trust issues)

#### From UNHEALTHY to HEALTHY
<a name="unhealthy-to-healthy"></a>

When the status of the encryption keys is updated from `UNHEALTHY` to `HEALTHY`, AWS IoT Core will emit an AWS IoT V2 log message in the following format.

```
{
    "timestamp": "2017-08-10 15:37:23.476",
    "logLevel": "INFO",
    "traceId": "8421693b-f4f0-4e4a-9235-0cff8bab897d",
    "accountId": "111122223333",
    "status": "SUCCESS",
    "cmkStatus": "HEALTHY",
    "kmsKeyArn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "kmsAccessRoleArn": "arn:aws:iam::111122223333:role/myrole",
    "eventType": "CmkHealthCheck"
}
```

#### From HEALTHY to UNHEALTHY
<a name="healthy-to-unhealthy"></a>

When the status of the encryption keys is updated from `HEALTHY` to `UNHEALTHY`, AWS IoT Core will emit an AWS IoT V2 log message in the following format.

```
{
    "timestamp": "2017-08-10 15:37:23.476",
    "logLevel": "ERROR",
    "traceId": "8421693b-f4f0-4e4a-9235-0cff8bab897d",
    "accountId": "111122223333",
    "status": "FAILURE",
    "cmkStatus": "UNHEALTHY",
    "errorCode": "KMS_KEY_VALIDATION_ERROR / ROLE_VALIDATION_ERROR",
    "errorMessage": "Error message on why there was a failure",
    "kmsKeyArn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "kmsAccessRoleArn": "arn:aws:iam::111122223333:role/myrole",
    "eventType": "CmkHealthCheck"
}
```

**Warning**  
When key health becomes `UNHEALTHY`, AWS IoT Core operations fail immediately. If this occurs, review your key configurations, IAM role permissions, and policies. Monitor the `CMK.Health` metric for status changes. If operations continue to fail after reviewing your configurations, contact your account manager or the [AWS Support Center](https://console.aws.amazon.com/support/home#/) for additional assistance.

#### AWS CloudTrail events
<a name="aws-cloudtrail-events"></a>

You can also monitor AWS IoT Core's usage of the KMS key for encrypt decrypt operations. AWS IoT Core will make `DescribeKey`, `Decrypt`, `ReEncrypt`, and `GenerateDataKeyWithoutPlaintext` operations on your KMS key to encrypt / decrypt data belonging to your AWS account stored at rest.

There are CloudTrail events for `DescribeKey`, `Decrypt`, `ReEncrypt`, and `GenerateDataKeyWithoutPlaintext`. These events monitor AWS KMS operations called by AWS IoT Core to access data encrypted by your customer managed key.

##### `Decrypt` example
<a name="decrypt"></a>

```
{
    "eventVersion": "1.09",
    "userIdentity": {
        "type": "AssumedRole",
        "principalId": "AROAIGDTESTANDEXAMPLE:Sampleuser01",
        "arn": "arn:aws:sts::111122223333:assumed-role/Admin/Sampleuser01",
        "accountId": "111122223333",
        "accessKeyId": "*********************",
        "sessionContext": {
            "sessionIssuer": {
                "type": "Role",
                "principalId": "AROAIGDTESTANDEXAMPLE:Sampleuser01",
                "arn": "arn:aws:sts::111122223333:assumed-role/Admin/Sampleuser01",
                "accountId": "111122223333",
                "userName": "*****"
            },
            "attributes": {
                "creationDate": "2024-09-16T20:23:39Z",
                "mfaAuthenticated": "false"
            }
        },
        "invokedBy": "iot.amazonaws.com"
    },
    "eventTime": "2024-09-16T20:32:48Z",
    "eventSource": "kms.amazonaws.com",
    "eventName": "Decrypt",
    "awsRegion": "us-west-2",
    "sourceIPAddress": "iot.amazonaws.com",
    "userAgent": "iot.amazonaws.com",
    "requestParameters": {
        "encryptionContext": {
            "kms-arn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
            "aws-crypto-ec:vendor": "iot.amazonaws.com",
            "branch-key-id": "111122223333",
            "type": "branch:ACTIVE"
        },
        "encryptionAlgorithm": "SYMMETRIC_DEFAULT",
        "keyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
    },
    "responseElements": null,
    "requestID": "1afb6d98-8388-455d-8b48-e62c9e0cf7f4",
    "eventID": "b59a5f16-0d98-46d8-a590-0e040a48b39b",
    "readOnly": true,
    "resources": [
        {
            "accountId": "111122223333",
            "type": "AWS::KMS::Key",
            "ARN": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
        }
    ],
    "eventType": "AwsApiCall",
    "managementEvent": true,
    "recipientAccountId": "111122223333",
    "eventCategory": "Management"
}
```

# Identity and access management for AWS IoT
<a name="security-iam"></a>

AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be *authenticated* (signed in) and *authorized* (have permissions) to use AWS IoT resources. IAM is an AWS service that you can use with no additional charge.

**Topics**
+ [Audience](#security_iam_audience)
+ [Authenticating with IAM identities](#security_iam_authentication)
+ [Managing access using policies](#security_iam_access-manage)
+ [How AWS IoT works with IAM](security_iam_service-with-iam.md)
+ [AWS IoT identity-based policy examples](security_iam_id-based-policy-examples.md)
+ [AWS managed policies for AWS IoT](security-iam-awsmanpol.md)
+ [Troubleshooting AWS IoT identity and access](security_iam_troubleshoot.md)

## Audience
<a name="security_iam_audience"></a>

How you use AWS Identity and Access Management (IAM) differs based on your role:
+ **Service user** - request permissions from your administrator if you cannot access features (see [Troubleshooting AWS IoT identity and access](security_iam_troubleshoot.md))
+ **Service administrator** - determine user access and submit permission requests (see [How AWS IoT works with IAM](security_iam_service-with-iam.md))
+ **IAM administrator** - write policies to manage access (see [AWS IoT identity-based policy examples](security_iam_id-based-policy-examples.md))

## Authenticating with IAM identities
<a name="security_iam_authentication"></a>

In AWS IoT identities can be device (X.509) certificates, Amazon Cognito identities, or IAM users or groups. This topic discusses IAM identities only. For more information about the other identities that AWS IoT supports, see [Client authentication](client-authentication.md).

Authentication is how you sign in to AWS using your identity credentials. You must be authenticated as the AWS account root user, an IAM user, or by assuming an IAM role.

You can sign in as a federated identity using credentials from an identity source like AWS IAM Identity Center (IAM Identity Center), single sign-on authentication, or Google/Facebook credentials. For more information about signing in, see [How to sign in to your AWS account](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

For programmatic access, AWS provides an SDK and CLI to cryptographically sign requests. For more information, see [AWS Signature Version 4 for API requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html) in the *IAM User Guide*.

### AWS account root user
<a name="security_iam_authentication-rootuser"></a>

 When you create an AWS account, you begin with one sign-in identity called the AWS account *root user* that has complete access to all AWS services and resources. We strongly recommend that you don't use the root user for everyday tasks. For tasks that require root user credentials, see [Tasks that require root user credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks) in the *IAM User Guide*. 

### IAM users and groups
<a name="security_iam_authentication-iamuser"></a>

An *[IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html)* is an identity with specific permissions for a single person or application. We recommend using temporary credentials instead of IAM users with long-term credentials. For more information, see [Require human users to use federation with an identity provider to access AWS using temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-users-federation-idp) in the *IAM User Guide*.

An [https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) specifies a collection of IAM users and makes permissions easier to manage for large sets of users. For more information, see [Use cases for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/gs-identities-iam-users.html) in the *IAM User Guide*.

### IAM roles
<a name="security_iam_authentication-iamrole"></a>

An *[IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)* is an identity with specific permissions that provides temporary credentials. You can assume a role by [switching from a user to an IAM role (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html) or by calling an AWS CLI or AWS API operation. For more information, see [Methods to assume a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage-assume.html) in the *IAM User Guide*.

IAM roles are useful for federated user access, temporary IAM user permissions, cross-account access, cross-service access, and applications running on Amazon EC2. For more information, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the *IAM User Guide*.

## Managing access using policies
<a name="security_iam_access-manage"></a>

You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy defines permissions when associated with an identity or resource. AWS evaluates these policies when a principal makes a request. Most policies are stored in AWS as JSON documents. For more information about JSON policy documents, see [Overview of JSON policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json) in the *IAM User Guide*.

Using policies, administrators specify who has access to what by defining which **principal** can perform **actions** on what **resources**, and under what **conditions**.

By default, users and roles have no permissions. An IAM administrator creates IAM policies and adds them to roles, which users can then assume. IAM policies define permissions regardless of the method used to perform the operation.

### Identity-based policies
<a name="security_iam_access-manage-id-based-policies"></a>

Identity-based policies are JSON permissions policy documents that you attach to an identity (user, group, or role). These policies control what actions identities can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see [Define custom IAM permissions with customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the *IAM User Guide*.

Identity-based policies can be *inline policies* (embedded directly into a single identity) or *managed policies* (standalone policies attached to multiple identities). To learn how to choose between managed and inline policies, see [Choose between managed policies and inline policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-choosing-managed-or-inline.html) in the *IAM User Guide*.

### Resource-based policies
<a name="security_iam_access-manage-resource-based-policies"></a>

Resource-based policies are JSON policy documents that you attach to a resource. Examples include IAM *role trust policies* and Amazon S3 *bucket policies*. In services that support resource-based policies, service administrators can use them to control access to a specific resource. You must [specify a principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html) in a resource-based policy.

Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies from IAM in a resource-based policy.

### Access control lists (ACLs)
<a name="security_iam_access-manage-acl"></a>

Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format.

Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs. To learn more about ACLs, see [Access control list (ACL) overview](https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html) in the *Amazon Simple Storage Service Developer Guide*.

### Other policy types
<a name="security_iam_access-manage-other-policies"></a>

AWS supports additional policy types that can set the maximum permissions granted by more common policy types:
+ **Permissions boundaries** – Set the maximum permissions that an identity-based policy can grant to an IAM entity. For more information, see [Permissions boundaries for IAM entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) in the *IAM User Guide*.
+ **Service control policies (SCPs)** – Specify the maximum permissions for an organization or organizational unit in AWS Organizations. For more information, see [Service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) in the *AWS Organizations User Guide*.
+ **Resource control policies (RCPs)** – Set the maximum available permissions for resources in your accounts. For more information, see [Resource control policies (RCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html) in the *AWS Organizations User Guide*.
+ **Session policies** – Advanced policies passed as a parameter when creating a temporary session for a role or federated user. For more information, see [Session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) in the *IAM User Guide*.

### Multiple policy types
<a name="security_iam_access-manage-multiple-policies"></a>

When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see [Policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) in the *IAM User Guide*.

# How AWS IoT works with IAM
<a name="security_iam_service-with-iam"></a>

Before you use IAM to manage access to AWS IoT, you should understand which IAM features are available to use with AWS IoT. To get a high-level view of how AWS IoT and other AWS services work with IAM, see [AWS Services That Work with IAM](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_aws-services-that-work-with-iam.html) in the *IAM User Guide*.

**Topics**
+ [AWS IoT identity-based policies](#security_iam_service-with-iam-id-based-policies)
+ [AWS IoT resource-based policies](#security_iam_service-with-iam-resource-based-policies)
+ [Authorization based on AWS IoT tags](#security_iam_service-with-iam-tags)
+ [AWS IoT IAM roles](#security_iam_service-with-iam-roles)

## AWS IoT identity-based policies
<a name="security_iam_service-with-iam-id-based-policies"></a>

With IAM identity-based policies, you can specify allowed or denied actions and resources as well as the conditions under which actions are allowed or denied. AWS IoT supports specific actions, resources, and condition keys. To learn about all of the elements that you use in a JSON policy, see [IAM JSON Policy Elements Reference](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_elements.html) in the *IAM User Guide*.

### Actions
<a name="security_iam_service-with-iam-id-based-policies-actions"></a>

Administrators can use AWS JSON policies to specify who has access to what. That is, which **principal** can perform **actions** on what **resources**, and under what **conditions**.

The `Action` element of a JSON policy describes the actions that you can use to allow or deny access in a policy. Include actions in a policy to grant permissions to perform the associated operation.

The following table lists the IAM IoT actions, the associated AWS IoT API, and the resource the action manipulates.


****  

| Policy actions | AWS IoT API | Resources | 
| --- | --- | --- | 
| iot:AcceptCertificateTransfer | AcceptCertificateTransfer |  `arn:aws:iot:region:account-id:cert/cert-id`  The AWS account specified in the ARN must be the account to which the certificate is being transferred.   | 
| iot:AddThingToThingGroup | AddThingToThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:AssociateTargetsWithJob | AssociateTargetsWithJob | none  | 
| iot:AttachPolicy | AttachPolicy |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` or `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:AttachPrincipalPolicy | AttachPrincipalPolicy |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:AttachSecurityProfile | AttachSecurityProfile |  `arn:aws:iot:region:account-id:securityprofile/security-profile-name` `arn:aws:iot:region:account-id:dimension/dimension-name`  | 
| iot:AttachThingPrincipal | AttachThingPrincipal |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:CancelCertificateTransfer | CancelCertificateTransfer |  `arn:aws:iot:region:account-id:cert/cert-id`  The AWS account specified in the ARN must be the account to which the certificate is being transferred.   | 
| iot:CancelJob | CancelJob |  `arn:aws:iot:region:account-id:job/job-id`  | 
| iot:CancelJobExecution | CancelJobExecution |  `arn:aws:iot:region:account-id:job/job-id` `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:ClearDefaultAuthorizer | ClearDefaultAuthorizer | None | 
| iot:CreateAuthorizer | CreateAuthorizer |  `arn:aws:iot:region:account-id:authorizer/authorizer-function-name`  | 
| iot:CreateCertificateFromCsr | CreateCertificateFromCsr | \$1 | 
| iot:CreateDimension | CreateDimension | `arn:aws:iot:region:account-id:dimension/dimension-name` | 
| iot:CreateJob | CreateJob |  `arn:aws:iot:region:account-id:job/job-id` `arn:aws:iot:region:account-id:thinggroup/thing-group-name` `arn:aws:iot:region:account-id:thing/thing-name` `arn:aws:iot:region:account-id:jobtemplate/job-template-id`  | 
| iot:CreateJobTemplate | CreateJobTemplate |  `arn:aws:iot:region:account-id:job/job-id` `arn:aws:iot:region:account-id:jobtemplate/job-template-id`  | 
| iot:CreateKeysAndCertificate | CreateKeysAndCertificate | \$1 | 
| iot:CreatePolicy | CreatePolicy | `arn:aws:iot:region:account-id:policy/policy-name` | 
| iot:CreatePolicyVersion | CreatePolicyVersion |  `arn:aws:iot:region:account-id:policy/policy-name`  This must be an AWS IoT policy, not an IAM policy.   | 
| iot:CreateRoleAlias | CreateRoleAlias |  (parameter: roleAlias) `arn:aws:iot:region:account-id:rolealias/role-alias-name`  | 
| iot:CreateSecurityProfile | CreateSecurityProfile |  `arn:aws:iot:region:account-id:securityprofile/security-profile-name` `arn:aws:iot:region:account-id:dimension/dimension-name`  | 
| iot:CreateThing | CreateThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:CreateThingGroup | CreateThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` for group being created and for parent group, if used  | 
| iot:CreateThingType | CreateThingType |  `arn:aws:iot:region:account-id:thingtype/thing-type-name`  | 
| iot:CreateTopicRule | CreateTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:DeleteAuthorizer | DeleteAuthorizer |  `arn:aws:iot:region:account-id:authorizer/authorizer-name`  | 
| iot:DeleteCACertificate | DeleteCACertificate |  `arn:aws:iot:region:account-id:cacert/cert-id`  | 
| iot:DeleteCertificate | DeleteCertificate |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:DeleteDimension | DeleteDimension |  `arn:aws:iot:region:account-id:dimension/dimension-name`  | 
| iot:DeleteJob | DeleteJob |  `arn:aws:iot:region:account-id:job/job-id`  | 
| iot:DeleteJobTemplate | DeleteJobTemplate |  `arn:aws:iot:region:account-id:job/job-template-id`  | 
| iot:DeleteJobExecution | DeleteJobExecution |  `arn:aws:iot:region:account-id:job/job-id` `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:DeletePolicy | DeletePolicy |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:DeletePolicyVersion | DeletePolicyVersion |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:DeleteRegistrationCode | DeleteRegistrationCode | \$1 | 
| iot:DeleteRoleAlias | DeleteRoleAlias |  `arn:aws:iot:region:account-id:rolealias/role-alias-name`  | 
| iot:DeleteSecurityProfile | DeleteSecurityProfile |  `arn:aws:iot:region:account-id:securityprofile/security-profile-name` `arn:aws:iot:region:account-id:dimension/dimension-name`  | 
| iot:DeleteThing | DeleteThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:DeleteThingGroup | DeleteThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:DeleteThingType | DeleteThingType |  `arn:aws:iot:region:account-id:thingtype/thing-type-name`  | 
| iot:DeleteTopicRule | DeleteTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:DeleteV2LoggingLevel | DeleteV2LoggingLevel |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:DeprecateThingType | DeprecateThingType |  `arn:aws:iot:region:account-id:thingtype/thing-type-name`  | 
| iot:DescribeAuthorizer | DescribeAuthorizer |  `arn:aws:iot:region:account-id:authorizer/authorizer-function-name` (parameter: authorizerName) none  | 
| iot:DescribeCACertificate | DescribeCACertificate |  `arn:aws:iot:region:account-id:cacert/cert-id`  | 
| iot:DescribeCertificate | DescribeCertificate |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:DescribeDefaultAuthorizer | DescribeDefaultAuthorizer | None  | 
| iot:DescribeEndpoint | DescribeEndpoint | \$1 | 
| iot:DescribeEventConfigurations | DescribeEventConfigurations | none  | 
| iot:DescribeIndex | DescribeIndex |  `arn:aws:iot:region:account-id:index/index-name`  | 
| iot:DescribeJob | DescribeJob |  `arn:aws:iot:region:account-id:job/job-id`  | 
| iot:DescribeJobExecution | DescribeJobExecution | None | 
| iot:DescribeJobTemplate | DescribeJobTemplate |  `arn:aws:iot:region:account-id:job/job-template-id`  | 
| iot:DescribeRoleAlias | DescribeRoleAlias |  `arn:aws:iot:region:account-id:rolealias/role-alias-name`  | 
| iot:DescribeThing | DescribeThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:DescribeThingGroup | DescribeThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:DescribeThingRegistrationTask | DescribeThingRegistrationTask | None | 
| iot:DescribeThingType | DescribeThingType |  `arn:aws:iot:region:account-id:thingtype/thing-type-name`  | 
| iot:DetachPolicy | DetachPolicy |  `arn:aws:iot:region:account-id:cert/cert-id` or `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:DetachPrincipalPolicy | DetachPrincipalPolicy |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:DetachSecurityProfile | DetachSecurityProfile |  `arn:aws:iot:region:account-id:securityprofile/security-profile-name` `arn:aws:iot:region:account-id:dimension/dimension-name`  | 
| iot:DetachThingPrincipal | DetachThingPrincipal |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:DisableTopicRule | DisableTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:EnableTopicRule | EnableTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:GetEffectivePolicies | GetEffectivePolicies |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:GetIndexingConfiguration | GetIndexingConfiguration | None | 
| iot:GetJobDocument | GetJobDocument |  `arn:aws:iot:region:account-id:job/job-id`  | 
| iot:GetLoggingOptions | GetLoggingOptions | \$1 | 
| iot:GetPolicy | GetPolicy |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:GetPolicyVersion | GetPolicyVersion |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:GetRegistrationCode | GetRegistrationCode | \$1 | 
| iot:GetTopicRule | GetTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:ListAttachedPolicies | ListAttachedPolicies |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` or `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:ListAuthorizers | ListAuthorizers | None | 
| iot:ListCACertificates | ListCACertificates | \$1 | 
| iot:ListCertificates | ListCertificates | \$1 | 
| iot:ListCertificatesByCA | ListCertificatesByCA | \$1 | 
| iot:ListIndices | ListIndices | None | 
| iot:ListJobExecutionsForJob | ListJobExecutionsForJob | None | 
| iot:ListJobExecutionsForThing | ListJobExecutionsForThing | None | 
| iot:ListJobs | ListJobs |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` if thingGroupName parameter used  | 
| iot:ListJobTemplates | ListJobs | None | 
| iot:ListOutgoingCertificates | ListOutgoingCertificates | \$1 | 
| iot:ListPolicies | ListPolicies | \$1 | 
| iot:ListPolicyPrincipals | ListPolicyPrincipals | \$1 | 
| iot:ListPolicyVersions | ListPolicyVersions |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:ListPrincipalPolicies | ListPrincipalPolicies |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:ListPrincipalThings | ListPrincipalThings |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:ListRoleAliases | ListRoleAliases | None | 
| iot:ListTargetsForPolicy | ListTargetsForPolicy |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:ListThingGroups | ListThingGroups | None | 
| iot:ListThingGroupsForThing | ListThingGroupsForThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:ListThingPrincipals | ListThingPrincipals |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:ListThingRegistrationTaskReports | ListThingRegistrationTaskReports | None | 
| iot:ListThingRegistrationTasks | ListThingRegistrationTasks | None | 
| iot:ListThingTypes | ListThingTypes | \$1 | 
| iot:ListThings | ListThings | \$1 | 
| iot:ListThingsInThingGroup | ListThingsInThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:ListTopicRules | ListTopicRules | \$1 | 
| iot:ListV2LoggingLevels | ListV2LoggingLevels | None | 
| iot:RegisterCACertificate | RegisterCACertificate | \$1 | 
| iot:RegisterCertificate | RegisterCertificate | \$1 | 
| iot:RegisterThing | RegisterThing | None | 
| iot:RejectCertificateTransfer | RejectCertificateTransfer |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:RemoveThingFromThingGroup | RemoveThingFromThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:ReplaceTopicRule | ReplaceTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:SearchIndex | SearchIndex |  `arn:aws:iot:region:account-id:index/index-id`  | 
| iot:SetDefaultAuthorizer | SetDefaultAuthorizer |  `arn:aws:iot:region:account-id:authorizer/authorizer-function-name`  | 
| iot:SetDefaultPolicyVersion | SetDefaultPolicyVersion |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:SetLoggingOptions | SetLoggingOptions |  `arn:aws:iot:region:account-id:role/role-name`  | 
| iot:SetV2LoggingLevel | SetV2LoggingLevel |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:SetV2LoggingOptions | SetV2LoggingOptions |  `arn:aws:iot:region:account-id:role/role-name`  | 
| iot:StartThingRegistrationTask | StartThingRegistrationTask | None | 
| iot:StopThingRegistrationTask | StopThingRegistrationTask | None | 
| iot:TestAuthorization | TestAuthorization |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:TestInvokeAuthorizer | TestInvokeAuthorizer | None | 
| iot:TransferCertificate | TransferCertificate |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:UpdateAuthorizer | UpdateAuthorizer |  `arn:aws:iot:region:account-id:authorizerfunction/authorizer-function-name`  | 
| iot:UpdateCACertificate | UpdateCACertificate |  `arn:aws:iot:region:account-id:cacert/cert-id`  | 
| iot:UpdateCertificate | UpdateCertificate |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:UpdateDimension | UpdateDimension |  `arn:aws:iot:region:account-id:dimension/dimension-name`  | 
| iot:UpdateEventConfigurations | UpdateEventConfigurations | None | 
| iot:UpdateIndexingConfiguration | UpdateIndexingConfiguration | None | 
| iot:UpdateRoleAlias | UpdateRoleAlias |  `arn:aws:iot:region:account-id:rolealias/role-alias-name`  | 
| iot:UpdateSecurityProfile | UpdateSecurityProfile |  `arn:aws:iot:region:account-id:securityprofile/security-profile-name` `arn:aws:iot:region:account-id:dimension/dimension-name`  | 
| iot:UpdateThing | UpdateThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:UpdateThingGroup | UpdateThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:UpdateThingGroupsForThing | UpdateThingGroupsForThing |  `arn:aws:iot:region:account-id:thing/thing-name` `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 

Policy actions in AWS IoT use the following prefix before the action: `iot:`. For example, to grant someone permission to list all IoT things registered in their AWS account with the `ListThings` API, you include the `iot:ListThings` action in their policy. Policy statements must include either an `Action` or `NotAction` element. AWS IoT defines its own set of actions that describe tasks that you can perform with this service.

To specify multiple actions in a single statement, separate them with commas as follows:

```
"Action": [
      "ec2:action1",
      "ec2:action2"
```

You can specify multiple actions using wildcards (\$1). For example, to specify all actions that begin with the word `Describe`, include the following action:

```
"Action": "iot:Describe*"
```

To see a list of AWS IoT actions, see [Actions Defined by AWS IoT](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions) in the *IAM User Guide*.

#### Device Advisor actions
<a name="security_iam_service-actions-device-advisor"></a>

The following table lists the IAM IoT Device Advisor actions, the associated AWS IoT Device Advisor API, and the resource the action manipulates.


****  

| Policy actions | AWS IoT API | Resources | 
| --- | --- | --- | 
| iotdeviceadvisor:CreateSuiteDefinition | CreateSuiteDefinition |  None  | 
| iotdeviceadvisor:DeleteSuiteDefinition | DeleteSuiteDefinition |  `arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-definition-id`  | 
| iotdeviceadvisor:GetSuiteDefinition | GetSuiteDefinition |  `arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-definition-id`  | 
| iotdeviceadvisor:GetSuiteRun | GetSuiteRun |  `arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-run-id`  | 
| iotdeviceadvisor:GetSuiteRunReport | GetSuiteRunReport |  `arn:aws:iotdeviceadvisor:region:account-id:suiterun/suite-definition-id/suite-run-id`  | 
| iotdeviceadvisor:ListSuiteDefinitions | ListSuiteDefinitions | None | 
| iotdeviceadvisor:ListSuiteRuns | ListSuiteRuns |  `arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-definition-id`  | 
| iotdeviceadvisor:ListTagsForResource | ListTagsForResource |  `arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-definition-id` `arn:aws:iotdeviceadvisor:region:account-id:suiterun/suite-definition-id/suite-run-id`  | 
| iotdeviceadvisor:StartSuiteRun | StartSuiteRun |  `arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-definition-id`  | 
| iotdeviceadvisor:TagResource | TagResource |  `arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-definition-id` `arn:aws:iotdeviceadvisor:region:account-id:suiterun/suite-definition-id/suite-run-id`  | 
| iotdeviceadvisor:UntagResource | UntagResource |  `arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-definition-id` `arn:aws:iotdeviceadvisor:region:account-id:suiterun/suite-definition-id/suite-run-id`  | 
| iotdeviceadvisor:UpdateSuiteDefinition | UpdateSuiteDefinition |  `arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-definition-id`  | 
| iotdeviceadvisor:StopSuiteRun | StopSuiteRun |  `arn:aws:iotdeviceadvisor:region:account-id:suiterun/suite-definition-id/suite-run-id`  | 

Policy actions in AWS IoT Device Advisor use the following prefix before the action: `iotdeviceadvisor:`. For example, to grant someone permission to list all suite definitions registered in their AWS account with the ListSuiteDefinitions API, you include the `iotdeviceadvisor:ListSuiteDefinitions` action in their policy.

### Resources
<a name="security_iam_service-with-iam-id-based-policies-resources"></a>

Administrators can use AWS JSON policies to specify who has access to what. That is, which **principal** can perform **actions** on what **resources**, and under what **conditions**.

The `Resource` JSON policy element specifies the object or objects to which the action applies. As a best practice, specify a resource using its [Amazon Resource Name (ARN)](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html). For actions that don't support resource-level permissions, use a wildcard (\$1) to indicate that the statement applies to all resources.

```
"Resource": "*"
```


**AWS IoT resources**  

| Policy actions | AWS IoT API | Resources | 
| --- | --- | --- | 
| iot:AcceptCertificateTransfer | AcceptCertificateTransfer |  `arn:aws:iot:region:account-id:cert/cert-id`  The AWS account specified in the ARN must be the account to which the certificate is being transferred.   | 
| iot:AddThingToThingGroup | AddThingToThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:AssociateTargetsWithJob | AssociateTargetsWithJob | None  | 
| iot:AttachPolicy | AttachPolicy | `arn:aws:iot:region:account-id:thinggroup/thing-group-name` or `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:AttachPrincipalPolicy | AttachPrincipalPolicy |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:AttachThingPrincipal | AttachThingPrincipal |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:CancelCertificateTransfer | CancelCertificateTransfer |  `arn:aws:iot:region:account-id:cert/cert-id`  The AWS account specified in the ARN must be the account to which the certificate is being transferred.   | 
| iot:CancelJob | CancelJob |  `arn:aws:iot:region:account-id:job/job-id`  | 
| iot:CancelJobExecution | CancelJobExecution |  `arn:aws:iot:region:account-id:job/job-id` `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:ClearDefaultAuthorizer | ClearDefaultAuthorizer | None | 
| iot:CreateAuthorizer | CreateAuthorizer |  `arn:aws:iot:region:account-id:authorizer/authorizer-function-name`  | 
| iot:CreateCertificateFromCsr | CreateCertificateFromCsr | \$1 | 
| iot:CreateJob | CreateJob |  `arn:aws:iot:region:account-id:job/job-id` `arn:aws:iot:region:account-id:thinggroup/thing-group-name` `arn:aws:iot:region:account-id:thing/thing-name` `arn:aws:iot:region:account-id:jobtemplate/job-template-id`  | 
| iot:CreateJobTemplate | CreateJobTemplate |  `arn:aws:iot:region:account-id:job/job-id` `arn:aws:iot:region:account-id:jobtemplate/job-template-id`  | 
| iot:CreateKeysAndCertificate | CreateKeysAndCertificate | \$1 | 
| iot:CreatePolicy | CreatePolicy | `arn:aws:iot:region:account-id:policy/policy-name` | 
| CreatePolicyVersion | iot:CreatePolicyVersion |  `arn:aws:iot:region:account-id:policy/policy-name`  This must be an AWS IoT policy, not an IAM policy.   | 
| iot:CreateRoleAlias | CreateRoleAlias |  (parameter: roleAlias) `arn:aws:iot:region:account-id:rolealias/role-alias-name`  | 
| iot:CreateThing | CreateThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:CreateThingGroup | CreateThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` for group being created and for parent group, if used  | 
| iot:CreateThingType | CreateThingType |  `arn:aws:iot:region:account-id:thingtype/thing-type-name`  | 
| iot:CreateTopicRule | CreateTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:DeleteAuthorizer | DeleteAuthorizer |  `arn:aws:iot:region:account-id:authorizer/authorizer-name`  | 
| iot:DeleteCACertificate | DeleteCACertificate |  `arn:aws:iot:region:account-id:cacert/cert-id`  | 
| iot:DeleteCertificate | DeleteCertificate |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:DeleteJob | DeleteJob |  `arn:aws:iot:region:account-id:job/job-id`  | 
| iot:DeleteJobExecution | DeleteJobExecution |  `arn:aws:iot:region:account-id:job/job-id` `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:DeleteJobTemplate | DeleteJobTemplate |  `arn:aws:iot:region:account-id:jobtemplate/job-template-id`  | 
| iot:DeletePolicy | DeletePolicy |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:DeletePolicyVersion | DeletePolicyVersion |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:DeleteRegistrationCode | DeleteRegistrationCode | \$1 | 
| iot:DeleteRoleAlias | DeleteRoleAlias |  `arn:aws:iot:region:account-id:rolealias/role-alias-name`  | 
| iot:DeleteThing | DeleteThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:DeleteThingGroup | DeleteThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:DeleteThingType | DeleteThingType |  `arn:aws:iot:region:account-id:thingtype/thing-type-name`  | 
| iot:DeleteTopicRule | DeleteTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:DeleteV2LoggingLevel | DeleteV2LoggingLevel |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:DeprecateThingType | DeprecateThingType |  `arn:aws:iot:region:account-id:thingtype/thing-type-name`  | 
| iot:DescribeAuthorizer | DescribeAuthorizer |  `arn:aws:iot:region:account-id:authorizer/authorizer-function-name` (parameter: authorizerName) none  | 
| iot:DescribeCACertificate | DescribeCACertificate |  `arn:aws:iot:region:account-id:cacert/cert-id`  | 
| iot:DescribeCertificate | DescribeCertificate |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:DescribeDefaultAuthorizer | DescribeDefaultAuthorizer | None  | 
| iot:DescribeEndpoint | DescribeEndpoint | \$1 | 
| iot:DescribeEventConfigurations | DescribeEventConfigurations | none  | 
| iot:DescribeIndex | DescribeIndex |  `arn:aws:iot:region:account-id:index/index-name`  | 
| iot:DescribeJob | DescribeJob |  `arn:aws:iot:region:account-id:job/job-id`  | 
| iot:DescribeJobExecution | DescribeJobExecution | None | 
| iot:DescribeJobTemplate | DescribeJobTemplate |  `arn:aws:iot:region:account-id:jobtemplate/job-template-id`  | 
| iot:DescribeRoleAlias | DescribeRoleAlias |  `arn:aws:iot:region:account-id:rolealias/role-alias-name`  | 
| iot:DescribeThing | DescribeThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:DescribeThingGroup | DescribeThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:DescribeThingRegistrationTask | DescribeThingRegistrationTask | None | 
| iot:DescribeThingType | DescribeThingType |  `arn:aws:iot:region:account-id:thingtype/thing-type-name`  | 
| iot:DetachPolicy | DetachPolicy |  `arn:aws:iot:region:account-id:cert/cert-id` or `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:DetachPrincipalPolicy | DetachPrincipalPolicy |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:DetachThingPrincipal | DetachThingPrincipal |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:DisableTopicRule | DisableTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:EnableTopicRule | EnableTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:GetEffectivePolicies | GetEffectivePolicies |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:GetIndexingConfiguration | GetIndexingConfiguration | None | 
| iot:GetJobDocument | GetJobDocument |  `arn:aws:iot:region:account-id:job/job-id`  | 
| iot:GetLoggingOptions | GetLoggingOptions | \$1 | 
| iot:GetPolicy | GetPolicy |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:GetPolicyVersion | GetPolicyVersion |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:GetRegistrationCode | GetRegistrationCode | \$1 | 
| iot:GetTopicRule | GetTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:ListAttachedPolicies | ListAttachedPolicies |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` or `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:ListAuthorizers | ListAuthorizers | None | 
| iot:ListCACertificates | ListCACertificates | \$1 | 
| iot:ListCertificates | ListCertificates | \$1 | 
| iot:ListCertificatesByCA | ListCertificatesByCA | \$1 | 
| iot:ListIndices | ListIndices | None | 
| iot:ListJobExecutionsForJob | ListJobExecutionsForJob | None | 
| iot:ListJobExecutionsForThing | ListJobExecutionsForThing | None | 
| iot:ListJobs | ListJobs |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` if thingGroupName parameter used  | 
| iot:ListJobTemplates | ListJobTemplates | None | 
| iot:ListOutgoingCertificates | ListOutgoingCertificates | \$1 | 
| iot:ListPolicies | ListPolicies | \$1 | 
| iot:ListPolicyPrincipals | ListPolicyPrincipals |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:ListPolicyVersions | ListPolicyVersions |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:ListPrincipalPolicies | ListPrincipalPolicies |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:ListPrincipalThings | ListPrincipalThings |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:ListRoleAliases | ListRoleAliases | None | 
| iot:ListTargetsForPolicy | ListTargetsForPolicy |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:ListThingGroups | ListThingGroups | None | 
| iot:ListThingGroupsForThing | ListThingGroupsForThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:ListThingPrincipals | ListThingPrincipals |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:ListThingRegistrationTaskReports | ListThingRegistrationTaskReports | None | 
| iot:ListThingRegistrationTasks | ListThingRegistrationTasks | None | 
| iot:ListThingTypes | ListThingTypes | \$1 | 
| iot:ListThings | ListThings | \$1 | 
| iot:ListThingsInThingGroup | ListThingsInThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:ListTopicRules | ListTopicRules | \$1 | 
| iot:ListV2LoggingLevels | ListV2LoggingLevels | None | 
| iot:RegisterCACertificate | RegisterCACertificate | \$1 | 
| iot:RegisterCertificate | RegisterCertificate | \$1 | 
| iot:RegisterThing | RegisterThing | None | 
| iot:RejectCertificateTransfer | RejectCertificateTransfer |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:RemoveThingFromThingGroup | RemoveThingFromThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name` `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:ReplaceTopicRule | ReplaceTopicRule |  `arn:aws:iot:region:account-id:rule/rule-name`  | 
| iot:SearchIndex | SearchIndex |  `arn:aws:iot:region:account-id:index/index-id`  | 
| iot:SetDefaultAuthorizer | SetDefaultAuthorizer |  `arn:aws:iot:region:account-id:authorizer/authorizer-function-name`  | 
| iot:SetDefaultPolicyVersion | SetDefaultPolicyVersion |  `arn:aws:iot:region:account-id:policy/policy-name`  | 
| iot:SetLoggingOptions | SetLoggingOptions | \$1 | 
| iot:SetV2LoggingLevel | SetV2LoggingLevel | \$1 | 
| iot:SetV2LoggingOptions | SetV2LoggingOptions | \$1 | 
| iot:StartThingRegistrationTask | StartThingRegistrationTask | None | 
| iot:StopThingRegistrationTask | StopThingRegistrationTask | None | 
| iot:TestAuthorization | TestAuthorization |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:TestInvokeAuthorizer | TestInvokeAuthorizer | None | 
| iot:TransferCertificate | TransferCertificate |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:UpdateAuthorizer | UpdateAuthorizer |  `arn:aws:iot:region:account-id:authorizerfunction/authorizer-function-name`  | 
| iot:UpdateCACertificate | UpdateCACertificate |  `arn:aws:iot:region:account-id:cacert/cert-id`  | 
| iot:UpdateCertificate | UpdateCertificate |  `arn:aws:iot:region:account-id:cert/cert-id`  | 
| iot:UpdateEventConfigurations | UpdateEventConfigurations | None | 
| iot:UpdateIndexingConfiguration | UpdateIndexingConfiguration | None | 
| iot:UpdateRoleAlias | UpdateRoleAlias |  `arn:aws:iot:region:account-id:rolealias/role-alias-name`  | 
| iot:UpdateThing | UpdateThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 
| iot:UpdateThingGroup | UpdateThingGroup |  `arn:aws:iot:region:account-id:thinggroup/thing-group-name`  | 
| iot:UpdateThingGroupsForThing | UpdateThingGroupsForThing |  `arn:aws:iot:region:account-id:thing/thing-name`  | 

For more information about the format of ARNs, see [Amazon Resource Names (ARNs) and AWS Service Namespaces](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html).

Some AWS IoT actions, such as those for creating resources, cannot be performed on a specific resource. In those cases, you must use the wildcard (\$1).

```
"Resource": "*"
```

To see a list of AWS IoT resource types and their ARNs, see [Resources Defined by AWS IoT](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-resources-for-iam-policies) in the *IAM User Guide*. To learn with which actions you can specify the ARN of each resource, see [Actions Defined by AWS IoT](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions).

#### Device Advisor resources
<a name="security_iam_service-device-advisor-resources"></a>

To define resource-level restrictions for AWS IoT Device Advisor IAM policies, use the following resource ARN formats for suite definitions and suite runs.

Suite definition resource ARN format  
`arn:aws:iotdeviceadvisor:region:account-id:suitedefinition/suite-definition-id`

Suite run resource ARN format  
`arn:aws:iotdeviceadvisor:region:account-id:suiterun/suite-definition-id/suite-run-id`

### Condition keys
<a name="security_iam_service-with-iam-id-based-policies-conditionkeys"></a>

Administrators can use AWS JSON policies to specify who has access to what. That is, which **principal** can perform **actions** on what **resources**, and under what **conditions**.

The `Condition` element specifies when statements execute based on defined criteria. You can create conditional expressions that use [condition operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html), such as equals or less than, to match the condition in the policy with values in the request. To see all AWS global condition keys, see [AWS global condition context keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) in the *IAM User Guide*.

AWS IoT defines its own set of condition keys and also supports using some global condition keys. To see all AWS global condition keys, see [AWS Global Condition Context Keys](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_condition-keys.html) in the *IAM User Guide*. 


**AWS IoT condition keys**  

| AWS IoT condition keys | Description | Type | 
| --- | --- | --- | 
| aws:RequestTag/\$1\$1tag-key\$1 | A tag key that is present in the request that the user makes to AWS IoT. | String | 
| aws:ResourceTag/\$1\$1tag-key\$1 | The tag key component of a tag attached to an AWS IoT resource. | String | 
| aws:TagKeys | The list of all the tag key names associated with the resource in the request. | String | 

To see a list of AWS IoT condition keys, see [Condition Keys for AWS IoT](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-policy-keys) in the *IAM User Guide*. To learn with which actions and resources you can use a condition key, see [Actions Defined by AWS IoT](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions).

### Examples
<a name="security_iam_service-with-iam-id-based-policies-examples"></a>



To view examples of AWS IoT identity-based policies, see [AWS IoT identity-based policy examples](security_iam_id-based-policy-examples.md).

## AWS IoT resource-based policies
<a name="security_iam_service-with-iam-resource-based-policies"></a>

Resource-based policies are JSON policy documents that specify what actions a specified principal can perform on the AWS IoT resource and under what conditions.

AWS IoT does not support IAM resource-based policies. It does, however, support AWS IoT resource-based policies. For more information, see [AWS IoT Core policies](iot-policies.md).

## Authorization based on AWS IoT tags
<a name="security_iam_service-with-iam-tags"></a>

You can attach tags to AWS IoT resources or pass tags in a request to AWS IoT. To control access based on tags, you provide tag information in the [condition element](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_elements_condition.html) of a policy using the `iot:ResourceTag/key-name`, `aws:RequestTag/key-name`, or `aws:TagKeys` condition keys. For more information, see [Using tags with IAM policies](tagging-iot-iam.md). For more information about tagging AWS IoT resources, see [Tagging your AWS IoT resources](tagging-iot.md).

To view an example identity-based policy for limiting access to a resource based on the tags on that resource, see [Viewing AWS IoT resources based on tags](security_iam_id-based-policy-examples.md#security_iam_id-based-policy-examples-view-thing-tags).

## AWS IoT IAM roles
<a name="security_iam_service-with-iam-roles"></a>

An [IAM role](https://docs.aws.amazon.com/service-authorization/latest/reference/id_roles.html) is an entity within your AWS account that has specific permissions.

### Using temporary credentials with AWS IoT
<a name="security_iam_service-with-iam-roles-tempcreds"></a>

You can use temporary credentials to sign in with federation, assume an IAM role, or to assume a cross-account role. You obtain temporary security credentials by calling AWS STS API operations such as [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) or [GetFederationToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html). 

AWS IoT supports using temporary credentials. 

### Service-linked roles
<a name="security_iam_service-with-iam-roles-service-linked"></a>

[Service-linked roles](https://docs.aws.amazon.com/service-authorization/latest/reference/id_roles_terms-and-concepts.html#iam-term-service-linked-role) allow AWS services to access resources in other services to complete an action on your behalf. Service-linked roles appear in your IAM account and are owned by the service. An IAM administrator can view but not edit the permissions for service-linked roles.

AWS IoT does not supports service-linked roles.

### Service roles
<a name="security_iam_service-with-iam-roles-service"></a>

This feature allows a service to assume a [service role](https://docs.aws.amazon.com/service-authorization/latest/reference/id_roles_terms-and-concepts.html#iam-term-service-role) on your behalf. This role allows the service to access resources in other services to complete an action on your behalf. Service roles appear in your IAM account and are owned by the account. This means that an IAM administrator can change the permissions for this role. However, doing so might break the functionality of the service.

# AWS IoT identity-based policy examples
<a name="security_iam_id-based-policy-examples"></a>

By default, IAM users and roles don't have permission to create or modify AWS IoT resources. They also can't perform tasks using the AWS Management Console, AWS CLI, or AWS API. An IAM administrator must create IAM policies that grant users and roles permission to perform specific API operations on the specified resources they need. The administrator must then attach those policies to the users or groups that require those permissions.

To learn how to create an IAM identity-based policy using these example JSON policy documents, see [Creating Policies on the JSON Tab](https://docs.aws.amazon.com/service-authorization/latest/reference/access_policies_create.html#access_policies_create-json-editor) in the *IAM User Guide*.

**Topics**
+ [Policy best practices](#security_iam_service-with-iam-policy-best-practices)
+ [Using the AWS IoT console](#security_iam_id-based-policy-examples-console)
+ [Allow users to view their own permissions](#security_iam_id-based-policy-examples-view-own-permissions)
+ [Viewing AWS IoT resources based on tags](#security_iam_id-based-policy-examples-view-thing-tags)
+ [Viewing AWS IoT Device Advisor resources based on tags](#security_iam-device-advisor-tags)

## Policy best practices
<a name="security_iam_service-with-iam-policy-best-practices"></a>

Identity-based policies determine whether someone can create, access, or delete AWS IoT resources in your account. These actions can incur costs for your AWS account. When you create or edit identity-based policies, follow these guidelines and recommendations:
+ **Get started with AWS managed policies and move toward least-privilege permissions** – To get started granting permissions to your users and workloads, use the *AWS managed policies* that grant permissions for many common use cases. They are available in your AWS account. We recommend that you reduce permissions further by defining AWS customer managed policies that are specific to your use cases. For more information, see [AWS managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) or [AWS managed policies for job functions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_job-functions.html) in the *IAM User Guide*.
+ **Apply least-privilege permissions** – When you set permissions with IAM policies, grant only the permissions required to perform a task. You do this by defining the actions that can be taken on specific resources under specific conditions, also known as *least-privilege permissions*. For more information about using IAM to apply permissions, see [ Policies and permissions in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) in the *IAM User Guide*.
+ **Use conditions in IAM policies to further restrict access** – You can add a condition to your policies to limit access to actions and resources. For example, you can write a policy condition to specify that all requests must be sent using SSL. You can also use conditions to grant access to service actions if they are used through a specific AWS service, such as CloudFormation. For more information, see [ IAM JSON policy elements: Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) in the *IAM User Guide*.
+ **Use IAM Access Analyzer to validate your IAM policies to ensure secure and functional permissions** – IAM Access Analyzer validates new and existing policies so that the policies adhere to the IAM policy language (JSON) and IAM best practices. IAM Access Analyzer provides more than 100 policy checks and actionable recommendations to help you author secure and functional policies. For more information, see [Validate policies with IAM Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-validation.html) in the *IAM User Guide*.
+ **Require multi-factor authentication (MFA)** – If you have a scenario that requires IAM users or a root user in your AWS account, turn on MFA for additional security. To require MFA when API operations are called, add MFA conditions to your policies. For more information, see [ Secure API access with MFA](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html) in the *IAM User Guide*.

For more information about best practices in IAM, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

## Using the AWS IoT console
<a name="security_iam_id-based-policy-examples-console"></a>

To access the AWS IoT console, you must have a minimum set of permissions. These permissions must allow you to list and view details about the AWS IoT resources in your AWS account. If you create an identity-based policy that is more restrictive than the minimum required permissions, the console won't function as intended for entities (users or roles) with that policy.

To ensure that those entities can still use the AWS IoT console, also attach the following AWS managed policy to the entities: `AWSIoTFullAccess`. For more information, see [Adding Permissions to a User](https://docs.aws.amazon.com/service-authorization/latest/reference/id_users_change-permissions.html#users_change_permissions-add-console) in the *IAM User Guide*.

You don't need to allow minimum console permissions for users that are making calls only to the AWS CLI or the AWS API. Instead, allow access to only the actions that match the API operation that you're trying to perform.

## Allow users to view their own permissions
<a name="security_iam_id-based-policy-examples-view-own-permissions"></a>

This example shows how you might create a policy that allows IAM users to view the inline and managed policies that are attached to their user identity. This policy includes permissions to complete this action on the console or programmatically using the AWS CLI or AWS API.

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ViewOwnUserInfo",
            "Effect": "Allow",
            "Action": [
                "iam:GetUserPolicy",
                "iam:ListGroupsForUser",
                "iam:ListAttachedUserPolicies",
                "iam:ListUserPolicies",
                "iam:GetUser"
            ],
            "Resource": ["arn:aws:iam::*:user/${aws:username}"]
        },
        {
            "Sid": "NavigateInConsole",
            "Effect": "Allow",
            "Action": [
                "iam:GetGroupPolicy",
                "iam:GetPolicyVersion",
                "iam:GetPolicy",
                "iam:ListAttachedGroupPolicies",
                "iam:ListGroupPolicies",
                "iam:ListPolicyVersions",
                "iam:ListPolicies",
                "iam:ListUsers"
            ],
            "Resource": "*"
        }
    ]
}
```

## Viewing AWS IoT resources based on tags
<a name="security_iam_id-based-policy-examples-view-thing-tags"></a>

You can use conditions in your identity-based policy to control access to AWS IoT resources based on tags. This example shows how you might create a policy that allows viewing a thing. However, permission is granted only if the thing tag `Owner` has the value of that user's user name. This policy also grants the permissions necessary to complete this action on the console.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ListBillingGroupsInConsole",
            "Effect": "Allow",
            "Action": "iot:ListBillingGroups",
            "Resource": "*"
        },
        {
            "Sid": "ViewBillingGroupsIfOwner",
            "Effect": "Allow",
           "Action": "iot:DescribeBillingGroup",
            "Resource": "arn:aws:iot:*:*:billinggroup/*",
            "Condition": {
                "StringEquals": {"aws:ResourceTag/Owner": "${aws:username}"}
        }
        }
    ]
}
```

You can attach this policy to the IAM users in your account. If a user named `richard-roe` attempts to view an AWS IoT billing group, the billing group must be tagged `Owner=richard-roe` or `owner=richard-roe`. Otherwise, he is denied access. The condition tag key `Owner` matches both `Owner` and `owner` because condition key names are not case-sensitive. For more information, see [IAM JSON Policy Elements: Condition](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_elements_condition.html) in the *IAM User Guide*.

## Viewing AWS IoT Device Advisor resources based on tags
<a name="security_iam-device-advisor-tags"></a>

You can use conditions in your identity-based policy to control access to AWS IoT Device Advisor resources based on tags. The following example shows how you can create a policy that allows viewing a particular suite definition. However, permission is granted only if the suite definition tag has `SuiteType` set to the value of `MQTT`. This policy also grants the permissions necessary to complete this action on the console.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ViewSuiteDefinition",
            "Effect": "Allow",
            "Action": "iotdeviceadvisor:GetSuiteDefinition",
            "Resource": "arn:aws:iotdeviceadvisor:*:*:suitedefinition/*",
            "Condition": {
                "StringEquals": {"aws:ResourceTag/SuiteType": "MQTT"}
        }
        }
    ]
}
```

# AWS managed policies for AWS IoT
<a name="security-iam-awsmanpol"></a>







To add permissions to users, groups, and roles, it is easier to use AWS managed policies than to write policies yourself. It takes time and expertise to [create IAM customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html) that provide your team with only the permissions they need. To get started quickly, you can use our AWS managed policies. These policies cover common use cases and are available in your AWS account. For more information about AWS managed policies, see [AWS managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) in the *IAM User Guide*.

AWS services maintain and update AWS managed policies. You can't change the permissions in AWS managed policies. Services occasionally add additional permissions to an AWS managed policy to support new features. This type of update affects all identities (users, groups, and roles) where the policy is attached. Services are most likely to update an AWS managed policy when a new feature is launched or when new operations become available. Services do not remove permissions from an AWS managed policy, so policy updates won't break your existing permissions.

Additionally, AWS supports managed policies for job functions that span multiple services. For example, the **ReadOnlyAccess** AWS managed policy provides read-only access to all AWS services and resources. When a service launches a new feature, AWS adds read-only permissions for new operations and resources. For a list and descriptions of job function policies, see [AWS managed policies for job functions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_job-functions.html) in the *IAM User Guide*.

**Note**  
AWS IoT works with both AWS IoT and IAM policies. This topic discusses only IAM policies, which defines a policy action for control plane and data plane API operations. See also [AWS IoT Core policies](iot-policies.md).









## AWS managed policy: AWSIoTConfigAccess
<a name="security-iam-awsmanpol-AWSIoTConfigAccess"></a>





You can attach the `AWSIoTConfigAccess` policy to your IAM identities.



This policy grants the associated identity permissions that allow access to all AWS IoT configuration operations. This policy can affect data processing and storage. To view this policy in the AWS Management Console, see [AWSIoTConfigAccess](https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTConfigAccess$jsonEditor?section=permissions).



**Permissions details**

This policy includes the following permissions.




+ `iot` – Retrieve AWS IoT data and perform IoT configuration actions.



****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:AcceptCertificateTransfer",
                "iot:AddThingToThingGroup",
                "iot:AssociateTargetsWithJob",
                "iot:AttachPolicy",
                "iot:AttachPrincipalPolicy",
                "iot:AttachThingPrincipal",
                "iot:CancelCertificateTransfer",
                "iot:CancelJob",
                "iot:CancelJobExecution",
                "iot:ClearDefaultAuthorizer",
                "iot:CreateAuthorizer",
                "iot:CreateCertificateFromCsr",
                "iot:CreateJob",
                "iot:CreateKeysAndCertificate",
                "iot:CreateOTAUpdate",
                "iot:CreatePolicy",
                "iot:CreatePolicyVersion",
                "iot:CreateRoleAlias",
                "iot:CreateStream",
                "iot:CreateThing",
                "iot:CreateThingGroup",
                "iot:CreateThingType",
                "iot:CreateTopicRule",
                "iot:DeleteAuthorizer",
                "iot:DeleteCACertificate",
                "iot:DeleteCertificate",
                "iot:DeleteJob",
                "iot:DeleteJobExecution",
                "iot:DeleteOTAUpdate",
                "iot:DeletePolicy",
                "iot:DeletePolicyVersion",
                "iot:DeleteRegistrationCode",
                "iot:DeleteRoleAlias",
                "iot:DeleteStream",
                "iot:DeleteThing",
                "iot:DeleteThingGroup",
                "iot:DeleteThingType",
                "iot:DeleteTopicRule",
                "iot:DeleteV2LoggingLevel",
                "iot:DeprecateThingType",
                "iot:DescribeAuthorizer",
                "iot:DescribeCACertificate",
                "iot:DescribeCertificate",
                "iot:DescribeDefaultAuthorizer",
                "iot:DescribeEndpoint",
                "iot:DescribeEventConfigurations",
                "iot:DescribeIndex",
                "iot:DescribeJob",
                "iot:DescribeJobExecution",
                "iot:DescribeRoleAlias",
                "iot:DescribeStream",
                "iot:DescribeThing",
                "iot:DescribeThingGroup",
                "iot:DescribeThingRegistrationTask",
                "iot:DescribeThingType",
                "iot:DetachPolicy",
                "iot:DetachPrincipalPolicy",
                "iot:DetachThingPrincipal",
                "iot:DisableTopicRule",
                "iot:EnableTopicRule",
                "iot:GetEffectivePolicies",
                "iot:GetIndexingConfiguration",
                "iot:GetJobDocument",
                "iot:GetLoggingOptions",
                "iot:GetOTAUpdate",
                "iot:GetPolicy",
                "iot:GetPolicyVersion",
                "iot:GetRegistrationCode",
                "iot:GetTopicRule",
                "iot:GetV2LoggingOptions",
                "iot:ListAttachedPolicies",
                "iot:ListAuthorizers",
                "iot:ListCACertificates",
                "iot:ListCertificates",
                "iot:ListCertificatesByCA",
                "iot:ListIndices",
                "iot:ListJobExecutionsForJob",
                "iot:ListJobExecutionsForThing",
                "iot:ListJobs",
                "iot:ListOTAUpdates",
                "iot:ListOutgoingCertificates",
                "iot:ListPolicies",
                "iot:ListPolicyPrincipals",
                "iot:ListPolicyVersions",
                "iot:ListPrincipalPolicies",
                "iot:ListPrincipalThings",
                "iot:ListRoleAliases",
                "iot:ListStreams",
                "iot:ListTargetsForPolicy",
                "iot:ListThingGroups",
                "iot:ListThingGroupsForThing",
                "iot:ListThingPrincipals",
                "iot:ListThingRegistrationTaskReports",
                "iot:ListThingRegistrationTasks",
                "iot:ListThings",
                "iot:ListThingsInThingGroup",
                "iot:ListThingTypes",
                "iot:ListTopicRules",
                "iot:ListV2LoggingLevels",
                "iot:RegisterCACertificate",
                "iot:RegisterCertificate",
                "iot:RegisterThing",
                "iot:RejectCertificateTransfer",
                "iot:RemoveThingFromThingGroup",
                "iot:ReplaceTopicRule",
                "iot:SearchIndex",
                "iot:SetDefaultAuthorizer",
                "iot:SetDefaultPolicyVersion",
                "iot:SetLoggingOptions",
                "iot:SetV2LoggingLevel",
                "iot:SetV2LoggingOptions",
                "iot:StartThingRegistrationTask",
                "iot:StopThingRegistrationTask",
                "iot:TestAuthorization",
                "iot:TestInvokeAuthorizer",
                "iot:TransferCertificate",
                "iot:UpdateAuthorizer",
                "iot:UpdateCACertificate",
                "iot:UpdateCertificate",
                "iot:UpdateEventConfigurations",
                "iot:UpdateIndexingConfiguration",
                "iot:UpdateRoleAlias",
                "iot:UpdateStream",
                "iot:UpdateThing",
                "iot:UpdateThingGroup",
                "iot:UpdateThingGroupsForThing",
                "iot:UpdateAccountAuditConfiguration",
                "iot:DescribeAccountAuditConfiguration",
                "iot:DeleteAccountAuditConfiguration",
                "iot:StartOnDemandAuditTask",
                "iot:CancelAuditTask",
                "iot:DescribeAuditTask",
                "iot:ListAuditTasks",
                "iot:CreateScheduledAudit",
                "iot:UpdateScheduledAudit",
                "iot:DeleteScheduledAudit",
                "iot:DescribeScheduledAudit",
                "iot:ListScheduledAudits",
                "iot:ListAuditFindings",
                "iot:CreateSecurityProfile",
                "iot:DescribeSecurityProfile",
                "iot:UpdateSecurityProfile",
                "iot:DeleteSecurityProfile",
                "iot:AttachSecurityProfile",
                "iot:DetachSecurityProfile",
                "iot:ListSecurityProfiles",
                "iot:ListSecurityProfilesForTarget",
                "iot:ListTargetsForSecurityProfile",
                "iot:ListActiveViolations",
                "iot:ListViolationEvents",
                "iot:ValidateSecurityProfileBehaviors"
            ],
            "Resource": "*"
        }
    ]
}
```

## AWS managed policy: AWSIoTConfigReadOnlyAccess
<a name="security-iam-awsmanpol-AWSIoTConfigReadOnlyAccess"></a>





You can attach the `AWSIoTConfigReadOnlyAccess` policy to your IAM identities.



This policy grants the associated identity permissions that allow read-only access to all AWS IoT configuration operations. To view this policy in the AWS Management Console, see [AWSIoTConfigReadOnlyAccess](https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTConfigReadOnlyAccess$jsonEditor?section=permissions).



**Permissions details**

This policy includes the following permissions.




+ `iot` – Perform read-only operations of IoT configuration actions.



****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:DescribeAuthorizer",
                "iot:DescribeCACertificate",
                "iot:DescribeCertificate",
                "iot:DescribeDefaultAuthorizer",
                "iot:DescribeEndpoint",
                "iot:DescribeEventConfigurations",
                "iot:DescribeIndex",
                "iot:DescribeJob",
                "iot:DescribeJobExecution",
                "iot:DescribeRoleAlias",
                "iot:DescribeStream",
                "iot:DescribeThing",
                "iot:DescribeThingGroup",
                "iot:DescribeThingRegistrationTask",
                "iot:DescribeThingType",
                "iot:GetEffectivePolicies",
                "iot:GetIndexingConfiguration",
                "iot:GetJobDocument",
                "iot:GetLoggingOptions",
                "iot:GetOTAUpdate",
                "iot:GetPolicy",
                "iot:GetPolicyVersion",
                "iot:GetRegistrationCode",
                "iot:GetTopicRule",
                "iot:GetV2LoggingOptions",
                "iot:ListAttachedPolicies",
                "iot:ListAuthorizers",
                "iot:ListCACertificates",
                "iot:ListCertificates",
                "iot:ListCertificatesByCA",
                "iot:ListIndices",
                "iot:ListJobExecutionsForJob",
                "iot:ListJobExecutionsForThing",
                "iot:ListJobs",
                "iot:ListOTAUpdates",
                "iot:ListOutgoingCertificates",
                "iot:ListPolicies",
                "iot:ListPolicyPrincipals",
                "iot:ListPolicyVersions",
                "iot:ListPrincipalPolicies",
                "iot:ListPrincipalThings",
                "iot:ListRoleAliases",
                "iot:ListStreams",
                "iot:ListTargetsForPolicy",
                "iot:ListThingGroups",
                "iot:ListThingGroupsForThing",
                "iot:ListThingPrincipals",
                "iot:ListThingRegistrationTaskReports",
                "iot:ListThingRegistrationTasks",
                "iot:ListThings",
                "iot:ListThingsInThingGroup",
                "iot:ListThingTypes",
                "iot:ListTopicRules",
                "iot:ListV2LoggingLevels",
                "iot:SearchIndex",
                "iot:TestAuthorization",
                "iot:TestInvokeAuthorizer",
                "iot:DescribeAccountAuditConfiguration",
                "iot:DescribeAuditTask",
                "iot:ListAuditTasks",
                "iot:DescribeScheduledAudit",
                "iot:ListScheduledAudits",
                "iot:ListAuditFindings",
                "iot:DescribeSecurityProfile",
                "iot:ListSecurityProfiles",
                "iot:ListSecurityProfilesForTarget",
                "iot:ListTargetsForSecurityProfile",
                "iot:ListActiveViolations",
                "iot:ListViolationEvents",
                "iot:ValidateSecurityProfileBehaviors"
            ],
            "Resource": "*"
        }
    ]
}
```

## AWS managed policy: AWSIoTDataAccess
<a name="security-iam-awsmanpol-AWSIoTDataAccess"></a>





You can attach the `AWSIoTDataAccess` policy to your IAM identities.



This policy grants the associated identity permissions that allow access to all AWS IoT data operations. Data operations send data over MQTT or HTTP protocols. To view this policy in the AWS Management Console, see [https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTDataAccess?section=permissions](https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTDataAccess?section=permissions).



**Permissions details**

This policy includes the following permissions.




+ `iot` – Retrieve AWS IoT data and allow full access to AWS IoT messaging actions.



****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect",
                "iot:Publish",
                "iot:Subscribe",
                "iot:Receive",
                "iot:GetThingShadow",
                "iot:UpdateThingShadow",
                "iot:DeleteThingShadow",
                "iot:ListNamedShadowsForThing"
            ],
            "Resource": "*"
        }
    ]
}
```

## AWS managed policy: AWSIoTFullAccess
<a name="security-iam-awsmanpol-AWSIoTFullAccess"></a>





You can attach the `AWSIoTFullAccess` policy to your IAM identities.



This policy grants the associated identity permissions that allow access to all AWS IoT configuration and messaging operations. To view this policy in the AWS Management Console, see [https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTFullAccess?section=permissions](https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTFullAccess?section=permissions).



**Permissions details**

This policy includes the following permissions.




+ `iot` – Retrieve AWS IoT data and allow full access to AWS IoT configuration and messaging actions.
+ `iotjobsdata` – Retrieve AWS IoT Jobs data and allow full access to AWS IoT Jobs data plane API operations.



****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:*",
                "iotjobsdata:*"
            ],
            "Resource": "*"
        }
    ]
}
```

## AWS managed policy: AWSIoTLogging
<a name="security-iam-awsmanpol-AWSIoTLogging"></a>





You can attach the `AWSIoTLogging` policy to your IAM identities.



This policy grants the associated identity permissions that allow access to create Amazon CloudWatch Logs groups and stream logs to the groups. This policy is attached to your CloudWatch logging role. To view this policy in the AWS Management Console, see [https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTLogging?section=permissions](https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTLogging?section=permissions).



**Permissions details**

This policy includes the following permissions.




+ `logs` – Retrieve CloudWatch logs. Also allows creation of CloudWatch Logs groups and stream logs to the groups.



****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents",
                "logs:PutMetricFilter",
                "logs:PutRetentionPolicy",
                "logs:GetLogEvents",
                "logs:DeleteLogStream"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

## AWS managed policy: AWSIoTOTAUpdate
<a name="security-iam-awsmanpol-AWSIoTOTAUpdate"></a>





You can attach the `AWSIoTOTAUpdate` policy to your IAM identities.



This policy grants the associated identity permissions that allow access to create AWS IoT jobs, AWS IoT code signing jobs, and to describe AWS code signer jobs. To view this policy in the AWS Management Console, see [`AWSIoTOTAUpdate`.](https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTOTAUpdate?section=permissions)



**Permissions details**

This policy includes the following permissions.




+ `iot` – Create AWS IoT jobs and code signing jobs.
+ `signer` – Perform creation of AWS code signer jobs.



****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Action": [
            "iot:CreateJob",
            "signer:DescribeSigningJob"
        ],
        "Resource": "*"
    }
}
```

## AWS managed policy: AWSIoTRuleActions
<a name="security-iam-awsmanpol-AWSIoTRuleActions"></a>





You can attach the `AWSIoTRuleActions` policy to your IAM identities.



This policy grants the associated identity permissions that allow access to all AWS services supported in AWS IoT rule actions. To view this policy in the AWS Management Console, see [https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTRuleActions?section=permissions](https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTRuleActions?section=permissions).



**Permissions details**

This policy includes the following permissions.




+ `iot` - Perform actions for publishing rule action messages.
+ `dynamodb` - Insert a message into a DynamoDB table or split a message into multiple columns of a DynamoDB table.
+ `s3` - Store an object in an Amazon S3 bucket.
+ `kinesis` - Send a message to an Amazon Kinesis stream object.
+ `firehose` - Insert a record in a Firehose stream object.
+ `cloudwatch` - Change CloudWatch alarm state or send message data to CloudWatch metric.
+ `sns` - Perform operation to publish a notification using Amazon SNS. This operation is scoped to AWS IoT SNS topics.
+ `sqs` - Insert a message to add to the SQS queue.
+ `es` - Send a message to the OpenSearch Service service.



****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Action": [
            "dynamodb:PutItem",
            "kinesis:PutRecord",
            "iot:Publish",
            "s3:PutObject",
            "sns:Publish",
            "sqs:SendMessage*",
            "cloudwatch:SetAlarmState",
            "cloudwatch:PutMetricData",
            "es:ESHttpPut",
            "firehose:PutRecord"
        ],
        "Resource": "*"
    }
}
```

## AWS managed policy: AWSIoTThingsRegistration
<a name="security-iam-awsmanpol-AWSIoTThingsRegistration"></a>





You can attach the `AWSIoTThingsRegistration` policy to your IAM identities.



This policy grants the associated identity permissions that allow access to register things in bulk using the `StartThingRegistrationTask` API. This policy can affect data processing and storage. To view this policy in the AWS Management Console, see [https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTThingsRegistration?section=permissions](https://console.aws.amazon.com//iam/home#/policies/arn:aws:iam::aws:policy/AWSIoTThingsRegistration?section=permissions).



**Permissions details**

This policy includes the following permissions.




+ `iot` - Perform actions for creating things and attaching policies and certificates when registering in bulk.



****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:AddThingToThingGroup",
                "iot:AttachPolicy",
                "iot:AttachPrincipalPolicy",
                "iot:AttachThingPrincipal",
                "iot:CreateCertificateFromCsr",
                "iot:CreatePolicy",
                "iot:CreateThing",
                "iot:DescribeCertificate",
                "iot:DescribeThing",
                "iot:DescribeThingGroup",
                "iot:DescribeThingType",
                "iot:DetachPolicy",
                "iot:DetachThingPrincipal",
                "iot:GetPolicy",
                "iot:ListAttachedPolicies",
                "iot:ListPolicyPrincipals",
                "iot:ListPrincipalPolicies",
                "iot:ListPrincipalThings",
                "iot:ListTargetsForPolicy",
                "iot:ListThingGroupsForThing",
                "iot:ListThingPrincipals",
                "iot:RegisterCertificate",
                "iot:RegisterThing",
                "iot:RemoveThingFromThingGroup",
                "iot:UpdateCertificate",
                "iot:UpdateThing",
                "iot:UpdateThingGroupsForThing",
                "iot:AddThingToBillingGroup",
                "iot:DescribeBillingGroup",
                "iot:RemoveThingFromBillingGroup"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```





## AWS IoT updates to AWS managed policies
<a name="security-iam-awsmanpol-updates"></a>



View details about updates to AWS managed policies for AWS IoT since this service began tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the AWS IoT Document history page.




| Change | Description | Date | 
| --- | --- | --- | 
|  [AWSIoTFullAccess](#security-iam-awsmanpol-AWSIoTFullAccess) – Update to an existing policy  |  AWS IoT added new permissions to allow users to access AWS IoT Jobs data plane API operations using the HTTP protocol. A new IAM policy prefix, `iotjobsdata:`, provides you finer grained access control to access AWS IoT Jobs data plane endpoints. For control plane API operations, you still use the `iot:` prefix. For more information, see [AWS IoT Core policies for HTTPS protocol](iot-data-plane-jobs.md#iot-jobs-data-http).  | May 11, 2022 | 
|  AWS IoT started tracking changes  |  AWS IoT started tracking changes for its AWS managed policies.  | May 11, 2022 | 

# Troubleshooting AWS IoT identity and access
<a name="security_iam_troubleshoot"></a>

Use the following information to help you diagnose and fix common issues that you might encounter when working with AWS IoT and IAM.

**Topics**
+ [I am not authorized to perform an action in AWS IoT](#security_iam_troubleshoot-no-permissions)
+ [I am not authorized to perform iam:PassRole](#security_iam_troubleshoot-passrole)
+ [I want to allow people outside of my AWS account to access my AWS IoT resources](#security_iam_troubleshoot-cross-account-access)

## I am not authorized to perform an action in AWS IoT
<a name="security_iam_troubleshoot-no-permissions"></a>

If you receive an error that you're not authorized to perform an action, your policies must be updated to allow you to perform the action.

The following example error occurs when the IAM user, `mateojackson`, tries to use the console to view details about a thing resource but doesn't have the `iot:DescribeThing` permissions.

```
User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: iot:DescribeThing on resource: MyIoTThing
```

In this case, the policy for the `mateojackson` user must be updated to allow access to the thing resource by using the `iot:DescribeThing` action. 

If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials.

Using AWS IoT Device Advisor  
If you're using AWS IoT Device Advisor, the following example error occurs when the user `mateojackson` tries to use the console to view details about a suite definition but doesn't have the `iotdeviceadvisor:GetSuiteDefinition` permissions.  

```
User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: iotdeviceadvisor:GetSuiteDefinition on resource: MySuiteDefinition
```
In this case, the policy for the `mateojackson` user must be updated to allow access to the *`MySuiteDefinition`* resource using the `iotdeviceadvisor:GetSuiteDefinition` action.

## I am not authorized to perform iam:PassRole
<a name="security_iam_troubleshoot-passrole"></a>

If you receive an error that you're not authorized to perform the `iam:PassRole` action, your policies must be updated to allow you to pass a role to AWS IoT.

Some AWS services allow you to pass an existing role to that service instead of creating a new service role or service-linked role. To do this, you must have permissions to pass the role to the service.

The following example error occurs when an IAM user named `marymajor` tries to use the console to perform an action in AWS IoT. However, the action requires the service to have permissions that are granted by a service role. Mary does not have permissions to pass the role to the service.

```
User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole
```

In this case, Mary's policies must be updated to allow her to perform the `iam:PassRole` action.

If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials.

## I want to allow people outside of my AWS account to access my AWS IoT resources
<a name="security_iam_troubleshoot-cross-account-access"></a>

You can create a role that users in other accounts or people outside of your organization can use to access your resources. You can specify who is trusted to assume the role. For services that support resource-based policies or access control lists (ACLs), you can use those policies to grant people access to your resources.

To learn more, consult the following:
+ To learn whether AWS IoT supports these features, see [How AWS IoT works with IAM](security_iam_service-with-iam.md).
+ To learn how to provide access to your resources across AWS accounts that you own, see [Providing access to an IAM user in another AWS account that you own](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html) in the *IAM User Guide*.
+ To learn how to provide access to your resources to third-party AWS accounts, see [Providing access to AWS accounts owned by third parties](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_third-party.html) in the *IAM User Guide*.
+ To learn how to provide access through identity federation, see [Providing access to externally authenticated users (identity federation)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_federated-users.html) in the *IAM User Guide*.
+ To learn the difference between using roles and resource-based policies for cross-account access, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the *IAM User Guide*.

# Logging and Monitoring
<a name="security-logging"></a>

Monitoring is an important part of maintaining the reliability, availability, and performance of AWS IoT and your AWS solutions. You should collect monitoring data from all parts of your AWS solution so that you can more easily debug a multi-point failure, if one occurs. For information on logging and monitoring procedures, see [Monitoring AWS IoT](monitoring_overview.md)

## Monitoring Tools
<a name="monitoring_automated_manual"></a>

AWS provides tools that you can use to monitor AWS IoT. You can configure some of these tools to do the monitoring for you. Some of the tools require manual intervention. We recommend that you automate monitoring tasks as much as possible.

### Automated Monitoring Tools
<a name="monitoring_automated_tools"></a>

You can use the following automated monitoring tools to watch AWS IoT and report when something is wrong:
+ **Amazon CloudWatch Alarms** – Watch a single metric over a time period that you specify, and perform one or more actions based on the value of the metric relative to a given threshold over a number of time periods. The action is a notification sent to an Amazon Simple Notification Service (Amazon SNS) topic or Amazon EC2 Auto Scaling policy. CloudWatch alarms do not invoke actions simply because they are in a particular state. The state must have changed and been maintained for a specified number of periods. For more information, see [Monitor AWS IoT alarms and metrics using Amazon CloudWatch](monitoring-cloudwatch.md).
+ **Amazon CloudWatch Logs** – Monitor, store, and access your log files from AWS CloudTrail or other sources. Amazon CloudWatch Logs also allows you to see critical steps AWS IoT Device Advisor test cases take, generated events and MQTT messages sent from your devices or AWS IoT Core during test execution. These logs make it possible to debug and take corrective actions on your devices. For more information, see [Monitor AWS IoT using CloudWatch Logs](cloud-watch-logs.md) For more information about using Amazon CloudWatch, see [Monitoring Log Files](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/WhatIsCloudWatchLogs.html) in the *Amazon CloudWatch User Guide*.
+ **Amazon CloudWatch Events** – Match events and route them to one or more target functions or streams to make changes, capture state information, and take corrective action. For more information, see [What Is Amazon CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/WhatIsCloudWatchEvents.html) in the *Amazon CloudWatch User Guide*.
+ **AWS CloudTrail Log Monitoring** – Share log files between accounts, monitor CloudTrail log files in real time by sending them to CloudWatch Logs, write log processing applications in Java, and validate that your log files have not changed after delivery by CloudTrail. For more information, see [Logging AWS IoT API calls using AWS CloudTrail](iot-using-cloudtrail.md) and also [Working with CloudTrail Log Files](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-working-with-log-files.html) in the *AWS CloudTrail User Guide*. 

### Manual Monitoring Tools
<a name="monitoring_manual_tools"></a>

Another important part of monitoring AWS IoT involves manually monitoring those items that the CloudWatch alarms don't cover. The AWS IoT, CloudWatch, and other AWS service console dashboards provide an at-a-glance view of the state of your AWS environment. We recommend that you also check the log files on AWS IoT.
+ AWS IoT dashboard shows:
  + CA certificates
  + Certificates
  + Polices
  + Rules
  + Things
+ CloudWatch home page shows:
  + Current alarms and status.
  + Graphs of alarms and resources.
  + Service health status.

  You can use CloudWatch to do the following: 
  + Create [customized dashboards](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CloudWatch_Dashboards.html) to monitor the services you care about.
  + Graph metric data to troubleshoot issues and discover trends.
  + Search and browse all your AWS resource metrics.
  + Create and edit alarms to be notified of problems.

# Compliance validation for AWS IoT Core
<a name="compliance"></a>

To learn whether an AWS service is within the scope of specific compliance programs, see [AWS services in Scope by Compliance Program](https://aws.amazon.com/compliance/services-in-scope/) and choose the compliance program that you are interested in. For general information, see [AWS Compliance Programs](https://aws.amazon.com/compliance/programs/).

You can download third-party audit reports using AWS Artifact. For more information, see [Downloading Reports in AWS Artifact](https://docs.aws.amazon.com/artifact/latest/ug/downloading-documents.html).

Your compliance responsibility when using AWS services is determined by the sensitivity of your data, your company's compliance objectives, and applicable laws and regulations. For more information about your compliance responsibility when using AWS services, see [AWS Security Documentation](https://docs.aws.amazon.com/security/).

# Resilience in AWS IoT Core
<a name="disaster-recovery-resiliency"></a>

The AWS global infrastructure is built around AWS Regions and Availability Zones. AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected with low-latency, high-throughput, and highly redundant networking. With Availability Zones, you can design and operate applications and databases that automatically fail over between Availability Zones without interruption. Availability Zones are more highly available, fault tolerant, and scalable than traditional single or multiple data center infrastructures. 

For more information about AWS Regions and Availability Zones, see [AWS Global Infrastructure](https://aws.amazon.com/about-aws/global-infrastructure/).

AWS IoT Core stores information about your devices in the device registry. It also stores CA certificates, device certificates, and device shadow data. In the event of hardware or network failures, this data is automatically replicated across Availability Zones but not across Regions.

AWS IoT Core publishes MQTT events when the device registry is updated. You can use these messages to back up your registry data and save it somewhere, like a DynamoDB table. You are responsible for saving certificates that AWS IoT Core creates for you or those you create yourself. Device shadow stores state data about your devices and can be resent when a device comes back online. AWS IoT Device Advisor stores information about your test suite configuration. This data is automatically replicated in the event of hardware or network failures.

AWS IoT Core resources are Region-specific and aren't replicated across AWS Regions unless you specifically do so.

For information about Security best practices, see [Security best practices in AWS IoT Core](security-best-practices.md).

# Using AWS IoT Core with interface VPC endpoints
<a name="IoTCore-VPC"></a>

With AWS IoT Core, you can create [IoT control plane endpoints](https://docs.aws.amazon.com//iot/latest/developerguide/connect-to-iot.html#iot-service-endpoint-intro) and [IoT data endpoints](https://docs.aws.amazon.com//iot/latest/developerguide/iot-connect-devices.html) within your virtual private cloud (VPC) by using [interface VPC endpoints](https://docs.aws.amazon.com//vpc/latest/userguide/vpce-interface.html#create-interface-endpoint). Interface VPC endpoints are powered by AWS PrivateLink, an AWS technology that you can use to access services running on AWS by using private IP addresses. For more information, see [Amazon Virtual Private Cloud](https://docs.aws.amazon.com//AmazonVPC/latest/UserGuide/VPC_Introduction.html). 

To connect devices in the field on remote networks, such as a corporate network to your Amazon VPC, refer to the options listed in the [Network-to-Amazon VPC connectivity matrix](https://docs.aws.amazon.com//whitepapers/latest/aws-vpc-connectivity-options/network-to-amazon-vpc-connectivity-options.html). 

**Topics**
+ [Creating VPC endpoints for AWS IoT Core control plane](#Create-VPC-endpoints-CP)
+ [Creating VPC endpoints for AWS IoT Core data plane](#Create-VPC-endpoints)
+ [Creating VPC endpoints for AWS IoT Core credential provider](#Create-VPC-endpoints-credential-provider)
+ [Creating an Amazon VPC interface endpoint](#Create-VPC-endpoints-core-create-vpc)
+ [Configure a private hosted zone](#connect-iot-core-create-phz-lns)
+ [Controlling Access to AWS IoT Core over VPC endpoints](#Control-VPC-access)
+ [Limitations](#VPC-limitations)
+ [Scaling VPC endpoints with AWS IoT Core](#Scaling-VPC-endpoints)
+ [Using custom domains with VPC endpoints](#VPC-custom-domains)
+ [Availability of VPC endpoints for AWS IoT Core](#VPC-availability)
+ [Using AWS IoT Device Management secure tunneling with interface VPC endpoints](IoTCore-ST-VPC.md)

## Creating VPC endpoints for AWS IoT Core control plane
<a name="Create-VPC-endpoints-CP"></a>

You can create a VPC endpoint for AWS IoT Core control plane API to connect your devices to AWS IoT services and other AWS services. To get started with VPC endpoints, [create an interface VPC endpoint](https://docs.aws.amazon.com//vpc/latest/privatelink/vpce-interface.html#create-interface-endpoint) and select AWS IoT Core as the AWS service. If you are using the CLI, first call [describe-vpc-endpoint-services](https://docs.aws.amazon.com//cli/latest/reference/ec2/describe-vpc-endpoint-services.html) to ensure that you are choosing an Availability Zone where AWS IoT Core is present in your particular AWS Region. For example, in us-east-1, this command would look like:

```
aws ec2 describe-vpc-endpoint-services --service-name com.amazonaws.us-east-1.iot.api
```

See the detailed instructions below to [Create an Amazon VPC interface endpoint](#Create-VPC-endpoints-core-create-vpc) for AWS IoT Core control plane.

## Creating VPC endpoints for AWS IoT Core data plane
<a name="Create-VPC-endpoints"></a>

You can create a VPC endpoint for AWS IoT Core data plane API to connect your devices to AWS IoT services and other AWS services. To get started with VPC endpoints, [create an interface VPC endpoint](https://docs.aws.amazon.com//vpc/latest/privatelink/vpce-interface.html#create-interface-endpoint) and select AWS IoT Core as the AWS service. If you are using the CLI, first call [describe-vpc-endpoint-services](https://docs.aws.amazon.com//cli/latest/reference/ec2/describe-vpc-endpoint-services.html) to ensure that you are choosing an Availability Zone where AWS IoT Core is present in your particular AWS Region. For example, in us-east-1, this command would look like:

```
aws ec2 describe-vpc-endpoint-services --service-name com.amazonaws.us-east-1.iot.data
```

**Note**  
The VPC feature for automatically creating a DNS record is disabled. To connect to these endpoints, you must manually create a Private DNS record. For more information about Private VPC DNS records, see [Private DNS for interface endpoints](https://docs.aws.amazon.com//vpc/latest/privatelink/vpce-interface.html#vpce-private-dns). For more information about AWS IoT Core VPC limitations, see [Limitations](#VPC-limitations) .

To connect MQTT clients to the VPC endpoint interfaces:
+ You must manually create DNS records in a private hosted zone that is attached to your VPC. To get started, see [Creating a private hosted zone](https://docs.aws.amazon.com//Route53/latest/DeveloperGuide/hosted-zone-private-creating.html). 
+ Within your private hosted zone, create an alias record for each elastic network interface IP for the VPC endpoint. If you have multiple network interface IPs for multiple VPC endpoints, create weighted DNS records with equal weights across all the weighted records. These IP addresses are available from the [DescribeNetworkInterfaces](https://docs.aws.amazon.com//AWSEC2/latest/APIReference/API_DescribeNetworkInterfaces.html) API call when filtered by the VPC endpoint ID in the description field.

See the detailed instructions below to [Create an Amazon VPC interface endpoint](#Create-VPC-endpoints-core-create-vpc) and [Configure private hosted zone](#connect-iot-core-create-phz-lns) for AWS IoT Core data plane.

## Creating VPC endpoints for AWS IoT Core credential provider
<a name="Create-VPC-endpoints-credential-provider"></a>

You can create a VPC endpoint for AWS IoT Core [credential provider](https://docs.aws.amazon.com//iot/latest/developerguide/authorizing-direct-aws.html) to connect devices using client certificate-based authentication and get temporary AWS credentials in [AWS Signature Version 4 format](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_aws-signing.html). To get started with VPC endpoints for AWS IoT Core credential provider, run the [create-vpc-endpoint](https://docs.aws.amazon.com//cli/latest/reference/ec2/create-vpc-endpoint.html) CLI command to [create an interface VPC endpoint](https://docs.aws.amazon.com//vpc/latest/privatelink/vpce-interface.html#create-interface-endpoint) and select AWS IoT Core credential provider as the AWS service. To ensure that you are choosing an Availability Zone where AWS IoT Core is present in your particular AWS Region, your first run the [describe-vpc-endpoint-services](https://docs.aws.amazon.com//cli/latest/reference/ec2/describe-vpc-endpoint-services.html) command. For example, in us-east-1, this command would look like:

```
aws ec2 describe-vpc-endpoint-services --service-name com.amazonaws.us-east-1.iot.credentials
```

**Note**  
The VPC feature for automatically creating a DNS record is disabled. To connect to these endpoints, you must manually create a Private DNS record. For more information about Private VPC DNS records, see [Private DNS for interface endpoints](https://docs.aws.amazon.com//vpc/latest/privatelink/vpce-interface.html#vpce-private-dns). For more information about AWS IoT Core VPC limitations, see [Limitations](#VPC-limitations) .

To connect HTTP clients to the VPC endpoint interfaces:
+ You must manually create DNS records in a private hosted zone that is attached to your VPC. To get started, see [Creating A private hosted zone](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-creating.html). 
+ Within your private hosted zone, create an alias record for each elastic network interface IP for the VPC endpoint. If you have multiple network interface IPs for multiple VPC endpoints, create weighted DNS records with equal weights across all the weighted records. These IP addresses are available from the [DescribeNetworkInterfaces](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeNetworkInterfaces.html) API call when filtered by the VPC endpoint ID in the description field.

See the detailed instructions below to [Create an Amazon VPC interface endpoint](#Create-VPC-endpoints-core-create-vpc) and [Configure private hosted zone](#connect-iot-core-create-phz-lns) for AWS IoT Core credential provider.

## Creating an Amazon VPC interface endpoint
<a name="Create-VPC-endpoints-core-create-vpc"></a>

You can create an interface VPC endpoint to connect to AWS services powered by AWS PrivateLink. Use the following procedure to create an interface VPC endpoint that connects to AWS IoT Core data plane or AWS IoT Core credential provider. For more information, see [Access an AWS service using an interface VPC endpoint](https://docs.aws.amazon.com//vpc/latest/privatelink/create-interface-endpoint.html). 

**Note**  
The processes to create an Amazon VPC interface endpoint for AWS IoT Core data plane and AWS IoT Core credential provider are similar, but you must make endpoint specific changes to make the connection work.

 **To create an interface VPC endpoint using [VPC](https://console.aws.amazon.com/vpc/home#/endpoints) **Endpoints** console** 

1. Navigate to the [VPC](https://console.aws.amazon.com/vpc/home#/endpoints) **Endpoints** console, under **Virtual private cloud** on the left menu, choose **Endpoints** then **Create Endpoint**. 

1. In the **Create endpoint** page, specify the following information.
   + Choose **AWS services** for **Service category**. 
   + For **Service Name**, search by entering the keyword `iot`. In the list of `iot` services displayed, choose the endpoint. 

     If you create a VPC endpoint for AWS IoT Core control plane, choose the AWS IoT Core control plane API endpoint for your AWS Region. The endpoint will be of the format `com.amazonaws.region.iot.api`. 

     If you create a VPC endpoint for AWS IoT Core data plane, choose the AWS IoT Core data plane API endpoint for your Region. The endpoint will be of the format `com.amazonaws.region.iot.data`. 

     If you create a VPC endpoint for AWS IoT Core credential provider, choose the AWS IoT Core credential provider endpoint for your Region. The endpoint will be of the format `com.amazonaws.region.iot.credentials`. 

     If you create a VPC endpoint for Federal Information Processing Standard (FIPS) regions, choose the FIPS API endpoint for your AWS Region. The endpoint will be of the format `com.amazonaws.region.iot-fips.api`. This is only for control plane.
**Note**  
The service name for AWS IoT Core data plane in China Region will be of the format `cn.com.amazonaws.region.iot.data`. The service name for AWS IoT Core control plane in China Region will be of the format `com.amazonaws.region.iot.api`. 
   + For **VPC** and **Subnets**, choose the VPC where you want to create the endpoint, and the Availability Zones (AZs) in which you want to create the endpoint network.
   + For **Enable DNS name**, make sure that **Enable for this endpoint** is not selected for AWS IoT Core data plane and AWS IoT Core credential provider. Neither AWS IoT Core data plane nor AWS IoT Core credential provider supports private DNS names yet.

     For AWS IoT Core control plane, **Enable DNS name** is selected by default. This ensures that any requests to the AWS IoT Core control plane public endpoints will route through the VPC endpoints instead. When this is enabled, you do not need to configure a privated hosted zone.
   + For **Security group**, choose the security groups you want to associate with the endpoint network interfaces.
   + Optionally, you can add or remove tags. Tags are name-value pairs that you use to associate with your endpoint. 

1. To create your VPC endpoint, choose **Create endpoint**. 

After you create the AWS PrivateLink endpoint, in the **Details** tab of your endpoint, you'll see a list of DNS names. You can use one of these DNS names you created in this section to [configure your private hosted zone](#connect-iot-core-create-phz-lns). If you are using AWS IoT Core control plane, you do not need to configure a private hosted zone.

## Configure a private hosted zone
<a name="connect-iot-core-create-phz-lns"></a>

**Note**  
If you are using AWS IoT Core control plane and have **Enable DNS name** selected, you do not need to configure a private hosted zone. If you disable it, you must follow this procedure to configure a private hosted zone.

You can use one of these DNS names you created in the previous section to configure your private hosted zone.

 **For AWS IoT Core data plane** 

The DNS name must be your domain configuration name or your `IoT:Data-ATS` endpoint. An example DNS name can be: ` xxx-ats.data.iot.region.amazonaws.com`. 

 **For AWS IoT Core credential provider** 

The DNS name must be your `iot:CredentialProvider` endpoint. An example DNS name can be: ` xxxx.credentials.iot.region.amazonaws.com`. 

 **For AWS IoT Core control plane** 

The DNS name must be your AWS IoT Core control plane endpoint. An example DNS name for AWS IoT Core control plane is ` xxxx.api.iot.region.amazonaws.com`. 

**Note**  
The processes to configure private hosted zone for AWS IoT Core data plane and AWS IoT Core credential provider are similar, but you must make endpoint specific changes to make the connection work.

### Create a private hosted zone
<a name="connect-iot-core-create-phz-lns-private-hosted-zone"></a>

 **To create a private hosted zone using Route 53 console** 

1. Navigate to the [Route 53](https://console.aws.amazon.com/route53/v2/hostedzones#/) **Hosted zones** console and choose **Create hosted zone**. 

1. In the **Create hosted zone** page, specify the following information.
   + For **Domain name**, enter the endpoint address for your `iot:Data-ATS` or `iot:CredentialProvider` endpoint. The following AWS CLI command shows how to get the endpoint through a public network: `aws iot describe-endpoint --endpoint-type iot:Data-ATS`, or `aws iot describe-endpoint --endpoint-type iot:CredentialProvider`. 
**Note**  
If you're using custom domains, see [ Using custom domains with VPC endpoints](https://docs.aws.amazon.com/iot/latest/developerguide/IoTCore-VPC.html#VPC-custom-domains). Custom domains are not supported for AWS IoT Core credential provider.
   + For **Type**, choose **Private hosted zone**. 
   + Optionally, you can add or remove tags to associate with your hosted zone.

1. To create your private hosted zone, choose **Create hosted zone**. 

For more information, see [Creating a private hosted zone](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-creating.html). 

### Create a record
<a name="connect-iot-core-create-phz-lns-create-record"></a>

After you have created a private hosted zone, you can create a record that tells the DNS how you want traffic to be routed to that domain. 

 **To create a record** 

1. In the list of hosted zones displayed, choose the private hosted zone that you created earlier and choose **Create record**. 

1. Use the wizard method to create the record. If the console presents you the **Quick create** method, choose **Switch to wizard**. 

1. Choose **Simple Routing** for **Routing policy** and then choose **Next**. 

1. In the **Configure records** page, choose **Define simple record**. 

1. In the **Define simple record** page:
   + For **Record name**, enter `iot:Data-ATS` endpoint or `iot:CredentialProvider` endpoint. This must be the same as the private hosted zone name.
   + For **Record type**, if you want only IPv4 support, keep the value as `A - Routes traffic to an IPv4 address and some AWS resources`. If you want only IPv6 support, keep the value as `AAAA - Routes traffic to an IPv6 address and some AWS resources`. If you want dual-stack support (both IPv4 and IPv6), create two records (`A` and `AAAA` in the hosted zone with the same **Record name** and **Value/Route traffic to**. 
   + For **Value/Route traffic to**, choose **Alias to VPC endpoint**. Then choose your **Region** and then choose the endpoint that you created previously, as described in [Creating an Amazon VPC interface endpoint](#Create-VPC-endpoints-core-create-vpc) from the list of endpoints displayed.

1. Choose **Define simple record** to create your record.

## Controlling Access to AWS IoT Core over VPC endpoints
<a name="Control-VPC-access"></a>

You can restrict device access to AWS IoT Core to be allowed only through VPC endpoint by using VPC [condition context keys](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_condition-keys.html). AWS IoT Core supports the following VPC related context keys:
+  [SourceVpc](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcevpc) 
+  [SourceVpce](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcevpce) 
+  [VPCSourceIp](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-vpcsourceip) 

**Note**  
AWS IoT Core doesn't support [Endpoints policies for VPC endpoints](https://docs.aws.amazon.com//vpc/latest/privatelink/vpc-endpoints-access.html#vpc-endpoint-policies). 

For example, the following policy grants permission to connect to AWS IoT Core using a client ID that matches the thing name, and to publish to any topic prefixed by the thing name, conditional on the device connecting to a VPC endpoint with a particular VPC Endpoint ID. This policy would deny connection attempts to your public IoT data endpoint.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:SourceVpce": "vpce-1a2b3c4d"
            }
        }
            
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/${iot:Connection.Thing.ThingName}/*"
            ]
        }
    ]
}
```

## Limitations
<a name="VPC-limitations"></a>

VPC endpoints are currently supported for [AWS IoT Core control plane endpoints](https://docs.aws.amazon.com//iot/latest/developerguide/connect-to-iot.html#iot-service-endpoint-intro), [AWS IoT Core data endpoints](https://docs.aws.amazon.com//iot/latest/developerguide/iot-connect-devices.html#iot-connect-device-endpoints), and [AWS IoT Core credential provider](https://docs.aws.amazon.com//iot/latest/developerguide/authorizing-direct-aws.htm) endpoints. VPC endpoints are only supported for [Federal Information Processing Standard (FIPS) endpoints](https://docs.aws.amazon.com//iot/latest/developerguide/iot-connect-fips.html) when using the AWS IoT Core control plane.

### Limitations of IoT control plane VPC endpoints
<a name="VPC-limitations-iot-control"></a>

This section covers the limitations of IoT control plane VPC endpoints.
+ VPC endpoints will serve ATS certificates only.
+ Custom domains are not supported for control plane endpoints.
+ For information regarding FIPS security policies, see [FIPS security policies](https://docs.aws.amazon.com//elasticloadbalancing/latest/application/describe-ssl-policies.html#fips-security-policies). 

### Limitations of IoT data VPC endpoints
<a name="VPC-limitations-iot-data"></a>

This section covers the limitations of IoT data VPC endpoints.
+ MQTT keep alive periods are limited to 230 seconds. Keep alive periods longer than that will be automatically reduced to 230 seconds.
+ Each VPC endpoint supports 100,000 total concurrent connected devices. If you require more connections see [Scaling VPC endpoints with AWS IoT Core](#Scaling-VPC-endpoints) .
+ VPC endpoints will serve [ATS certificates](https://docs.aws.amazon.com//iot/latest/developerguide/server-authentication.html) only, except for custom domains.
+  [VPC endpoint policies](https://docs.aws.amazon.com//vpc/latest/privatelink/vpc-endpoints-access.html) are not supported.
+ For VPC endpoints that are created for the AWS IoT Core data plane, AWS IoT Core doesn't support using zonal or regional public DNS records.

### Limitations of credential provider endpoints
<a name="VPC-limitations-credential-provider"></a>

This section covers the limitations of credential provider VPC endpoints.
+ VPC endpoints will serve [ATS certificates](https://docs.aws.amazon.com//iot/latest/developerguide/server-authentication.html) only.
+  [VPC endpoint policies](https://docs.aws.amazon.com//vpc/latest/privatelink/vpc-endpoints-access.html) are not supported.
+ Custom domains are not supported for credential provider endpoints.
+ For VPC endpoints that are created for the AWS IoT Core credential provider, AWS IoT Core doesn't support using zonal or regional public DNS records.

## Scaling VPC endpoints with AWS IoT Core
<a name="Scaling-VPC-endpoints"></a>

AWS IoT Core Interface VPC endpoints are limited to 100,000 connected devices over a single interface endpoint. If your use case calls for more concurrent connections to the broker, then we recommend using multiple VPC endpoints and manually routing your devices across your interface endpoints. When creating private DNS records to route traffic to your VPC endpoints, make sure to create as many weighted records as you have VPC endpoints to distribute traffic across your multiple endpoints. 

## Using custom domains with VPC endpoints
<a name="VPC-custom-domains"></a>

If you want to use custom domains with VPC endpoints, you must create your custom domain name records in a private hosted zone and create routing records in Route53. For more information, see [Creating A private hosted zone](https://docs.aws.amazon.com//Route53/latest/DeveloperGuide/hosted-zone-private-creating.html). 

**Note**  
Custom domains are only supported for AWS IoT Core data endpoints.

## Availability of VPC endpoints for AWS IoT Core
<a name="VPC-availability"></a>

AWS IoT Core Interface VPC endpoints are available in all [AWS IoT Core supported regions](https://aws.amazon.com//about-aws/global-infrastructure/regional-product-services/). AWS IoT Core Interface VPC endpoints for AWS IoT Core credential provider are not supported in China Region and AWS GovCloud (US) Regions.

# Using AWS IoT Device Management secure tunneling with interface VPC endpoints
<a name="IoTCore-ST-VPC"></a>

AWS IoT Device Management secure tunneling supports interface VPC endpoints. You can use VPC endpoints to keep traffic between your VPC and AWS IoT Secure Tunneling within the AWS network, without requiring an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection.

Interface VPC endpoints are powered by [AWS PrivateLink](https://docs.aws.amazon.com//vpc/latest/privatelink/what-is-privatelink.html), a technology that enables you to privately access services by using private IP addresses. For more information, see [Access an AWS service using an interface VPC endpoint](https://docs.aws.amazon.com//vpc/latest/privatelink/create-interface-endpoint.html) in the AWS PrivateLink Guide. 

**Topics**
+ [Prerequisites](#Create-ST-VPC-endpoints-prereq)
+ [Receiving tunnel notifications through VPC endpoints](#ST-VPC-Receive-notifications)
+ [Creating VPC endpoints for secure tunneling](#Create-ST-VPC-endpoints-Create)
+ [Configuring VPC endpoint policies on Proxy Server](#Create-ST-VPC-endpoints-Configure)
+ [Next steps](#Create-ST-VPC-endpoints-Next)

## Prerequisites
<a name="Create-ST-VPC-endpoints-prereq"></a>

Before you create VPC endpoints for AWS IoT Secure Tunneling, verify that you have the following:
+ An AWS account with the necessary permissions to create VPC endpoints.
+ A VPC in your AWS account.
+ Understanding of AWS IoT Device Management secure tunneling concepts.
+ Familiarity with VPC endpoint policies and AWS Identity and Access Management (IAM)

## Receiving tunnel notifications through VPC endpoints
<a name="ST-VPC-Receive-notifications"></a>

To receive tunnel notifications through a VPC endpoint, your devices can connect to the AWS IoT Core data plane through a VPC endpoint and subscribe to the secure tunneling reserved MQTT topic.

For instructions on how to create and configure a VPC endpoint in the AWS IoT Core data plane, see [Using AWS IoT Core with interface VPC endpoints](https://docs.aws.amazon.com/iot/latest/developerguide/IoTCore-VPC.html) in the AWS IoT Developer Guide.

## Creating VPC endpoints for secure tunneling
<a name="Create-ST-VPC-endpoints-Create"></a>

You can create VPC endpoints for both secure tunneling control plane and proxy server.

**To create a VPC endpoint for secure tunneling**

1. Follow the steps in [Creating an interface endpoint](https://docs.aws.amazon.com//vpc/latest/privatelink/create-interface-endpoint.html) in the Amazon VPC Developer Guide

1. For **Service name**, choose one of the following options based on your endpoint type:

**Control plane**
   + Standard: `com.amazonaws.<region>.iot.tunneling.api` 
   + FIPS (available in FIPS regions): `com.amazonaws.<region>.iot-fips.tunneling.api` 

**Proxy server**
   + Standard: `com.amazonaws.<region>.iot.tunneling.data` 
   + FIPS (available in FIPS regions): `com.amazonaws.<region>.iot-fips.tunneling.data` 

   Replace *<region>* with your AWS Region. For example, `us-east-1`. 

1. Complete the remaining steps in the VPC endpoint creation process according to your network requirements.

## Configuring VPC endpoint policies on Proxy Server
<a name="Create-ST-VPC-endpoints-Configure"></a>

In addition to client access token-based authorization that is used to authorize connections to tunnels, you can use VPC endpoint policies to further restrict how devices can use a VPC endpoint to connect to the Secure Tunneling Proxy Server. VPC endpoint policies follow an IAM-like syntax and are configured on the VPC endpoint itself.

Note that the only supported IAM action for proxy server VPC endpoint policies is `iot:ConnectToTunnel`. 

Below are examples of different VPC endpoint policies.

### Proxy server VPC endpoint policy examples
<a name="w2aac17c35c31c15b9"></a>

The following examples show Proxy Server VPC endpoint policy configurations for common use cases.

**Example - Default policy**  
This policy allows devices within your VPC to connect to any tunnel in the same AWS Region where the endpoint is created, across any AWS account.  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "*",
            "Resource": "*"
        }
    ]
}
```

**Example - Restrict access to specific AWS accounts**  
This policy allows the VPC endpoint to connect only to tunnels in specific AWS accounts.  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "iot:ConnectToTunnel",
            "Resource": [
                "arn:aws:iot:us-east-1:111122223333:tunnel/*",
                "arn:aws:iot:us-east-1:444455556666:tunnel/*"
            ]
        }
    ]
}
```

**Example - Restrict connections by tunnel endpoint**  
You can restrict VPC endpoint access to only allow devices to connect to the source or destination end of a tunnel.  
Source only:  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "iot:ConnectToTunnel",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iot:ClientMode": "source"
                }
            }
        }
    ]
}
```

Destination only:

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "iot:ConnectToTunnel",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iot:ClientMode": "destination"
                }
            }
        }
    ]
}
```

**Example - Restrict access based on resource tags**  
This policy allows the VPC endpoint to connect only to tunnels that are tagged with a specific key-value pair.  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "iot:ConnectToTunnel",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/Environment": "Production"
                }
            }
        }
    ]
}
```

**Example - Combined policy conditions**  
This policy demonstrates combining multiple policy elements. It allows connections to any tunnel in a specific AWS account, but only if the tunnel is tagged with `AllowConnectionsThroughPrivateLink` set to `true` and the client is not connecting to the destination end of the tunnel.  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "iot:ConnectToTunnel",
            "Resource": [
                "arn:aws:iot:us-east-1:111122223333:tunnel/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/AllowConnectionsThroughPrivateLink": "true"
                }
            }
        },
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "iot:ConnectToTunnel",
            "Resource": [
                "arn:aws:iot:us-east-1:111122223333:tunnel/*"
            ],
            "Condition": {
                "StringEquals": {
                    "iot:ClientMode": "destination"
                }
            }
        }
    ]
}
```

## Next steps
<a name="Create-ST-VPC-endpoints-Next"></a>

After you create and configure your VPC endpoints for AWS IoT Secure Tunneling, consider the following:
+ Test your VPC endpoint configuration by connecting devices through the endpoint.
+ Monitor VPC endpoint usage through Amazon CloudWatch metrics.
+ Review and update your VPC endpoint policies as needed for your security requirements.

For more information about AWS IoT Device Management secure tunneling, see [AWS IoT Secure Tunneling](https://docs.aws.amazon.com//iot/latest/developerguide/secure-tunneling.html). 

# Infrastructure security in AWS IoT
<a name="infrastructure-security"></a>

As a collection of managed services, AWS IoT is protected by the AWS global network security procedures that are described in the [Amazon Web Services: Overview of Security Processes](https://d0.awsstatic.com/whitepapers/Security/AWS_Security_Whitepaper.pdf) whitepaper.

You use AWS published API calls to access AWS IoT through the network. Clients must support Transport Layer Security (TLS) 1.2 or later. Clients must also support cipher suites with perfect forward secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral Diffie-Hellman (ECDHE). Most modern systems, such as Java 7 and later, support these modes. For more information, see [Transport security in AWS IoT Core](transport-security.md).

Requests must be signed by using an access key ID and a secret access key that is associated with an IAM principal. Or you can use the [AWS Security Token Service](https://docs.aws.amazon.com/STS/latest/APIReference/Welcome.html) (AWS STS) to generate temporary security credentials to sign requests.

# Security monitoring of production fleets or devices with AWS IoT Core
<a name="security-monitoring"></a>

IoT fleets can consist of large numbers of devices that have diverse capabilities, are long-lived, and are geographically distributed. These characteristics make fleet setup complex and prone to errors. And because devices are often constrained in computational power, memory, and storage capabilities, this limits the use of encryption and other forms of security on the devices themselves. Also, devices often use software with known vulnerabilities. These factors make IoT fleets an attractive target for hackers and make it difficult to secure your device fleet on an ongoing basis.

AWS IoT Device Defender addresses these challenges by providing tools to identify security issues and deviations from best practices. You can use AWS IoT Device Defender to analyze, audit, and monitor connected devices to detect abnormal behavior, and mitigate security risks. AWS IoT Device Defender can audit device fleets to ensure they adhere to security best practices and detect abnormal behavior on devices. This makes it possible to enforce consistent security policies across your AWS IoT device fleet and respond quickly when devices are compromised. For more information, see [AWS IoT Device Defender](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/what-is-device-defender.html).

AWS IoT Device Advisor pushes updates and patches your fleet as needed. AWS IoT Device Advisor updates test cases automatically. The test cases that you select are always with latest version. For more information, see [Device Advisor](device-advisor.md).

# Security best practices in AWS IoT Core
<a name="security-best-practices"></a>

This section contains information about security best practices for AWS IoT Core. For information about security rules for Industrial IoT solutions, see [Ten security golden rules for Industrial IoT solutions](https://aws.amazon.com/blogs/iot/ten-security-golden-rules-for-industrial-iot-solutions/).

## Protecting MQTT connections in AWS IoT
<a name="secure-mqtt"></a>

[AWS IoT Core](https://aws.amazon.com/iot-core/) is a managed cloud service that makes it possible for connected devices to interact with cloud applications and other devices easily and securely. AWS IoT Core supports HTTP, [WebSocket](https://en.wikipedia.org/wiki/WebSocket), and [MQTT](https://en.wikipedia.org/wiki/MQTT), a lightweight communication protocol specifically designed to tolerate intermittent connections. If you are connecting to AWS IoT using MQTT, each of your connections must be associated with an identifier known as a client ID. MQTT client IDs uniquely identify MQTT connections. If a new connection is established using a client ID that is already claimed for another connection, the AWS IoT message broker drops the old connection to allow the new connection. Client IDs must be unique within each AWS account and each AWS Region. This means that you don't need to enforce global uniqueness of client IDs outside of your AWS account or across Regions within your AWS account.

The impact and severity of dropping MQTT connections on your device fleet depends on many factors. These include:
+ Your use case (for example, the data your devices send to AWS IoT, how much data, and the frequency that the data is sent).
+ Your MQTT client configuration (for example, auto reconnect settings, associated back-off timings, and use of [MQTT persistent sessions](mqtt.md#mqtt-persistent-sessions)).
+ Device resource constraints.
+ The root cause of the disconnections, its aggressiveness, and persistence.

To avoid client ID conflicts and their potential negative impacts, make sure that each device or mobile application has an AWS IoT or IAM policy that restricts which client IDs can be used for MQTT connections to the AWS IoT message broker. For example, you can use an IAM policy to prevent a device from unintentionally closing another device's connection by using a client ID that is already in use. For more information, see [Authorization](iot-authorization.md).

All devices in your fleet must have credentials with privileges that authorize intended actions only, which include (but not limited to) AWS IoT MQTT actions such as publishing messages or subscribing to topics with specific scope and context. The specific permission policies can vary for your use cases. Identify the permission policies that best meet your business and security requirements.

To simplify creation and management of permission policies, you can use [AWS IoT Core policy variables](iot-policy-variables.md) and [IAM policy variables](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html). Policy variables can be placed in a policy and when the policy is evaluated, the variables are replaced by values that come from the device's request. Using policy variables, you can create a single policy for granting permissions to multiple devices. You can identify the relevant policy variables for your use case based on your AWS IoT account configuration, authentication mechanism, and network protocol used in connecting to AWS IoT message broker. However, to write the best permission policies, consider the specifics of your use case and your [threat model](https://en.wikipedia.org/wiki/Threat_model).

For example, if you registered your devices in the AWS IoT registry, you can use [thing policy variables](thing-policy-variables.md) in AWS IoT policies to grant or deny permissions based on thing properties like thing names, thing types, and thing attribute values. The thing name is obtained from the client ID in the MQTT connect message sent when a thing connects to AWS IoT. The thing policy variables are replaced when a thing connects to AWS IoT over MQTT using TLS mutual authentication or MQTT over the WebSocket protocol using authenticated [Amazon Cognito identities](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identities.html). You can use the [AttachThingPrincipal](https://docs.aws.amazon.com/iot/latest/apireference/API_AttachThingPrincipal.html) API to attach certificates and authenticated Amazon Cognito identities to a thing. `iot:Connection.Thing.ThingName` is a useful thing policy variable to enforce client ID restrictions. The following example AWS IoT policy requires a registered thing's name to be used as the client ID for MQTT connections to the AWS IoT message broker:

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": "iot:Connect",
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
			]
		}
	]
}
```

If you want to identify ongoing client ID conflicts, you can enable and use [CloudWatch Logs for AWS IoT](cloud-watch-logs.md). For every MQTT connection that the AWS IoT message broker disconnects due to client ID conflicts, a log record similar to the following is generated:

```
{
    "timestamp": "2019-04-28 22:05:30.105",
    "logLevel": "ERROR",
    "traceId": "02a04a93-0b3a-b608-a27c-1ae8ebdb032a",
    "accountId": "123456789012",
    "status": "Failure",
    "eventType": "Disconnect",
    "protocol": "MQTT",
    "clientId": "clientId01",
    "principalId": "1670fcf6de55adc1930169142405c4a2493d9eb5487127cd0091ca0193a3d3f6",
    "sourceIp": "203.0.113.1",
    "sourcePort": 21335,
    "reason": "DUPLICATE_CLIENT_ID",
    "details": "A new connection was established with the same client ID"
}
```

You can use a [CloudWatch Logs filter](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/MonitoringLogData.html) such as `{$.reason= "DUPLICATE_CLIENT_ID" }` to search for instances of client ID conflicts or to set up [CloudWatch metric filters](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/MonitoringPolicyExamples.html) and corresponding CloudWatch alarms for continuous monitoring and reporting.

You can use [AWS IoT Device Defender](https://aws.amazon.com/iot-device-defender/) to identify overly permissive AWS IoT and IAM policies. AWS IoT Device Defender also provides an audit check that notifies you if multiple devices in your fleet are connecting to the AWS IoT message broker using the same client ID.

You can use AWS IoT Device Advisor to validate that your devices can reliably connect to AWS IoT Core and follow security best practices.

### See also
<a name="mqtt-security-see-also"></a>
+ [AWS IoT Core](https://aws.amazon.com/iot-core/)
+ [AWS IoT's Security Features](authentication.md)
+ [AWS IoT Core policy variables](iot-policy-variables.md)
+ [IAM Policy Variables](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_variables.html)
+ [Amazon Cognito Identity](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identities.html)
+ [AWS IoT Device Defender](https://aws.amazon.com/iot-device-defender/)
+ [CloudWatch Logs for AWS IoT](cloud-watch-logs.md)

## Keep your device's clock in sync
<a name="device-clock"></a>

It's important to have an accurate time on your device. X.509 certificates have an expiry date and time. The clock on your device is used to verify that a server certificate is still valid. If you're building commercial IoT devices, remember that your products may be stored for extended periods before being sold. Real-time clocks can drift during this time and batteries can get discharged, so setting time in the factory is not sufficient.

For most systems, this means that the device's software must include a network time protocol (NTP) client. The device should wait until it synchronizes with an NTP server before it tries to connect to AWS IoT Core. If this isn't possible, the system should provide a way for a user to set the device's time so that subsequent connections succeed.

After the device synchronizes with an NTP server, it can open a connection with AWS IoT Core. How much clock skew that is allowed depends on what you're trying to do with the connection. 

## Validate the server certificate
<a name="validate-server-cert"></a>

The first thing a device does to interact with AWS IoT is to open a secure connection. When you connect your device to AWS IoT, ensure that you're talking to AWS IoT and not another server impersonating AWS IoT. Each of the AWS IoT servers is provisioned with a certificate issued for the `iot.amazonaws.com` domain. This certificate was issued to AWS IoT by a trusted certificate authority that verified our identity and ownership of the domain.

One of the first things AWS IoT Core does when a device connects is send the device a server certificate. Devices can verify that they were expecting to connect to `iot.amazonaws.com` and that the server on the end of that connection possesses a certificate from a trusted authority for that domain.

TLS certificates are in X.509 format and include a variety of information such as the organization's name, location, domain name, and a validity period. The validity period is specified as a pair of time values called `notBefore` and `notAfter`. Services like AWS IoT Core use limited validity periods (for example, one year) for their server certificates and begin serving new ones before the old ones expire.

## Use a single identity per device
<a name="cert-per-device"></a>

Use a single identity per client. Devices generally use X.509 client certificates. Web and mobile applications use Amazon Cognito Identity. This enables you to apply fine-grained permissions to your devices.

For example, you have an application that consists of a mobile phone device that receives status updates from two different smart home objects – a light bulb and a thermostat. The light bulb sends the status of its battery level, and a thermostat sends messages that report the temperature.

AWS IoT authenticates devices individually and treats each connection individually. You can apply fine-grained access controls using authorization policies. You can define a policy for the thermostat that allows it to publish to a topic space. You can define a separate policy for the light bulb that allows it to publish to a different topic space. Finally, you can define a policy for the mobile app that only allows it to connect and subscribe to the topics for the thermostat and the light bulb to receive messages from these devices.

Apply the principle of least privilege and scope down the permissions per device as much as possible. All devices or users should have an AWS IoT policy in AWS IoT that only allows it to connect with a known client ID, and to publish and subscribe to an identified and fixed set of topics.

## Use a second AWS Region as backup
<a name="use-second-region"></a>

Consider storing a copy of your data in a second AWS Region as a backup. Note that the AWS solution named [Disaster Recovery for AWS IoT](https://aws.amazon.com/solutions/implementations/disaster-recovery-for-aws-iot/) is no longer available. While the associated [GitHub library](https://github.com/awslabs/disaster-recovery-for-aws-iot) remains accessible, AWS deprecated it in July 2023 and no longer provides maintenance or support for it. To implement your own solutions or to explore additional support options, visit [Contact AWS](https://aws.amazon.com/contact-us/). If there is an AWS Technical Account Manager associated with your account, reach out to them for help.

## Use just in time provisioning
<a name="use-jitp"></a>

Manually creating and provisioning each device can be time consuming. AWS IoT provides a way to define a template to provision devices when they first connect to AWS IoT. For more information, see [Just-in-time provisioning](jit-provisioning.md).

## Permissions to run AWS IoT Device Advisor tests
<a name="device-advisor-perms"></a>

The following policy template shows the minimum permissions and IAM entity required to run AWS IoT Device Advisor test cases. You will need to replace *your-device-role-arn* with the device role Amazon Resource Name (ARN) that you created under the [prerequisites](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-workflow.html#device-advisor-workflow-prereqs).

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iot:us-east-1:123456789012:thinggroup/your-thing-group",
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "iotdeviceadvisor.amazonaws.com"
            }
        }
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "execute-api:Invoke*",
                "iam:ListRoles",
                "iot:Connect",
                "iot:CreateJob",
                "iot:DeleteJob",
                "iot:DescribeCertificate",
                "iot:DescribeEndpoint",
                "iotjobsdata:DescribeJobExecution",
                "iot:DescribeJob",
                "iot:DescribeThing",
                "iotjobsdata:GetPendingJobExecutions",
                "iot:GetPolicy",
                "iot:ListAttachedPolicies",
                "iot:ListCertificates",
                "iot:ListPrincipalPolicies",
                "iot:ListThingPrincipals",
                "iot:ListThings",
                "iot:Publish",
                "iotjobsdata:StartNextPendingJobExecution",
                "iotjobsdata:UpdateJobExecution",
                "iot:UpdateThingShadow",
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:DescribeLogGroups",
                "logs:DescribeLogStreams",
                "logs:PutLogEvents",
                "logs:PutRetentionPolicy"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": "iotdeviceadvisor:*",
            "Resource": "*"
        }
    ]
}
```

## Cross-service confused deputy prevention for Device Advisor
<a name="cross-service-confused-deputy-prevention-DA"></a>

The confused deputy problem is a security issue where an entity that doesn't have permission to perform an action can coerce a more-privileged entity to perform the action. In AWS, cross-service impersonation can result in the confused deputy problem. Cross-service impersonation can occur when one service (the *calling service*) calls another service (the *called service*). The calling service can be manipulated to use its permissions to act on another customer's resources in a way it should not otherwise have permission to access. To prevent this, AWS provides tools that help you protect your data for all services with service principals that have been given access to resources in your account. 

We recommend using the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn) and [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount) global condition context keys in resource policies to limit the permissions that Device Advisor gives another service to the resource. If you use both global condition context keys, the `aws:SourceAccount` value and the account in the `aws:SourceArn` value must use the same account ID when used in the same policy statement.

The value of `aws:SourceArn` must be the ARN of your suite definition resource. The suite definition resource refers to the test suite you created with Device Advisor.

The most effective way to protect against the confused deputy problem is to use the `aws:SourceArn` global condition context key with the full ARN of the resource. If you don't know the full ARN of the resource or if you are specifying multiple resources, use the `aws:SourceArn` global context condition key with wildcards (`*`) for the unknown portions of the ARN. For example, `arn:aws:iotdeviceadvisor:*:account-id:suitedefinition/*` 

The following example shows how you can use the `aws:SourceArn` and `aws:SourceAccount` global condition context keys in Device Advisor to prevent the confused deputy problem.

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Sid": "ConfusedDeputyPreventionExamplePolicy",
        "Effect": "Allow",
        "Principal": {
            "Service": "iotdeviceadvisor.amazonaws.com"
        },
        "Action": "sts:AssumeRole",
        "Condition": {
            "ArnLike": {
                "aws:SourceArn": "arn:aws:iotdeviceadvisor:us-east-1:123456789012:suitedefinition/ygp6rxa3tzvn"
        },
            "StringEquals": {
                "aws:SourceAccount": "123456789012"
        }
        }
    }
}
```

## AWS training and certification
<a name="iot-security-training"></a>

Take the following course to learn about key concepts for AWS IoT security: [AWS IoT Security Primer](https://www.aws.training/Details/Curriculum?id=42304).