mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
864 lines
36 KiB
HTML
864 lines
36 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>cloud-aws-iam-security</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/cloud-aws-iam-security.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/cloud-aws-iam-security">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/cloud-aws-iam-security.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>cloud-aws-iam-security</h1><p class="lede">AWS IAM policies, roles, Cognito authentication, Secrets Manager, KMS encryption, and security best practices</p><h1>AWS IAM Security</h1>
|
|
<p><strong>Scope</strong>: AWS security - IAM policies, roles, Cognito, Secrets Manager, KMS, STS, least privilege, credential management <strong>Lines</strong>: ~340 <strong>Last Updated</strong>: 2025-10-25 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<hr>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Creating IAM policies and roles for AWS services</li><li>Implementing user authentication with Cognito</li><li>Managing secrets with Secrets Manager or Parameter Store</li><li>Configuring encryption with KMS</li><li>Setting up temporary credentials with STS</li><li>Implementing least privilege access control</li><li>Troubleshooting permission errors or access denied issues</li><li>Auditing security configurations and credentials</li></ul>
|
|
<h2>Core Concepts</h2>
|
|
<h3>Concept 1: IAM Policies</h3>
|
|
<p><strong>Policy types</strong>:</p>
|
|
<ul><li><strong>Identity-based</strong>: Attached to users, groups, roles</li><li><strong>Resource-based</strong>: Attached to resources (S3, Lambda)</li><li><strong>Permission boundaries</strong>: Maximum permissions</li><li><strong>Service control policies</strong>: Organization-level restrictions</li></ul>
|
|
<pre><code class="lang-python">import boto3
|
|
import json
|
|
|
|
iam = boto3.client('iam')
|
|
|
|
def create_lambda_execution_role():
|
|
"""Create IAM role for Lambda with least privilege"""
|
|
|
|
# Trust policy - who can assume this role
|
|
trust_policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Effect": "Allow",
|
|
"Principal": {
|
|
"Service": "lambda.amazonaws.com"
|
|
},
|
|
"Action": "sts:AssumeRole"
|
|
}
|
|
]
|
|
}
|
|
|
|
# Create role
|
|
role_response = iam.create_role(
|
|
RoleName='lambda-execution-role',
|
|
AssumeRolePolicyDocument=json.dumps(trust_policy),
|
|
Description='Execution role for Lambda functions',
|
|
Tags=[
|
|
{'Key': 'Purpose', 'Value': 'Lambda'},
|
|
{'Key': 'ManagedBy', 'Value': 'automation'}
|
|
]
|
|
)
|
|
|
|
role_arn = role_response['Role']['Arn']
|
|
|
|
# Attach AWS managed policy for CloudWatch Logs
|
|
iam.attach_role_policy(
|
|
RoleName='lambda-execution-role',
|
|
PolicyArn='arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
|
|
)
|
|
|
|
# Create custom policy for DynamoDB access
|
|
dynamodb_policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Effect": "Allow",
|
|
"Action": [
|
|
"dynamodb:GetItem",
|
|
"dynamodb:PutItem",
|
|
"dynamodb:UpdateItem",
|
|
"dynamodb:Query"
|
|
],
|
|
"Resource": [
|
|
"arn:aws:dynamodb:us-east-1:123456789012:table/Users",
|
|
"arn:aws:dynamodb:us-east-1:123456789012:table/Users/index/*"
|
|
]
|
|
}
|
|
]
|
|
}
|
|
|
|
# Create and attach custom policy
|
|
policy_response = iam.create_policy(
|
|
PolicyName='lambda-dynamodb-access',
|
|
PolicyDocument=json.dumps(dynamodb_policy),
|
|
Description='Allow Lambda to access DynamoDB Users table'
|
|
)
|
|
|
|
iam.attach_role_policy(
|
|
RoleName='lambda-execution-role',
|
|
PolicyArn=policy_response['Policy']['Arn']
|
|
)
|
|
|
|
print(f"Created Lambda execution role: {role_arn}")
|
|
|
|
return role_arn
|
|
|
|
def create_s3_readonly_policy(bucket_name):
|
|
"""Create policy for read-only S3 access"""
|
|
|
|
policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Effect": "Allow",
|
|
"Action": [
|
|
"s3:GetObject",
|
|
"s3:ListBucket"
|
|
],
|
|
"Resource": [
|
|
f"arn:aws:s3:::{bucket_name}",
|
|
f"arn:aws:s3:::{bucket_name}/*"
|
|
]
|
|
}
|
|
]
|
|
}
|
|
|
|
response = iam.create_policy(
|
|
PolicyName=f'{bucket_name}-readonly',
|
|
PolicyDocument=json.dumps(policy)
|
|
)
|
|
|
|
return response['Policy']['Arn']</code></pre>
|
|
<h3>Concept 2: Cognito User Authentication</h3>
|
|
<p><strong>Cognito components</strong>:</p>
|
|
<ul><li><strong>User Pools</strong>: User directory, sign-up/sign-in</li><li><strong>Identity Pools</strong>: AWS credentials for users</li><li><strong>Authentication flows</strong>: Username/password, OAuth, SAML</li></ul>
|
|
<pre><code class="lang-python">import boto3
|
|
|
|
cognito = boto3.client('cognito-idp')
|
|
|
|
def create_user_pool():
|
|
"""Create Cognito User Pool for authentication"""
|
|
|
|
response = cognito.create_user_pool(
|
|
PoolName='myapp-users',
|
|
Policies={
|
|
'PasswordPolicy': {
|
|
'MinimumLength': 12,
|
|
'RequireUppercase': True,
|
|
'RequireLowercase': True,
|
|
'RequireNumbers': True,
|
|
'RequireSymbols': True
|
|
}
|
|
},
|
|
AutoVerifiedAttributes=['email'],
|
|
EmailConfiguration={
|
|
'EmailSendingAccount': 'COGNITO_DEFAULT'
|
|
},
|
|
Schema=[
|
|
{
|
|
'Name': 'email',
|
|
'AttributeDataType': 'String',
|
|
'Required': True,
|
|
'Mutable': False
|
|
},
|
|
{
|
|
'Name': 'name',
|
|
'AttributeDataType': 'String',
|
|
'Required': True,
|
|
'Mutable': True
|
|
}
|
|
],
|
|
MfaConfiguration='OPTIONAL',
|
|
UserAttributeUpdateSettings={
|
|
'AttributesRequireVerificationBeforeUpdate': ['email']
|
|
}
|
|
)
|
|
|
|
user_pool_id = response['UserPool']['Id']
|
|
|
|
# Create app client
|
|
app_response = cognito.create_user_pool_client(
|
|
UserPoolId=user_pool_id,
|
|
ClientName='myapp-web',
|
|
GenerateSecret=False, # Public client (SPA)
|
|
RefreshTokenValidity=30, # Days
|
|
AccessTokenValidity=60, # Minutes
|
|
IdTokenValidity=60,
|
|
TokenValidityUnits={
|
|
'RefreshToken': 'days',
|
|
'AccessToken': 'minutes',
|
|
'IdToken': 'minutes'
|
|
},
|
|
ExplicitAuthFlows=[
|
|
'ALLOW_USER_PASSWORD_AUTH',
|
|
'ALLOW_REFRESH_TOKEN_AUTH'
|
|
]
|
|
)
|
|
|
|
client_id = app_response['UserPoolClient']['ClientId']
|
|
|
|
print(f"Created User Pool: {user_pool_id}")
|
|
print(f"App Client ID: {client_id}")
|
|
|
|
return user_pool_id, client_id
|
|
|
|
def authenticate_user(username, password, client_id):
|
|
"""Authenticate user and get tokens"""
|
|
|
|
response = cognito.initiate_auth(
|
|
ClientId=client_id,
|
|
AuthFlow='USER_PASSWORD_AUTH',
|
|
AuthParameters={
|
|
'USERNAME': username,
|
|
'PASSWORD': password
|
|
}
|
|
)
|
|
|
|
# Get tokens
|
|
id_token = response['AuthenticationResult']['IdToken']
|
|
access_token = response['AuthenticationResult']['AccessToken']
|
|
refresh_token = response['AuthenticationResult']['RefreshToken']
|
|
|
|
return {
|
|
'id_token': id_token,
|
|
'access_token': access_token,
|
|
'refresh_token': refresh_token
|
|
}</code></pre>
|
|
<h3>Concept 3: Secrets Manager</h3>
|
|
<p><strong>Secrets Manager vs Parameter Store</strong>:</p>
|
|
<ul><li><strong>Secrets Manager</strong>: Automatic rotation, audit, encryption ($0.40/secret/month)</li><li><strong>Parameter Store</strong>: Simple key-value, cheaper (free tier available)</li></ul>
|
|
<pre><code class="lang-python">import boto3
|
|
import json
|
|
|
|
secrets = boto3.client('secretsmanager')
|
|
|
|
def create_database_secret(db_username, db_password, db_host, db_name):
|
|
"""Store database credentials in Secrets Manager"""
|
|
|
|
secret_value = {
|
|
'username': db_username,
|
|
'password': db_password,
|
|
'host': db_host,
|
|
'database': db_name,
|
|
'port': 5432
|
|
}
|
|
|
|
response = secrets.create_secret(
|
|
Name='myapp/database/credentials',
|
|
Description='Database credentials for myapp',
|
|
SecretString=json.dumps(secret_value),
|
|
Tags=[
|
|
{'Key': 'Environment', 'Value': 'production'},
|
|
{'Key': 'Application', 'Value': 'myapp'}
|
|
]
|
|
)
|
|
|
|
print(f"Created secret: {response['ARN']}")
|
|
|
|
return response['ARN']
|
|
|
|
def get_database_secret():
|
|
"""Retrieve database credentials"""
|
|
|
|
response = secrets.get_secret_value(
|
|
SecretId='myapp/database/credentials'
|
|
)
|
|
|
|
secret_data = json.loads(response['SecretString'])
|
|
|
|
return {
|
|
'username': secret_data['username'],
|
|
'password': secret_data['password'],
|
|
'host': secret_data['host'],
|
|
'database': secret_data['database'],
|
|
'port': secret_data['port']
|
|
}
|
|
|
|
def rotate_secret(secret_id, lambda_arn):
|
|
"""Configure automatic rotation"""
|
|
|
|
secrets.rotate_secret(
|
|
SecretId=secret_id,
|
|
RotationLambdaARN=lambda_arn,
|
|
RotationRules={
|
|
'AutomaticallyAfterDays': 30
|
|
}
|
|
)
|
|
|
|
print(f"Configured rotation for {secret_id}")</code></pre>
|
|
<h3>Concept 4: KMS Encryption</h3>
|
|
<p><strong>KMS key types</strong>:</p>
|
|
<ul><li><strong>AWS managed</strong>: Created by AWS services (free)</li><li><strong>Customer managed</strong>: Full control, custom policies</li><li><strong>Symmetric</strong>: Same key for encrypt/decrypt</li><li><strong>Asymmetric</strong>: Public/private key pair</li></ul>
|
|
<pre><code class="lang-python">import boto3
|
|
import base64
|
|
|
|
kms = boto3.client('kms')
|
|
|
|
def create_kms_key():
|
|
"""Create customer-managed KMS key"""
|
|
|
|
response = kms.create_key(
|
|
Description='Application data encryption key',
|
|
KeyUsage='ENCRYPT_DECRYPT',
|
|
Origin='AWS_KMS',
|
|
MultiRegion=False,
|
|
Tags=[
|
|
{'TagKey': 'Application', 'TagValue': 'myapp'},
|
|
{'TagKey': 'Purpose', 'TagValue': 'data-encryption'}
|
|
]
|
|
)
|
|
|
|
key_id = response['KeyMetadata']['KeyId']
|
|
|
|
# Create alias
|
|
kms.create_alias(
|
|
AliasName='alias/myapp-data-key',
|
|
TargetKeyId=key_id
|
|
)
|
|
|
|
print(f"Created KMS key: {key_id}")
|
|
|
|
return key_id
|
|
|
|
def encrypt_data(plaintext, key_id):
|
|
"""Encrypt data with KMS key"""
|
|
|
|
response = kms.encrypt(
|
|
KeyId=key_id,
|
|
Plaintext=plaintext.encode('utf-8')
|
|
)
|
|
|
|
# Return base64-encoded ciphertext
|
|
ciphertext_blob = response['CiphertextBlob']
|
|
encrypted = base64.b64encode(ciphertext_blob).decode('utf-8')
|
|
|
|
return encrypted
|
|
|
|
def decrypt_data(encrypted_data):
|
|
"""Decrypt data (KMS determines key automatically)"""
|
|
|
|
# Decode base64
|
|
ciphertext_blob = base64.b64decode(encrypted_data)
|
|
|
|
response = kms.decrypt(
|
|
CiphertextBlob=ciphertext_blob
|
|
)
|
|
|
|
plaintext = response['Plaintext'].decode('utf-8')
|
|
|
|
return plaintext
|
|
|
|
def envelope_encryption(plaintext, key_id):
|
|
"""Encrypt large data using envelope encryption"""
|
|
|
|
# Generate data key
|
|
response = kms.generate_data_key(
|
|
KeyId=key_id,
|
|
KeySpec='AES_256'
|
|
)
|
|
|
|
plaintext_key = response['Plaintext']
|
|
encrypted_key = response['CiphertextBlob']
|
|
|
|
# Encrypt data with plaintext key (client-side)
|
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
from cryptography.hazmat.backends import default_backend
|
|
import os
|
|
|
|
iv = os.urandom(16)
|
|
cipher = Cipher(
|
|
algorithms.AES(plaintext_key),
|
|
modes.CBC(iv),
|
|
backend=default_backend()
|
|
)
|
|
encryptor = cipher.encryptor()
|
|
|
|
# Pad plaintext to block size
|
|
padded = plaintext + ' ' * (16 - len(plaintext) % 16)
|
|
ciphertext = encryptor.update(padded.encode()) + encryptor.finalize()
|
|
|
|
return {
|
|
'encrypted_data': base64.b64encode(ciphertext).decode(),
|
|
'encrypted_key': base64.b64encode(encrypted_key).decode(),
|
|
'iv': base64.b64encode(iv).decode()
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Patterns</h2>
|
|
<h3>Pattern 1: Cross-Account Access with STS</h3>
|
|
<p><strong>When to use</strong>: Grant temporary access to resources in another account</p>
|
|
<pre><code class="lang-python">import boto3
|
|
|
|
sts = boto3.client('sts')
|
|
|
|
def assume_role(role_arn, session_name):
|
|
"""Assume role in another account"""
|
|
|
|
response = sts.assume_role(
|
|
RoleArn=role_arn,
|
|
RoleSessionName=session_name,
|
|
DurationSeconds=3600 # 1 hour
|
|
)
|
|
|
|
credentials = response['Credentials']
|
|
|
|
# Create client with assumed role credentials
|
|
s3_client = boto3.client(
|
|
's3',
|
|
aws_access_key_id=credentials['AccessKeyId'],
|
|
aws_secret_access_key=credentials['SecretAccessKey'],
|
|
aws_session_token=credentials['SessionToken']
|
|
)
|
|
|
|
return s3_client
|
|
|
|
# Trust policy for cross-account role
|
|
cross_account_trust_policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Effect": "Allow",
|
|
"Principal": {
|
|
"AWS": "arn:aws:iam::123456789012:root" # Trusting account
|
|
},
|
|
"Action": "sts:AssumeRole",
|
|
"Condition": {
|
|
"StringEquals": {
|
|
"sts:ExternalId": "unique-external-id"
|
|
}
|
|
}
|
|
}
|
|
]
|
|
}</code></pre>
|
|
<h3>Pattern 2: Service-to-Service Authentication</h3>
|
|
<p><strong>Use case</strong>: EC2 instance accessing S3 without credentials</p>
|
|
<pre><code class="lang-python"># No credentials needed - use IAM instance profile
|
|
|
|
def create_ec2_instance_profile():
|
|
"""Create instance profile for EC2"""
|
|
|
|
# Create role
|
|
trust_policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Effect": "Allow",
|
|
"Principal": {"Service": "ec2.amazonaws.com"},
|
|
"Action": "sts:AssumeRole"
|
|
}
|
|
]
|
|
}
|
|
|
|
role_response = iam.create_role(
|
|
RoleName='ec2-s3-access-role',
|
|
AssumeRolePolicyDocument=json.dumps(trust_policy)
|
|
)
|
|
|
|
# Attach S3 read policy
|
|
iam.attach_role_policy(
|
|
RoleName='ec2-s3-access-role',
|
|
PolicyArn='arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'
|
|
)
|
|
|
|
# Create instance profile
|
|
iam.create_instance_profile(
|
|
InstanceProfileName='ec2-s3-profile'
|
|
)
|
|
|
|
# Add role to profile
|
|
iam.add_role_to_instance_profile(
|
|
InstanceProfileName='ec2-s3-profile',
|
|
RoleName='ec2-s3-access-role'
|
|
)
|
|
|
|
print("Created instance profile: ec2-s3-profile")
|
|
|
|
# EC2 instance code - no credentials needed
|
|
s3 = boto3.client('s3') # Automatically uses instance profile
|
|
buckets = s3.list_buckets()</code></pre>
|
|
<h3>Pattern 3: Multi-Factor Authentication (MFA)</h3>
|
|
<p><strong>Use case</strong>: Require MFA for sensitive operations</p>
|
|
<pre><code class="lang-python">def enforce_mfa_policy():
|
|
"""Create policy requiring MFA for sensitive actions"""
|
|
|
|
mfa_policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Sid": "AllowAllActionsWithMFA",
|
|
"Effect": "Allow",
|
|
"Action": "*",
|
|
"Resource": "*",
|
|
"Condition": {
|
|
"BoolIfExists": {
|
|
"aws:MultiFactorAuthPresent": "true"
|
|
}
|
|
}
|
|
},
|
|
{
|
|
"Sid": "DenyAllActionsWithoutMFA",
|
|
"Effect": "Deny",
|
|
"Action": [
|
|
"ec2:TerminateInstances",
|
|
"rds:DeleteDBInstance",
|
|
"s3:DeleteBucket"
|
|
],
|
|
"Resource": "*",
|
|
"Condition": {
|
|
"BoolIfExists": {
|
|
"aws:MultiFactorAuthPresent": "false"
|
|
}
|
|
}
|
|
}
|
|
]
|
|
}
|
|
|
|
response = iam.create_policy(
|
|
PolicyName='require-mfa-for-sensitive-ops',
|
|
PolicyDocument=json.dumps(mfa_policy)
|
|
)
|
|
|
|
return response['Policy']['Arn']</code></pre>
|
|
<h3>Pattern 4: Least Privilege with Permission Boundaries</h3>
|
|
<p><strong>Use case</strong>: Limit maximum permissions for developers</p>
|
|
<pre><code class="lang-python">def create_developer_role_with_boundary():
|
|
"""Create developer role with permission boundary"""
|
|
|
|
# Permission boundary - maximum allowed permissions
|
|
boundary_policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Effect": "Allow",
|
|
"Action": [
|
|
"s3:*",
|
|
"dynamodb:*",
|
|
"lambda:*",
|
|
"logs:*",
|
|
"cloudwatch:*"
|
|
],
|
|
"Resource": "*"
|
|
},
|
|
{
|
|
"Effect": "Deny",
|
|
"Action": [
|
|
"iam:*",
|
|
"organizations:*",
|
|
"account:*"
|
|
],
|
|
"Resource": "*"
|
|
}
|
|
]
|
|
}
|
|
|
|
# Create boundary policy
|
|
boundary_response = iam.create_policy(
|
|
PolicyName='developer-boundary',
|
|
PolicyDocument=json.dumps(boundary_policy)
|
|
)
|
|
|
|
# Create developer role with boundary
|
|
trust_policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Effect": "Allow",
|
|
"Principal": {"AWS": "arn:aws:iam::123456789012:root"},
|
|
"Action": "sts:AssumeRole"
|
|
}
|
|
]
|
|
}
|
|
|
|
iam.create_role(
|
|
RoleName='developer-role',
|
|
AssumeRolePolicyDocument=json.dumps(trust_policy),
|
|
PermissionsBoundary=boundary_response['Policy']['Arn']
|
|
)
|
|
|
|
# Developer can only create resources within boundary limits
|
|
print("Created developer role with permission boundary")</code></pre>
|
|
<hr>
|
|
<h2>Quick Reference</h2>
|
|
<h3>IAM Policy Structure</h3>
|
|
<pre><code class="lang-json">{
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Sid": "DescriptiveStatementId",
|
|
"Effect": "Allow", // or "Deny"
|
|
"Principal": {"AWS": "arn:aws:iam::123456789012:user/Alice"},
|
|
"Action": ["s3:GetObject", "s3:PutObject"],
|
|
"Resource": "arn:aws:s3:::my-bucket/*",
|
|
"Condition": {
|
|
"IpAddress": {"aws:SourceIp": "192.0.2.0/24"}
|
|
}
|
|
}
|
|
]
|
|
}</code></pre>
|
|
<h3>Common IAM Actions</h3>
|
|
<pre><code>Service | Common Actions
|
|
-----------|----------------------------------
|
|
S3 | s3:GetObject, s3:PutObject, s3:DeleteObject
|
|
DynamoDB | dynamodb:GetItem, dynamodb:PutItem, dynamodb:Query
|
|
Lambda | lambda:InvokeFunction, lambda:UpdateFunctionCode
|
|
EC2 | ec2:RunInstances, ec2:TerminateInstances
|
|
RDS | rds:CreateDBInstance, rds:DeleteDBInstance</code></pre>
|
|
<h3>Key Guidelines</h3>
|
|
<pre><code>✅ DO: Follow principle of least privilege
|
|
✅ DO: Use IAM roles instead of access keys
|
|
✅ DO: Enable MFA for privileged users
|
|
✅ DO: Rotate credentials regularly
|
|
✅ DO: Use Secrets Manager for sensitive data
|
|
✅ DO: Encrypt data at rest with KMS
|
|
✅ DO: Use resource-based policies when possible
|
|
|
|
❌ DON'T: Hardcode credentials in code
|
|
❌ DON'T: Use root account for daily operations
|
|
❌ DON'T: Grant full access (*:*) unless absolutely necessary
|
|
❌ DON'T: Share IAM user credentials
|
|
❌ DON'T: Leave unused access keys active
|
|
❌ DON'T: Disable CloudTrail logging</code></pre>
|
|
<hr>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>Critical Violations</h3>
|
|
<pre><code class="lang-python"># ❌ NEVER: Hardcode credentials
|
|
AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE"
|
|
AWS_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
|
|
|
|
s3 = boto3.client(
|
|
's3',
|
|
aws_access_key_id=AWS_ACCESS_KEY_ID,
|
|
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
|
|
)
|
|
|
|
# ✅ CORRECT: Use IAM roles (EC2, Lambda) or environment variables
|
|
s3 = boto3.client('s3') # Automatically uses IAM role
|
|
|
|
# Or for local development
|
|
# Use AWS CLI: aws configure
|
|
# Or environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY</code></pre>
|
|
<p>❌ <strong>Hardcoded credentials</strong>: Security breach, exposed in code, logs, version control</p>
|
|
<p>✅ <strong>Correct approach</strong>: IAM roles for services, AWS CLI config for local, Secrets Manager for apps</p>
|
|
<h3>Common Mistakes</h3>
|
|
<pre><code class="lang-json">// ❌ Don't grant overly broad permissions
|
|
{
|
|
"Effect": "Allow",
|
|
"Action": "*",
|
|
"Resource": "*"
|
|
}
|
|
|
|
// ✅ Correct: Specific actions and resources
|
|
{
|
|
"Effect": "Allow",
|
|
"Action": [
|
|
"s3:GetObject",
|
|
"s3:PutObject"
|
|
],
|
|
"Resource": "arn:aws:s3:::my-bucket/data/*"
|
|
}</code></pre>
|
|
<p>❌ <strong>Overly broad permissions</strong>: Security risk, violates least privilege</p>
|
|
<p>✅ <strong>Better</strong>: Specific actions, specific resources, conditions when appropriate</p>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><code>aws-lambda-functions.md</code> - IAM execution roles for Lambda</li><li><code>aws-ec2-compute.md</code> - IAM instance profiles for EC2</li><li><code>aws-databases.md</code> - IAM database authentication</li><li><code>aws-networking.md</code> - Security groups and network security</li></ul>
|
|
<hr>
|
|
<p><strong>Last Updated</strong>: 2025-10-25 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/cloud-aws-iam-security.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |