OnCallReadyStart learning

AWS Lesson 39.29 · AWS VI: Architecting on AWS & the exams · 16 min read

Designing for security: least privilege across services, encryption, segmentation, identity

In plain words

In an office, each employee's badge opens only the doors they need, and each door has its own list of who may enter. A delivery company may drop parcels at the loading dock, but only parcels addressed to your company. Valuables sit in a safe whose key is held by security. On AWS the badges are identity policies, the door lists are resource policies, the delivery rule is the source condition, and the safe is KMS encryption.

Designing for security: least privilege across services, encryption, segmentation, identity

Security on the Solutions Architect exam is 30% of the score, and in a design review it is the part nobody wants to own. It is not one service: it is every role, policy, key and subnet in the design, each asking "who can do what to which resource, from where?". AWS I taught IAM policy evaluation, AWS II network segmentation, AWS III SCPs, AWS IV secrets and findings. This lesson applies them to the serverless and container designs of this chapter.

Need to know: two kinds of policies meet on every call - identity policies (what a role may do) and resource policies (who may use this queue, function, bucket, key). A service that acts for a resource - SNS delivering to a queue, S3 invoking a function, API Gateway calling Lambda - is a service principal and needs a resource policy statement, scoped with aws:SourceArn / aws:SourceAccount so no one else's resource can use it (the confused deputy problem). Encryption at rest is a KMS decision: who controls the key, and who may use it - a key policy is a resource policy too.

Least privilege for a function's role

try-worker-wide is the role a hurried developer wrote: sqs:* and s3:* on everything. Ask IAM what it allows instead of reading it:

$ aws iam get-role-policy --role-name try-worker-wide --policy-name app --query PolicyDocument.Statement
[
    {
        "Effect": "Allow",
        "Action": [
            "sqs:*",
            "s3:*"
        ],
        "Resource": "*"
    }
]
$ W=arn:aws:iam::111122223333:role/try-worker-wide
$ aws iam simulate-principal-policy --policy-source-arn $W --action-names sqs:DeleteQueue s3:DeleteBucket sqs:ReceiveMessage --resource-arns '*' --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output text
sqs:DeleteQueue	allowed
s3:DeleteBucket	allowed
sqs:ReceiveMessage	allowed

A bug or a stolen credential in that function can delete every queue and bucket in the account. The worker needs three SQS actions on one queue and s3:PutObject under one prefix:

$ aws iam get-role-policy --role-name try-worker-tight --policy-name app --query PolicyDocument.Statement
[
    {
        "Effect": "Allow",
        "Action": [
            "sqs:ReceiveMessage",
            "sqs:DeleteMessage",
            "sqs:GetQueueAttributes"
        ],
        "Resource": "arn:aws:sqs:eu-central-1:111122223333:try-secure"
    },
    {
        "Effect": "Allow",
        "Action": "s3:PutObject",
        "Resource": "arn:aws:s3:::oncall-try-thumbs-111122223333/thumbs/*"
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "arn:aws:kms:eu-central-1:111122223333:alias/try-app"
    }
]
$ T=arn:aws:iam::111122223333:role/try-worker-tight
$ aws iam simulate-principal-policy --policy-source-arn $T --action-names sqs:ReceiveMessage sqs:DeleteMessage --resource-arns arn:aws:sqs:eu-central-1:111122223333:try-secure --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output text
sqs:ReceiveMessage	allowed
sqs:DeleteMessage	allowed
$ aws iam simulate-principal-policy --policy-source-arn $T --action-names sqs:DeleteQueue --resource-arns arn:aws:sqs:eu-central-1:111122223333:try-secure --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output text
sqs:DeleteQueue	implicitDeny

One role per function (and per ECS task role), actions listed, resources by ARN, conditions where they help. IAM Access Analyzer can generate a policy from the role's CloudTrail activity, and its findings flag resource policies shared outside the account (AWS IV).

Resource policies and the confused deputy

$ aws lambda get-policy --function-name try-thumbs --query Policy --output text | jq '.Statement[] | {Principal, Action, Condition}'
{
  "Principal": {
    "Service": "s3.amazonaws.com"
  },
  "Action": "lambda:InvokeFunction",
  "Condition": {
    "ArnLike": {
      "AWS:SourceArn": "arn:aws:s3:::oncall-try-thumbs-111122223333"
    },
    "StringEquals": {
      "AWS:SourceAccount": "111122223333"
    }
  }
}
$ Q=$(aws sqs get-queue-url --queue-name try-secure --query QueueUrl --output text)
$ aws sqs get-queue-attributes --queue-url $Q --attribute-names Policy --query Attributes.Policy --output text | jq '.Statement[] | {Principal, Action, Condition}'
{
  "Principal": {
    "Service": "sns.amazonaws.com"
  },
  "Action": "sqs:SendMessage",
  "Condition": {
    "ArnEquals": {
      "aws:SourceArn": "arn:aws:sns:eu-central-1:111122223333:try-uploads"
    }
  }
}

