Menu
AWS Identity and Access Management
User Guide

IAM Policy Elements Reference

This section describes the elements that you can use in an IAM policy. The elements are listed here in the general order you use them in a policy. The order of the elements doesn't matter—for example, the Resource element can come before the Action element. You're not required to specify any Condition elements in the policy.

Note

The details of what goes into a policy vary for each service, depending on what actions the service makes available, what types of resources it contains, and so on. When you're writing policies for a specific service, it's helpful to see examples of policies for that service. For a list of all the services that support IAM, and for links to the documentation in those services that discusses IAM and policies, see AWS Services That Work with IAM.

Version

The Version element specifies the policy language version. If you include the Version element, it must appear before the Statement element. The only allowed values are these:

  • 2012-10-17. This is the current version of the policy language, and you should use this version number for all policies.

  • 2008-10-17. This was an earlier version of the policy language. You might see this version on existing policies. Do not use this version for any new policies or any existing policies that you are updating.

If you do not include a Version element, the value defaults to 2008-10-17. However, it is a good practice to always include a Version element and set it to 2012-10-17.

Note

If your policy includes policy variables, you must include a Version element and set it to 2012-10-17. If you don't include a Version element set to 2012-10-17 or later, variables such as ${aws:username} won't be recognized as variables and will instead be treated as literal strings in the policy.

"Version":"2012-10-17"

Id

The Id element specifies an optional identifier for the policy. The ID is used differently in different services.

For services that let you set an ID element, we recommend you use a UUID (GUID) for the value, or incorporate a UUID as part of the ID to ensure uniqueness.

"Id":"cd3ad3d9-2776-4ef1-a904-4c229d1642ee"

Note

Some AWS services (for example, Amazon SQS or Amazon SNS) might require this element and have uniqueness requirements for it. For service-specific information about writing policies, refer to the documentation for the service you're working with.

Statement

The Statement element is the main element for a policy. This element is required. It can include multiple elements (see the subsequent sections in this page). The Statement element contains an array of individual statements. Each individual statement is a JSON block enclosed in braces { }.

"Statement":[{...},{...},{...}]

The following example shows a policy that contains an array of three statements inside a single Statement element. (The policy allows you to access your own "home folder" in the Amazon S3 console.) The policy includes the aws:username variable, which is replaced during policy evaluation with the user name from the request. For more information, see Introduction.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListAllMyBuckets",
        "s3:GetBucketLocation"
      ],
      "Resource": "arn:aws:s3:::*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::BUCKET-NAME",
      "Condition": {"StringLike": {"s3:prefix": [
        "",
        "home/",
        "home/${aws:username}/"
      ]}}
    },
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::BUCKET-NAME/home/${aws:username}",
        "arn:aws:s3:::BUCKET-NAME/home/${aws:username}/*"
      ]
    }
  ]
}

Sid

The Sid (statement ID) is an optional identifier that you provide for the policy statement. You can assign a Sid value to each statement in a statement array. In services that let you specify an ID element, such as SQS and SNS, the Sid value is just a sub-ID of the policy document's ID. In IAM, the Sid value must be unique within a policy.

"Sid":"1"

In IAM, the Sid is not exposed in the IAM API. You can't retrieve a particular statement based on this ID.

Note

Some AWS services (for example, Amazon SQS or Amazon SNS) might require this element and have uniqueness requirements for it. For service-specific information about writing policies, refer to the documentation for the service you're working with.

Effect

The Effect element is required and specifies whether the statement will result in an allow or an explicit deny. Valid values for Effect are Allow and Deny.

"Effect":"Allow"

By default, access to resources is denied. To allow access to a resource, you must set the Effect element to Allow. To override an allow (for example, to override an allow that is otherwise in force), you set the Effect element to Deny. For more information, see IAM Policy Evaluation Logic.

Principal

Use the Principal element to specify the user (IAM user, federated user, or assumed-role user), AWS account, AWS service, or other principal entity that is allowed or denied access to a resource. You use the Principal element in the trust policies for IAM roles and in resource-based policies—that is, in policies that you embed directly in a resource. For example, you can embed such policies in an Amazon S3 bucket, an Amazon Glacier vault, an Amazon SNS topic, an Amazon SQS queue, or an AWS KMS customer master key (CMK).

Use the Principal element in these ways:

  • In IAM roles, use the Principal element in the role's trust policy to specify who can assume the role. For cross-account access, you typically specify the identifier of the trusted account. You cannot specify a wildcard (*) in a role's trust policy.

  • In resource-based policies, use the Principal element to specify the accounts or users who are allowed to access the resource.

Do not use the Principal element in policies that you attach to IAM users and groups. Similarly, you do not specify a principal in the access policy for an IAM role. In those cases, the principal is implicitly the user that the policy is attached to (for IAM users) or the user who assumes the role (for role access policies). When the policy is attached to an IAM group, the principal is the IAM user in that group who is making the request.

Specifying a Principal

You specify a principal using the Amazon Resource Name (ARN) of the AWS account, IAM user, IAM role, federated user, or assumed-role user. You cannot specify IAM groups as principals. When you specify an AWS account, you can use a shortened form that consists of the AWS: prefix followed by the account ID, instead of using the account's full ARN.

The following examples show various ways in which principals can be specified.

Everyone (anonymous users)

The following are equivalent:

"Principal": "*"
"Principal" : { "AWS" : "*" }

Note

In these examples, the asterisk (*) is used as a placeholder for Everyone/Anonymous. You cannot use it as a wildcard to match part of a name or an ARN. Additionally, you cannot use a wildcard in the Principal element in a role's trust policy.

Specific AWS accounts

When you use an AWS account identifier as the principal in a policy, the permissions in the policy statement can be granted to all identities contained in that account, including IAM users and roles in that account. The following examples show different ways to specify an AWS account as a principal.

"Principal": { "AWS": "arn:aws:iam::AWS-account-ID:root" }
"Principal": { "AWS": "AWS-account-ID" }

