IAM & STS

Who is allowed to do what, and how do we prove they are that "who". Exam themes: policy shapes, roles vs resource-based policies, permission boundaries, and federating in external identities (SAML, OIDC, GitHub Actions).

Ai được làm gì, và làm sao chứng minh mình đúng là "ai" đó. Exam hay xoáy vào: các dạng policy, role vs resource-based policy, permission boundary, và kéo identity từ ngoài vào (SAML, OIDC, GitHub Actions).

Prefer roles whenƯu tiên role khi

  • EC2 / Lambda / ECS need AWS creds — attach a role, no keys on diskEC2 / Lambda / ECS cần cred — gán role, không có key trên máy
  • Cross-account access with clean audit trailCross-account có audit rõ ràng
  • Human devs via SSO / SAML federationDev truy cập qua SSO / SAML federation
  • CI/CD via OIDC (GitHub Actions, GitLab)CI/CD qua OIDC (GitHub Actions, GitLab)
  • On-prem servers via IAM Roles Anywhere — X.509 cert → temp creds, no stored keysServer on-prem qua IAM Roles Anywhere — X.509 cert → cred tạm, không lưu key

Prefer resource-based whenƯu tiên resource-based khi

  • External account should keep its identity (S3 bucket → other account)Account ngoài phải giữ danh tính (S3 bucket → account khác)
  • Same-account service-to-service call, no persona swapCùng account, service gọi service, không đổi persona
  • You want the policy to live with the resourceMuốn policy sống cùng resource

Acronyms — what the letters stand forViết tắt — chữ cái là của từ gì

ShortViết tắt Stands forLà của từ
IAMIdentity & Access Management
STSSecurity Token Service
SCPService Control Policy — org cap on principals— trần org cho principal
RCPResource Control Policy — org cap on resources— trần org cho resource
OUOrganizational Unit — a group of accounts in Organizations— nhóm account trong Organizations
SLRService-Linked Role
ABACAttribute-Based Access Control — allow by tag match— cho phép theo khớp tag
OIDCOpenID Connect
SAMLSecurity Assertion Markup Language
MFAMulti-Factor Authentication
ARNAmazon Resource Name
ACLAccess Control List — legacy, pre-IAM grant— cách cấp quyền cũ, có trước IAM

The vocabulary — each term answers one questionTừ vựng — mỗi khái niệm trả lời một câu hỏi

When a word blurs, snap it back to the question it answers. That alone disambiguates most exam wording. Khi rối, kéo mỗi khái niệm về đúng câu hỏi nó trả lời. Chỉ vậy là gỡ được phần lớn câu chữ trong exam.

TermKhái niệm Answers the question…Trả lời câu hỏi…
User Who is this human (or app)?Con người (hay app) này là ai?
Group What do these users share? — a bag of users, not an identity you assume; no nesting.Nhóm user này share quyền gì? — cái túi gom user, không phải identity để assume; không lồng nhau.
Role Who / what may borrow this identity?Ai / cái gì được mượn danh tính này?
Trust policyTrust policy WHO may assume the role? — it is the role's resource-based policy.AI được assume role? — nó chính là resource-based policy của role.
Permission policyPermission policy WHAT is allowed?Được làm GÌ?
Resource policyResource policy This resource lets WHO in? — the only policy with a Principal.Resource này cho AI vào? — policy duy nhất có Principal.

Policy shapesCác dạng policy

Managed vs inline decides lifecycle. Identity-based vs resource-based decides where the policy lives. Managed vs inline quyết vòng đời. Identity-based vs resource-based quyết policy sống ở đâu.

AWS Managed AdministratorAccess · PowerUserAccess
Customer Managed Standalone, reusable across users/rolesĐộc lập, tái sử dụng cho nhiều user/role
Inline Bound to one entity — dies with itGắn 1 entity — chết cùng entity
Resource-based Lives on the resource (S3 bucket, SQS queue, Lambda)Sống trên resource (S3 bucket, SQS queue, Lambda)
Action vs NotAction Action = allow/deny exactly these APIs. NotAction = allow/deny everything except these. Handy but easy to misuse — combine with tight Resource scoping. Action = allow/deny đúng những API liệt kê. NotAction = allow/deny tất cả trừ những cái liệt kê. Tiện nhưng dễ sai — kết hợp Resource siết chặt.

Every policy type in one tableGom hết loại policy vào một bảng

Nine shapes, but two questions split them all: does it grant, or only cap? and does it carry a Principal? Only three ever grant (identity-based, resource-based, and the legacy ACL); everything else can only cut. Chín dạng, nhưng chỉ hai câu là chia hết: nó cấp quyền, hay chỉ đặt trần? và nó có Principal không? Chỉ ba dạng cấp quyền (identity-based, resource-based, và ACL kiểu cũ); còn lại chỉ biết cắt.

