Study guide
Technical reference and lesson notes
Purpose of This Lesson
This hands-on exercise demonstrates how an application running on Amazon EC2 can encrypt and decrypt data using AWS Key Management Service (AWS KMS) and the Boto3 Python SDK.
The central design pattern is:
- Create an IAM role for EC2.
- Create a symmetric KMS key.
- Grant the EC2 role permission to use the key through the KMS key policy.
- Attach the role to the EC2 instance through an instance profile.
- Use Boto3 to call the KMS
EncryptandDecryptAPIs. - Clean up the temporary resources and schedule key deletion if the key is no longer needed.
Key Concepts
KMS key administration and key usage are separate
When creating a KMS key, AWS distinguishes between:
- Key administrators: Principals allowed to manage the key, such as enabling, disabling, describing, tagging, and scheduling deletion of the key.
- Key users: Principals allowed to use cryptographic operations, such as
Encrypt,Decrypt,ReEncrypt, andGenerateDataKey.
A principal that can administer a key does not automatically need to be allowed to encrypt or decrypt data. Conversely, an application role should normally receive usage permissions without key-administration permissions.
This separation supports least privilege. An operations team can manage the key lifecycle while an application role can use the key without being able to disable or delete it.
KMS key policies are resource-based policies
A KMS key policy is attached directly to the KMS key. It identifies which AWS accounts, IAM users, and IAM roles can administer or use the key.
IAM policies and KMS key policies work together:
- The IAM principal must have an identity-based policy allowing the requested KMS action, unless the key policy grants access in an appropriate way.
- The KMS key policy must permit the principal to use the key, either directly or through an account-level delegation statement.
- Explicit denies in any applicable policy override allows.
For cross-account access, both the key-owning account and the principal’s account must be configured correctly.
Use an EC2 IAM role, not embedded credentials
An EC2 application should obtain temporary credentials from an IAM role attached through an instance profile. The role should contain only the permissions the application needs.
Avoid placing long-lived access keys in source code, configuration files, or the instance filesystem. Boto3 automatically uses the instance role credentials when the application runs on EC2 and no higher-priority credentials are supplied.
Symmetric KMS keys for standard application encryption
A symmetric KMS key uses the same underlying key material for encryption and decryption. It is the usual choice for encrypting application data with the KMS APIs and for envelope encryption workflows.
A typical Boto3 call conceptually looks like this:
import boto3
kms = boto3.client("kms")
response = kms.encrypt(
KeyId="arn:aws:kms:REGION:ACCOUNT_ID:key/KEY_ID",
Plaintext=b"secret message"
)
ciphertext = response["CiphertextBlob"]
result = kms.decrypt(CiphertextBlob=ciphertext)
plaintext = result["Plaintext"]
The application must have permission to call the relevant KMS operations, and the KMS key must be available in the correct Region.
Direct KMS encryption is for small plaintext values
The KMS Encrypt API is designed for relatively small plaintext values. The direct plaintext size limit is 4 KB. Larger data should not be sent directly to KMS.
For larger objects or files, use envelope encryption:
- Call
GenerateDataKeyusing the KMS key. - Encrypt the application data locally with the returned plaintext data key, commonly using an authenticated encryption algorithm such as AES-GCM.
- Store the encrypted data key alongside the ciphertext.
- Remove the plaintext data key from memory when it is no longer needed.
- During decryption, call
Decrypton the encrypted data key, then use the recovered plaintext data key locally to decrypt the data.
This design limits KMS operations while allowing efficient encryption of large datasets.
Encrypted and decrypted data are different artifacts
The KMS encryption response contains ciphertext, which is not expected to be human-readable. The decrypt operation returns the original plaintext only to an authorized caller.
Applications should protect both:
- The ciphertext, which may be stored in files, databases, or object storage.
- The metadata needed to identify the KMS key and encryption context.
KMS does not replace application authorization. A user who is allowed to retrieve ciphertext may still need separate application-level authorization before the application decrypts it.
Encryption context improves authorization and auditing
For symmetric KMS operations, an application can provide an encryption context: a set of non-secret key-value pairs describing the encryption request. The same context must be supplied during decryption.
A key policy or IAM policy can require specific encryption-context values. This can help prevent a ciphertext from being decrypted in an unintended workflow. Encryption context is not encrypted and must not contain secrets.
Key deletion is intentionally delayed
KMS key deletion is not immediate. Scheduling deletion places the key into a pending-deletion state for a configurable waiting period, with seven days as the minimum. During this period, the key is generally unavailable for cryptographic use, but the scheduled deletion can be canceled.
After deletion, data encrypted only with that key cannot be decrypted. Before scheduling deletion, identify all dependent resources, backups, databases, objects, and applications. A temporary lab key and its EC2 instance should both be removed after testing to avoid unnecessary charges.
Disabling a key is different from deleting it:
- Disable: Temporarily prevents cryptographic operations while preserving the key.
- Schedule deletion: Starts a deletion workflow that ultimately destroys the key material unless canceled during the waiting period.
Exam-Relevant Takeaways
- A KMS key policy controls access to a specific key and is central to KMS authorization.
- Separate key administrators from key users.
- Attach an IAM role to EC2 rather than distributing access keys.
- The EC2 role needs cryptographic permissions such as
kms:Encryptandkms:Decrypt; it should not normally receive administrative actions such askms:ScheduleKeyDeletion. - Direct KMS encryption is limited to small payloads. Use envelope encryption for larger data.
- The KMS key and encrypted data must be used in a compatible Region unless the solution uses an appropriate multi-Region or replication design.
- Deleting a KMS key can cause permanent data loss because ciphertext cannot be decrypted without the required key material.
- Scheduling deletion is not the same as disabling a key.
- KMS encrypt and decrypt calls are authenticated API operations; network access, IAM, key policy, and Region selection all matter.
Architecture Decision Guide
| Requirement | Recommended approach | Important consideration |
|---|---|---|
| Encrypt a short secret or token | Direct KMS Encrypt and Decrypt | Plaintext is limited to 4 KB; protect the returned ciphertext |
| Encrypt a large file or object | Envelope encryption with GenerateDataKey | Encrypt the data locally and protect the encrypted data key with KMS |
| Application runs on EC2 | Attach an IAM role through an instance profile | Avoid long-lived credentials on the instance |
| Application needs cryptographic operations | Grant key-user permissions | Limit permissions to required actions such as Encrypt, Decrypt, or GenerateDataKey |
| Operations team manages key lifecycle | Grant key-administrator permissions separately | Administration does not imply application data access |
| Temporarily stop use of a key | Disable the KMS key | Data remains associated with the key, but cryptographic operations are blocked |
| Permanently retire a key | Schedule key deletion after dependency analysis | Deletion can make encrypted data permanently unrecoverable |
| Enforce use for a specific application purpose | Use an encryption context and policy conditions | The context is not secret and must match during decryption |
Common Exam Traps
- Assuming an IAM policy alone always grants KMS access: The KMS key policy must also support the requested access pattern.
- Giving an EC2 role full KMS administrator permissions: The workload generally needs cryptographic use permissions, not key-management permissions.
- Using direct
Encryptfor a multi-megabyte file: Use envelope encryption instead. - Confusing disabling with deletion: Disabling is reversible; deletion permanently destroys the key after the waiting period.
- Deleting a key because no current workload is using it: Historical ciphertext, backups, snapshots, and archived data may still depend on it.
- Assuming KMS encrypts data automatically anywhere it is stored: The application must call KMS or use an AWS service integration configured with the key.
- Ignoring Region constraints: A KMS key is Regional. A resource or application in another Region may require a replica, multi-Region key strategy, or a different design.
- Putting secrets in encryption context: Encryption context is visible as request metadata and should contain identifiers, not confidential values.
Real-World Engineer Notes
- Prefer AWS service integrations where available. For example, Amazon S3 server-side encryption with KMS keys can encrypt objects without requiring application code to perform every encryption operation.
- For custom applications, use envelope encryption rather than writing ad hoc cryptographic storage logic.
- Log KMS usage with AWS CloudTrail and monitor administrative actions such as key policy changes, disabling, and deletion scheduling.
- Restrict key policies to specific role ARNs where practical. Avoid broad principals such as
*. - Consider key rotation, separation of duties, and the operational ownership of the key before selecting a customer managed key.
- Test recovery procedures. A backup of ciphertext is not sufficient if the KMS key, key policy, or required permissions are unavailable.
- In a temporary lab, terminate the EC2 instance and remove or schedule deletion of the KMS key only after confirming that no data needs to be recovered.
Quick Reference Summary
- KMS key administrators manage the key lifecycle.
- KMS key users perform encryption and decryption operations.
- EC2 applications should use IAM roles and instance profiles.
- Direct KMS encryption is suitable for plaintext up to 4 KB.
- Envelope encryption is the standard pattern for larger data.
- KMS key policies are resource-based policies that must align with IAM permissions.
- Disable is reversible; schedule deletion starts a delayed destruction process.
- Key deletion can permanently prevent decryption of dependent ciphertext.
Flashcards
- Q: What is the difference between a KMS key administrator and a key user?
A: An administrator manages the key lifecycle and configuration; a key user performs cryptographic operations such as encryption and decryption.
- Q: How should an EC2 application authenticate to AWS KMS?
A: Through an IAM role attached to the EC2 instance using an instance profile.
- Q: What is the direct KMS
Encryptplaintext limit?
A: 4 KB.
- Q: What should be used to encrypt large files with KMS?
A: Envelope encryption: encrypt the data locally with a data key and use KMS to protect that data key.
- Q: Which permissions are typical for a workload that only encrypts and decrypts data?
A: kms:Encrypt, kms:Decrypt, and possibly kms:ReEncrypt or kms:GenerateDataKey, depending on the design.
- Q: What does a KMS key policy control?
A: Access to a specific KMS key, including which principals can administer or use it.
- Q: What happens when a KMS key is disabled?
A: Cryptographic operations using the key are blocked, but the key remains available to re-enable later.
- Q: Why is KMS key deletion delayed?
A: The waiting period provides an opportunity to cancel deletion if encrypted data or dependencies are discovered.
- Q: What is encryption context?
A: Non-secret key-value metadata supplied during encryption and required during decryption when used; policies can constrain it.
- Q: Why should long-lived access keys not be stored on an EC2 instance?
A: They are difficult to rotate and can be exposed; an instance role provides temporary credentials automatically.
Practice Questions
Question 1
An application running on EC2 must encrypt and decrypt short customer tokens using a customer managed KMS key. The security team must manage the key, while the application must not be able to disable or delete it. What is the best design?
A. Give the EC2 role administrator access to the KMS key.
B. Store an IAM access key on the instance and allow kms:*.
C. Attach an IAM role to EC2 and grant it only the required KMS cryptographic permissions; grant key administration to a separate principal.
D. Use the AWS account root user to perform every KMS operation.
Correct answer: C
Explanation: Separate key administration from key usage and use an EC2 IAM role with least-privilege cryptographic permissions. The workload should not receive permissions to disable or delete the key.
Question 2
A workload must encrypt 500 MB files before storing them in Amazon S3. Which approach is most appropriate?
A. Send each entire file in a single KMS Encrypt API request.
B. Use GenerateDataKey, encrypt the file locally with the plaintext data key, and store the encrypted data key with the ciphertext.
C. Convert the file to Base64 and send it to KMS.
D. Disable the KMS key after each encryption operation.
Correct answer: B
Explanation: Direct KMS encryption is limited to small plaintext values. Envelope encryption uses KMS to protect a data key while the application efficiently encrypts the large file locally.
Question 3
An administrator schedules deletion of a KMS key used by an old database. The database is currently offline, but backups encrypted with the key must be retained for seven years. What should happen next?
A. Proceed because the database is not currently running.
B. Disable the key and immediately delete it.
C. Cancel the deletion and verify all ciphertext, backups, and recovery procedures that depend on the key.
D. Copy the encrypted backups to another S3 bucket; the key is no longer needed.
Correct answer: C
Explanation: Encrypted backups may require the original key for recovery. Copying ciphertext does not replace the key. The deletion should be canceled until retention and recovery dependencies are understood.
Question 4
An EC2 instance has an IAM policy allowing kms:Decrypt, but calls to decrypt data with a customer managed key fail with an access-denied error. What is the most likely area to investigate first?
A. Whether the KMS key policy permits the role or delegates permission to the account.
B. Whether the instance has a larger root volume.
C. Whether the security group allows inbound HTTP traffic.
D. Whether the ciphertext was stored in a different S3 prefix.
Correct answer: A
Explanation: KMS authorization depends on the key policy as well as the principal’s permissions and other policy controls. The role must be authorized to use that specific key.
Question 5
A company wants to ensure that a KMS key can decrypt data only when the request identifies the correct application and tenant. Which feature is designed for this requirement?
A. Key alias only
B. Encryption context combined with policy conditions
C. KMS key deletion waiting period
D. EC2 security group rules
Correct answer: B
Explanation: Encryption context provides request metadata that can be required during decryption and constrained in IAM or key policies. It is not a replacement for encryption and must not contain secrets.