# Security and secrets: KMS, Secrets Manager and threat detection

Encrypt with KMS, keep secrets in Secrets Manager or Parameter Store, and let GuardDuty and Security Hub watch your account.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 15. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/15-security-and-secrets

## What you will learn

- Explain envelope encryption and the difference between AWS-managed and customer-managed KMS keys
- Store application credentials in Secrets Manager and retrieve them at runtime
- Choose String, StringList or SecureString in SSM Parameter Store
- Explain what GuardDuty, Security Hub, WAF and Shield protect
- Delete practice secrets safely and verify they are no longer retrievable

## KMS protects keys, not your design

Before managed key services, teams stored encryption keys beside the data they were meant to protect. A server
disk failure could lose both; a stolen credential could expose both. AWS Key Management Service (KMS) keeps key
operations behind an access-controlled service. In this lesson, you'll see how KMS supports encryption, then
compare secrets, configuration parameters, detection and edge protections. KMS protects keys, but IAM and
application design still decide who may use them.

KMS is a key-management service. It does not decide who should read a database password or whether an application
should have access to production. IAM policies and KMS key policies decide that.

Most AWS encryption uses envelope encryption. A service generates a data key, encrypts the data with the plaintext
data key, then asks KMS to encrypt the data key with a KMS key. The plaintext data key is discarded after use.
KMS protects the small key operation; the service protects the data.

AWS-managed keys are created and operated by AWS for a service, such as the key behind SSM SecureString. A
customer-managed key gives you more control over policy, rotation, aliases and deletion, but also gives you more
responsibility and can add cost. This lesson uses no customer-managed key.

```sh
$ aws kms describe-key \
    --key-id alias/aws/ssm \
    --query 'KeyMetadata.{KeyManager:KeyManager,KeyState:KeyState}'
```

The real practice run returned KeyManager AWS and KeyState Enabled. That confirms the SSM parameter uses an
AWS-managed key, not a customer-created key.

