Skip to main content

Chương 28: API Security

Khái niệm

API Security là bảo mật cho REST/GraphQL/gRPC APIs. Với microservices architecture, API là attack surface chính.

OWASP API Security Top 10 (2023):

  1. API1: Broken Object Level Authorization → IDOR
  2. API2: Broken Authentication
  3. API3: Broken Object Property Level Authorization → Mass assignment
  4. API4: Unrestricted Resource Consumption → Rate limiting
  5. API5: Broken Function Level Authorization → Missing auth
  6. API6: Unrestricted Access to Sensitive Business Flows
  7. API7: Server Side Request Forgery
  8. API8: Security Misconfiguration
  9. API9: Improper Inventory Management → Shadow APIs
  10. API10: Unsafe Consumption of APIs → Third-party API injection

API1: BOLA — Broken Object Level Authorization

Giống IDOR nhưng specific với APIs:

GET /api/v1/accounts/123/transactions HTTP/1.1
Authorization: Bearer token_of_account_456

→ Nếu không check "account 123 belongs to token owner" → BOLA

API3: Mass Assignment

# Vulnerable: Update user từ entire request body
@app.route('/api/user/update', methods=['PUT'])
def update_user():
user = User.query.get(g.current_user.id)
user.update_from_dict(request.json) # ← Tất cả fields từ request!
db.save(user)

# Attack payload:
{
"name": "Alice",
"email": "alice@example.com",
"role": "admin", ← Escalate to admin!
"is_verified": true, ← Self-verify!
"account_balance": 99999 ← Inject arbitrary fields!
}

Phòng chống:

# Whitelist allowed fields
ALLOWED_UPDATE_FIELDS = {'name', 'email', 'phone', 'bio'}

def update_user():
update_data = {
k: v for k, v in request.json.items()
if k in ALLOWED_UPDATE_FIELDS
}
user.update(**update_data)

API4: Rate Limiting

Không có rate limiting → brute force, enumeration, scraping

Implement ở multiple levels:
1. API Gateway (Kong, AWS API Gateway)
2. Application level (Flask-Limiter, Express rate-limit)
3. Nginx

Per-endpoint limits:
/api/login: 5/minute
/api/search: 60/minute
/api/export: 1/hour
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

limiter = Limiter(
app,
key_func=get_remote_address,
default_limits=["200 per day", "50 per hour"]
)

@app.route('/api/login', methods=['POST'])
@limiter.limit("5 per minute")
def login():
...

@app.route('/api/export', methods=['GET'])
@limiter.limit("1 per hour")
def export_data():
...

API Versioning Security

Vấn đề: v1 bị deprecated nhưng vẫn accessible
/api/v1/users → Không có auth
/api/v2/users → Có auth
/api/v1/users → Bypass auth!

Shadow APIs: endpoints không documented, không monitored
# Discover API versions và hidden endpoints
ffuf -w /usr/share/wordlists/api-list.txt \
-u https://example.com/api/FUZZ \
-mc 200,201,400,401,403

# Common API patterns
/api/v1/ /api/v2/ /api/v3/
/v1/ /v2/
/api/internal/
/api/admin/

Authentication cho APIs

API Keys: Không expire → nếu lộ → permanent compromise
X-API-Key: sk-abc123...

JWT Bearer tokens: Expire, revocable
Authorization: Bearer eyJhbG...

OAuth 2.0: Best for third-party access

mTLS: Certificate-based, cho service-to-service

Góc nhìn DevOps

API Gateway:

# Kong Gateway config
services:
- name: user-api
url: http://user-service:8080
plugins:
- name: rate-limiting
config:
minute: 60
hour: 1000
- name: key-auth
- name: cors
config:
origins:
- https://app.example.com
- name: request-size-limiting
config:
allowed_payload_size: 10 # 10MB max

API Inventory — Biết tất cả APIs:

# Scan code để list tất cả API endpoints
grep -rn "@app.route\|@router.get\|@router.post" src/
# Hoặc dùng code analysis tools

Tóm tắt

  • API Top 10: BOLA (IDOR), broken auth, mass assignment, no rate limiting quan trọng nhất.
  • Mass assignment: whitelist allowed fields, không nhận arbitrary input.
  • Rate limiting: implement ở gateway và application level.
  • API versioning: deprecated versions phải truly disabled, không chỉ hidden.
  • Dùng API Gateway để centralize auth, rate limiting, logging.