iam.md

# AWS IAM

## Authentication

There are three ways IAM authenticates a principal:

- User Name/Password
- Access Key
- Session Token

IAM allows you to create a password policy enforcing password complexity and expiration.

An Access Key is a combination of an access key ID `(20 characters)` and an access secret key `(40 characters)`.

When a process operates under an assumed role, the `temporary security token` provides an access key for authentication. In addition to the access key, _the token also includes a session token_.

---

## Authorization

Authorization is controlled by IAM polices:

- Customer Managed Policy
- AWS Managed Policy

---

## IAM User

An IAM user has no permission when its freshly created.

- Hard Limit of `5000 users` per account
- Overcome this using Identity federation

---

## IAM Group

We cant login to an IAM Group.

- Hard Limit of `500 groups` per account
- Groups are not true identity
- Can be referenced as a principal in a policy.

---

## IAM Role

Unlike an IAM User which is supposed to be used by a single principal, an IAM Role is supposed to be used by many or an unknown number of principles (humans, applications or services) inside or outside your AWS account.

Why cant you use group instead?

With a role we borrow the permission for a short period of time.

Whats the difference between logging into an IAM User vs using an IAM Role?

- IAM Users can have identity, permission and policy attached to them. This is either via inline JSON or attached managed policy. These are called `Permissions Policy`.

- IAM Roles can have two types of policy attached:
  - Trust Policy
  - Permissions Policy

### Trust Policy

This controls which identities can assume this given role.

A trust policy can reference different things:

- IAM Users, IAM Role and even AWS Services such as EC2
- Can refer to policies in other AWS accounts
- Can even allow anonymous usage of that account
- Can refer types of identity such as facebook, twitter, etc

[include example/sample here]

### Temporary Security Credentials

If role gets assumed by something that is allowed to assume it, then AWS creates Temporary Security Credentials.

- These credentials are then made available to the identity that assumed that role.
- Similar to access keys but have an expiry.
- On expiry, the identity will have to re-assume that role and then new credentials will be issued.

  When a process operates under an assumed role, the `temporary security token` provides an access key for authentication. In addition to the access key, _the token also includes a session token_.

### Permission Policy

AWS Resouces that are specified within the Permission Policy are allowed to be accessed using the Temporary Security Credentials.

- Every time the Temporary Security Credentials are used, the access is checked against the Permission Policy.
- Any change in permission policy implies a change in access allowed using the Temporary Security Credentials.

You could use a permission policy to limit the ability for the associated role to attach other roles to Amazon EC2 instances with the following permission policy, unless the role name is prefixed with `EC2-Webserver-`:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["iam:GetRole", "iam:PassRole"],
      "Resource": "arn:aws:iam::111122223333:role/EC2-Webserver-*"
    }
  ]
}
```

You should use restrictions on access to the `iam:PassRole` action with permission policies and permission boundaries. This means that the ability to attach roles to instance profiles for Amazon EC2 is limited, rather than using the trust policy on the role assumed by the EC2 instance to achieve this. This approach makes it much easier to manage scaling for both those principals attaching roles to EC2 instances, and the instances themselves.

### STS

When you assume a role, Temporary Security Credentials are generated by STS (Secure Token Service).

- `sts:AssumeRole` operation is used to assume the role.

Following policy allows only a user named PauloSantos, in AWS account number 111122223333, to assume the role if they have also authenticated with an MFA, are logging in from an IP address in the 203.0.113.0 to 203.0.113.24 CIDR range.

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:user/PauloSantos"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "BoolIfExists": {
          "aws:MultiFactorAuthPresent": "true"
        },
        "IpAddress": {
          "aws:SourceIp": "203.0.113.0/24"
        }
      }
    }
  ]
}
```

Here’s an example trust policy for a role designed for an Amazon EC2 instance to assume. You can see that the principal provided is the ec2.amazonaws.com service:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

---

## Referencing

A resource policy on S3 bucket can give acess to one or more, IAM User or IAM Roles.

- But an IAM group cant be referenced in a similar manner.

---

## When to use IAM Roles

Say for an Lambda function, there might be single copy or unknown number of copies runnning at the same time. Then a role might be an ideal entity to use in this case, as you dont have to provide any static credentials.

**Break Glass Situation**:

Say a helpdesk member has read only access as part of a certain group. But under special circumstances, he might need permissions to perform a certain operation. Such permission can be given on temporary basis using a Role.

**Reuse Existing Identities**:

Say, you have more than 5000 identites in your companies existing Microsoft Active Directory. External account can't be used in AWS directly. That means you cant access an S3 bucket using your external account in AWS directly.

So, ideally in this case you would make the external identity assume a role which is Active Directory in this case. When this role is assumed, temporary credentials are generated to allow access to resources within AWS such as S3 bucket.

**Cross Account Access**:

Say, your project that uses an AWS account relies on a Partner AWS account to retrieve the computations they have performed whose results are stored in an S3 bucket in their account. Your account has 1000's of identities. And the partner AWS account doesn't want to create IAM users for all your users in their account.