> **Video.** [AWS Envelope Encryption Explained | Data Encryption Keys (DEK) & KMS](https://www.youtube.com/watch?v=OPCzAwY3Wj4) (CloudWolf AWS)

## Secrets have a lifecycle

Secrets Manager is for credentials and other values that need a secret lifecycle. It stores versions, controls
access with IAM, records API use in CloudTrail and can support rotation. The application should retrieve a secret at
runtime using its role, not bake the value into an image or repository.

```sh
$ aws secretsmanager create-secret \
    --name academy-security-demo \
    --secret-string '{"username":"demo-app","token":"lesson-only"}'
$ aws secretsmanager get-secret-value \
    --secret-id academy-security-demo \
    --query SecretString \
    --output text
$ aws secretsmanager delete-secret \
    --secret-id academy-security-demo \
    --force-delete-without-recovery
```

Force deletion is appropriate only for disposable practice data. Production deletion normally uses a recovery
window so an accidental delete can be reversed. Secret names and values are different: a name can appear in
configuration, while the value must stay out of logs and shell history.

> **The shell remembers.** A secret passed directly in a command can land in shell history, process listings or CI logs. Prefer the AWS SDK, a protected input mechanism or a file with controlled permissions. Never paste a real production credential into this lesson.

> **Video.** [AWS Secrets Manager Step-by-Step: Store, Rotate & Delete Secrets](https://www.youtube.com/watch?v=ItzzgWe7elE&t=69s) (Tiny Technical Tutorials)

> **Figure.** Step one, the app running on ECS or Lambda calls GetSecretValue using its task or execution role; no password is stored with the app. Step two, IAM checks that the role may read that one secret. Step three, Secrets Manager decrypts the secret with its KMS key and returns it. Step four, the app connects to the database with it. Separately, a rotation function changes the database password on a schedule and stores the new value in the secret, so the old password stops working. CloudTrail records every read.
>
> The app reads the secret at run time with its role; a rotation function replaces the password on a schedule.

## Parameters are configuration

SSM Parameter Store is a convenient hierarchy for configuration. String is readable configuration. StringList is a
comma-separated list. SecureString encrypts the value and requires permission to decrypt it.

```sh
$ aws ssm put-parameter \
    --name /academy/security-demo/app-name \
    --type String \
    --value academy-demo
$ aws ssm put-parameter \
    --name /academy/security-demo/api-token \
    --type SecureString \
    --key-id alias/aws/ssm \
    --value lesson-only-token
$ aws ssm get-parameters \
    --names /academy/security-demo/app-name /academy/security-demo/api-token \
    --with-decryption \
    --query 'Parameters[].{Name:Name,Type:Type,Value:Value}'
```

Use a path that reflects ownership and environment, then grant access to only that path. SecureString encrypts at
rest; it does not make a value safe to print in a CI log. Delete a practice parameter when the exercise ends.

Parameter Store is a good fit for settings that belong in a named hierarchy, such as `/academy/dev/log-level`.
Applications can request a specific name or a path, which makes it possible to scope an IAM policy to a team's
configuration. Use `String` when the value is not secret. Use `SecureString` when it must be encrypted at rest;
the caller also needs permission to retrieve and decrypt it. `StringList` is only a delimited value, not a typed
array with escaping rules. Choose Secrets Manager instead when the credential needs managed version handling or
a rotation workflow. Neither service prevents your code from logging a value after it retrieves it.

> **Video.** [AWS Systems Manager Parameter Store Tutorial](https://www.youtube.com/watch?v=zxi3M_rIE2k) (Stephane Maarek)

## Detection is not prevention

GuardDuty analyses supported AWS account and workload signals for suspicious activity. Security Hub collects
security findings and standards in one place. Neither is a replacement for least privilege, patching, backups or
an incident response process.

I did not enable GuardDuty or Security Hub in this lesson. Enabling account-wide detection services was outside the
approved resource list. In a real account, check the region, delegated administration and cost before enabling them,
then route findings to the people who can act.

Detection is valuable because preventive controls are never perfect. GuardDuty analyzes supported signals and
creates findings that need investigation; Security Hub can collect findings and show how accounts compare with
enabled standards. A finding is not automatically an incident response. Decide which severity levels page someone,
who owns triage, and what evidence they should preserve. Keep preventive controls such as least privilege and
patching in place even when detection is enabled. For this lesson, these services remain unenabled because they
were outside its approved practice resources.

## Edge controls have different jobs

AWS WAF filters HTTP requests at supported application edges. It can match rules for IPs, headers, paths or known
attack patterns. AWS Shield helps protect against distributed denial-of-service attacks. WAF is an application-layer
filter; Shield is a DDoS protection service. Neither is a secret store or a substitute for secure application code.

Use WAF when you need request-level rules in front of a supported web endpoint, such as filtering a path or
matching a known attack pattern. Test rules in a mode that lets you review matches before enforcing a block, so
legitimate requests are not caught by mistake. Shield addresses denial-of-service traffic at a different layer;
it does not decide whether a user may read a record. Authentication, authorization, input validation and safe
application code still belong in the service itself. These controls can work together, but they answer separate
questions and have separate configuration and cost implications.

> **In production.** Give workloads roles rather than access keys, use short-lived credentials, scope IAM and KMS permissions to the smallest useful resource, rotate secrets, and alert on unusual reads. Keep WAF rules tested and keep GuardDuty and Security Hub findings connected to an owner.

> **Video.** [AWS Security Tools Shield, WAF, GuardDuty, Inspector - How they work](https://www.youtube.com/watch?v=r_4EEClM_j0) (Unus AWS)

## Secret storage is a lifecycle, not a string

Secrets Manager is for credentials that need versions, retrieval auditing and optional rotation. Parameter Store
is a hierarchical configuration store: use `String` for ordinary settings and `SecureString` when the value needs
encryption at rest. KMS AWS-managed aliases such as `aws/secretsmanager` and `aws/ssm` avoid creating a customer
key for a short exercise; customer-managed keys are for ownership and key-policy control that you are prepared to
operate.

> **Figure.** Secrets Manager store a new secret wizard, Configure rotation step, with automatic rotation left disabled.
>
> Rotation is optional per secret: a Lambda function changes the value on a schedule. It's left off for a demo secret.

> **Figure.** Secrets Manager review step: secret type Other type of secret, encryption key aws/secretsmanager, secret name academy/orders-app/db, replication disabled.
>
> The review step: the AWS-managed key aws/secretsmanager encrypts the secret, so no customer key is needed.

```sh
$ aws secretsmanager get-secret-value --secret-id "$SECRET" --query SecretString --output text
$ aws ssm get-parameters --names "$PLAIN" "$SECURE" --with-decryption \
    --query 'Parameters[].{Name:Name,Type:Type,Value:Value}' --output table
$ aws kms list-aliases --query 'Aliases[?starts_with(AliasName, `alias/aws/`)].AliasName' --output text
```

The first command reads one version; the second deliberately uses `--with-decryption` for the SecureString; the
third confirms that the exercise uses AWS-managed aliases. Delete the secret with
`--force-delete-without-recovery`, delete both parameters, and verify each identifier is gone.

## Mission: Store and remove a practice secret

Create one Secrets Manager secret, one String parameter and one SecureString parameter protected by the AWS-managed SSM key. Retrieve each value, inspect the key manager, force-delete the secret without recovery, delete both parameters and verify that the values cannot be retrieved.

- You need: An AWS account, the AWS CLI configured with the anythinkx profile, and ap-south-1
- You'll have: Secret and parameter values from real reads, KeyManager AWS, then ResourceNotFound or ParameterNotFound after cleanup

```sh
$ REGION=ap-south-1
$ PROFILE=anythinkx
$ SECRET=academy-security-demo
$ PLAIN=/academy/security-demo/app-name
$ SECURE=/academy/security-demo/api-token
$ aws secretsmanager create-secret --profile $PROFILE --region $REGION --name $SECRET --secret-string '{"username":"demo-app","token":"lesson-only"}'
$ aws ssm put-parameter --profile $PROFILE --region $REGION --name $PLAIN --type String --value academy-demo
$ aws ssm put-parameter --profile $PROFILE --region $REGION --name $SECURE --type SecureString --key-id alias/aws/ssm --value lesson-only-token
$ aws secretsmanager get-secret-value --profile $PROFILE --region $REGION --secret-id $SECRET --query SecretString --output text
$ aws ssm get-parameters --profile $PROFILE --region $REGION --names $PLAIN $SECURE --with-decryption --query 'Parameters[].{Name:Name,Type:Type,Value:Value}'
$ aws kms describe-key --profile $PROFILE --region $REGION --key-id alias/aws/ssm --query 'KeyMetadata.{KeyManager:KeyManager,KeyState:KeyState}'
$ aws secretsmanager delete-secret --profile $PROFILE --region $REGION --secret-id $SECRET --force-delete-without-recovery
$ aws ssm delete-parameters --profile $PROFILE --region $REGION --names $PLAIN $SECURE
$ aws secretsmanager get-secret-value --profile $PROFILE --region $REGION --secret-id $SECRET --query SecretString --output text
$ aws ssm get-parameter --profile $PROFILE --region $REGION --name $SECURE --with-decryption --query Parameter.Value --output text
```

The last two reads should fail after cleanup. The failures are the proof: a secret or parameter that can still be
read is not deleted. Never use force deletion for a credential that another workload may still need.

## Try it

- Open KMS and compare AWS-managed keys with customer-managed keys without creating one.
- Create a short-lived Secrets Manager secret, read it, and force-delete it.
- Create a String and SecureString SSM parameter and retrieve them with decryption.
- Check which key protects a SecureString parameter.
- Open GuardDuty and Security Hub and read their service state without enabling new paid features.
- Inspect the difference between a secret value and a parameter name in shell history.

## Quiz

1. Why should an application not put a database password in its source repository?
   - Git automatically encrypts every file
   - **Repositories, builds, logs and backups can copy the value beyond its intended lifetime** (answer)
   - AWS refuses to run code that contains a password
   Why: A secret needs controlled retrieval, rotation and audit. Source code is the wrong lifetime and access boundary.

2. What does envelope encryption mean?
   - **A data key encrypts the data and KMS protects the data key** (answer)
   - KMS stores every application byte forever
   - The application sends plaintext to a public bucket
   Why: KMS manages key-encryption operations while the data service or SDK encrypts the payload with a data key.

3. When is SSM SecureString appropriate?
   - **For small configuration values that need encryption at rest and IAM-controlled decryption** (answer)
   - For streaming gigabytes of log data
   - For public documentation
   Why: Parameter Store is useful for configuration and small secrets. Secrets Manager adds secret lifecycle features such as rotation.

4. What is GuardDuty’s role?
   - It is a web application firewall
   - **It analyses supported account and workload signals for suspicious activity** (answer)
   - It stores application passwords
   Why: GuardDuty is threat detection. WAF filters web requests, while Secrets Manager stores credentials.

5. Why does the lesson use an AWS-managed SSM key?
   - **It avoids creating a customer-managed KMS key for a short practice exercise** (answer)
   - Customer-managed keys cannot encrypt anything
   - AWS-managed keys make IAM unnecessary
   Why: The approved practice scope allows AWS-managed keys only. Production ownership and rotation requirements may justify a customer-managed key.

## Resources

- [AWS Key Management Service developer guide](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) (AWS Docs)
- [AWS Secrets Manager user guide](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) (AWS Docs)
- [Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) (AWS Docs)
- [Amazon GuardDuty user guide](https://docs.aws.amazon.com/guardduty/latest/ug/what-is-guardduty.html) (AWS Docs)
- [AWS WAF developer guide](https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html) (AWS Docs)
