kms.md

# KMS

- Regional and a Public Service.
- Each region is isolated when using KMS.
- It's a public service and occupies AWS public zone.
- It can be connected to by anything with permission in the public zone.

Create, store, and manage keys.

- Can handle both symmetric and asymmetric keys.
- Can perform cryptographic operations itself.

Keys never leave KMS

- KMS can create keys, manage keys, import keys and these keys can be used to perform operations
- But keys are locked inside KMS
- Primary function of KMS is that keys never leave KMS

KMS provides `FIPS 140-2 (L2)` complaint service.

- Some features are level 3 complaint as well

Update:

- Keys can now be replicated into other regions.

---

## Create Key

- key name
- key alias
- adminstrative permissions (choose who can administor this key)
- key usage permissions (choose who can use this key)

```json
{
  "Id": "key-consolepolicy-3",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Enable IAM User Permissions",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:root"
      },
      "Action": "kms:*",
      "Resource": "*"
    },
    {
      "Sid": "Allow access for Key Administrators",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:user/jack"
      },
      "Action": [
        "kms:Create*",
        "kms:Describe*",
        "kms:Enable*",
        "kms:List*",
        "kms:Put*",
        "kms:Update*",
        "kms:Revoke*",
        "kms:Disable*",
        "kms:Get*",
        "kms:Delete*",
        "kms:TagResource",
        "kms:UntagResource",
        "kms:ScheduleKeyDeletion",
        "kms:CancelKeyDeletion"
      ],
      "Resource": "*"
    },
    {
      "Sid": "Allow use of the key",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:user/jack"
      },
      "Action": [
        "kms:Encrypt",
        "kms:Decrypt",
        "kms:ReEncrypt*",
        "kms:GenerateDataKey*",
        "kms:DescribeKey"
      ],
      "Resource": "*"
    },
    {
      "Sid": "Allow attachment of persistent resources",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:user/jack"
      },
      "Action": ["kms:CreateGrant", "kms:ListGrants", "kms:RevokeGrant"],
      "Resource": "*",
      "Condition": {
        "Bool": {
          "kms:GrantIsForAWSResource": "true"
        }
      }
    }
  ]
}
```

---

## Customer Master Keys (CMK)

CMK's are containers for the actual `physical` master key.

It is logical and contains

- ID
- Date
- Policy
- Description
- State

Every CMK is backed by physical key material

- This physical key material is held by KMS and is used for encryption and decryption
- This physical key material can be generated by KMS
- Or imported into KMS

This physical key material can be used to encrypt or decrypt data thats upto `4KB` in size.

### Types of CMK

- AWS Managed
- Customer Managed CMK

### Key Concepts

- CMK's are isolated to a region and never leave that region. They also never leave KMS.
- You cannot extract a CMK.
- CMK's are configurable. You can allow other AWS accounts to access this.
- Both AWS and Customer Managed CMK's support key rotation.
  - During the key rotation the physical key material used for encryption is changed.
- AWS managed keys are always rotated. This feature can't be disabled for AWS managed keys.
  - Keys are rotated every 1095 days(3 years)
  - When we start using encyprt with KMS for different services, AWS managed keys are created
- Customer Managed Keys support rotation.
  - Disabled by default
  - Keys are rotated once a year
  - Once enabled, this cannot be disabled

### Aliases

These can be used to specify the CMK. So the underlying CMK can be changed.

- Just like CMK, aliases are regional too.
- Every alias in each region has its associated CMK different from other regions.

---

## KMS and CMK

On `CreateKey` a CMK will be created in KMS. This key will be stored into KMS in an encrypted form.

During `Encrypt` we send the data to be encrypted. Also specifying the key to be used.

- If all permissions are met, KMS decrypts the CMK.
- Uses the CMK to encrypt the plain text data.
- Returns the encrypted data.

During `Decrypt` we send the encrypted data to KMS

- Key to be used doesnt have to be specifed
- KMS gets this information from the cyphertext encoded into the encrypted data
- If permissions are met, KMS will decrypt the CMK and uses that to decrypt the encrypted data

CreateKey, Encrypt and Decrypt are individual operations and require their own permissions.