You can specify more than one AWS account as a principal, as shown in the following example.

"Principal": { 
  "AWS": [
    "arn:aws:iam::AWS-account-ID:root",
    "arn:aws:iam::AWS-account-ID:root"
  ]
}

Individual IAM user or users

You can specify an individual IAM user (or array of users) as the principal, as in the following examples.

Note

In a Principal element, the user name is case sensitive.

"Principal": { "AWS": "arn:aws:iam::AWS-account-ID:user/user-name" }
"Principal": {
  "AWS": [
    "arn:aws:iam::AWS-account-ID:user/user-name-1", 
    "arn:aws:iam::AWS-account-ID:user/UserName2"
  ]
}

When you specify users in a Principal element, you cannot use a wildcard (*) to mean "all users". Principals must always name a specific user or users.

Federated users (using web identity federation)

"Principal": { "Federated": "cognito-identity.amazonaws.com" }

"Principal": { "Federated": "www.amazon.com" }

"Principal": { "Federated": "graph.facebook.com" }

"Principal": { "Federated": "accounts.google.com" }

Federated users (using a SAML identity provider)

"Principal": { "Federated": "arn:aws:iam::AWS-account-ID:saml-provider/provider-name" }

IAM role

"Principal": { "AWS": "arn:aws:iam::AWS-account-ID:role/role-name" }

Specific assumed-role user

"Principal": { "AWS": "arn:aws:sts::AWS-account-ID:assumed-role/role-name/role-session-name" }

AWS service

When you create a trust policy for an IAM role that will be assumed by an AWS service, you typically specify the principal using a friendly name for that service, as in the following example.

"Principal": {
  "Service": [
    "ec2.amazonaws.com",
    "datapipeline.amazonaws.com" 
  ]
}

Some AWS services support additional options for specifying a principal. For example, Amazon S3 lets you use a canonical user in a format like this:

"Principal": { "CanonicalUser": "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be" }

More Information

For more information, see the following:

NotPrincipal

Use the NotPrincipal element to specify an exception to a list of principals. For example, you can deny access to all principals except the one named in the NotPrincipal element. The syntax for specifying NotPrincipal is the same as for specifying Principal.

Note that you can also use NotPrincipal to allow all principals except the one named in the NotPrincipal element; however, we do not recommend this.

Warning

When you use NotPrincipal in the same policy statement as "Effect": "Allow", the permissions specified in the policy statement will be granted to all principals except for the one(s) specified, including anonymous (unauthenticated) users. We strongly recommend you do not use NotPrincipal in the same policy statement as "Effect": "Allow".

When you use NotPrincipal in the same policy statement as "Effect": "Deny", the permissions specified in the policy statement are explicitly denied to all principals except for the one(s) specified. This enables you to implement a form of "whitelisting". When you explicitly deny access to an AWS account, you deny access to all users contained in that account.

Note that if a resource-based policy combines "Effect": "Deny" with a NotPrincipal element that specifies only a principal in an AWS account, the policy is likely denying access to the account containing the principal, and that in turn results in the specified principal not being able to access the resource. To understand how this can happen, see the examples in the next section.

Caution

Very few scenarios require the use of NotPrincipal, and we recommend that you explore other authorization options before you decide to use NotPrincipal.

Specifying NotPrincipal in the same policy statement as "Effect": "Deny"

You specify principals in the NotPrincipal element using the same syntax that you use for specifying principals in the Principal element. However, it can be difficult to achieve the intended effect, particularly when you combine NotPrincipal with "Effect": "Deny" in the same policy statement and you work across AWS account boundaries.

Important

Combining Deny and NotPrincipal is the only time that the order in which AWS evaluates principals makes a difference. AWS internally validates the principals from the "top down," meaning that AWS checks the account first and then the user. If an assumed-role user (someone who is using a role rather than an IAM user) is being evaluated, AWS looks at the account first, then the role, and finally the assumed-role user. The assumed-role user is identified by the role session name that is specified when the user assumes the role.

Normally, this order does not have any impact on the results of the policy evaluation. However, when you use both Deny and NotPrincipal, the evaluation order requires you to explicitly include the ARNs for the entities associated with the specified principal. For example, to specify a user, you must explicitly include the ARN for the user's account. To specify an assumed-role user, you must also include both the ARN for the role and the ARN for the account containing the role.

The following examples show how to use NotPrincipal and "Effect": "Deny" in the same policy statement effectively.

Example 1: An IAM user in the same or a different account

In the following example, all principals except the user named Bob in AWS account 444455556666 are explicitly denied access to a resource. Note that to achieve the intended effect, the NotPrincipal element contains the ARN of both the user Bob and the AWS account that Bob belongs to (arn:aws:iam::444455556666:root). If the NotPrincipal element contained only Bob's ARN, the effect of the policy would be to explicitly deny access to the AWS account that contains the user Bob. A user cannot have more permissions than its parent account, so if Bob's account is explicitly denied access then Bob is also unable to access the resource.

This example works as intended when it is part of a policy statement in a resource-based policy that is attached to a resource in either the same or a different AWS account (not 444455556666). This example by itself does not grant access to Bob, it only omits Bob from the list of principals that are explicitly denied. To give Bob access to the resource, another policy statement must explicitly allow access using "Effect": "Allow".

"Effect": "Deny",
"NotPrincipal": {
  "AWS": [
    "arn:aws:iam::444455556666:user/Bob",
    "arn:aws:iam::444455556666:root"
  ]
}

Example 2: An IAM role in the same or different account

In the following example, all principals except the assumed-role user named cross-account-audit-app in AWS account 444455556666 are explicitly denied access to a resource. Note that to achieve the intended effect, the NotPrincipal element contains the ARN of the assumed-role user (cross-account-audit-app), the role (cross-account-read-only-role), and the AWS account that the role belongs to (444455556666). If the NotPrincipal element was missing the ARN of the role, the effect of the policy would be to explicitly deny access to the role. Similarly, if the NotPrincipal element was missing the ARN of the AWS account that the role belongs to, the effect of the policy would be to explicitly deny access to the AWS account and all entities in that account. Assumed-role users cannot have more permissions than their parent role, and roles cannot have more permissions than their parent AWS account, so when the role or the account is explicitly denied access, the assumed role user is unable to access the resource.

