-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path315-iam.mdc
More file actions
373 lines (286 loc) · 15.4 KB
/
Copy path315-iam.mdc
File metadata and controls
373 lines (286 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
---
title: Identity, Access, and Authentication (IAM, OIDC, SAML, PKCE, PKI, PAM)
description: Practical security guidance for IAM design and identity protocols (OIDC/OAuth2/PKCE, SAML/ADFS) plus PKI and PAM operational patterns.
priority: 315
alwaysApply: false
files:
include:
- "**/*auth*.*"
- "**/*oauth*.*"
- "**/*oidc*.*"
- "**/*pkce*.*"
- "**/*saml*.*"
- "**/*adfs*.*"
- "**/*iam*.*"
- "**/*identity*.*"
- "**/*login*.*"
- "**/.github/workflows/*.yaml"
- "**/.github/workflows/*.yml"
- "**/*.tf"
- "**/*.yaml"
- "**/*.yml"
---
# Identity, Access, and Authentication (IAM, OIDC, SAML, PKCE, PKI, PAM)
**Audience**: engineers designing authentication/authorization and cloud access patterns
**Goal**: build secure-by-default identity systems with least privilege, strong verification, and clean operations
> [!IMPORTANT]
> This ruleset complements `310-security.mdc` (OWASP) and `320-api-design.mdc` (API auth patterns).
> Use this for identity-specific decisions: token validation, federation, access boundaries, and certificate lifecycle.
---
## Non-negotiables
- **Default deny**: no implicit access - access must be explicitly granted
- **Least privilege**: minimal actions, minimal resources, minimal time (short-lived creds)
- **Separation of duties**: admin != deploy != runtime
- **No secret material in logs**: never log passwords, tokens, session cookies, private keys, assertions
- **Prove authenticity**: always validate signatures (JWT/JWS, SAML XML signature), issuer, audience, and time bounds
- **Assume breach**: monitor, rotate, revoke, and limit blast radius
---
## Security research and citation discipline
- Prefer current primary sources: standards bodies, protocol specifications, and official vendor documentation.
- Cite a standard by name. Include an RFC, NIST publication, or CVE identifier only after verifying it.
- Never invent a plausible-looking specification, control, CVE, feature, or version number.
- State uncertainty plainly and identify what must be verified before implementation.
- Recheck current vendor documentation when behavior depends on defaults, supported flows, versions, or
recently disclosed vulnerabilities.
For OAuth deployments, use the current
[Best Current Practice for OAuth 2.0 Security (RFC 9700 / BCP 240)](https://www.rfc-editor.org/rfc/rfc9700.html)
alongside the applicable base and extension specifications.
---
## IAM (cloud access control)
### Policy design principles
- **Prefer roles over users** for workloads and automation
- **Prefer short-lived credentials** (STS, workload identity) over long-lived access keys
- **Use conditions** to reduce blast radius:
- source IP / VPC conditions (when valid)
- required tags (ABAC)
- MFA requirement for interactive access
- session duration limits
- **Use boundaries and guardrails**:
- permission boundaries for roles created by automation
- org-level controls (SCPs) where applicable
- break-glass roles with strong protections and monitoring
> [!WARNING]
> Avoid wildcarding both **action** and **resource**. `Action: "*" + Resource: "*"` is almost never acceptable.
### Session and identity propagation
- **Use session tags** to propagate identity attributes when supported
- **Log principal context**, not secrets:
- principal ARN / role ARN
- session name
- request ID / trace ID
- account / region
### Common anti-patterns (avoid)
- Using root/admin for automation
- Reusing a single “god role” across multiple apps/environments
- Long session durations by default
- Attaching `*` permissions “temporarily” and forgetting to remove them
- Storing cloud access keys in repos, CI logs, or shell history
---
## Identity Governance and Administration (IGA)
Authentication and authorization controls decay without lifecycle governance. Human and non-human identities
must have an accountable owner, approved purpose, bounded entitlements, and a reliable end-of-life path.
### Lifecycle requirements
- Automate **joiner, mover, and leaver** events from an authoritative source.
- Remove or recalculate access when employment, team, workload, environment, or business purpose changes.
- Define maximum deprovisioning times by risk; privileged and production access should be revoked immediately.
- Disable first, investigate dependencies, then delete after the documented recovery and retention period.
- Treat dormant, orphaned, shared, and ownerless identities as findings, not inventory noise.
### Entitlement governance
- Maintain an entitlement catalog with business meaning, technical scope, risk, owner, and approval path.
- Separate birthright access from requestable, privileged, emergency, and machine access.
- Enforce separation-of-duties constraints before granting access, not only during retrospective audits.
- Run risk-based access certifications; privileged, production, and sensitive-data access requires more frequent
review than low-risk access.
- Review effective access, including nested groups, inherited roles, resource policies, and temporary grants.
- Expire unused and time-bound grants automatically; do not rely on ticket closure as proof of revocation.
### NHI governance
- Inventory service accounts, IAM roles, OAuth clients, API keys, certificates, CI identities, and agents.
- Assign every NHI an owner, workload, environment, purpose, credential type, and expected last-used pattern.
- Couple NHI provisioning and deprovisioning to the workload lifecycle.
- Alert on unexpected use, stale credentials, missing owners, privilege growth, and use after retirement.
- Preserve review decisions and revocation evidence in an auditable system of record.
These controls align with account-management and access-review concepts in
[NIST SP 800-53 Rev. 5](https://csrc.nist.gov/pubs/sp/800/53/r5/upd1/final), including AC-2.
---
## Protocol analysis contract
When designing or reviewing OAuth, OIDC, SAML, SCIM, mTLS, federation, token exchange, or delegated access:
1. Identify every actor, trust boundary, authorization server, resource server, and policy enforcement point.
2. Trace the actual messages and credential exchanges in order; use a Mermaid sequence diagram when the flow is
not obvious.
3. For each token, assertion, or certificate, state the issuer, subject, actor/delegator, audience, scope,
lifetime, proof-of-possession model, storage location, and revocation mechanism.
4. Separate authentication, token issuance, delegation, authorization, and policy enforcement. Do not collapse
them into a generic "auth" step.
5. Describe replay, substitution, confused-deputy, token-theft, downgrade, and stale-access failure modes.
6. Identify the audit event and correlation identifier emitted at each trust decision.
---
## OIDC and OAuth2 (with PKCE)
### Recommended baseline (public clients)
For browser/native clients:
- **Authorization Code Flow + PKCE**
- **No implicit flow**
- **Use state + nonce**
- **Strict redirect URI allowlist**
```mermaid
sequenceDiagram
autonumber
participant Client
participant AS as Authorization Server (OIDC)
participant RS as Resource Server (API)
Client->>Client: Generate code_verifier + code_challenge (S256)
Client->>AS: /authorize (response_type=code, code_challenge, state, nonce)
AS-->>Client: redirect with code (+ state)
Client->>AS: /token (code + code_verifier)
AS-->>Client: id_token + access_token (and refresh_token if allowed)
Client->>RS: API request with access_token
RS-->>Client: Response
```
### Token validation checklist (resource servers)
When validating JWT access tokens (or ID tokens where applicable):
- **Signature**:
- verify using provider JWKS
- pin **issuer** and validate `kid` lookup
- cache JWKS with sane TTL, handle key rotation
- **Claims**:
- `iss` must match expected issuer
- `aud` must include your API audience
- `exp` and `nbf` enforced (allow small clock skew only)
- `sub` present and stable per identity provider rules
- `nonce` validated for OIDC ID tokens (client-side)
- **Transport**:
- only accept tokens over HTTPS
- do not accept tokens in query strings (prefer `Authorization: Bearer`)
> [!CAUTION]
> Do not treat an ID token as an access token. ID tokens are for the client to learn about the user; access tokens are for APIs.
### PKCE checklist (authorization server + client)
- **S256 required** (avoid plain)
- **code_verifier length and charset** per spec
- **Single use** authorization codes (replay protection)
- **state required** (CSRF protection)
- **nonce required** for OIDC (replay protection for ID token)
### Operational guidance
- Prefer short access token TTLs and rotate refresh tokens if used
- Rate limit token endpoints and sensitive auth paths
- Log:
- auth failures (reason category, not raw tokens)
- token verification failures (issuer mismatch, audience mismatch, expired)
---
## SAML and ADFS (enterprise federation)
SAML is common with enterprise IdPs and ADFS.
```mermaid
sequenceDiagram
autonumber
participant User
participant SP as Service Provider (App)
participant IdP as IdP (ADFS)
User->>SP: Access app
SP-->>User: Redirect with SAMLRequest
User->>IdP: Authenticate + MFA
IdP-->>User: POST SAMLResponse to SP ACS URL
User->>SP: SAMLResponse (signed assertion)
SP->>SP: Validate signature, audience, recipient, time, replay
SP-->>User: Session established
```
### SAML validation checklist (service provider)
- Validate **XML signature** against trusted IdP cert(s)
- Validate **audience** and **recipient** / ACS URL
- Validate **NotBefore/NotOnOrAfter** with small skew
- Enforce **replay protection** (assertion ID)
- Validate **issuer** and required attributes
- Treat IdP metadata and cert rotation as a normal event (test rotation)
> [!WARNING]
> Never accept unsigned assertions. Never “skip signature validation to unblock a launch”.
---
## PKI (certificates, keys, and mTLS)
### CA hierarchy and key custody
- Keep production root CA keys offline or in appropriately controlled HSMs.
- Use purpose- and environment-specific intermediate or issuing CAs to constrain blast radius.
- Separate CA administration, certificate approval, issuance, and key-recovery duties.
- Document ceremonies for root creation, intermediate signing, rotation, compromise, and disaster recovery.
- Do not export private keys unless the use case explicitly requires it and custody controls are documented.
### Certificate profiles
Define and enforce profiles rather than accepting arbitrary certificate requests:
- identity in SAN (`URI`, `DNS`, or other approved SAN type), not the legacy common name
- allowed key algorithms, parameters, signature algorithms, and validity periods
- `KeyUsage` and `ExtendedKeyUsage` constrained to the intended purpose
- name constraints and path-length constraints where applicable
- issuance policy, approver, renewal window, and revocation behavior
- environment and workload boundaries that prevent certificate reuse
### mTLS guidance
- Prefer mTLS for service-to-service authentication where operationally feasible
- Validate:
- chain to trusted CA
- SAN (service identity)
- EKU constraints
- revocation strategy per environment needs
- Authentication is not authorization: map the verified certificate identity to an explicit policy decision.
### Revocation design
- Choose CRL, OCSP, OCSP stapling, short-lived certificates, or a combination based on availability and freshness
requirements.
- Document fail-open versus fail-closed behavior for unavailable or stale revocation data.
- Test revoked, expired, not-yet-valid, unknown-issuer, wrong-SAN, and wrong-EKU cases.
- Short certificate lifetimes reduce exposure but do not replace an emergency kill path where rapid revocation is
required.
### Certificate lifecycle
- Automate enrollment, issuance, renewal, deployment, and replacement using ACME or an approved internal workflow.
- Track identity, serial number, profile, issuer, location, owner, expiry, key custody, and dependent services.
- Monitor renewal failures and alert early enough to remediate without emergency manual issuance.
- Verify that replacement certificates are in use before revoking or removing their predecessors.
### Crypto-agility and post-quantum readiness
- Maintain a cryptographic inventory covering protocols, libraries, certificates, keys, algorithms, hardware,
firmware, data-retention periods, and external dependencies.
- Keep algorithms and key parameters policy-driven and replaceable; do not hardcode them throughout applications.
- Design protocol negotiation to prevent downgrade and make cryptographic transitions observable.
- Prioritize systems with long-lived confidentiality requirements and broad, long-lived trust infrastructure.
- Test classical, hybrid, and post-quantum migration paths in controlled environments before production rollout.
- Follow current standards-body and vendor interoperability guidance; do not deploy experimental cryptography as
a production default.
See NIST's
[Post-Quantum Cryptography project](https://csrc.nist.gov/Projects/Post-Quantum-Cryptography) and
[Considerations for Achieving Crypto Agility](https://nvlpubs.nist.gov/nistpubs/CSWP/NIST.CSWP.39.pdf).
---
## Secret delivery to workloads
First ask whether workload identity can eliminate the secret. If a secret remains necessary, compare delivery
mechanisms across:
- workload identity and attestation source
- initial retrieval, renewal, and rotation behavior
- startup failure versus runtime degradation
- sidecar, node-plugin, control-plane, and application critical-path coupling
- exposure through environment variables, files, tmpfs, process memory, logs, and crash dumps
- file ownership, permissions, readers, and backup behavior
- audit granularity, revocation latency, and stale-secret detection
- platform dependencies and operational burden
Prefer workload-bound retrieval and file or memory delivery over environment variables. Do not prescribe Vault
Agent Injector, Secrets Store CSI Driver, or another mechanism without verifying the current provider-specific
rotation semantics and failure modes.
---
## PAM (Privileged Access Management)
PAM is about controlling and auditing privileged actions.
### Recommended patterns
- **Just-in-time (JIT) access**: time-bound elevation, not standing access
- **Strong MFA** for privileged operations
- **Approval workflows** for production changes and break-glass access
- **Session recording** and tamper-evident audit logs for privileged sessions
- **Separate break-glass** path:
- minimal principals
- stored offline where possible
- heavily monitored
- tested regularly
### “Break-glass” checklist
- Explicit runbook with owner + steps
- Alarm on use, notify security/on-call
- Immediate post-incident review and credential rotation
---
## Review checklist (quick)
- [ ] Default deny and least privilege enforced
- [ ] Short-lived creds preferred over static secrets
- [ ] Token/assertion signatures validated
- [ ] Issuer + audience validation implemented
- [ ] Replay protection (auth codes, SAML assertions) implemented
- [ ] Secrets (tokens/keys/assertions) never logged
- [ ] Rotation and revocation paths exist and are tested
- [ ] Joiner/mover/leaver and NHI lifecycle controls exist
- [ ] Entitlements have owners, expiry, and risk-based access reviews
- [ ] Protocol flows identify actors, token properties, and trust decisions
- [ ] PKI profiles, key custody, revocation behavior, and crypto-agility are documented
- [ ] Workload identity was considered before introducing a delivered secret
- [ ] PAM controls exist for privileged actions (JIT, MFA, auditability)