What is Amazon IAM or AWS IAM?

Have you every tried login to AWS account , if yes then certainly you are using Amazon IAM service, but do you know how is this service being called when you login. If no this tutorial is for you.

One of the most important service in Amazon cloud i.e. AWS cloud is IAM because without this service you will not be able perform any operation within AWS account.

Why not learn and completely understand what is AWS IAM and what you can do to secure your AWS Cloud.

Lets quickly dive in.

Table of content

  1. What is AWS IAM ?
  2. How to find your AWS account ID
  3. AWS root login
  4. Features of IAM AWS
  5. How IAM Login Works?
  6. How to find your AWS account ID
  7. Authorized to access AWS resources
  8. AWS IAM users
  9. AWS Access Keys
  10. What is AWS IAM role?
  11. Assuming IAM Role
  12. Granting a IAM user permissions to switch roles
  13. Allowing IAM user to assume Role in same AWS account
  14. Granting a IAM user permissions to pass a IAM role to an AWS service
  15. How to use a IAM role to delegate access to resources in different AWS accounts.
  16. AWS IAM Policy
  17. Session Policies in IAM policy
  18. AWS Managed Policies
  19. AWS Inline Policies
  20. Customer Managed Policy
  21. How an IAM user can access DynamoDB Table using IAM Managed Policy
  22. What is IAM policy generator?
  23. AWS IAM CLI
  24. AWS STS (Security Token Service)
  25. IAM access analyzer
  26. Conclusion

What is AWS IAM ?

AWS Identity and Access management (IAM) is a Amazon web service that allows you to control access to AWS resources. IAM controls who can be authenticated that is who can sign in and authorized (has permissions) to use the resources.

AWS IAM is used to securely control access to AWS resources.  When you create your AWS account by default the user is root which has access to everything.

Root user has access to AWS resources which is created at the time of creation of an AWS account. Service control policies In organizations can restrict the permission that are granted to root user.

There are three important things that one must know in the AWS IAM.

  • Principal: When you use AWS IAM user or role to perform actions in AWS you are considered principal. Principal can be a user, role, federated users such as FB, Amazon or corporate users or if any application. Policies grant
  • Identities: Identities are things that are used to identify themselves. users, group and a role.

How to find your AWS account ID

Lets get into this section and quickly see how you can find AWS account ID.

  • Use aws sts get-caller-identity command to fetch the AWS account ID
  • Under Support and Support center on the console you will find the AWS account ID

If you want the URL for your sign-in page to contain your company name (or other friendly identifier) instead of your AWS account ID, you can create an account alias. 

AWS root login

AWS root user has complete access to AWS account. You can login to AWS account using root user with email address and the password. Also you can create, rotate, disable, or delete access keys (access key IDs and secret access keys) for your AWS account root user.

You may feel free to do change the password of AWS root user. Also you can configure and enable a virtual MFA device for your root user and to do that sign in to the AWS Management Console and on the right side of the navigation bar, choose your account name, and choose Security credentials. If necessary, choose Continue to Security credentials.


                  Security credentials in the navigation menu

Features of IAM AWS

There are various benefits and features of AWS IAM which one must know. Lets discuss them now.

  • Even if you don’t have password or credentials to AWS account still you can login to AWS account using AWS IAM.
  • You can manage different level of permissions in AWS IAM.
  • With AWS IAM you can grant access to applications running on AWS EC2.
  • With AWS IAM you can grant access to those users who credentials are stored outside of AWS as well. AWS IAM allows users by granting temporary credentials.

How IAM Login Works?

There are multiple ways in which you can access AWS IAM such as:

  • AWS Management Console
  • AWS Command Line Tools
  • AWS SDKs
  • IAM Query API

Authorized to access AWS resources