This example works as intended when it is part of a policy statement in a resource-based policy that is attached to a resource in a different AWS account (not 444455556666). This example by itself does not grant access to the assumed-role user cross-account-audit-app, it only omits cross-account-audit-app from the list of principals that are explicitly denied. To give cross-account-audit-app access to the resource, another policy statement must explicitly allow access using "Effect": "Allow".

"Effect": "Deny",
"NotPrincipal": {
  "AWS": [
    "arn:aws:sts::444455556666:assumed-role/cross-account-read-only-role/cross-account-audit-app",
    "arn:aws:iam::444455556666:role/cross-account-read-only-role",
    "arn:aws:iam::444455556666:root"
  ]
}

Action

The Action element describes the specific action or actions that will be allowed or denied. Statements must include either an Action or NotAction element. Each AWS service has its own set of actions that describe tasks that you can perform with that service. For example, the list of actions for Amazon S3 can be found at Specifying Permissions in a Policy in the Amazon Simple Storage Service Developer Guide, the list of actions for Amazon EC2 can be found in the Amazon EC2 API Reference, and the list of actions for AWS Identity and Access Management can be found in the IAM API Reference. To find the list of actions for other services, consult the API reference documentation for the service.

You specify a value using a namespace that identifies a service (iam, ec2 sqs, sns, s3, etc.) followed by the name of the action to allow or deny. The name must match an action that is supported by the service. The prefix and the action name are case insensitive. For example, iam:ListAccessKeys is the same as IAM:listaccesskeys. The following examples show Action elements for different services.

Amazon SQS action

"Action":"sqs:SendMessage"

Amazon EC2 action

"Action":"ec2:StartInstances"

IAM action

"Action":"iam:ChangePassword"

Amazon S3 action

"Action":"s3:GetObject"

You can specify multiple values for the Action element.

"Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ]

You can use a wildcard (*) to give access to all the actions the specific AWS product offers. For example, the following Action element applies to all S3 actions.

"Action": "s3:*"

You can also use wildcards (*) as part of the action name. For example, the following Action element applies to all IAM actions that include the string AccessKey, including CreateAccessKey, DeleteAccessKey, ListAccessKeys, and UpdateAccessKey.

"Action": "iam:*AccessKey*"

Some services let you limit the actions that are available. For example, Amazon SQS lets you make available just a subset of all the possible Amazon SQS actions. In that case, the * wildcard doesn't allow complete control of the queue; it allows only the subset of actions that you've shared. For more information, see Understanding Permissions in the Amazon Simple Queue Service Developer Guide.

NotAction

The NotAction element lets you specify an exception to a list of actions. For example, you can use NotAction to let users use only the Amazon SQS SendMessage action, without having to list all the actions that the user is not allowed to perform. Using NotAction can sometimes result in shorter policies than using an Action element and listing many actions.

The following example refers to all actions other than the Amazon SQS SendMessage action. You might use this in a policy with "Effect":"Deny" to keep users from accessing any other actions except SendMessage Note, however, that this would not grant the user access to any actions, it would only explicitly deny all other actions except SendMessage.

"NotAction": "sqs:SendMessage"

The following example matches any action except Publish.

"NotAction": "sns:Publish"

The following example shows how to reference all actions except Amazon S3's GetObject action.

"NotAction": "s3:GetObject"

For an example of how to use the NotAction element in a policy that controls access to an Amazon S3 bucket, see Example Policies for Amazon S3 in the Amazon Simple Storage Service Developer Guide.

Resource

The Resource element specifies the object or objects that the statement covers. Statements must include either a Resource or a NotResource element. You specify a resource using an ARN. (For more information about the format of ARNs, see Amazon Resource Names (ARNs) and AWS Service Namespaces.)

Each service has its own set of resources. Although you always use an ARN to specify a resource, the details of the ARN for a resource depend on the service and the resource. For information about how to specify a resource, refer to the documentation for the service whose resources you're writing a statement for.

Note

Some services do not let you specify actions for individual resources; instead, any actions that you list in the Action or NotAction element apply to all resources in that service. In these cases, you use the wildcard * in the Resource element.

The following example refers to a specific Amazon SQS queue.

"Resource": "arn:aws:sqs:us-west-2:account-ID-without-hyphens:queue1"

The following example refers to the IAM user named Bob in an AWS account.

"Resource": "arn:aws:iam::account-ID-without-hyphens:user/Bob"

You can use wildcards as part of the resource ARN. You can use wildcard characters (* and ?) within any ARN segment (the parts separated by colons). An asterisk (*) represents any combination of characters and a question mark (?) represents any single character. You can have use multiple * or ? characters in each segment, but a wildcard cannot span segments. The following example refers to all IAM users whose path is /accounting.

"Resource": "arn:aws:iam::account-ID-without-hyphens:user/accounting/*"

The following example refers to all items within a specific Amazon S3 bucket.

"Resource": "arn:aws:s3:::my_corporate_bucket/*"

You can specify multiple resources. The following example refers to two DynamoDB tables.

"Resource": [
    "arn:aws:dynamodb:us-west-2:account-ID-without-hyphens:table/books_table",
    "arn:aws:dynamodb:us-west-2:account-ID-without-hyphens:table/magazines_table"
]

In the Resource element, you can use policy variables in the part of the ARN that identifies the specific resource (that is, in the trailing part of the ARN). For example, you can use the key {aws:username} as part of a resource ARN to indicate that the current user's name should be included as part of the resource's name. The following example shows how you can use the {aws:username} key in a Resource element. The policy allows access to a Amazon DynamoDB table that matches the current user's name.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "dynamodb:*",
    "Resource": "arn:aws:dynamodb:us-east-1:ACCOUNT-ID-WITHOUT-HYPHENS:table/${aws:username}"
  }
}