## Data Encryption Key (DEK)

### Why to use DEK

CMK will be used to create encrypted DEK. This process of encrypting one key with another is called envelope encryption.

    CMK will be a symmetric key as its used for both encryption and decryption

Now encrytped DEK and encrypted object is stored without the need of storing the plaintext DEK.

So even if someone gained access to encrypted DEK and encrypted object, they will not be able to perform decryption as the CMK was used to encrypt DEK. And CMK is stored in KMS.

### GenerateDataKey

Using the GenerateDataKey operation will indicate KMS which CMK to be used, which will be used to generate Data Encryption Key.

- Data Encryption Key can be used to overcome the 4KB limit over data to be encrypted

When a DEK is generated, KMS returns the key in two forms:

- Plain text
- Encrypted

### Encyption Process

You use the plain text version of the DEK to encrypt the data. Once done, you discard the plain text DEK.

- KMS doesnt perform encryption on data larger than 4KB using the DEK
- This operation is to be done by customer or the service using the DEK
- KMS doesnt track the DEK usage
- So we can use the same DEK to encrypt multiple files or request one for each file

### Decryption Process

You pass the DEK back to KMS and you ask it to decrypt it using the CMK that was used to generate the DEK.

- Use the plain text DEK returned by KMS
- Decrypt the encrypted file
- Discard the plain text DEK

### Storage of DEK

KMS does not store DEK in any form

- Its returns the DEK to the service requesting the key and then discards it
- Key is discarded as KMS doesn't perform encryption or decryption of data using DEK

### S3

S3 uses DEK for every object that is encrypted in it.

- It encrypts the object using plain text DEK and then only stores the encrypted version of DEK

---

## Key Policies and Security

Key Policy is the starting point for security on AWS.

- Its a `resource policy`, similar to bucket policy on S3 bucket, but on a key
- Every CMK has a key policy

Unlike other AWS services, KMS should be explicitly told the keys trust the AWS account they are in.

The following policy means that the key having the following key policy, will allow AWS account `111122223333` to manage it.

```json
{
  "Sid": "Enable IAM policies",
  "Effect": "Allow",
  "Principal": { "AWS": "arn:aws:iam::111122223333:root" },
  "Action": "kms:*",
  "Resource": "*"
}
```

You always need such key policies.

- The key trusts the account
- So the account can manage it by applying IAM permissions policy to the IAM users in that account

So, in order for IAM to work.

- IAM is trusted by the account
- The account must be trusted by the key

Chain of trust:

    key -    account -    IAM -    IAM user

### IAM Policy

The following gives the holder of the policy the rights to use the key to Encrypt or Decrypt the data.

```json
{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": ["kms:Encrypt", "kms:Decrypt"],
    "Resource": "arn:aws:iam:*:111122223333:key/*"
  }
}
```

These kinds of policy can be used to create groups of users. Say, you create groups of user:

- who can create and manage the keys but not use them
- users who can only use the keys

---

## Using CMK to encrypt and decrypt data via CLI

```sh
echo "find all the doggos, distract them with the yumz" > battleplans.txt

aws kms encrypt \
    --key-id alias/catrobot \
    --plaintext fileb://battleplans.txt \
    --output text \
    --query CiphertextBlob \
    | base64 --decode not_battleplans.enc

aws kms decrypt \
    --ciphertext-blob fileb://not_battleplans.enc \
    --output text \
    --query Plaintext | base64 --decode decryptedplans.txt
```

---

# Object Encryption

Buckets aren't encrypted, **objects are**. Each object can use a different encryption method.

## Types of S3 Encryption

Client Side Encryption

- Objects are encrypted before they are sent to S3.
- Client decides the keys to be used, process to be followed for the encryption
- Doesnt use S3 for any part of the encryption. Just stores the encrypted objects post encryption on client side.

Server Side Encryption

- The objects arent initially encrypted, only when data is sent to S3 it is encrypted via HTTPS (encryption in transit)
- When the data hits the S3 endpoint, the object are encrypted.

```

User or App     ---      S3 Endpoint     ---     S3 Storage

```

Both of these refer to encryption at rest.