PolicyPolicy Attached toGắn vào đâu Principal? Grants?Cấp quyền? Its one jobLàm đúng một việc
Identity-basedIdentity-based User, group, roleUser, group, role NoKhông YesCó What may this identity do?Identity này được làm gì?
Resource-basedResource-based S3, SQS, KMS key, Lambda… YesCó YesCó Who may touch this resource?Ai được đụng vào resource này?
Trust policyTrust policy IAM roleIAM role YesCó Yes — assume onlyCó — chỉ để assume Who may assume this role?Ai được assume role này?
Permission boundaryPermission boundary One user or roleMột user hoặc role NoKhông No — capsKhông — chỉ đặt trần Ceiling on that one entityTrần quyền của riêng entity đó
Session policySession policy An STS sessionMột STS session NoKhông No — capsKhông — chỉ đặt trần Shrinks the temp sessionSiết nhỏ phiên tạm
SCP Root / OU / accountRoot / OU / account Usually notThường không No — capsKhông — chỉ đặt trần Ceiling on principals in the accountTrần cho principal trong account
RCP Root / OU / accountRoot / OU / account "*" No — capsKhông — chỉ đặt trần Ceiling on resources in the accountTrần cho resource trong account
ACL S3 bucket / object…S3 bucket / object… Not IAM JSONKhông theo IAM JSON Yes — legacyCó — kiểu cũ Pre-IAM grant — turn it offCấp quyền thời tiền-IAM — nên tắt
VPC endpoint policyVPC endpoint policy A VPC endpointMột VPC endpoint YesCó No — filtersKhông — chỉ lọc What may pass through the endpointCái gì được đi qua endpoint
The two you'll meet less oftenHai cái ít gặp hơn ACL — the way you granted S3 access before IAM: no JSON, just a grantee plus a permission. AWS now says turn it off — set Object Ownership = Bucket owner enforced, which disables ACLs, then control access with bucket policy + IAM only. VPC endpoint policy — a resource policy living on the endpoint; it filters which requests may pass through but grants nothing. Effective access = IAM policy ∩ endpoint policy ∩ resource/bucket policy — use it to say "traffic through this endpoint may only reach these buckets". ACL — cách cấp quyền S3 từ trước khi có IAM: không JSON, chỉ là một grantee kèm một quyền. Giờ AWS khuyên tắt hẳn — đặt Object Ownership = Bucket owner enforced để vô hiệu ACL, rồi quản access chỉ bằng bucket policy + IAM. VPC endpoint policy — một resource policy nằm ngay trên endpoint; nó lọc request nào được đi qua chứ không tự cấp quyền gì. Quyền thực = IAM policy ∩ endpoint policy ∩ resource/bucket policy — dùng để nói "traffic qua endpoint này chỉ được với tới mấy bucket kia".

Role vs resource-based — the persona swapRole vs resource-based — đổi persona

Assume roleAssume role Resource-basedResource-based
Your original permissionsQuyền gốc Given upMất KeptGiữ
Where policy livesPolicy sống ở đâu On the roleTrên role On the resourceTrên resource
Good forTốt cho Cross-account, workloads on AWSCross-account, workload trên AWS Shared bucket, cross-account fanoutBucket share, fanout cross-account
Two policy JSON blocks side by side. On the left, an identity-based policy attached to an IAM user or role: it asks "what am I allowed to do?" and contains Effect, Action and Resource but has no Principal. On the right, a resource-based policy living on an S3 bucket, SQS queue or Lambda function: it asks "who is allowed into me?" and its distinguishing field is Principal, followed by Effect and Action. IDENTITY-BASED · policy bình thường IAM User / Role “tôi được làm gì?” "Effect": "Allow" "Action": "s3:GetObject" "Resource": "arn:…:bucket/*" // KHÔNG có Principal RESOURCE-BASED · gắn trên resource S3 · SQS · Lambda… “ai được vào tôi?” "Principal": {"AWS": "acct-A"} "Effect": "Allow" "Action": "s3:GetObject" // CÓ Principal = ai được vào

Same JSON dialect, one field apart. Identity-based says "what can I do" and never names a principal — the principal is whatever it's attached to. Resource-based says "who may come in", so it must spell out the Principal. That single field is why a resource policy can grant an external account access while keeping its own identity.

Cùng một kiểu JSON, chỉ lệch một field. Identity-based nói "tôi được làm gì" và không bao giờ ghi principal — principal ngầm là entity nó gắn vào. Resource-based nói "ai được vào", nên phải ghi rõ Principal. Chính field đó khiến resource policy cấp quyền cho account bên ngoài mà vẫn giữ nguyên danh tính gốc.

Which services even have oneService nào mới có Not every service supports a resource policy. The ones that matter: S3, SQS, SNS, Lambda, KMS key, Secrets Manager, ECR, EFS, API Gateway, VPC endpoint, and the IAM role trust policy. No resource policy (e.g. EC2, a DynamoDB table) → you must use identity-based + assume role. Không phải service nào cũng có resource policy. Nhóm hay gặp: S3, SQS, SNS, Lambda, KMS key, Secrets Manager, ECR, EFS, API Gateway, VPC endpoint, và trust policy của IAM role. Không có resource policy (VD EC2, bảng DynamoDB) → bắt buộc identity-based + assume role.
Cross-account needs both sidesCross-account cần cả hai phía Cross-account via resource-based policy: the caller's identity policy AND the resource policy must both allow. Same-account: either one is enough (exception: KMS — the key policy must allow). Cross-account qua resource-based policy: identity policy của caller VÀ resource policy đều phải Allow. Cùng account: một trong hai là đủ (ngoại lệ: KMS — key policy phải Allow).

Role flavors — same mechanism, different jobCác "vị" của role — cùng cơ chế, khác việc

These names aren't different features — they're all "a role an AWS service assumes on your behalf". They differ by who the role is for and who controls it. Những cái tên này không phải feature khác nhau — đều là "một role mà AWS service assume thay bạn". Khác nhau ở role dành cho ai và ai kiểm soát.

