---
title: '24 AWS Security and Encryption'
disqus: hackmd
---
:::info
AWS Certified Developer Associate DVA-C01
:::
24 AWS Security and Encryption
===
<style>
img{
/* border: 2px solid red; */
margin-left: auto;
margin-right: auto;
width: 90%;
display: block;
}
</style>
## Table of Contents
[TOC]
AWS KMS
---
### Why Encryption?
#### Encryption in Flight (SSL)
- data encrypted before sending and decrypted after receiving
- ssl certs help with encryption (https)
- green lock on browser
- encryption in flight ensures no MITM can happen

#### Server Side Encryption at Rest
- data encrypted after being received by server
- decrypted before sent
- stored in encrypted form using a data key
- encryption/decryption keys must be managed somewhr and server must have access to it

#### Client Side Encryption
- data encrypted by client and nvr decrypted by server
- data will be decrypted by receiving client
- data stored on server but server dont know what it means
- server shldnt be able to decrypt data
- can leverage envelope encryption

### AWS KMS Introduction
- anything related to encryption, it's kms
- easy way to control access to data
- aws manages keys for us
- fully integrated with iam for authorisation
- seamlessly integrated into a lot of services
- amazon ebs
- encrypt volumes
- amazon s3
- server side encryption of objs
- amazon redshift
- encryption of data
- amazon rds
- encryption of data
- amazon ssm
- param store
- etc
- can also use cli/sdk
- able to fully manage keys and policies
- create
- rotate policies
- disable
- enable
- able to audit key usage using cloudtrial
- see who use keys and whenz
- 3 types of CMK
- aws managed service default cmk
- free
- user keys created in kms
- $1/month
- user keys imported
- must be 256bit symmetric key
- $1/month
- + pay for api call to kms
- $0.03 / 10000 calls
#### More KMS
- use kms anytime u need to share sensitive info
- db passwords
- creds to external services
- priv key for ssl certs
- value in kms is that the cmk used to encrypt data can nvr be retrieved by the user
- cmk can also be rotated for extra security
- never ever store secrets in plaintxt especially in code
- however encrypted secrets can be stored in the code/env vars
- kms only help in encrypting up to 4kb of data per call
- if data > 4kb, use envelope encryption
- to give access to kms to someone,
- ensure key policy allows user
- ensure iam policy allows api calls
### Customer Master Key (CMK) Types
- symmetric (AES-256 keys)
- 1st offering of kms, single encryption key used to encrypt and decrypt
- aws services integrated with kms use symmetric cmks
- needed for envelope encryption
- nvr get access to the key unencrypted
- must call kms api to use
- asymmetric (RSA & ECC key pairs)
- public (encrypt) and private key (decrypt) pair
- pub key is downloadable but can access priv key unencrypted
- used for encrypt/decrypt or sign/verify operations
- use case
- encryption outside aws by users who cant call kms api
### Copying Snapshots across Regions

- key in region a cannot be transmitted to region b
- hence first create snapshot of volume
- copy snapshot to new region but specify a new kms key to reencrypt the data with
### KMS Key Policies
- control access to kms keys similar to s3 bucket policies
- diff - cannot control access w/o them
- if u dont specify key policy then nobody can access your key
- default kms key policy
- created if u dont provide specific kms key policy
- is very permissive
- complete access to key to root user = entire aws acc can use kms key
- give access to iam policy to kms key to give user access to the key
- custom kms key policy
- define users, roles that can access kms key
- define who can administer key
- useful for cross-account access of kms key
### Copying Snapshots across Accounts
- create snapshot encrypted with own cmk
- attach kms key policy to authorise cross acc access
- share encrypted snapshot
- in target, create copy of snapshot with kms key in its acc
- create vol from snapshot

### KMS API - Encrypt & Decrypt