In this situation, its ideal to use a role created in the Partner AWS account. So, your users can assume that role and get temporary credentials to access the S3 bucket.

---

# AWS Organistaions

Without AWS Organisations, each AWS account for a given organistaion would have a set of IAM Users in each AWS account as well as payment methods.

Beyond 5-to-10 AWS Accounts, this becomes unmanagable.

---

## Management Account

With a standard AWS Account, we create an AWS Organistaion. This standard AWS Account then becomes the Management Account (previously known as Master Account).

- Though the standard AWS Account created the AWS Organisation, it doesnt become part of it.

With Management Account, you can invite existing standard AWS Accounts.

- When standard AWS account join an AWS Organisation, they are called Member Account.

So, we can have only one Management Account. And zero or more Member accounts.

---

## Organisation Root

You can create an structure of AWS Account within an AWS Organisation. This is useful when you have lots of accounts, that you want to group using business unit, function, development stage of the application, etc.

The structure of AWS Organisation is hierarchichal. Its similar to an inverted tree. The top of this tree is the root container called Organisation Root.

An Organisation Root contains, Management Account, Member Accounts or other Organisations called Organisational Unit.

---

## Organisational Unit (OU)

Contains Member Accounts or other Organisational Units.

---

## Consolidated Billing

The payment methods can be removed from the AWS Member Account and the consolidated billing can be done using the Management Account.

Management Account in this context is called the Payer Account.

---

## Cheaper Rates

With AWS you get discounts when using certain resources above a certain threshold.

These benefits gets pooled when using AWS Organisation.

---

## Create new member account

When adding standard AWS Account, there is invite process that needs to be followed.

But when a AWS Account is created directly under the AWS Organisation, invite is not needed.

- While adding a new account, the IAM role `OrganizationAccountAccessRole` is automatically created _within_ the newly created account.
- In case adding an existing account, `OrganizationAccountAccessRole` role needs to be created manually _within_ that account.

### Creating the role

To create the role under the existing member acount:

- Select type of trusted entity: Another AWS Account (Specifies we are gonna trust another AWS account)

- Specify accounts that can use this role:

  - Account ID: Management Account ID

- Role name: OrganizationAccountAccessRole

Another AWS Account (Specifies we are gonna trust another AWS account)

This role is created by making Management Account as the `Trusted Account` and its granted adminstrator priviledges.

---

## IAM Roles instead of IAM Users

When using AWS Organisation, you dont create users in every Member Account. Instead you create a role instead.

You need not keep all the users in a the Management Account. You can instead use any one AWS account to hold all the users.

- You essentially login to, say, non-production AWS account or use identity fedration.
- Once logged in, we can role switch into other accounts of the AWS Organisation.

### Switch Role

From Management Account, choose `Switch Role` option.

Enter the following:

- Account ID: account id of the account you are gonna switch into
- Role: role within that account you want to switch to
- Display Name
- Color

Say you switch using the above from training to production, notice that you dont need IAM Users to be created.

Since the role `OrganizationAccountAccessRole` had admin access, we will have admin access into the production account.

---

## Service Control Policies (SCP)

SCP is a policy document. It can be attached to:

- An Organisation (The Root Container)
- One or more Organisational Unit (OU) or
- A Member Account

### Allow list vs Deny list

While using SCP default is DENY

- You need to explicitly define the allow and deny permissions
- DENY always takes precedence

**FullAWSAccess policy**

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "*",
      "Resource": "*"
    }
  ]
}
```

**DenyS3 policy**

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Action": "s3:*",
      "Resource": "*"
    }
  ]
}
```

The above two policies will allow all resource access but deny AWS identities to access S3 under the AWS account.

### Inheritance

SCP inherit down the organisational tree. So, if they are attached to the organisation as a whole, they affect all the accounts within the organisation.

If they are attached to an organisational unit, they affect all the organisational units and accounts directly under that organisational unit.

If they are attached to member accounts, they affect only those accounts.

### Management Account

The Management Account is special and is not affected by the Service Control Policies.

### Defination

SCP are account permission boundries

- They limit what the account can do, `including account root user`

  Though root user can do everything under a given account. You can never restrict a root user. With SCP we are restricting what is allowed under a given account, in effect we are also restricting the root user.

- You can define which regions are allowed for a given account
- You can define what sizes of EC2 instances can be launched under a given account

### Permissions

SCP only act as boundries

- They dont grant any permissions
- You still need to give permissions to AWS identities to use AWS resources
- SCP's will limit the permissions that can be assigned

### Identity Policies

    Things that are both in SCP and Identity policy is allowed.

- Permission only in SCP is allowed but not granted as its not granted by identity policy

- Permission only in Identity Policy but not in SCP, is not allowed as its beyond whats allowed by SCP

![permission-evaluation-flow](ss/permission-evaluation-flow.webp)