Who actually uses itAi thực sự dùng Controlled byAi kiểm soát
Execution roleExecution role The service runtime — Lambda writing logs, ECS pulling the imagePhần runtime của service — Lambda ghi log, ECS kéo image về YouBạn
Task roleTask role Your app code in the container — calling DynamoDB, S3…Code app trong container — gọi DynamoDB, S3… YouBạn
Instance roleInstance role EC2 (via an instance profile wrapper) — the SDK on the boxEC2 (qua vỏ instance profile) — SDK chạy trên máy YouBạn
Service roleService role An AWS service acting for you — CodeBuild, CodePipeline, ConfigMột AWS service làm thay bạn — CodeBuild, CodePipeline, Config YouBạn
Service-linked roleService-linked role The service managing its own resources — ELB creating ENIs, Auto Scaling calling EC2Service tự quản resource của chính nó — ELB tạo ENI, Auto Scaling gọi EC2 AWS — lockedAWS — khoá
"Execution / task / instance role" are all just service roles"Execution / task / instance role" đều chỉ là service role Same thing, a job-specific name per service: execution role (Lambda), task role (ECS), instance role (EC2). For every one of them you write the trust policy (Principal: Service + sts:AssumeRole) and the permissions. So what makes something a "service role" isn't "a service assumes it" — it's that you author the policy. The service-linked role is the one exception: a service assumes it too, but AWS predefines and locks both trust and permissions (AWSServiceRoleFor…). Same mechanism, opposite owner. Cùng một thứ, chỉ khác tên theo từng service: execution role (Lambda), task role (ECS), instance role (EC2). Cái nào bạn cũng tự viết trust policy (Principal: Service + sts:AssumeRole) lẫn permission. Nên cái khiến một role là "service role" không phải "service assume nó" — mà là bạn viết policy. Service-linked role là ngoại lệ duy nhất: cũng được service assume, nhưng AWS định nghĩa sẵn và khoá cả trust lẫn permission (AWSServiceRoleFor…). Cùng cơ chế, ngược chủ.
Two setups side by side. On the left, a service role: you write the policy and hand it to a role that Lambda, EC2 or CodeBuild assumes; you can edit, rename and delete it freely. On the right, a service-linked role: the AWS service comes with a locked, pre-defined policy named AWSServiceRoleForSomething that only it can assume; you cannot edit it and cannot delete it while the service is still using it. SERVICE ROLE · bạn cầm dây Bạn / You bạn viết policy Role Lambda / EC2 / CodeBuild assume để chạy sửa · xoá · đặt tên tự do SERVICE-LINKED ROLE · AWS cầm dây AWS service khoá sẵn AWSServiceRoleFor… service tự assume để tự quản resource của nó KHÔNG sửa · KHÔNG xoá khi còn dùng

The tell: name starts with AWSServiceRoleFor… or sits under path /aws-service-role/ → it's service-linked, hands off. Otherwise it's an ordinary role you own. AWS ships SLRs so a service can't be crippled by a mis-scoped role you'd otherwise have to hand-build.

Dấu hiệu nhận: tên bắt đầu bằng AWSServiceRoleFor… hoặc nằm ở path /aws-service-role/ → là service-linked, đừng đụng vào. Còn lại là role thường của bạn. AWS đóng gói SLR để service không hỏng vì một role bạn tự set thiếu quyền.

ECS trap: execution role vs task roleBẫy ECS: execution role vs task role Same task, two roles. Execution role = the infrastructure — pull the image from ECR, ship logs to CloudWatch. Task role = your application — what your code may call (S3, DynamoDB, SQS). App gets AccessDenied to DynamoDB? Fix the task role. Image won't pull? Fix the execution role. Cùng một task, hai role. Execution role = phần hạ tầng — kéo image từ ECR, đẩy log lên CloudWatch. Task role = phần ứng dụng — code của bạn được gọi gì (S3, DynamoDB, SQS). App bị AccessDenied vào DynamoDB? Sửa task role. Không kéo được image? Sửa execution role.

Grants vs guardrails — the evaluation chainGrant vs guardrail — chuỗi đánh giá

Only two policy types grant permission. The rest are guardrails that can only cut. A request needs ≥1 grant Allow AND every guardrail to pass — any explicit Deny, anywhere, wins. Chỉ hai loại policy cấp quyền. Còn lại là guardrail chỉ biết cắt. Một request cần ≥1 grant Allow VÀ mọi guardrail đều lọt — bất kỳ explicit Deny ở đâu cũng thắng.

Grant vs guardrailGrant vs guardrail Grant (adds): identity-based policy · resource-based policy. Guardrail (only cuts, never adds): permission boundary · SCP · RCP · session policy. Effective = (union of grants) ∩ (every guardrail) − (any Deny). Grant (thêm quyền): identity-based policy · resource-based policy. Guardrail (chỉ cắt, không thêm): permission boundary · SCP · RCP · session policy. Quyền thực = (union các grant) ∩ (mọi guardrail) − (mọi Deny).
An evaluation funnel drawn top to bottom. A request enters at the top, then passes through six gates in order: no explicit Deny anywhere; SCP allows (the org-level cap on principals); RCP allows (the org-level cap on resources); at least one grant Allow from an identity-based or resource-based policy; within the permission boundary; within the session policy. Failing any single gate branches out to DENY on the right. Only a request that passes all six reaches ALLOW at the bottom. request: principal → action → resource Deny thắng tất Không dính Explicit Deny nào? DENY guardrail · org → principal SCP cho phép? DENY guardrail · org → resource RCP cho phép? DENY GRANT — chỉ đây mới cho quyền Có ≥1 Allow? (identity HOẶC resource) DENY guardrail · 1 entity Trong Permission boundary? DENY guardrail · session tạm Trong Session policy? (nếu có) DENY ✅ ALLOW