You must be authenticated (signed in to AWS) as the AWS account root user, as an IAM user, or by assuming an IAM role to access any AWS resources.

  • When you access AWS by using IAM users then it has specific permissions but the credentials are for longer terms. IAM groups are collection of IAM users and you cannot sign as IAM groups in AWS account.
  • When you access AWS by using federation, you are indirectly assuming a role. Users have permanent long-term credentials, but roles provide temporary credentials

AWS IAM users

AWS IAM user is a human identity who interacts with AWS account using username-password or access keys or by assuming a role.

An IAM user with administrator permissions is not the same thing as the AWS account root user.

Users or groups can have multiple policies attached to them that grant different permissions. IAM users sign in to AWS account using the below link.

https://My_AWS_Account_ID.signin.aws.amazon.com/console/

AWS Access Keys

Access keys are long term credentials which are used to login via API or AWS CLI’s. It contains two parts access key ID and a secret access key. As a best practice it is advisable to rotate the access keys.

To create access keys for your own IAM user, you must have the permissions from the following policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "CreateOwnAccessKeys",
            "Effect": "Allow",
            "Action": [
                "iam:CreateAccessKey",
                "iam:GetUser",
                "iam:ListAccessKeys",
                "iam:TagUser"
            ],
            "Resource": "arn:aws:iam::*:user/${aws:username}"
        }
    ]
}

What is AWS IAM role?

IAM role is an identity in AWS account which has permissions attached as polices and you or a AWS service can assume it to access another AWS services.

IAM roles are secure way to grant permissions to your AWS resources. Role doesn’t have standard long term credentials such as password or access keys rather it has temporary security credentials for your role session.

There are three types of IAM roles:

  • IAM role is intended to be assumable by anyone who needs it. when you assume a role, it provides you with temporary security credentials for your role session.
  • Service Roles: A service role is an IAM role that a service assumes to perform actions on your behalf
  • Service Role for EC2 instance: A special type of service role that an application running on an Amazon EC2 instance can assume to perform actions in your account

Roles have two types of policies:

Permission policy: Policy which defines which AWS resources a role can access and the actions it can perform on those resources.

Trust policy: Policy which defines which identities can assume the role. One role can have one Trust policy.

Assuming IAM Role

In this sections lets learn when you can assume role.

  • Federated user access: Federated user access AWS account by assuming a role.
  • Temporary IAM user permissions: A user can assume an IAM role to temporarily take on different permissions.
  • Cross account access: You can use an IAM role to allow someone in a different account to access resources in your account. However, with some AWS services, you can attach a policy directly to a resource (instead of using a role as a proxy)
  • Cross service access: Some of AWS services access other AWS services in AWS account.
  • Applications running on AWS EC2

Granting a IAM user permissions to switch roles

When an administrator creates a role for cross-account access, they establish trust between the account that owns the role, the resources (trusting account), and the account that contains the users (trusted account). To do this, the administrator of the trusting account specifies or adds the trusted account number as the principal in the role’s trust policy which will actually allow any user in the trusted account to assume the role.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "sts:AssumeRole",
    "Resource": "arn:aws:iam::account-id:role/Test*"
  }
}

Allowing IAM user to assume Role in same AWS account

In this section we will learn to allow the IAM user DevUser in account 123456789012 to assume the Developer_Role in the same account. Lets checkout how to achieve this.

  • On the role page, within the role add a policy as shown below.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AssumeRole",
      "Effect": "Allow",
      "Action": "sts:AssumeRole",
      "Resource": "arn:aws:iam::123456789012:role/Developer_Role"
    },
    {
      "Sid": "SetAwsUserNameAsSourceIdentity",
      "Effect": "Allow",
      "Action": "sts:SetSourceIdentity",
      "Resource": "arn:aws:iam::123456789012:role/Developer_Role",
      "Condition": {
        "StringLike": {
          "sts:SourceIdentity": "${aws:username}"
        }
      }
    }
  ]
}

  • Again on the same role page within Trust policy add the below policy and permissions.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowDevUserAssumeRole",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:user/DevUser"
      },
      "Action": [
        "sts:AssumeRole",
        "sts:SetSourceIdentity"
      ],
      "Condition": {
        "StringEquals": {
          "sts:SourceIdentity": "DevUser"
        }
      }
    }
  ]
}

