MMNA
Money Mitra Network Academy
IAM Hardening & Secure Function Design
Module 2 • Intermediate Security Architecture
Master least-privilege IAM policies, role-based execution models, and secure function design patterns. Learn to prevent lateral movement, protect sensitive data, and build defense-in-depth security for Lambda functions in enterprise environments.
IAM for Serverless Computing
Role-Based Execution Model (Conceptual)
Every Lambda function is assigned an IAM role that grants permissions to AWS resources. The function assumes this role during execution, and all API calls are authorized based on role permissions.
Execution Flow:
- 1. Event triggers Lambda function
- 2. Function assumes attached IAM role
- 3. STS provides temporary credentials
- 4. Function calls AWS APIs with credentials
- 5. IAM evaluates policy against API action
- 6. Access allowed/denied based on policy
// IAM Role attached to Lambda function
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:us-east-1:123456789:*"
}
]
}
Least Privilege Principles
Grant only the minimum permissions required for the function to operate. This limits blast radius if credentials are compromised.
-
✓
Resource-Specific Policies
Specify exact ARNs instead of wildcards (arn:aws:s3:::my-bucket/data/* NOT arn:aws:s3:::*/
-
✓
Action-Specific Permissions
Use specific actions (s3:GetObject) not wildcards (s3:*)
-
✓
Condition-Based Access
Add conditions like IP restrictions, time-based access, MFA requirements
-
✓
No Privilege Escalation
Prevent functions from creating roles, assuming higher-privilege roles, or modifying policies
❌ OVERPRIVILEGED:
{
"Action": "*",
"Resource": "*"
}
✅ LEAST PRIVILEGE:
{
"Action": ["s3:GetObject"],
"Resource": "arn:aws:s3:::my-bucket/*"
}
IAM Permission Matrix Example
| API Action | Resource | Permission | Rationale |
|---|---|---|---|
| s3:GetObject | arn:aws:s3:::input-bucket/data/* | ✓ Allow | Function reads input data from S3 |
| s3:PutObject | arn:aws:s3:::output-bucket/* | ✓ Allow | Function writes results to output bucket |
| s3:DeleteObject | arn:aws:s3:::*/* | ✗ Deny | No need to delete; prevents data destruction |
| iam:CreateRole | * | ✗ Deny | Prevents privilege escalation attack |
| dynamodb:Query | arn:aws:dynamodb:us-east-1:123456789:table/users | ✓ Allow | Function queries specific DynamoDB table |
| dynamodb:Scan | * | ✗ Deny | Scan is inefficient; use Query instead |
Secure Function Design
Input Validation Awareness
Never trust external input. Attackers craft malicious payloads to trigger code execution, data theft, or denial of service. Validate all event data.
// ❌ VULNERABLE
const user_id = event.user_id;
db.query(`SELECT * FROM users WHERE id = ${user_id}`);
// ✅ SECURE
const user_id = parseInt(event.user_id);
if (!Number.isInteger(user_id) || user_id < 1) {
throw new Error('Invalid user_id');
}
const result = db.query(
'SELECT * FROM users WHERE id = ?',
[user_id]
);
- → Type Checking: Validate data types (string, number, boolean)
- → Range Validation: Check bounds (age 0-150, IDs > 0)
- → Parameterized Queries: Use placeholders, never string concatenation
- → Whitelist Patterns: Allow only known-good characters/formats
Environment Variable Management (High-Level)
Lambda can store configuration and secrets in environment variables. However, they're stored plaintext in Lambda. Use AWS Secrets Manager or Parameter Store for sensitive data.
Database hostnames, feature flags, API endpoints, log levels
Database passwords, API keys, encryption keys, private credentials
// ❌ VULNERABLE - Secrets in environment
const db_password = process.env.DB_PASSWORD;
// ✅ SECURE - Secrets Manager
const secretsManager =
new AWS.SecretsManager();
const secret = await secretsManager
.getSecretValue({SecretId: 'db-password'})
.promise();
const db_password = secret.SecretString;
Secure Function Design Patterns
Error Handling
Never expose stack traces or internal errors to clients. Log detailed errors server-side; return generic error messages to users.
Timeout Management
Set appropriate timeouts on Lambda function and external API calls. Prevent indefinite hangs that consume resources.
Request Size Limits
Reject oversized payloads. Lambda event limit is 6 MB synchronous, 256 KB asynchronous. Enforce client-side limits to prevent resource exhaustion.
VPC Security
When accessing private resources (RDS, ElastiCache), deploy Lambda in VPC with restrictive security groups. Avoid exposing databases to public internet.
Encryption in Transit
Always use HTTPS/TLS for external API calls. Encrypt data sent to databases, caches, and S3. Use AWS KMS for encryption key management.
Dependency Management & Supply Chain Security
Third-Party Library Risks
Lambda functions depend on external packages. Vulnerable or malicious libraries can compromise function security and cloud infrastructure.
Popular npm packages (lodash, request, etc.) frequently have CVEs. Stale packages leave functions vulnerable to known exploits.
Attackers publish malicious packages with typosquatting names or compromise popular projects. Code executes with function's IAM permissions.
Your package depends on X, X depends on Y, Y is vulnerable. Hard to track nested dependency vulnerabilities.
Secure Packaging Mindset
Adopt practices that minimize dependency risk and maintain supply chain security.
-
✓
Minimal Dependencies
Only include packages you actually use. Remove dead code and unused imports.
-
✓
Regular Audits
Run npm audit, Snyk, or OWASP Dependency-Check regularly. Fix high-risk CVEs immediately.
-
✓
Lock Files
Use package-lock.json or yarn.lock to freeze versions. Prevents unexpected updates.
-
✓
Verify Package Integrity
Check SHA-256 hashes, use trusted package registries, avoid untested packages.
Dependency Scanning Best Practices
npm audit
Built into npm. Checks for known vulnerabilities in dependencies.
npm audit npm audit fix
Snyk
Comprehensive vulnerability scanner with CI/CD integration and fix recommendations.
snyk test snyk monitor
OWASP Dep-Check
Identifies component dependencies with known vulnerabilities across multiple languages.
dependency-check \ --project "MyLambda" \ --scan ./node_modules
Secure Deployment & Change Management
Version Control Concepts
Source code control (Git) provides audit trails, enables code review, and allows rollback of malicious or broken deployments.
-
✓
Branch Protection
Require pull request reviews before merging to main branch. Prevent direct pushes.
-
✓
Code Review
At least one other developer reviews all code changes. Catches security issues and logic bugs.
-
✓
Commit Signing
Use GPG signatures to verify commit author identity. Prevents attacker impersonation.
-
✓
Audit Trail
Every change logged with who, what, when, why. Enables forensics and compliance.
Change Management Practices
Structured process for deploying Lambda updates. Reduces risk of outages and security incidents.
-
✓
Staged Deployments
Deploy to dev → staging → production. Test thoroughly before production release.
-
✓
Canary Releases
Route small % of traffic to new version. Monitor for errors before full rollout.
-
✓
Rollback Plan
Keep previous version available. If new deployment breaks, quickly revert.
-
✓
Change Log
Document every deployment with version, date, changes, approver.
Secure Deployment Workflow
Developer Pushes Code
Commit to feature branch with descriptive message. Include security considerations in commit.
Automated Security Checks
CI/CD pipeline runs SAST (static analysis), dependency scanning, and secrets detection automatically.
Code Review
Pull request requires review by another engineer. Security team reviews if applicable. All concerns addressed before approval.
Deploy to Staging
Merge to main triggers deployment to staging environment. Runs integration tests, security scans, performance tests.
Staging Validation
QA and security team validate staging deployment. Check IAM permissions, logs, monitoring setup.
Approved Production Release
Deployment approved by team lead/manager. Version tagged in git. Changelog documented. Deployed with canary release strategy.
Production Monitoring
Monitor CloudWatch logs, X-Ray traces, and error rates. Rollback immediately if issues detected.
External Learning References
AWS IAM Best Practices
Official AWS guide for designing least-privilege IAM policies and security best practices.
docs.aws.amazon.com/IAM/best-practices →AWS Lambda Security
Lambda-specific security considerations, execution role management, and hardening recommendations.
docs.aws.amazon.com/lambda/security →OWASP Top 10
Most critical web application security risks. Essential reading for secure function design and input validation.
owasp.org/www-project-top-ten →npm Audit & Security
Managing npm package security, dependency vulnerabilities, and supply chain best practices.
docs.npmjs.com/npm-audit →AWS Secrets Manager
Secure storage and rotation of credentials, API keys, and sensitive configuration for Lambda functions.
docs.aws.amazon.com/secretsmanager →AWS Lambda DevOps Best Practices
CI/CD, infrastructure as code (SAM, CloudFormation), and deployment patterns for Lambda.
docs.aws.amazon.com/serverless-application-model →