- encrypting
- secret file less than 4kb
- sent into kms service using encrypt apt
- specify cmk
- kms then check with iam for permissions
- kms sends encrypted secret
- decrypting
- similar to encrypting
- though we are limited by size of file to be encrypted (4kb)
### Envelope Encryption
- kms encrypt api has limit of 4kb
- if want to encrypt >4kb, use envelope encryption
- main api is `GenerateDataKey` api
- NOTE
- for exam, anything >4kb must use envelope encryption == GenerateDataKey API
#### Deep Dive

- big file 10mb
- use gendatakey api to send file to kms
- specify cmk
- kms check with iam perms if we can generate the key
- if yes, key generated and returned
- key returned in .dek (data encryption key) format
- key sent to client side - can encrypt the big file on client side uing our own cpu
- returns both plaintxt key and encrypted key
- we build envelope around the encrypted file using the .dek key
- includes encrypted file and encrypted dek key

- encrypted envelope file is big, decrypt api only takes 4kb of data
- hence only send encrypted dek
- kms decrypts dek and returns plaintxt dek key
- use it to decrypt the encrypted file
#### Encryption SDK
- aws encryption sdk implements envelope encryption for us
- encryption sdk also exists as cli tool to install
- implementations for java, python, C, js
- has feature - **Data Key Caching**
- reuse data keys instead of creating new ones for ea encryption
- reduces num of calls to kms with security trade-off
- since u reuse keys
- sec concern - using same key for many files
- uses `LocalCryptoMaterialsCache`
- max age, max bytes, max num of msgs
### API Summary
- `Encrypt`
- encrypt up to 4kb of data through kms
- `GenerateDataKey`
- generates unique symmetric data key (dek)
- returns plaintxt copy of data key and encrypted copy of same cmk specified
- `GenerateDataKeyWithoutPlaintext`
- generate dek to use at some pt (not immediately)
- dek encrypted under the cmk that you specify
- must use decrypt ltr to use it
- envelope encryption uses the prev api not this one
- exam might try to trick you
- `Decrypt`
- decrypt up to 4kb of data
- includes dek keys
- `GenerateRandom`
- returns random byte string
### KMS Request Quotas
- when u exceed a req quota, u get `ThrottlingException`
- to respond, use exponential backoff
- backoff and retry
- for crypto operations, they share a quota
- includes reqs made aws on your behalf
- eg. SSE-KMS
- 2 other options to counter throttling
- for gendatakey, consider using dek caching from encryption sdk
- can request quota increase through api or aws support

- symmetric cmk quota differs by region
### Console

- all aws managed keys here
- cuz they start with aws/
- if want to use key, wil ref alias
- the key cannot be used outside of its service

- visaservice clause decides what service can use this key

- out our own keys here
- need to pay $1 per month to do that

- for aws cloudhsm cluster
- out of scope for exam
![Uploading file..._qu4urvbud]()
- kms will generate key for us or we provide own key


- define key's admin
- if leave this blank, will use default policy

- define who can use the key

- can also specify accounts for cross acc key usage instead of just using users


- key actions

- crypto info of key

- key rotation
- rotate key every year
#### CLI usage of Key


- encryption, specify
- key alias
- file to encrypt
- output format
- crypto algo
- region
- the cmd returns a base64 file wiith your key

- windows use 1st, linux 2nd

- decrypt the file (after u decoded base64)
#### Encryption SDK CLI

- refer to doc to see installation guide
- https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/crypto-cli-install.html


- metadata file generated
- can use `jq` command to process the json


#### KMS and Lambda

- defining env var in lambda
- if user has access to env var, can still see our secret var
- hence can use encryption console within the lambda console

- specify key to encrypt var with
- must also copy snippet of code and paste into lambda func code


- lambda func might timeout if encrypt/decrypt taking too much time
- change your func timeout in its basic settings

- accessdenied error if iam role dont have perms to call decrypt api

- attach inline policy
- give specific arn the abi to call decrypt api

S3 Security
---
### S3 Encryption for Objects
- 4 methods of encrypting objs in s3
- SSE-S3
- encrypts s3 objs using keys handled & managed by aws
- SSE-KMS
- leverage aws kms to manage encrypted keys
- SSE-C
- manage own encryption keys
- client side encryption
- NOTE
- need to understand which ones to use for which situation
### SSE-KMS
- encryption keys handled and managed by kms
- kms advantages
- user control
- audit trial
- obj encrypted server side
- must set header `"x-amz-server-side-encryption":"awskms"`

#### Deep Dive
- sse-kms leverages the `GenerateDataKey` and `Decrypt` kms api calls
- these kms api calls will show up in cloudtrial
- helpful for logging
- to perform sse-kms, u need
- kms key policy that authorises the user/role
- iam policy that authorises access to kms
- else will get access denied error
- s3 calls kms for sse-kms count against your kms limits
- if throttling, try exponential backoff
- or request inc in kms limits if throttling way too much/often
- service throttled is kms, not s3
### S3 Bucket Policy - Force SSL
- to force ssl, create s3 bucket policy with deny on the condition `aws:SecureTransport = false`
- using allow on that condition will allow anonymous `GetObject` if using ssl
- [read more](https://aws.amazon.com/premiumsupport/knowledge-center/s3-bucket-policy-for-config-rule/)

### S3 Bucket Policy - Force Encryption of SSE-KMS
- deny incorrect encryption header
- make sure includes `aws:kms` == SSE-KMS
- deny no encryption header to ensure objs not uploaded unencrypted
- or can also config default encryption to SSE-KMS

SSM Parameter Store
---
- secure storage for config and secrets
- optional seamless encryption using kms
- serverless, scalable, durable, easy sdk
- ver tracking of configs/secrets
- config management using path and iam
- notifs with cloudwatch events
- integration with cloudformation

#### SSM Param Store Hierarchy

#### Standard and Advanced Param Tiers

#### Parameters Policies for Advanced Params
- allow to assign ttl to param (exp date) to force updating/deleting sensitive data like passwords
- can assign multiple policies at once

### Console

- param store can be found in secrets manager service




- encrypt param val using kms key


- use ssl to get params from param store
- secure string returns encrypted value when `--with-decryption` flag is on


- get param value based on path
- gives abi to organise our secrets
#### With Lambda

- change lambda func to include boto and call ssm store from code

- can also use env vars in code to call param from param store
AWS Secrets Manager
---
- newer service for storing secrets
- can force rotation of secret every x days
- automate generation of secrets on rotation using lambda
- integrate with amazon rds
- eg. mysql, postgresql, aurora
- secrets encrypted using kms
- mostly meant for rds integration
### SSM Param Store vs Secrets Manager
- secrets manager
- automatic rotation of secrets with aws lambda
- integration with rds, redshift, documentdb
- kms encryption mandatory
- can integrate with cloudformation
- ssm param store
- simple api
- no secret rotation
- kms encryption optional
- can integrate with cloudformation
- can pull secrets manager using ssm param store api
### Console

- can have creds and key value pairs



- sample code to get your secret value

- for other secret type, you can specify db to integrate with
CloudWatch Logs Encryption
---
- can encrypt cloudwatch logs with kms keys
- encryption enabled at log grp lvl
- associate cmk with log grp when creating log grp or after it exists
- cannot associate cmk with log grp using cloudwatch console
- must use cloudwatch logs api
- `associate-kms-key` - if log grp alr exists
- `create-log-grp` - if log grp doesnt exist yet
### Console

- kms key id is blank

- key policy need to be applied to allow access to it

- allow cloudwatch logs with specific action

CodeBuild Security
---
- to access res in your vpc, make sure u specify vpc config for your codebuild
- secrets in codebuild
- dont store as plaintxt in env vars
- have env var reference param store params
- or ref secrets manager secrets
### Console

- in codebuild specify param type
- or secrets manager
- ensure iam policy allows access to these 2 services
###### tags: `AWS Developer Associate` `Notes`