For more information about policy variables, see IAM Policy Variables Overview.

NotResource

The NotResource element lets you grant or deny access to all but a few of your resources, by allowing you to specify only those resources to which your policy should not be applied.

For example, imagine you have a group named Developers. Members of Developers should have access to all of your Amazon S3 resources except the CompanySecretInfo folder in the mybucket bucket. The following example shows what the policy to establish these permissions might look like.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "s3:*",
    "NotResource": [
      "arn:aws:s3:::mybucket/CompanySecretInfo",
      "arn:aws:s3:::mybucket/CompanySecretInfo/*"
    ]
  }
}

Normally you would write a policy that uses "Effect":"Allow" and that includes a Resources element that lists each folder individually that the Developers group has access to. However, in that case, each time you added a folder to mybucket that users should have access to, you would have to add its name to the list in Resource. If you use a NotResource element instead, users will automatically have access to new folders unless you add the folder names to the NotResource element.

Condition

The Condition element (or Condition block) lets you specify conditions for when a policy is in effect. The Condition element is optional. In the Condition element, you build expressions in which you use boolean condition operators (equal, less than, etc.) to match the condition in the policy against values in the request. Condition values can include date, time, the IP address of the requester, the ARN of the request source, the user name, user ID, and the user agent of the requester. Some services let you specify additional values in conditions; for example, Amazon S3 lets you write a condition using the s3:VersionId key, which is unique to that service. (For more information about writing conditions in policies for Amazon S3, see Using IAM Policies in the Amazon Simple Storage Service Developer Guide.)

The Condition Block

The following example shows the basic format of a Condition element:

"Condition": {
  "DateGreaterThan" : {
     "aws:CurrentTime" : "2013-12-15T12:00:00Z"
   }
}

A value from the request is represented by a key, in this case aws:CurrentTime. The key value is compared to a value that you specify either as a literal value (2013-08-16T12:00:00Z) or as a policy variable, as explained later. The type of comparison to make is specified by the condition operator (here, DateGreaterThan). You can create conditions that compare strings, dates, numbers, and so on, using typical boolean comparisons like equals, greater than, and less than.

Under some circumstances, keys can contains multiple values. For example, a request to DynamoDB might ask to return or update multiple attributes from a table. A policy for access to DynamoDB tables can include the dynamodb:Attributes key, which contains all the attributes listed in the request. You can test the multiple attributes in the request against a list of allowed attributes in a policy by using set operators in the Condition element. For more information, see Creating a Condition That Tests Multiple Key Values (Set Operations).

When the policy is evaluated during a request, AWS replaces the key with the corresponding value from the request. (In this example, AWS would use the date and time of the request.) The condition is evaluated to return true or false, which is then factored into whether the policy as a whole allows or denies the request.

Multiple Values in a Condition

A Condition element can contain multiple conditions, and each condition can contain multiple key-value pairs. The following figure illustrates this. Unless otherwise specified, all keys can have multiple values.

Let's say you want to let John use a resource only if a numeric value foo equals either A or B, and another numeric value bar equals C. You would create a condition block that looks like the following figure.

Condition block that includes two NumericEquals conditions

Let's say you also want to restrict John's access to after January 1, 2009. You would add another condition, DateGreaterThan, with a date equal to January 1, 2009. The condition block would then look like the following figure.

Condition block that includes DateGreaterThan condition

If there are multiple condition operators, or if there are multiple keys attached to a single condition operator, the conditions are evaluated using a logical AND. If a single condition operator includes multiple values for one key, that condition operator is evaluated using a logical OR. All condition operators must be met for an allow or an explicit deny decision. If any one condition operator isn't met, the result is a deny.

Condition block showing how AND and OR are applied to multiple values

As noted, AWS has predefined condition operators and keys (like aws:CurrentTime). Individual AWS services also define service-specific keys.

As an example, let's say you want to let user John access your Amazon SQS queue under the following conditions:

  • The time is after 12:00 noon on 8/16/2013

  • The time is before 3:00 p.m. on 8/16/2013

  • The request (IAM or SQS) or message (SNS) comes from an IP address within the range 192.0.2.0 to 192.0.2.255 or 203.0.113.0 to 203.0.113.255.

Your condition block has three separate condition operators, and all three of them must be met for John to have access to your queue, topic, or resource.

The following shows what the condition block looks like in your policy. The two values for aws:SourceIp are evaluated using OR. The three separate condition operators are evaluated using AND.

"Condition" :  {
      "DateGreaterThan" : {
         "aws:CurrentTime" : "2013-08-16T12:00:00Z"
       },
      "DateLessThan": {
         "aws:CurrentTime" : "2013-08-16T15:00:00Z"
       },
       "IpAddress" : {
          "aws:SourceIp" : ["192.0.2.0/24", "203.0.113.0/24"]
      }
}

Finally, under some circumstances, individual keys in a policy can contain multiple values, and you can use condition set operators to test these multi-valued keys against one or more values listed in the policy. For more information, see Creating a Condition That Tests Multiple Key Values (Set Operations).

Available Keys for Conditions