Granting a IAM user permissions to pass a IAM role to an AWS service

This allows the service to assume the role later and perform actions on your behalf. for example AWS EC2 service to perform later tasks on your behalf. Lets say if you want a IAM user the ability to pass any of an approved set of roles to the Amazon EC2 service then you need below policies.

  • IAM permissions policy.
{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": [ 
            "iam:GetRole",
            "iam:PassRole" 
        ],
        "Resource":  "arn:aws:iam::account-id:role/EC2-roles-for-XYZ-*"
    }
}     
  • A trust policy for the role that allows the service to assume the role. 
{
    "Version": "2012-10-17",
    "Statement": {
        "Sid": "TrustPolicyStatementThatAllowsEC2ServiceToAssumeTheAttachedRole",
        "Effect": "Allow",
        "Principal": { "Service": "ec2.amazonaws.com" },
       "Action": "sts:AssumeRole"
    }
}                    

How to use a IAM role to delegate access to resources in different AWS accounts.

In this section we will learn how to use a IAM role to delegate access to different AWS resources in different account. Here, a user named user1 will access AWS S3 bucket stored in different AWS account. Lets check what we need to accomplish this activity..

  • Two AWS account where Account 1 named Dev and Account 2 named Prod.
  • User 1 already created in Dev account.
  • AWS S3 bucket created in production account named productionapp.
  • IAM role named updateApp in production account.

Adding Trust policy to IAM role

For user 1 to be able to access the production IAM role from dev account you need to add trust policy in AWS IAM role named UpdateApp. A JSON policy document in which you define the principals that you trust to assume the role.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "stsAssumeRole",
      "Principal" : {
                   "AWS": [
                                "arn:aws:iam:: user1:user/UpdateApp"         
                                 "AWS-account-no"                 
              ]
          }
}

Granting AWS IAM user access

To allow IAM user user1 to access AWS S3 in production account we need to allow IAM user user1 from dev account to assume role of production account.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "sts:AssumeRole",
    "Resource": "arn:aws:iam:: Prod:role/UpdateApp"
  }
}

Adding Resource policy on AWS S3

For bucket to allow user1 to perform operations we need to grant below permissions.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListBucket",
        "s3:GetBucketLocation",
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"

       ],
      "Resource": "arn:aws:s3:::productionapp"
    },
  ]
}

Assume a IAM role

Next step is to assume role ( UpdateApp ) by IAM user user1 and to do that create a profile in aws credentials path.

[profile sandbox3]
  Role_Arn = “arn:aws:iam::999999999999:role/UpdateApp”
  Source_Profile = default

Testing AWS access to AWS S3 buckets

To test if the user1 in dev account is able to access AWS S3 bucket in production account.

aws s3 ls –profile sandbox3 

aws sts assume-role --role-arn "arn:aws:iam::999999999999:role/UpdateApp" --role-session-name "David-ProdUpdate" 

AWS IAM Policy

In AWS account when a principal makes a request to AWS service then principal is authenticated that is it is signed in and then later it is authorized ( has permissions).

The permissions are granted by attaching policies that are in JSON documents. By default, all requests are implicitly denied. So, we apply explicit allow on identities or by granting resource policy. Even if policies are applied there are SCP ( Organization SCP ) or session policy which overrides it.

  • Identity-based policies are permissions policies that you attach to an IAM identity, such as an IAM user, group, or role.
    • Managed policies: Standalone identity-based policies that you can attach to multiple users, groups, and roles in your AWS account
      • AWS managed policies – Managed policies that are created and managed by AWS.
      • Customer managed policies – Managed policies that you create and manage in your AWS account.
    • Inline policies – Policies that you create and manage and that are embedded directly into a single user, group, or role
  • Resource-based policies are permissions policies that you attach to a resource such as an Amazon S3 bucket or an IAM role trust policy. Resource-based policies are inline policies, and there are no managed resource-based policies. The IAM service supports only one type of resource-based policy called a role trust policy, which is attached to an IAM role
  • Roles have two types of policies attached to them:
    • Trust policy – Policy which defines which identities can assume the role
    • Permissions policy – Policy which defines which AWS resources a role can access and the actions it can perform on those resources.

Session Policies in IAM policy

The session policies are passed as a parameter when you create a temporary session for a role or federated user. You will pass the session policies when you use AWS CLI or AWS API.

The permissions for a session are the intersection or a combination of the identity-based policies for the IAM entity (user or role) used to create the session and the session policies. Permissions can also come from a resource-based policy.

AWS Managed Policies

This policy is managed solely by Amazon or AWS. This policy has its own ARN and includes the policy name. Some of the Example of AWS Managed policies are:

  • arn:aws:iam::aws:policy/IAMReadOnlyAccess
  • AmazonDynamoDBFullAccess
  • IAMFullAccess

AWS Inline Policies

An inline policy is a policy created for a single IAM identity such as AWS IAM user, group, or role. Inline policies are mapped between a policy and to an identity.

Customer Managed Policies

Customer managed policies are those policies which are created by you and according to that ARN and name is provided.

Below is the example of customer managed policy in IAM. Customer managed policy that allows any attached user to sign into the AWS Management Console with read-only access to IAM data.

{
    "Version": "2012-10-17",
    "Statement": [ {
        "Effect": "Allow",
        "Action": [
            "iam:GenerateCredentialReport",
            "iam:Get*",
            "iam:List*"
        ],
        "Resource": "*"
    } ]
}

How an IAM user can access DynamoDB Table using IAM Managed Policy

Below is the policy through which an IAM user can access DynamoDB Table using IAM Managed Policy.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "dynamodb:*",
    "Resource": "arn:aws:dynamodb:us-east-2:123456789012:table/Books"
  }
}

What is IAM policy generator?

If you need a handy way to generate and use a IAM policy then AWS provides a tool that allows you to create a policy generator for you based on UI. In Policy generator tool you need to define the policy type and add statements as shown below.

AWS IAM CLI

With AWS CLI that is command line utility you can perform various operations on IAM services such as creating IAM users, policies, groups etc. One of the example is to create a AWS IAM policy as below. The following command creates a customer managed policy named my-policy

aws iam create-policy --policy-name my-policy --policy-document file://policy

AWS STS (Security Token Service)

AWS STS is used for generating temporary credentials. Temporary credentials are generated by STS service. The endpoint of STS service is https://sts.amazonaws.com . You can use this endpoint in any region. The AWS STS API operations create a new session with temporary security credentials that include an access key pair and a session token.

Temporary credentials are used for:

  1. Identity federation  
    1. Enterprise Identity Federation
      1. Custom Federation Broker
      1. Federation using SAML
    1. Web Identity Federation (Google, FB, Amazon)
  2. Roles for cross account access also known as delegation
  3. Roles for EC2
  4. Roles for other AWS services.
  • Using temporary credentials in Amazon EC2 instances

You can create an IAM Role and attach it to the AWS EC2 instance. It is also known as Instance profile.

  • Using temporary security credentials with the AWS SDKs

You can programmatically call AWS STS API like AssumeRole and extract credentials and token and use them as a session.

assumeRoleResult = AssumeRole(role-arn);
tempCredentials = new SessionAWSCredentials(
   assumeRoleResult.AccessKeyId, 
   assumeRoleResult.SecretAccessKey, 
   assumeRoleResult.SessionToken);
s3Request = CreateAmazonS3Client(tempCredentials);

  • Using temporary security credentials with the AWS CLI