Both statements name a service and pin it to one source: only this bucket may invoke the function, only this topic may send to the queue. Without the condition, any S3 bucket or SNS topic

  • in any account - that is configured to target your function or queue could use the permission.

Encryption choices

DataOptionsChoose by
S3 objectsSSE-S3 (default), SSE-KMS (AWS managed or customer managed key), DSSE-KMS, client-sidewho must control and audit the key; KMS adds per-request cost (bucket keys reduce it)
EBS, RDS, EFS, DynamoDBencrypted with a KMS key at creation (RDS: an unencrypted instance needs a snapshot copy to encrypt)default encryption on; a customer managed key for cross-account sharing and key policy control
SQS / SNSSSE-SQS (SQS-owned keys) or SSE-KMSKMS when you must restrict who can read via the key policy
secretsSecrets Manager (rotation) or SSM Parameter Store SecureStringnever in code, images or plain environment variables
in transitTLS everywhere: ACM certificates on ALB / CloudFront / API Gateway, aws:SecureTransport in bucket policies
$ aws sqs get-queue-attributes --queue-url $Q --attribute-names KmsMasterKeyId SqsManagedSseEnabled --output text
ATTRIBUTES	alias/try-app
$ aws kms describe-key --key-id alias/try-app --query 'KeyMetadata.[KeyManager,KeyUsage,KeyState]' --output text
CUSTOMER	ENCRYPT_DECRYPT	Enabled

With SSE-KMS on a queue, producers need kms:GenerateDataKey and consumers kms:Decrypt on the key - and a service principal that sends to it (SNS, EventBridge, S3) needs the same in the key policy. Forgetting that is the classic "messages silently stopped arriving after we turned on encryption".

Segmentation and the edge (recap)

  • Subnets: public for load balancers and NAT gateways only; private for tasks, functions in a VPC and databases; isolated (no route out) for data stores. Security groups that reference security groups (the ALB's group may reach the tasks' group), NACLs as a coarse second layer.
  • No internet path to AWS APIs: gateway endpoints (S3, DynamoDB) and interface endpoints (PrivateLink) for ECR, Logs, Secrets Manager, SQS - with endpoint policies.
  • The edge: AWS WAF on CloudFront, ALB or API Gateway (SQL injection, XSS, rate-based rules, bot control), AWS Shield Standard everywhere and Shield Advanced for DDoS response - taught hands-on in AWS V. GuardDuty, Inspector (ECR images and Lambda code too) and Macie (sensitive data in S3) watch from behind.
  • Hybrid connections: Site-to-Site VPN (encrypted, over the internet, quick) or Direct Connect (private, consistent, not encrypted by itself - add MACsec or a VPN over it); AWS V.

Identity for people and customers

  • Your workforce: IAM Identity Center with your identity provider (Entra ID, Okta, Google), permission sets per account, no IAM users. A directory (AD) federates through Identity Center or SAML to IAM roles.
  • Your customers: Amazon Cognito user pools - sign-up, sign-in, MFA, social and SAML identity providers, JWT tokens that API Gateway and ALB can validate. Identity pools trade a token for temporary AWS credentials (a mobile app uploading to its own S3 prefix).
$ aws cognito-idp create-user-pool --pool-name try-customers --query 'UserPool.[Id,Name]' --output text
eu-central-1_x00AdF5Ex	try-customers
$ aws cognito-idp describe-user-pool --user-pool-id $(aws cognito-idp list-user-pools --max-results 10 --query "UserPools[?Name=='try-customers'].Id" --output text) --query 'UserPool.Policies.PasswordPolicy'
{
    "MinimumLength": 8,
    "RequireUppercase": true,
    "RequireLowercase": true,
    "RequireNumbers": true,
    "RequireSymbols": true,
    "TemporaryPasswordValidityDays": 7
}