Every gate but one only answers "am I blocking this?". The single green gate — a grant — is the only place a permission is ever added. That's why the phrase "all must allow" holds: the request has to survive every guardrail and find at least one Allow.

Mọi cửa trừ một chỉ trả lời "tôi có chặn không?". Cửa xanh duy nhất — một grant — là chỗ duy nhất quyền được thêm. Vì thế câu "tất cả phải Allow" mới đúng: request phải sống sót qua mọi guardrail và tìm được ít nhất một Allow.

The green gate: "≥1 Allow" depends on same- vs cross-accountCửa xanh: "≥1 Allow" tuỳ same- hay cross-account Same account: identity-based OR resource-based — either one Allow is enough (a union). Cross-account: the caller's identity policy AND the resource policy must both Allow. Either way, an explicit Deny in either policy → Deny — Deny always wins. Same account: identity-based HOẶC resource-based — 1 bên Allow là đủ (union). Cross-account: identity policy của caller VÀ resource policy phải Allow cả hai. Dù trường hợp nào, một explicit Deny ở một trong hai → Deny — Deny luôn thắng.
  • Permission boundary caps one IAM user or role. Classic use: let a dev team create roles, but every role they make is stuck inside the boundary — they can't escalate to admin. Permission boundary giới hạn một IAM user hoặc role. Dùng kinh điển: cho dev team tạo role, nhưng mọi role họ tạo đều kẹt trong boundary — không thể escalate lên admin.
  • Session policy is passed at AssumeRole time by the broker (SSO / app). Session permissions = role policy ∩ session policy — it can only shrink, never exceed the role. Session policy được broker (SSO / app) truyền lúc AssumeRole. Quyền session = policy của role ∩ session policy — chỉ thu nhỏ, không bao giờ vượt role.

SCP & RCP — org-wide guardrailsSCP & RCP — trần cấp tổ chức

Only exist inside AWS Organizations. Attach at Root / OU / Account and they flow down. SCP (Service Control Policy) guards the caller side, RCP (Resource Control Policy) guards the resource side. Chỉ tồn tại trong AWS Organizations. Gắn ở Root / OU / Account rồi chảy xuống. SCP (Service Control Policy) canh phía gọi, RCP (Resource Control Policy) canh phía resource.

An AWS Organizations tree. At the top a Root node branches to two organizational units, OU Prod and OU Dev. OU Prod branches to two member accounts, pay and billing; OU Dev branches to account team-a. A note explains that an SCP or RCP can attach at any level — Root, OU, or Account — and applies to everything beneath it, and that a request must pass the cap at every level, an intersection down the tree. Root ← gắn được ở đây OU · Prod OU · Dev ← và đây acct pay acct billing acct team-a ← và đây trần chảy xuống · phải lọt qua ở MỌI tầng (giao ∩)

Attach a cap at Root, an OU, or a single account — it applies to everything beneath. A permission must be allowed by the cap at every level it passes through (an intersection down the tree). Both SCP and RCP attach exactly here; the difference is what they filter.

Gắn trần ở Root, một OU, hay một account — áp cho mọi thứ bên dưới. Một quyền phải được cho phép ở trần của mọi tầng nó đi qua (giao ∩ đi xuống). SCP và RCP gắn đúng chỗ này; khác nhau ở cái chúng lọc.

A request has two sides. SCP filters the principal's account; RCP filters the resource's account. RCP is the only one that bites when the caller sits outside your org. Một request có hai phía. SCP lọc account của principal; RCP lọc account của resource. RCP là cái duy nhất cắn khi caller nằm ngoài org của bạn.

Two rows showing why both guardrails are needed. Top row: a principal inside your org, in account A, calls an S3 resource in account B, also inside your org — SCP applies to the caller and RCP applies to the resource, both guardrails bite. Bottom row: a principal outside your org calls the same S3 resource in account B — SCP cannot reach the external caller, but RCP still guards the resource and blocks it. ① Người TRONG org gọi Principal · acct A (trong org) SCP áp ✓ gọi S3 · acct B (trong org) RCP áp ✓ ② Người NGOÀI org gọi Principal · NGOÀI org SCP KHÔNG với tới ✗ gọi cùng resource cùng S3 · acct B RCP vẫn chặn ✓

SCP can only trap principals inside your org — an external caller sails past it. RCP sits on the resource side, so it holds the line against anyone, in or out of the org. That asymmetry is the whole reason RCP was added.

SCP chỉ trói được principal trong org — người ngoài đi thẳng qua. RCP nằm ở phía resource nên giữ được cửa với bất kỳ ai, trong hay ngoài org. Chính sự bất đối xứng đó là lý do RCP ra đời.

SCP example — attach to OU ProdVí dụ SCP — gắn lên OU Prod Every principal in pay & billing is region-locked and can't disable logging.Mọi principal trong pay & billing bị khoá region, không tắt được log.
RCP example — attach to OU ProdVí dụ RCP — gắn lên OU Prod Every S3 bucket in the OU rejects non-org callers and non-TLS access.Mọi S3 bucket trong OU từ chối caller ngoài org và truy cập không TLS.
// SCP — trói principal của mình
{ "Effect": "Deny", "Action": "*", "Resource": "*",
  "Condition": { "StringNotEquals": { "aws:RequestedRegion": "us-east-1" } } }
{ "Effect": "Deny", "Action": "cloudtrail:StopLogging", "Resource": "*" }