aws sts assume-role --role-arn arn:aws:iam::123456789012:role/role-name --role-session-name "RoleSession1" --profile IAM-user-name > assume-role-output.txt
  • If you’re making direct HTTPS API requests to AWS, you can sign those requests with the temporary security credentials that you get from the AWS Security Token Service (AWS STS). To do this, you use the access key ID and secret access key that you receive from AWS STS. You use the access key ID and secret access key the same way you would use long-term credentials to sign a request. You also add to your API request the session token that you receive from AWS STS

IAM access analyzer

AWS Identity and Access Management Access Analyzer allows you to identify and find the resources in your organization and accounts, such as Amazon S3 buckets , AWS EC2 or even IAM roles, that are shared with an external entity. With IAM access analyzer you can easily identify unintended access to your resources and data, which is a security risk.

With IAM access analyzer you also manage below activities.

  • Use IAM Access Analyzer to generate least-privilege policies based on access activity.
  • Verify public and cross-account access to resources with IAM Access Analyzer.
  • Use IAM Access Analyzer to validate your IAM policies to ensure secure and functional permissions

Conclusion

In this tutorial you learnt everything one should know about AWS IAM. After this knowledge you should be able to secure your users within AWS account or external users and AWS resources efficiently.

Advertisement

How to Create an IAM user on an AWS account using shell script

Are you using the correct credentials and right permissions to log in to your AWS account? From a security point of view, it is essential to grant the right permissions to users and identities that access AWS accounts. That is where Identity and access management (AWS IAM) plays a vital role.

In this tutorial, you will learn how to create an IAM user on an AWS account using shell script step by step. Let’s get started.

Join 50 other followers

Table of Content

  1. What is Shell Scripting or Bash Scripting?
  2. What is AWS IAM or What is IAM in AWS ?
  3. AWS IAM Resources
  4. AWS IAM entities
  5. AWS IAM Principals
  6. AWS IAM Identities
  7. Prerequisites
  8. How to create IAM user in AWS manually
  9. How to create AWS IAM user using shell script in Amazon account
  10. Executing the Shell Script to Create AWS IAM user
  11. Verifying the Newly created IAM user in AWS
  12. Conclusion

What is Shell Scripting or Bash Scripting?

Shell Script is a text file containing lists of commands executed on the terminal or shell in one go in sequential order. Shell Script performs various important tasks such as file manipulation, printing text, program execution.

Shell script includes various environmental variables, comments, conditions, pipe commands, functions, etc., to make it more dynamic.

When you execute a shell script or function, a command interpreter goes through the ASCII text line-by-line, loop-by-loop, test-by-test, and executes each statement as each line is reached from top to bottom.

What is AWS IAM or What is IAM in AWS ?

AWS IAM stands for Amazon Managed service Identity and access management service that controls who can access AWS account and what resources in AWS account can be accessed.

When you create a new AWS account by default, you are the root user, have control over the entire AWS account, and can access everything. The Root user can log in to an AWS account using an email address and password you registered.

There are some important components in AWS IAM such as:

AWS IAM Resources

AWS IAM resources are the objects stored in IAM, such as user, role, policy, group, and identity provider.

AWS IAM Resources
AWS IAM Resources

AWS IAM entities

AWS IAM entities are those objects which can authenticate on AWS account, such as root user, IAM user, federated user, and assumed IAM roles.

AWS IAM entities
AWS IAM entities

AWS IAM Principals

AWS IAM Principals are the applications or users who use entities and work with AWS services. For example, Python AWS Boto3 or any person such as Robert.

AWS IAM Identities

AWS IAM Identities are the objects which identify themselves to another service such as IAM user “user1” accessing AWS EC2 instance. This shows that user1 shows its own identity that I have access to create an AWS EC2 instance. Examples of identity are group, users, and role.

AWS IAM Identities
AWS IAM Identities

Prerequisites

  1. AWS account to create ec2 instance. If you don’t have AWS account please create from AWS account or AWS Account
  2. Windows 7 or plus edition where you will execute the shell script.
  3. AWS CLI installed. To install AWS CLI click here.
  4. Git bash. Yo install Git bash click here
  5. Code editor for writing the shell script on windows machine such as visual studio code. To install visual studio click here.