Condition keys in a condition element represent values that are part of the request sent by a user. AWS provides the following predefined condition keys for all AWS services that support IAM for access control:

  • aws:CurrentTime – The current date and time to check for date/time conditions (see Date Condition Operators).

  • aws:EpochTime – The current date and time in epoch or UNIX time to check for date/time conditions (see Date Condition Operators).

  • aws:TokenIssueTime – To check the date/time that temporary security credentials were issued (see Date Condition Operators). This key is only present in requests that are signed using temporary security credentials. For more information about temporary security credentials, see Temporary Security Credentials.

  • aws:MultiFactorAuthPresent – To check whether multi-factor authentication (MFA) was used to validate the temporary security credentials that made the current request (see Boolean Condition Operators). This key is present in the request context only when the user uses temporary credentials to call the API. Such credentials are used with IAM roles, federated users, IAM users with credentials from sts:GetSessionToken, and users of the AWS Management Console. (The console uses temporary credentials that are generated on the users' behalf in the background.) The aws:MultiFactorAuthPresent key is never present when an API or CLI command is called with long-term credentials, such as standard access key pairs. Therefore we recommend that when you check for this key that you use the ...IfExists versions of the condition operators.

    It is important to understand that the following Condition element is not a reliable way to check for the use of MFA:

    "Sid": "THISPOLICYDOESNOTWORK",
    "Condition" : { "Bool" : { "aws:MultiFactorAuthPresent" : false } }

    This is because when long term credentials are used, the aws:MultiFactorAuthPresent key is not present in the request and the test always fails, resulting in a non-match. Instead, we recommend that you use the BoolIfExists operator to check the value. For example::

        "Condition" : { "BoolIfExists" : { "aws:MultiFactorAuthPresent" : false } }

    This operator indicates that the statement matches either if the value exists and has the value of "false" or if the value does not exist. ...IfExists says that in effect you don't care whether the key to check does not exist in the context of the request; it's absence will not result in a nonmatch.

    Do not use a policy construct similar to the following to check whether the MFA key is present:

    "Sid": "THISPOLICYDOESNOTWORK",
    "Action" : "Deny",
    "Condition" : { "Null" : { "aws:MultiFactorAuthPresent" : true } }

    You might expect the previous example to deny access if MFA is not used. However, when you make an API request with long-term credentials (access keys), the MFA condition context keys are always missing. Consequently, testing for MFA this way always results in denied access to long-term credentials.

  • aws:MultiFactorAuthAge – To check how long ago (in seconds) the MFA-validated security credentials making the request were issued using multi-factor authentication (MFA). If MFA was not used, this key is not present (see Numeric comparison operators and Using Multi-Factor Authentication (MFA) in AWS. Therefor, this is another key with which you should consider using the ...IfExists versions of the comparison operators. This ensures that the results of the comparison are what you expect even when the key is not present in the request context.

  • aws:PrincipalType – To check the type of principal (user, account, federated user, etc.) for the current request (see String Condition Operators).

  • aws:Referer – To check who referred the client browser to the address the request is being sent to. It is only supported by some services, such as Amazon S3, as a service that can be directly addressed by a web browser. The value comes from the referer header in the HTTPS request made to AWS.

    Caution

    This key should be used carefully: aws:referer allows Amazon S3 bucket owners to help prevent their content from being served up by unauthorized third-party sites to standard web browsers (for more information, see the link above). Since the aws:referer value is provided by the caller in an http header, unauthorized parties can use modified or custom browsers to provide any aws:referer value that they choose. As a result, aws:referer should not be used to prevent unauthorized parties from making direct AWS requests. It is offered only to allow customers to protect their digital content, stored in Amazon S3, from being referenced on unauthorized, third-party sites.

  • aws:SecureTransport – To check whether the request was sent using SSL (see Boolean Condition Operators).

  • aws:SourceArn – To check the source of the request, using the Amazon Resource Name (ARN) of the source. (This value is available for only some services.)

  • aws:SourceIp – To check the requester's IP address (see IP Address Condition Operators).

    Note

    If the request comes from a host that uses an Amazon VPC endpoint, then the aws:SourceIp key is not available. You should instead use a VPC-specific key. For more information, see VPC Endpoints - Controlling the Use of Endpoints in the Amazon VPC User Guide.

  • aws:SourceVpc – To restrict access to a specific VPC. For more information, see Restricting Access to a Specific VPC in the Amazon Simple Storage Service Developer Guide. (This value is available for only some services.)

  • aws:SourceVpce – To restrict access to a specific VPC endpoint For more information, see Restricting Access to a Specific VPC Endpoint in the Amazon Simple Storage Service Developer Guide.

  • aws:UserAgent – To check the requester's client application. For more information, see String Condition Operators.

  • aws:userid – To check the requester's user ID. For more information, see String Condition Operators.

  • aws:username – To check the requester's user name. For more information, see String Condition Operators.

Some AWS services also provide service-specific keys. For example, for information about keys that you can use in policies for Amazon S3 resources, see Amazon S3 Policy Keys in the Amazon Simple Storage Service Developer Guide. For information about keys that you can use in policies for IAM resources, see the following section. For information about keys that you can use in policies for other services, see the documentation for the individual services.

Note

If you use condition keys that are available only in some scenarios (such as aws:SourceIp and aws:SourceVpc) you must use the IfExists versions of the comparison operators. This is necessary because these context keys are not always present. If they are missing (and you haven't set IfExists), the policy engine may fail the evaluation and fall back to not match the statement. For example, if you want to write a policy that restricts access from a particular IP range or from a particular VPC, you must construct the conditions as follows:

"Condition": {"IpAddressIfExists": {"aws:SourceIp" : ["xxx"] }, "StringEqualsIfExists" : {"aws:SourceVpc" : ["yyy"]} }

This condition matches (1) if the aws:SourceIp context key exists and has the value xxx or (2) if the aws:SourceVpc context key exists and has the value yyy.

Available Keys for IAM

You can use the following condition keys in policies that control access to IAM resources:

Available Keys for Web Identity Federation

If you are using web identity federation to give temporary security credentials to users who have been authenticated using an identity provider (IdP) such as Login with Amazon, Amazon Cognito, Google, or Facebook, additional condition keys are available when the temporary security credentials are used to make a request. These keys let you write policies that make sure that federated users can get access only to resources that are associated with a specific provider, app, or user.

Federated Provider

The aws:FederatedProvider key identifies which of the IdPs was used to authenticate the user. For example, if the user authenticated using Amazon Cognito, the key would contain cognito-identity.amazonaws.com. Similarly, if the user authenticated using Login with Amazon, the key would contain the value www.amazon.com. You might use the key in a resource policy like the following, which uses the aws:FederatedProvider key as a policy variable in the ARN of a resource. The policy allows any user who has been authenticated using an IdP to get objects out of a folder in an Amazon S3 bucket that's specific to the provider they used to authenticate with.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Principal": "*",
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::BUCKET-NAME/${aws:FederatedProvider}/*"
  }
}

Application ID and User ID

You can also use two keys that provide a unique identifier for the user and an identifier for the application or site that the user authenticated with. These keys have the following IdP-specific names:

  • For Amazon Cognito users, the keys are cognito-identityamazonaws.com:aud (for the identity pool ID) and cognito-identity.amazonaws.com:sub (for the user ID).

  • For Login With Amazon users, the keys are www.amazon.com:app_id and www.amazon.com:user_id

  • For Facebook users, the keys are graph.facebook.com:app_id and graph.facebook.com:id

  • For Google users, the keys are accounts.google.com:aud (for the app ID) and accounts.google.com:sub (for the user ID).

The amr Key in Amazon Cognito

If you are using Amazon Cognito for web identity federation, the cognito-identity.amazonaws.com:amr key (Authenticated Methods Reference) in a trust policy includes login information about the user. The key is multivalued, meaning that you test it in a policy using condition set operators. The key can contain the following values:

  • If the user is unauthenticated, the key contains only unauthenticated.

  • If the user is authenticated, the key contains the value authenticated and the name of the login provider used in the call (graph.facebook.com, accounts.google.com, or www.amazon.com).

As an example, the following condition in the trust policy for an Amazon Cognito role tests whether the user is unauthenticated:

"Condition": {
  "StringEquals": 
    { "cognito-identity.amazonaws.com:aud": "us-east-1:identity-pool-id" },
  "ForAnyValue:StringLike": 
    { "cognito-identity.amazonaws.com:amr": "unauthenticated" }
}

More Information About Web Identity Federation

For more information about web identity federation, see the following:

Available Keys for SAML-Based Federation

If you are working with SAML-based federation, you can include additional condition keys in the policy.

Trust Policies

In the trust policy of a role, you can include the following keys, which help you establish whether the caller is allowed to assume the role. Except for saml:doc, all the values are derived from the SAML assertion. Items in the list that are marked with an asterisk (*) are available in the console UI to create conditions.

  • saml:aud (URL). An endpoint to which SAML assertions are presented. The value for this key comes from the SAML Recipient field in the assertion, not the Audience field.

  • saml:cn (list). This is an eduOrg attribute.

  • saml:doc (string).* This represents the principal that was used to assume the role. The format is account-ID/provider-friendly-name, such as 123456789012/SAMLProviderName. The account-ID value refers to the account that owns the SAML provider.

  • saml:edupersonaffiliation (list). This is an eduPerson attribute.

  • saml:edupersonassurance (list). This is an eduPerson attribute.

  • saml:edupersonentitlement (list).* This is an eduPerson attribute.

  • saml:edupersonnickname (list). This is an eduPerson attribute.

  • saml:edupersonorgdn (string).* This is an eduPerson attribute.

  • saml:edupersonorgunitdn (list). This is an eduPerson attribute.

  • saml:edupersonprimaryaffiliation (string). This is an eduPerson attribute.

  • saml:edupersonprimaryorgunitdn (string). This is an eduPerson attribute.

  • saml:edupersonprincipalname (string). This is an eduPerson attribute.

  • saml:edupersonscopedaffiliation (list). This is an eduPerson attribute.

  • saml:edupersontargetedid (list). This is an eduPerson attribute.

  • saml:eduorghomepageuri (list). This is an eduOrg attribute.

  • saml:eduorgidentityauthnpolicyuri (list). This is an eduOrg attribute.

  • saml:eduorglegalname (list). This is an eduOrg attribute.

  • saml:eduorgsuperioruri (list). This is an eduOrg attribute.

  • saml:eduorgwhitepagesuri (list). This is an eduOrg attribute.

  • saml:namequalifier (string). * A hash value based on the concatenation of the Issuer response value (saml:iss), the AWS account ID and the friendly name (the last part of the ARN) of the SAML provider in IAM, separated by a '/' character. The concatenation of the account ID and friendly name of the SAML provider is available to IAM policies as the key saml:doc. For more information, see Uniquely Identifying Users in SAML-Based Federation.

  • saml:iss (string).* The issuer, which is represented by a URN.

  • saml:sub (string).* This is the subject of the claim, which includes a value that uniquely identifies an individual user within an organization (for example, _cbb88bf52c2510eabe00c1642d4643f41430fe25e3).

  • saml:sub_type (string).* This key can be "persistent" or "transient". A value of "persistent" indicates that the value in saml:sub is the same for a user between sessions. If the value is "transient", the user has a different saml:sub value for each session.

For general information about eduPerson and eduOrg attributes, see the Internet2 website. For a list of eduPerson attributes, see eduPerson Object Class Specification (201203).

Condition keys whose type is a list can include multiple values. To create conditions in the policy for list values, you can use set operators (ForAllValues, ForAnyValue). For example, to allow any user whose affiliation is "faculty", "staff", or "employee" (but not "student", "alum", or other possible affiliations), you might use a condition like the following:

"Condition": {
   "ForAllValues:StringLike": {
     "saml:edupersonaffiliation":[ "faculty", "staff", "employee" ] 
   }
}

Permission (Access) Policies

In the permission policy of a role for SAML federation that defines what users are allowed to access in AWS, you can include the following keys:

  • saml:namequalifier. This contains a hash value that represents the combination of the saml:doc and saml:iss values. It is used as a namespace qualifier; the combination of saml:namequalifier and saml:sub uniquely identifies a user.

  • saml:sub. As described in the previous list.

  • saml:sub_type. As described in the previous list.

For more information about using these keys, see About SAML 2.0-based Federation.

Condition Operators

Condition operators are the "verbs" of conditions and specify the type of comparison that IAM performs. The condition operators can be grouped into the following categories:

String Condition Operators

String condition operators let you construct Condition elements that restrict access based on comparing a key to a string value.

Condition OperatorDescription

StringEquals

Exact matching, case sensitive

StringNotEquals

Negated matching

StringEqualsIgnoreCase

Exact matching, ignoring case

StringNotEqualsIgnoreCase

Negated matching, ignoring case

StringLike

Case-sensitive matching. The values can include a multi-character match wildcard (*) or a single-character match wildcard (?) anywhere in the string.

Note

If a key contains multiple values, StringLike can be qualified with set operators—ForAllValues:StringLike and ForAnyValue:StringLike. For more information, see Creating a Condition That Tests Multiple Key Values (Set Operations).

StringNotLike

Negated case-sensitive matching. The values can include a multi-character match wildcard (*) or a single-character match wildcard (?) anywhere in the string.

For example, the following statement contains a Condition element that uses the StringEquals condition operator with the aws:UserAgent key to specify that the request must include a specific value in its user agent header.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "iam:*AccessKey*",
    "Resource": "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:user/*",
    "Condition": {"StringEquals": {"aws:UserAgent": "Example Corp Java Client"}}
  }
}

The following example uses the StringLike condition operator to perform string matching with a policy variable to create a policy that lets an IAM user use the Amazon S3 console to manage his or her own "home directory" in an Amazon S3 bucket. The policy allows the specified actions on an S3 bucket as long as the s3:prefix matches any one of the specified patterns.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListAllMyBuckets",
        "s3:GetBucketLocation"
      ],
      "Resource": "arn:aws:s3:::*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::BUCKET-NAME",
      "Condition": {"StringLike": {"s3:prefix": [
        "",
        "home/",
        "home/${aws:username}/"
      ]}}
    },
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::BUCKET-NAME/home/${aws:username}",
        "arn:aws:s3:::BUCKET-NAME/home/${aws:username}/*"
      ]
    }
  ]
}

For an example of a policy that shows how to use the Condition element to restrict access to resources based on an application ID and a user ID for web identity federation, see Allow Users Signed In with Amazon Cognito to Access their Own Amazon S3 Folder.

Numeric Condition Operators

Numeric condition operators let you construct Condition elements that restrict access based on comparing a key to an integer or decimal value.

Condition OperatorDescription

NumericEquals

Matching

NumericNotEquals

Negated matching

NumericLessThan

"Less than" matching

NumericLessThanEquals

"Less than or equals" matching

NumericGreaterThan

"Greater than" matching

NumericGreaterThanEquals

"Greater than or equals" matching

For example, the following statement contains a Condition element that uses the NumericLessThanEquals condition operator with the s3:max-keys key to specify that the requester can list up to 10 objects in example_bucket at a time.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "s3:ListBucket",
    "Resource": "arn:aws:s3:::example_bucket",
    "Condition": {"NumericLessThanEquals": {"s3:max-keys": "10"}}
  }
}

Date Condition Operators

Date condition operators let you construct Condition elements that restrict access based on comparing a key to a date/time value. You use these condition operators with the aws:CurrentTime key or aws:EpochTime keys. You must specify date/time values with one of the W3C implementations of the ISO 8601 date formats or in epoch (UNIX) time.

Note

Wildcards are not permitted for date condition operators.

Condition OperatorDescription

DateEquals

Matching a specific date

DateNotEquals

Negated matching

DateLessThan

Matching before a specific date and time

DateLessThanEquals

Matching at or before a specific date and time

DateGreaterThan

Matching after a specific a date and time

DateGreaterThanEquals

Matching at or after a specific date and time

For example, the following statement contains a Condition element that uses the DateLessThan condition operator with the aws:CurrentTime key to specify that the request must be received before June 30, 2013.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "iam:*AccessKey*",
    "Resource": "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:user/*",
    "Condition": {"DateLessThan": {"aws:CurrentTime": "2013-06-30T00:00:00Z"}}
  }
}

Boolean Condition Operators

Boolean conditions let you construct Condition elements that restrict access based on comparing a key to "true" or "false."

Condition OperatorDescription

Bool

Boolean matching

For example, the following statement uses the Bool condition operator with the aws:SecureTransport key to specify that the request must use SSL.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "iam:*AccessKey*",
    "Resource": "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:user/*",
    "Condition": {"Bool": {"aws:SecureTransport": "true"}}
  }
}

Binary Condition Operators

The BinaryEquals condition operator let you construct Condition elements that test key values that are in binary format. It compares the value of the specified key byte for byte against a base-64 encoded representation of the binary value in the policy.

"Condition" : {
  "BinaryEquals": {
    "key" : "QmluYXJ5VmFsdWVJbkJhc2U2NA=="
  }
}     

IP Address Condition Operators

IP address condition operators let you construct Condition elements that restrict access based on comparing a key to an IPv4 or IPv6 address or range of IP addresses. You use these with the aws:SourceIp key. The value must be in the standard CIDR format (for example, 203.0.113.0/24 or 2001:DB8:1234:5678::/64). For IPv6, we support using :: to represent a range of 0s.

Note

Not all AWS services support IPv6 yet. Please refer to the documentation of a specific service for information about whether it supports IPv6.

Condition OperatorDescription

IpAddress

The specified IP address or range

NotIpAddress

All IP addresses except the specified IP address or range

For example, the following statement uses the IpAddress condition operator with the aws:SourceIp key to specify that the request must come from the IP range 203.0.113.0 to 203.0.113.255.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "iam:*AccessKey*",
    "Resource": "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:user/*",
    "Condition": {"IpAddress": {"aws:SourceIp": "203.0.113.0/24"}}
  }
}

The aws:SourceIp condition key resolves to the IP address that the request originates from. If the requests originates from an Amazon EC2 instance, aws:SourceIp evaluates to the instance's public IP address. <para>The following example shows how to mix IPv4 and IPv6 addresses to cover all of your organization's valid IP addresses. We recommend that you augment your organization's policies with your IPv6 address ranges in addition to IPv4 ranges you already have to ensure the policies continue to work as you make the transition to IPv6.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "someservice:*",
    "Resource": "*",
    "Condition": {
      "IpAddress": {
        "aws:SourceIp": [
          "203.0.113.0/24",
          "2001:DB8:1234:5678::/64"
        ]
      }
    }
  }
}

The aws:SourceIp condition key works only in an IAM policy if you are calling the tested API directly as a user. If you instead use a service to call the target service on your behalf, the target service sees the IP address of the calling service rather than the IP address of the originating user. This can happen, for example, if you use AWS CloudFormation to call Amazon EC2 to construct instances for you. There is currently no way to pass the originating IP address through a calling service to the target service for evaluation in an IAM policy. For these types of service API calls, do not use the aws:SourceIp condition key.

Amazon Resource Name (ARN) Condition Operators

Amazon Resource Name (ARN) condition operators let you construct Condition elements that restrict access based on comparing a key to an ARN. The ARN is considered a string. This value is available for only some services; not all services support request values that can be compared as ARNs.

Condition OperatorDescription

ArnEquals

Matching for ARN

ArnNotEquals

Negated matching for ARN

ArnLike

Case-insensitive matching of the ARN. Each of the six colon-delimited components of the ARN is checked separately and each can include a multi-character match wildcard (*) or a single-character match wildcard (?).

ArnNotLike

Negated case-insensitive matching of the ARN. The values can include a multi-character match wildcard (*) or a single-character match wildcard (?) anywhere in the string.

The following example shows a policy you need to attach to any Amazon SNS queue that you want to send SNS messages to. It gives Amazon SNS permission to send messages to the queue (or queues) of your choice, but only if the service is sending the messages on behalf of a particular Amazon SNS topic (or topics). You specify the queue in the Resource field, and the Amazon SNS topic as the value for the SourceArn key.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Principal": {"AWS": "123456789012"},
    "Action": "SQS:SendMessage",
    "Resource": "arn:aws:sqs:REGION:123456789012:QUEUE-ID",
    "Condition": {"ArnEquals": {"aws:SourceArn": "arn:aws:sns:REGION:123456789012:TOPIC-ID"}}
  }
}

...IfExists Condition Operators

You can add IfExists to the end of any condition operator name except the Null condition—for example, StringLikeIfExists. You do this to say "If the policy key is present in the context of the request, process the key as specified in the policy. If the key is not present, I don't care; don't fail the comparison because of its absence." Other condition elements in the statement can still result in a nonmatch, but not a missing key when checked with ...IfExists.

Example using IfExists

Many condition keys describe information about a certain type of resource and only exist when accessing that type of resource. These condition keys are not present on other types of resources. This doesn't cause an issue when the policy statement applies to only one type of resource. However, there are cases where a single statement can apply to multiple types of resources, such as when the policy statement references actions from multiple services or when a given action within a service accesses several different resource types within the same service. In such cases, including a condition key that applies to only one of the resources in the policy statement can cause the Condition element in the policy statement to fail such that the statement's "Effect" does not apply.

For example, consider the following policy example:

{
  "Version": "2012-10-17",
  "Statement": {
    "Sid": "THISPOLICYDOESNOTWORK",
    "Effect": "Allow",
    "Action": "ec2:RunInstances",
    "Resource": "*",
    "Condition": {"StringLike": {"ec2:InstanceType": [
      "t1.*",
      "t2.*",
      "m3.*"
    ]}}
  }
}

The intent of the preceding policy is to enable the user to launch any instance that is type t1, t2 or m3. However, launching an instance actually requires accessing many resources in addition to the instance itself; for example, images, key pairs, security groups, etc. The entire statement is evaluated against every resource that is required to launch the instance. These additional resources do not have the ec2:InstanceType condition key, so the StringLike check fails, and the user is not granted the ability to launch any instance type. To address this, use the StringLikeIfExists condition operator instead. This way, the test only happens if the condition key exists. You could read the following as: "If the resource being checked has an "ec2:InstanceType" condition key, then allow the action only if the key value begins with "t1.*", "t2.*", or "m3.*". If the resource being checked does not have that condition key, then don't worry about it."

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "ec2:RunInstances",
    "Resource": "*",
    "Condition": {"StringLikeIfExists": {"ec2:InstanceType": [
      "t1.*",
      "t2.*",
      "m3.*"
    ]}}
  }
}

Condition Operator to Check Existence of Condition Keys

Use a Null condition operator to check if a condition key is present at the time of authorization. In the policy statement, use either true (the key doesn't exist — it is null) or false (the key exists and its value is not null).

For example, you can use this condition operator to determine whether a user is using their own credentials for the operation or temporary credentials. If the user is using temporary credentials, then the key aws:TokenIssueTime exists and has a value. The following example shows a condition that states that the user must not be using temporary credentials (the key must not exist) for the user to use the Amazon EC2 API.

{
  "Version": "2012-10-17",
  "Statement":{
      "Action":"ec2:*",
      "Effect":"Allow",
      "Resource":"*",
      "Condition":{"Null":{"aws:TokenIssueTime":"true"}}
  }
}

Supported Data Types

This section lists the data types that are supported when you specify values in IAM policies. The policy language doesn't support all types for each policy element; for information about each element, see the preceding sections.

  • Strings

  • Numbers (Ints and Floats)

  • Boolean

  • Null

  • Lists

  • Maps

  • Structs (which are just nested Maps)

The following table maps each data type to the serialization. Note that all policies must be in UTF-8. For information about the JSON data types, go to RFC 4627.

TypeJSON

String

String

Integer

Number

Float

Number

Boolean

true false

Null

null

Date

String adhering to the W3C Profile of ISO 8601

IpAddress

String adhering to RFC 4632

List

Array

Object

Object