// RCP — canh resource, chặn cả người ngoài org
{ "Effect": "Deny", "Principal": "*", "Action": "s3:*", "Resource": "*",
  "Condition": { "StringNotEquals": { "aws:PrincipalOrgID": "o-myorg" } } }
{ "Effect": "Deny", "Principal": "*", "Action": "s3:*", "Resource": "*",
  "Condition": { "Bool": { "aws:SecureTransport": "false" } } }
  • Neither grants. An account whose identities have no policies does nothing, even under a wide-open FullAWSAccess SCP. Cả hai không cấp quyền. Account mà identity không có policy thì chẳng làm được gì, dù SCP có FullAWSAccess mở toang.
  • SCP skips the management account and service-linked roles — don't run sensitive workloads in the management account expecting SCP protection. SCP bỏ qua management account và service-linked role — đừng chạy workload nhạy cảm ở management account rồi tưởng SCP che.
  • RCP currently covers S3, STS, SQS, KMS, Secrets Manager (expanding). Other services aren't guarded by RCP yet. RCP hiện phủ S3, STS, SQS, KMS, Secrets Manager (đang mở rộng). Service khác chưa được RCP canh.

STS — the important APIsSTS — các API quan trọng

Sort the five by which persona you get back. The AssumeRole* family gives you a role. The other two derive from the calling IAM user — no role at all. Phân loại 5 cái theo bạn nhận persona nào. Họ AssumeRole* cho bạn một role. Hai cái còn lại lấy quyền từ chính IAM user gọi — không có role nào.

APIAPI Use it whenDùng khi Persona you getPersona nhận về
AssumeRole Assume a role, same- or cross-accountAssume một role, same- hay cross-account The role's permissionsQuyền của role
AssumeRoleWithSAML User logged in via a SAML IdP (ADFS, Okta)User login qua SAML IdP (ADFS, Okta) The role's permissionsQuyền của role
AssumeRoleWithWebIdentity User logged in via an OIDC IdP (Google, Facebook…). AWS recommends Cognito instead.User login qua OIDC IdP (Google, Facebook…). AWS khuyên dùng Cognito thay thế. The role's permissionsQuyền của role
GetSessionToken Need an MFA-backed session for an existing IAM user (or root)Cần session có MFA cho IAM user sẵn có (hoặc root) The same IAM user + MFAVẫn chính IAM user đó + MFA
GetFederationToken A broker app hands temp creds to users from a non-AWS store (AD / custom DB)App broker phát cred tạm cho user từ kho ngoài AWS (AD / DB tự viết) A federated user — broker ∩ passed policyMột federated user — broker ∩ policy truyền vào
Three lanes sorting the STS APIs by the persona returned. The AssumeRole family — AssumeRole, AssumeRoleWithSAML, AssumeRoleWithWebIdentity — returns the permissions of a role, swapping persona. GetSessionToken returns the same calling IAM user plus MFA. GetFederationToken returns a synthetic federated user whose permissions are the broker's intersected with a passed policy. AssumeRole family …WithSAML · …WithWebIdentity → quyền của 1 ROLE (đổi persona) GetSessionToken → VẪN chính IAM user đó + MFA GetFederationToken → "federated user" ảo (broker ∩ policy)

Top lane = assume a role, swap persona. Bottom two = no role: GetSessionToken is just you with MFA; GetFederationToken mints a synthetic identity through a broker. That single split answers most STS exam wording.

Làn trên = assume role, đổi persona. Hai làn dưới = không role: GetSessionToken chỉ là chính bạn + MFA; GetFederationToken tạo danh tính ảo qua broker. Chỉ cái phân đôi đó là trả lời được phần lớn câu STS trong exam.

GetSessionToken = MFA gatecổng MFA Policies require aws:MultiFactorAuthPresent = true; the user calls GetSessionToken with their MFA code, and the returned session carries the MFA proof so the gated actions now work. Same permissions as the user — it adds MFA, not access. Policy đòi aws:MultiFactorAuthPresent = true; user gọi GetSessionToken kèm mã MFA, session trả về mang dấu MFA nên các action bị khoá mới chạy được. Quyền y hệt user — nó thêm MFA, không thêm quyền.

GetFederationToken in one scenario: 5,000 staff already live in corporate AD — you don't want an IAM user each. A broker app authenticates them and vends scoped temp creds. GetFederationToken qua một tình huống: 5.000 nhân viên đã có sẵn trong AD công ty — bạn không muốn tạo IAM user cho từng người. Một app broker xác thực họ rồi phát cred tạm đã siết nhỏ.