How to create IAM user in AWS manually

Do you know root user is a shared account with all privileges,’ but it is not recommended to be used for any activity on an AWS account?

Instead of using a root user, a shared user, use an individual user and have various permissions accordingly.

IAM user can access a single AWS EC2 instance or multiple AWS S3 buckets or even attain admin access to gain complete access to AWS account.

  • Navigate to the Amazon Management console and and search for IAM.
  • Under AWS IAM page click on Add users button in IAM dashboard.
Adding a IAM user in AWS Cloud
Adding an IAM user in AWS Cloud
  • Now, provide the username, add a custom password and also select Programmatic access as shown below.
Providing the details to create a IAM user
Providing the details to create an IAM user
  • Click on Next permissions and choose Attach existing policies. This tutorial will grant Administrator access to the IAM user that you created previously.
Attaching IAM policy to IAM user in AWS
Attaching IAM policy to IAM users in AWS
  • For now skip tagging and click on create user. IAM user is created successfully . Now save the access key ID and Secret access key that will be used later in the article.
Downloading the AWS IAM user credentials for IAM user
Downloading the AWS IAM user credentials for IAM user

How to create AWS IAM user using shell script in Amazon account

Previously you learned how to create an IAM user manually within the Amazon Management console, but this section lets you create an AWS IAM user using a shell script in an Amazon account. Let’s quickly jump into and create the script.

  • Create a folder of your windows machine at any location. Further under the same folder create a file named create-iam-user.sh and copy/paste the below code.
#! /bin/bash
# Checking if access key is setup in your system 

if ! grep -q aws_access_key_id ~/.aws/config; then      # grep -q  Turns off Writing to standard output
   if ! grep -q aws_access_key_id ~/.aws/credentials; then 
      echo "AWS config not found or CLI is not installed"
      exit 1
    fi 
fi


# read command will prompt you to enter the name of IAM user you wish to create 

read -r -p "Enter the username to create": username

# Using AWS CLI Command create IAM user 

aws iam create-user --user-name "${username}" --output json

# Here we are creating access and secret keys and then using query and storing the values in credentials

credentials=$(aws iam create-access-key --user-name "${username}" --query 'AccessKey.[AccessKeyId,SecretAccessKey]'  --output text)

# cut command formats the output with correct coloumn.

access_key_id=$(echo ${credentials} | cut -d " " -f 1)
secret_access_key=$(echo ${credentials} | cut --complement -d " " -f 1)

# echo command will print on the screen 

echo "The Username "${username}" has been created"
echo "The access key ID  of "${username}" is $access_key_id "
echo "The Secret access key of "${username}" is $secret_access_key "

Executing the Shell Script to Create AWS IAM user

Previously you created the shell script to create the AWS IAM user, which is great, but it is not doing much unless you run it. Let’s execute the shell script now.

  • Open the visual studio code and then open the location of file create-iam-user.sh.
Opening Shell script on visual studio code
Opening Shell script on visual studio code
  • Finally execute the shell script.
./create-iam-user.sh
Executing the shell script to create the AWS IAM user
Executing the shell script to create the AWS IAM user

Verifying the Newly created IAM user in AWS

Earlier in the previous section, the shell script ran successfully; let’s verify the if IAM user has been created in the AWS account.

  • Open your favorite web browser and navigate to the AWS Management Console and log in.
  • While in the Console, click on the search bar at the top, search for ‘IAM’, and click on the IAM menu item and you should see the IAM user is creared.
Verifying the Newly created IAM user in AWS
Verifying the Newly created IAM user in AWS

Conclusion

In this tutorial, you learned how to create AWS IAM users using shell script on AWS step by step. With IAM, you get individual access to AWS account, and you can manage permissions accordingly.

Now that you have newly created IAM users in the AWS account, which AWS resource do you plan to create next using this?