(simulator) Only the pool itself is simulated here; sign-up and sign-in flows are concepts.

  • Many accounts: AWS Organizations with SCPs (AWS III), and AWS Control Tower to set up a landing zone: a log archive and an audit account, guardrails (preventive = SCPs, detective = Config rules, proactive = CloudFormation hooks), and Account Factory for new accounts with the baseline already applied.

The shared responsibility model, per service

YouAWS
EC2the OS (patches), firewall config, apps, data, IAMhardware, hypervisor, facilities
RDSdata, users and grants, network access, encryption choice, parameter settingsthe OS and database engine patching, backups mechanics, Multi-AZ failover
Lambda / Fargatecode, dependencies, the role, configuration, dataruntime patching, the OS, capacity
S3 / DynamoDBdata, access policies, encryption choice, versioningstorage durability, infrastructure

The more managed the service, the more AWS takes - but data, identities and access are always yours.

On the exam (SAA-C03 1.1, 1.2, 1.3; SOA-C03 4.1, 4.2; CLF-C02 2.1, 2.3): least privilege with roles per workload, resource policies with source conditions, KMS key choices and the GenerateDataKey / Decrypt permissions, Secrets Manager over hard-coded credentials, private subnets + endpoints, WAF and Shield at the edge, Cognito for customer sign-in vs Identity Center for the workforce, Control Tower for multi-account guardrails, and who patches what.

In an interview: "You turned on KMS encryption on an SQS queue and an SNS topic stopped delivering to it. Why?" - "SNS has to encrypt the messages with the queue's key, so the key policy must let sns.amazonaws.com use kms:GenerateDataKey and kms:Decrypt. The SQS queue policy alone isn't enough any more. I'd add that to the key policy - scoped to the topic with aws:SourceArn - and check the topic's delivery failures go back to zero."

You can now: test a role with simulate-principal-policy and cut it down to the actions and resources it needs, write resource policies that pin a service to one source, choose encryption for each data store and the permissions it implies, place subnets, endpoints, WAF and Shield in a design, choose Cognito user pools, identity pools or Identity Center, describe a Control Tower landing zone, and split responsibilities by service.

Why it helps

Security is the largest domain of the Solutions Architect exam and the part of a design that fails silently until an incident. Least privilege per function and task, resource policies pinned to their source, KMS permissions that follow encryption, private subnets with endpoints, the right identity service for people and customers, and a clear split of responsibilities with AWS turn a working design into a defensible one.

Commands in this lesson

aws

FAQ

Why one role per function?

A shared role accumulates the permissions of every function that uses it, so a bug or stolen credential in the smallest function can do everything the largest one can. One role per function or task keeps each blast radius small and makes it obvious which code needs which permission when you review or tighten it.

What does aws:SourceArn protect against?

The confused deputy problem: a service principal such as S3 or SNS could be configured by someone else to invoke your function or send to your queue, using the permission you granted to the service. Pinning the statement to your bucket or topic with aws:SourceArn, and your account with aws:SourceAccount, closes that gap.

What changes when a queue uses a customer managed KMS key?

Producers need kms:GenerateDataKey and consumers kms:Decrypt on the key, in addition to their SQS permissions. Service principals that send to the queue, such as SNS or EventBridge, need the same through the key policy. Forgetting this is a common cause of messages silently stopping after encryption was turned on.

What are Cognito user pools and identity pools?

A user pool is a user directory for your application's customers: sign-up, sign-in, MFA, social and SAML federation, and tokens that API Gateway or an ALB can validate. An identity pool exchanges such a token for temporary AWS credentials so a client can call AWS services directly within a narrow role.

What is AWS Control Tower?

A service that sets up and governs a multi-account landing zone on top of AWS Organizations: a log archive and an audit account, guardrails implemented as service control policies, AWS Config rules and proactive CloudFormation hooks, and Account Factory to create new accounts with the baseline already applied.

In an interview Mid

You turned on KMS encryption on an SQS queue and an SNS topic stopped delivering to it. Why?

SNS now has to encrypt messages with the queue's key, so the key policy must allow sns.amazonaws.com to use kms:GenerateDataKey and kms:Decrypt - the queue policy alone is no longer enough. I would add that statement to the key policy, scoped to the topic with aws:SourceArn, and check that the topic's failed deliveries return to zero. Consumers of the queue need kms:Decrypt too.

Also asked: How do you apply least privilege to a Lambda function? · What is the confused deputy problem? · How is responsibility split between you and AWS for RDS?

Practise this lesson in the terminal Free, in your browser - a real Ubuntu terminal to try it in, with missions that check your work.