Both of these use encryption in transit for S3. This comes standard with S3.

---

## Server Side Encryption

Involves:

- Encryption of the objects
- Management of keys

### SSE-C (Server-side encryption with customer provided keys)

- Customer is responsible for the keys management.
- S3 endpoint performs the encryption of objects.
- Customer needs to pass the key along with the object(unencrypted) to be encrypted to S3 endpoint.

Hash of the key:

- Once the key and object arrive, it is encrypted. A hash of the key is taken and attached to the object.
- The hash can identify if the specific key was used to encrypt the object.
- The key is then discarded after the hash is taken.

Post encryption:

- The key is discarded and is not stored along with the object in S3.

For decryption:

- You need to specify the object to be decrypyted with the key that was used to encrypt the object.
- If the has of the key specified in the request matches with the hash attached to the requested object, S3 returns the unencrypted object and discards the key.

### SSE-S3 AES256 (Server-side encryption using S3 managed keys)

```

User or App     ---      S3 Endpoint     ---     S3 Storage
                              |
                              |
                              |
                              |
                    Master Key (Handled by S3)

```

- S3 is responsible for the keys management.
- S3 generates master key, when you pick SSE-S3 for the first time. This master key is fully managed and rotated by S3.

For encryption:

- You just provide the object to be encrypted to S3 endpoint.
- When an object is added, it generates a key specifically for that object. It uses that key to encrypt the given object.
- The master key is used to encrypt that key used.

Post encryption:

- The original key is discarded.
- The encrypted key and the encrypted object are stored in S3 post this process.

Challenges with using SSE-S3

- Regulatory enviromment where the keys and access needs to be controlled.
- No way to control key material rotation.
- No role seperation. A full S3 admin can rotate keys as well as encrypt or decrypt data. (In some domains, these is against the company policy. A clear role seperation on who can manage the keys and who can use the keys needs to be maintained)

### SSE-KMS (Server-side encryption using customer master keys stored in AWS KMS)

```

User or App     ---      S3 Endpoint     ---     S3 Storage
                              |
                              |
                              |
                              |
                  Customer Master Key (In KMS)


```

- S3 generates a customer master key, when you pick SSE-KMS for the first time.
- Allows control over key rotation

For encryption:

- Everytime an object is uploaded, S3 uses a dedicated key to encrypt the given object.
- This key is called Data Encryption Key and is generated using the Customer Master Key.
- S3 endpoint is passed the given object by the request. KMS provides plain text and encrypted Data Encryption Key to be used to encrypt this object.

Post encryption:

- The plain text data encryption key is discarded.
- The encrypted data encryption key and the encrypted object are stored in S3 post this process.

Data Encryption Key based architecture

- Data Encryption Key is used to encrypt data more than 4KB
- SSE-KMS is one of the service that uses the Data Encryption Key based architecture

You can also use a customer managed key as well instead of the customer master key from KMS.

Advantage of using SSE-KMS:

- To decrypt any object, you need access to the CMK that was used to generate the unique key that was used to generate them.
- The CMK is used to decrypt the data encryption key for that object. That decrypted data encryption key is used to decrypt the object itself.
- The best benefit is the role seperation. If you don't have access to KMS, you don't have access to the object.

---

## Enabling Amazon S3 default bucket encryption

You can set the default encryption behavior on an Amazon S3 bucket so that `all objects are encrypted` when they are stored in the bucket. The objects can be encrypted using server-side encryption with

- either Amazon S3-managed keys (SSE-S3)
- or AWS Key Management Service (AWS KMS) keys.

After you enable default encryption for a bucket, there is no change to the encryption of the objects that existed in the bucket before default encryption was enabled.

Any new file uploaded without any encryption specified will use the default bucket encryption.

When you upload objects after enabling default encryption:

- If your PUT request headers don't include encryption information, Amazon S3 uses the bucket’s default encryption settings to encrypt the objects.

- If your PUT request headers include encryption information, Amazon S3 uses the encryption information from the PUT request to encrypt objects before storing them in Amazon S3.

---

Reference: Keys usage demo (https://learn.cantrill.io/courses/1101194/lectures/25997332)