The GetFederationToken broker flow. Step one, employee bob logs into the internal portal with his corporate password, checked against Active Directory. Step two, the portal is the broker, running under a single IAM user called TokenVendor whose long-term key lives only here. Step three, the portal calls GetFederationToken with Name equal to bob and a policy scoped to only S3 under home/bob. Step four, STS returns temporary credentials for federated-user/bob. Step five, bob uses those credentials and can only touch S3 under home/bob, and CloudTrail records the actions as federated-user/bob. ① bob login portal (password công ty → check AD) ② Portal = BROKER (1 IAM user: TokenVendor) ← key chỉ ở đây ③ GetFederationToken(Name=bob, Policy = s3 chỉ trên home/bob/* ) ← siết nhỏ ④ STS → cred tạm cho federated-user/bob ⑤ bob dùng cred → chỉ đụng S3 home/bob/* ← CloudTrail thấy bob

No IAM user per employee — identities stay in AD, AWS only ever sees a short-lived federated-user/bob. The one long-term key sits in the broker; everything downstream holds only temp creds. And CloudTrail still attributes actions to bob.

Không cần IAM user cho từng nhân viên — danh tính vẫn ở AD, AWS chỉ thấy federated-user/bob tạm thời. Long-term key duy nhất nằm ở broker; mọi thứ phía sau chỉ cầm cred tạm. Và CloudTrail vẫn quy đúng hành động về bob.

Modern replacementCách làm hiện đại GetFederationToken is the legacy custom-broker pattern (no IdP, no role). Today prefer IAM Identity Center or SAML/OIDC + AssumeRole for staff, and Cognito for app/mobile users. GetFederationToken là pattern broker tự viết kiểu cũ (không IdP, không role). Nay nên dùng IAM Identity Center hoặc SAML/OIDC + AssumeRole cho nhân viên, và Cognito cho user app/mobile.

STS & session tagsSTS & session tag

Session tags travel with the assumed session. Use them for ABAC: allow only if aws:PrincipalTag/team matches the resource tag. Session tag đi cùng session. Dùng cho ABAC: chỉ Allow khi aws:PrincipalTag/team khớp resource tag.

Common condition keysCondition key hay gặp aws:PrincipalTag/*, aws:RequestTag/*, aws:ResourceTag/*, aws:SourceIp, aws:MultiFactorAuthPresent. aws:PrincipalTag/*, aws:RequestTag/*, aws:ResourceTag/*, aws:SourceIp, aws:MultiFactorAuthPresent.
  • Passing session tags needs sts:TagSession allowed in the role's trust policy — forget it and AssumeRole with Tags fails with AccessDenied. Truyền session tag cần sts:TagSession được Allow trong trust policy của role — quên là AssumeRole kèm Tags báo AccessDenied.
  • External ID stops the confused deputy when a third party assumes your role — full section below. External ID chặn confused deputy khi bên thứ ba assume role của bạn — section riêng ở dưới.

Confused deputy & External IDConfused deputy & External ID

A trusted middle-man (the deputy) has real permission to assume your role. An attacker who shares that deputy tricks it into using that permission against your account. The ExternalId is a per-customer tag that binds each assume to "which customer am I acting for". Một bên trung gian được tin (deputy) có quyền thật để assume role của bạn. Kẻ tấn công dùng chung deputy đó lừa nó xài quyền ấy lên chính account bạn. ExternalId là nhãn theo từng customer, buộc mỗi lần assume với "tôi đang làm thay customer nào".

The three partiesBa bên You = customer, own Role A. Example Corp = the third-party SaaS you hired (the deputy), trusted to assume Role A. Attacker = another customer of Example Corp. Bạn = customer, sở hữu Role A. Example Corp = SaaS bên thứ ba bạn thuê (deputy), được tin để assume Role A. Attacker = một customer khác của Example Corp.
The confused deputy attack without an external ID. An attacker hands Example Corp the ARN of your Role A and asks it to scan that account. Example Corp, which is genuinely trusted to assume Role A, calls AssumeRole on Role A. AWS checks only whether Example Corp is trusted, sees yes, and allows it — with no way to tell whether Example Corp is acting for you or for the attacker, so the attacker gains access to your account. ① giao ARN role của A ② AssumeRole (Role A) Attacker customer khác của Corp Example Corp deputy · được A tin ✓ Role A account của bạn ③ AWS: "Example Corp có được tin không?" ✓ → ALLOW AWS không biết deputy làm cho A hay attacker → attacker chiếm quyền

The deputy isn't hacked — it has genuine, legitimate permission. The attacker simply feeds it your role ARN, and AWS's trust check ("is Example Corp allowed?") can't see on whose behalf the deputy is acting. That blind spot is the whole vulnerability.

Deputy không hề bị hack — nó có quyền thật, hợp lệ. Attacker chỉ đưa cho nó ARN role của bạn, và bước kiểm tra trust của AWS ("Example Corp có được phép không?") không thấy được deputy đang làm thay ai. Đúng cái điểm mù đó là toàn bộ lỗ hổng.

Fix: Example Corp assigns each customer a unique ExternalId; you add it as a condition on the trust policy. Now the deputy must say which customer it's acting for — and it can't be forced to send someone else's ID. Cách chặn: Example Corp cấp cho mỗi customer một ExternalId riêng; bạn thêm nó làm condition trong trust policy. Giờ deputy phải khai đang làm thay customer nào — và không thể bị ép gửi ID của người khác.

The external ID fix, two rows. Top row, the normal case: you, Customer A, ask Example Corp; it assumes Role A sending ExternalId 12345; Role A requires 12345, they match, so it is allowed. Bottom row, the attack: the attacker who is Customer B asks Example Corp; because Example Corp thinks the request is from Customer B, it sends Customer B's ExternalId 67890; the same Role A still requires 12345; 67890 does not equal 12345, so it is denied and you are protected. yêu cầu ExternalId=12345 Customer A (bạn) Example Corp Role A · cần ExternalId 12345 12345 == 12345 → ALLOW ✓ yêu cầu ExternalId=67890 Attacker (Cust. B) Example Corp cùng Role A · cần 12345 67890 ≠ 12345 → DENY ✓ (bạn được bảo vệ)

Example Corp thinks the attacker's request is Customer B, so it sends B's ID (67890) — not A's. Role A demands 12345, they mismatch, denied. The attacker never gets to choose which ID the deputy sends; that's what actually protects you.

Example Corp tưởng request của attacker là của Customer B, nên nó gửi ID của B (67890) — không phải của A. Role A đòi 12345, lệch nhau, bị chặn. Attacker không bao giờ chọn được deputy gửi ID nào; chính điều đó mới bảo vệ bạn.

// Trust policy của Role A — thêm condition ExternalId
{
  "Effect": "Allow",
  "Principal": { "AWS": "<Example Corp's AWS account>" },
  "Action": "sts:AssumeRole",
  "Condition": {
    "StringEquals": { "sts:ExternalId": "12345" }
  }
}
External ID is NOT a secretExternal ID KHÔNG phải secret AWS explicitly says it isn't treated as a secret — anyone who can read the role can see it. Its security doesn't come from "the attacker doesn't know 12345". It comes from: the attacker can't force the deputy to send 12345 for the attacker's own request. It's a customer-context binding, not a password. AWS nói rõ nó không được coi là secret — ai đọc được role đều thấy. An toàn của nó không đến từ "attacker không biết 12345". Nó đến từ: attacker không thể ép deputy gửi 12345 cho request của chính attacker. Đây là binding theo customer, không phải password.
  • The third party generates the ID, unique per customer — they're the ones who know "12345 = Customer A". You just drop it into the trust policy condition. Bên thứ ba tạo ID, riêng cho từng customer — họ mới là bên chắc chắn "12345 = Customer A". Bạn chỉ việc bỏ nó vào condition của trust policy.
  • The ID rides inside the AssumeRole request as a condition — checked during the assume, not after. It's not part of any access key or credential. ID đi trong chính request AssumeRole dưới dạng condition — kiểm ngay lúc assume, không phải sau. Nó không nằm trong access key hay credential nào.
  • Exam reflex: "grant a third-party / vendor account access to your account" → cross-account role + External ID. Never share access keys. Phản xạ exam: "cấp cho account bên thứ ba / vendor quyền vào account bạn" → cross-account role + External ID. Không bao giờ share access key.

GitHub Actions ↔ AWS via OIDCGitHub Actions ↔ AWS qua OIDC

No long-lived access keys. GitHub becomes an OIDC identity provider; the role's trust condition pins which repo & branch may assume it. Không dùng access key vĩnh viễn. GitHub thành OIDC identity provider; trust condition của role ghim repo & branch nào được phép assume.

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {
      "Federated": "arn:aws:iam::<ACCOUNT>:oidc-provider/token.actions.githubusercontent.com"
    },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "token.actions.githubusercontent.com:sub":
          "repo:my-org/my-repo:ref:refs/heads/main"
      }
    }
  }]
}
Missing the sub conditionThiếu condition sub Without a sub filter any GitHub repo in the world could assume the role. This is the top OIDC mistake. Không có filter sub, bất kỳ repo GitHub nào cũng assume được role. Đây là sai lầm OIDC số 1.

Service roles & iam:PassRoleService role & iam:PassRole

A service role is a role whose trusted principal is an AWS service, so the service can act on your behalf. The interesting part isn't the role — it's that handing a role to a service is itself a privileged action, gated by iam:PassRole. Một service role là role có trusted principal là một service AWS, để service hành động thay bạn. Phần đáng chú ý không phải bản thân role — mà là việc trao một role cho service cũng là một hành động đặc quyền, canh bởi iam:PassRole.

Splitting permissions between an engineer and a CloudFormation service role. The engineer's IAM role holds only two permissions: CloudFormation actions such as CreateStack, and iam colon PassRole scoped to one approved role ARN. The engineer therefore cannot create EC2 instances or S3 buckets directly. When the engineer creates a stack and names the service role, CloudFormation assumes that role, and the service role's policy is what actually grants permission to create the approved resource types. A note explains that without a service role CloudFormation would use the caller's own permissions, which would force you to grant the engineer the resource permissions directly and let them bypass CloudFormation entirely. engineer role cloudformation:CreateStack iam:PassRole (one ARN) no ec2:* · no s3:* pass CloudFormation sts:AssumeRole on the named service role CloudFormationServiceRole trusts cloudformation.amazonaws.com allows only the approved resource types template asks for RDS → stack fails without a service role, CloudFormation runs with the CALLER's permissions — so you would have to grant the engineer ec2:* and s3:* …and then they could create those resources directly, bypassing CloudFormation entirely — which was the whole thing you were trying to prevent same shape everywhere: Lambda execution role · ECS task role · CodeBuild service role · Step Functions execution role · EC2 instance profile

Two layers of permission, deliberately disjoint: the human may only drive the service, and the service alone may build. That's how "engineers must provision only via CloudFormation" is actually enforced.

Hai tầng quyền, cố ý không giao nhau: con người chỉ được điều khiển service, và chỉ service mới được dựng. Đó là cách "kỹ sư chỉ được provisioning qua CloudFormation" thật sự được ép.

// trust policy của service role — ai được assume nó
{ "Effect": "Allow",
  "Principal": { "Service": "cloudformation.amazonaws.com" },
  "Action": "sts:AssumeRole" }

// quyền engineer cần để "đưa" role đó cho CloudFormation
{ "Effect": "Allow",
  "Action": "iam:PassRole",
  "Resource": "arn:aws:iam::123456789012:role/CloudFormationApprovedRole",
  "Condition": { "StringEquals": { "iam:PassedToService": "cloudformation.amazonaws.com" } } }
  • iam:PassRole does not let the engineer assume the role. It only lets them say "service, use this role". Scope it to specific role ARNs — a wildcard PassRole is a privilege-escalation hole.iam:PassRole không cho engineer assume role đó. Nó chỉ cho phép nói "service ơi, dùng role này". Giới hạn theo ARN cụ thể — PassRole với wildcard là một lỗ leo thang đặc quyền.
  • A service role is an IAM role, never an IAM user. It has no access keys; the service gets short-lived STS credentials. If your Terraform or CI still uses an IAM user with long-lived keys, the modern shape is OIDC → AssumeRoleWithWebIdentity → deployment role.Service role là một IAM role, không bao giờ là IAM user. Nó không có access key; service nhận credential STS ngắn hạn. Nếu Terraform hay CI của bạn vẫn dùng IAM user với key dài hạn, hình dạng hiện đại là OIDC → AssumeRoleWithWebIdentity → deployment role.
  • The same permission policy can be reused across several roles that differ only in trust — one trusting CloudFormation, one trusting the GitHub OIDC provider, one trusting CodeBuild.Cùng một permission policy dùng lại được cho nhiều role chỉ khác nhau ở phần trust — một cái trust CloudFormation, một cái trust GitHub OIDC provider, một cái trust CodeBuild.
  • Lambda invoking ecs:RunTask needs iam:PassRole for both the task role and the task execution role — a very common missing permission.Lambda gọi ecs:RunTask cần iam:PassRole cho cả task role lẫn task execution role — một quyền rất hay bị thiếu.

IAM Access Analyzer

It reads your resource-based policies and answers one question: can anything outside my zone of trust reach this? It reasons about the policies mathematically — it is not looking at logs, so a finding means "this access is possible", not "this happened". Nó đọc resource-based policy của bạn và trả lời đúng một câu: có thứ gì ngoài zone of trust với tới được cái này không? Nó suy luận toán học trên policy — nó không nhìn log, nên một finding nghĩa là "truy cập này có thể xảy ra", không phải "đã xảy ra".

External access findingsExternal access findings Set the zone of trust to your account or your organization. Anything granting a principal outside it raises a finding: S3 buckets, IAM roles, KMS keys, SQS queues, Lambda functions, Secrets Manager secrets, EFS, ECR, RDS snapshots.Đặt zone of trust là account hoặc organization của bạn. Bất cứ thứ gì cấp quyền cho principal ngoài đó đều sinh finding: S3 bucket, IAM role, KMS key, SQS queue, Lambda function, secret của Secrets Manager, EFS, ECR, snapshot RDS.
Unused access findingsUnused access findings Roles nobody assumes, permissions nobody uses, access keys gone cold — the raw material for cutting a role down to least privilege.Role không ai assume, quyền không ai dùng, access key nguội lạnh — nguyên liệu để cắt một role về least privilege.
Policy generation & validationSinh & kiểm tra policy Generate a least-privilege policy from CloudTrail history, validate policies against grammar and best practice, and check no new access in a pipeline before a policy change ships.Sinh policy least-privilege từ lịch sử CloudTrail, kiểm tra policy theo cú pháp và best practice, và check no new access trong pipeline trước khi thay đổi policy được deploy.
The three "who's my advisor" services, pulled apartTách ba service "ai là cố vấn của tôi" Trusted Advisor — broad best-practice checks across cost, performance, security, fault tolerance, service limits (the general practitioner). Compute Optimizer — rightsizing from CloudWatch utilization: this instance is too big, use that one (the sizing specialist). IAM Access Analyzer — who outside the org is permitted to reach my resources (the access auditor). They're confused constantly because all three "give recommendations"; the data they read is completely different. Trusted Advisor — kiểm tra best practice diện rộng về cost, performance, security, fault tolerance, service limit (bác sĩ đa khoa). Compute Optimizer — rightsizing dựa trên utilization từ CloudWatch: máy này quá to, dùng máy kia (chuyên gia chọn cỡ máy). IAM Access Analyzer — ai ngoài org được phép với tới resource của tôi (kiểm toán viên quyền truy cập). Ba cái này liên tục bị nhầm vì đều "đưa khuyến nghị"; nhưng dữ liệu chúng đọc thì hoàn toàn khác nhau.
  • Don't confuse it with the network analyzers. IAM Access Analyzer = permissions. VPC Network Access Analyzer = "is there any network path from the internet to this?" VPC Reachability Analyzer = "can this specific source reach that specific destination, and where does it stop?"Đừng nhầm với các analyzer về mạng. IAM Access Analyzer = quyền. VPC Network Access Analyzer = "có đường mạng nào từ internet tới cái này không?" VPC Reachability Analyzer = "nguồn cụ thể này có với tới đích cụ thể kia không, và tắc ở đâu?"
  • "Access Analyzer for S3" in the S3 console is the same engine viewed through an S3 lens. It is a security tool — it says nothing about storage cost or access frequency, so it's a distractor in any storage-class question."Access Analyzer for S3" trong console S3 là cùng một bộ máy nhìn qua lăng kính S3. Nó là công cụ bảo mật — không nói gì về chi phí lưu trữ hay tần suất truy cập, nên là bẫy trong mọi câu hỏi về storage class.
  • Run it from a delegated administrator account so findings from every member account land in one place.Chạy nó từ account delegated administrator để finding của mọi member account đổ về một chỗ.