Piątek wieczór. Security team dostaje alert: nietypowy wzorzec ruchu na API. Analiza pokazuje: atakujący znalazł endpoint /api/users/{id} który zwraca dane dowolnego użytkownika po podaniu ID. Iteruje przez miliony ID, scraping pełną bazę użytkowników. BOLA (Broken Object Level Authorization) - endpoint nie sprawdza czy żądający user ma prawo widzieć dane tego konkretnego usera.
Przeczytaj także: Phishing w erze AI 2026: Jak rozpoznać i bronić się przed za
Dane 3 milionów użytkowników wyciekły. RODO breach notification. Kara, reputacja, pozwy. A wystarczyło jedno sprawdzenie: “czy user X ma prawo do obiektu Y?”
API jest wszędzie. Mobile apps komunikują się z backendem przez API. Single Page Applications - przez API. Microservices - API. Third-party integrations - API. IoT devices - API. API to główna powierzchnia ataku nowoczesnych aplikacji. I często najsłabiej chroniona.
Dlaczego API security jest trudniejsze niż traditional web security?
API nie mają “strony logowania”. Traditional web app: jest login form, jest sesja, są cookies. API: bearer token, API key, JWT - różne mechanizmy, różne podatności.
Machine-to-machine communication. API często służy innym systemom, nie ludziom. Trudniej zastosować tradycyjne anti-automation measures (CAPTCHA).
Scale i velocity. API obsługuje tysiące requestów na sekundę. Ataki mogą być subtle - nie DDoS, ale slow data extraction przez miesiące.
Documentation as attack surface. OpenAPI/Swagger specs są publiczne. Atakujący wie dokładnie jakie endpoints istnieją, jakie parametry przyjmują.
Business logic exposure. API eksponuje business logic bezpośrednio. Web app może ukryć logikę za UI - API nie ma takiej warstwy.
Multiple consumers. Jedno API służy: mobile app, web app, third-party integrations, internal services. Każdy ma inne potrzeby bezpieczeństwa.
Jakie są najważniejsze zagrożenia według OWASP API Top 10?
API1: Broken Object Level Authorization (BOLA) - API nie sprawdza czy user ma prawo do konkretnego obiektu. /api/orders/123 - czy user może widzieć order 123, czy tylko swoje?
API2: Broken Authentication - słabe mechanizmy uwierzytelniania: weak tokens, no expiration, credential stuffing vulnerability.
API3: Broken Object Property Level Authorization - user może widzieć obiekt ale nie wszystkie jego pola, lub może modyfikować pola których nie powinien.
API4: Unrestricted Resource Consumption - brak limitów: rate limiting, payload size, query complexity. Prowadzi do DoS, excessive costs.
API5: Broken Function Level Authorization - user wywołuje funkcje admin (/api/admin/delete-user) które nie są dla niego.
API6: Unrestricted Access to Sensitive Business Flows - automatyzacja biznesowych operacji (mass ticket buying, credential stuffing, scraping).
API7: Server Side Request Forgery (SSRF) - API przyjmuje URL od użytkownika i robi request - atakujący może skanować internal network.
API8: Security Misconfiguration - default configs, verbose errors, unnecessary HTTP methods, missing security headers.
API9: Improper Inventory Management - stare wersje API nadal dostępne, undocumented endpoints, deprecated features nie wyłączone.
API10: Unsafe Consumption of APIs - twoje API konsumuje third-party APIs bez proper validation - supply chain risk.
Jak implementować proper authentication dla API?
OAuth 2.0 + OpenID Connect. Standard dla delegated authorization i authentication. Use proven implementations (Auth0, Okta, Keycloak), nie roll your own.
JWT (JSON Web Tokens) best practices:
- Use strong signing algorithm (RS256 > HS256 dla public clients)
- Short expiration times (15 min access token + refresh token flow)
- Validate signature, expiration, issuer, audience
- Store signing keys securely (HSM, KMS)
- Consider token binding / proof of possession
API Keys - kiedy używać:
- Service-to-service authentication (server-side only)
- Identify calling application (not user)
- Always over HTTPS
- Rotate regularly
- Scope and rate limit per key
Don’t do:
- Basic auth (unless over HTTPS and for legacy support)
- Custom token schemes without crypto expertise
- Long-lived tokens without refresh mechanism
- Tokens in URLs (logged, cached, leaked in referrers)
Multi-factor dla sensitive operations. Token daje access, ale dla DELETE /api/account wymagaj dodatkowej weryfikacji.
Jak implementować authorization na poziomie obiektu i funkcji?
Object Level Authorization (vs. BOLA):
# Bad - returns any order by ID
def get_order(order_id):
return Order.find(order_id)
# Good - checks ownership
def get_order(order_id, current_user):
order = Order.find(order_id)
if order.user_id != current_user.id:
raise AuthorizationError("Not your order")
return order
Function Level Authorization (vs. BFLA):
# Bad - anyone can call
@app.route('/api/admin/users', methods=['DELETE'])
def delete_user(user_id):
User.delete(user_id)
# Good - checks role
@app.route('/api/admin/users', methods=['DELETE'])
@require_role('admin')
def delete_user(user_id):
User.delete(user_id)
Property Level Authorization:
# Return different fields based on role
def serialize_user(user, requester):
data = {'id': user.id, 'name': user.name}
if requester.is_admin:
data['email'] = user.email
data['last_login'] = user.last_login
return data
Use policy engines. OPA (Open Policy Agent), Casbin - externalize authorization logic. Centralized, testable, auditable.
Jak implementować rate limiting i throttling?
Rate limiting strategies:
- Per user/API key (authenticated requests)
- Per IP (unauthenticated / as fallback)
- Per endpoint (sensitive endpoints stricter)
- Sliding window vs. fixed window
Example tiers:
- Anonymous: 100 requests/hour
- Basic user: 1000 requests/hour
- Premium: 10000 requests/hour
- Internal service: higher limits with monitoring
Implementation options:
- API Gateway (Kong, Apigee, AWS API Gateway)
- Reverse proxy (nginx, HAProxy)
- Application-level (redis-based counters)
- Cloud-native (AWS WAF, Cloudflare)
Response handling:
- Return 429 Too Many Requests
- Include
Retry-Afterheader - Explain limit in response body
- Consider exponential backoff in clients
Beyond request rate:
- Payload size limits
- Query complexity limits (GraphQL)
- Concurrent connections limit
- Cost-based limiting (expensive operations)
Jak walidować input i chronić przed injection?
Validate everything:
- Schema validation (JSON Schema, OpenAPI validation)
- Type checking (string, integer, email, UUID)
- Length limits
- Allowed values (enums)
- Format validation (regex with care)
Sanitize/escape output, not input. Principle: validate input strictly, encode output for context (HTML, SQL, shell).
SQL Injection via API:
# Bad - string concatenation
query = f"SELECT * FROM users WHERE name = '{name}'"
# Good - parameterized queries
query = "SELECT * FROM users WHERE name = %s"
cursor.execute(query, (name,))
NoSQL Injection (MongoDB):
# Bad - accepts object from user
db.users.find(request.json) # User sends {"$gt": ""}
# Good - validate expected structure
name = request.json.get('name')
if not isinstance(name, str):
raise ValidationError()
db.users.find({'name': name})
Command Injection:
# Bad - user input in shell
os.system(f"ping {user_input}")
# Good - use libraries, not shell
import subprocess
subprocess.run(['ping', '-c', '1', validated_hostname], check=True)
Jak zabezpieczyć API przed SSRF?
SSRF scenario: API accepts URL parameter, fetches resource:
# Vulnerable
@app.route('/api/fetch')
def fetch_url():
url = request.args.get('url')
return requests.get(url).content # Attacker: url=http://169.254.169.254/
Mitigations:
- Whitelist allowed domains/IPs
- Block private IP ranges (10.x, 192.168.x, 169.254.x, 127.x)
- Block cloud metadata endpoints (169.254.169.254)
- Use DNS resolution and check resolved IP before connecting
- Disable redirects or validate redirect targets
- Use egress proxy with restrictions
# Better
ALLOWED_HOSTS = ['api.trusted.com', 'cdn.trusted.com']
def fetch_url(url):
parsed = urlparse(url)
if parsed.hostname not in ALLOWED_HOSTS:
raise SecurityError("Host not allowed")
# Additional: resolve DNS, check IP
return requests.get(url, allow_redirects=False).content
Jak monitorować i wykrywać ataki na API?
Logging essentials:
- All authentication attempts (success/failure)
- Authorization failures
- Rate limit hits
- Error responses (4xx, 5xx patterns)
- Unusual patterns (off-hours, unusual geolocations)
Do NOT log:
- Full credentials/tokens
- PII unnecessarily
- Sensitive business data
Anomaly detection:
- Baseline normal traffic patterns
- Alert on deviations (volume, endpoints, user agents)
- Sequence analysis (unusual API call sequences)
API-specific monitoring:
- Authentication failure spikes (credential stuffing)
- Sequential ID access (BOLA exploitation)
- Unusual data volume per user (data exfiltration)
- Deprecated endpoint access
Tools:
- API Gateways with analytics (Kong, Apigee)
- SIEM integration (Splunk, ELK, Datadog)
- Specialized API security (Salt Security, Traceable, Noname Security)
Jak testować bezpieczeństwo API?
DAST (Dynamic Application Security Testing):
- OWASP ZAP (free, scriptable)
- Burp Suite (professional standard)
- Postman security tests
- API-specific scanners (Astra, APIsec)
SAST dla API code:
- SonarQube rules dla API security
- Semgrep custom rules
- CodeQL queries
Manual testing checklist:
- Authorization testing (access other users’ resources)
- Authentication bypass attempts
- Injection testing (SQL, NoSQL, command)
- Rate limiting validation
- Error message information disclosure
- Deprecated endpoint discovery
- IDOR (Insecure Direct Object Reference) testing
Fuzzing:
- Invalid input types
- Boundary values
- Malformed JSON/XML
- Unicode edge cases
Penetration testing:
- Regular professional pentests
- Bug bounty programs for APIs
- Red team exercises
Jak budować secure API development lifecycle?
Design phase:
- Threat modeling for API
- Define authentication/authorization requirements
- Plan rate limiting strategy
- Design for minimal data exposure
Development:
- Secure coding guidelines for API
- Code review with security focus
- Pre-commit hooks for secrets detection
- Dependency scanning
Testing:
- Security unit tests (authorization logic)
- Integration security tests
- DAST in CI/CD pipeline
- Manual security review for sensitive endpoints
Deployment:
- Security configuration review
- Secrets management (not in code)
- HTTPS only, proper TLS config
- API Gateway security features enabled
Operations:
- Continuous monitoring
- Incident response plan for API breaches
- Regular security assessments
- Deprecation process for old versions
Tabela: API Security Checklist
| Kategoria | Kontrola | Priority | Jak sprawdzić | Narzędzia |
|---|---|---|---|---|
| Authentication | OAuth 2.0 / OIDC implementation | Critical | Code review, pentest | Auth0, Keycloak |
| Authentication | JWT proper validation | Critical | Unit tests, DAST | jwt.io, Burp |
| Authentication | Token expiration < 15 min | High | Config review | - |
| Authorization | Object-level access checks | Critical | Code review, pentest | OPA, Casbin |
| Authorization | Function-level access checks | Critical | Code review, pentest | Role-based tests |
| Authorization | Property-level filtering | High | Code review | Custom tests |
| Input Validation | Schema validation | High | Unit tests, fuzzing | JSON Schema, AJV |
| Input Validation | SQL injection prevention | Critical | DAST, code review | SQLMap, Burp |
| Rate Limiting | Per-user/IP limits | High | Load testing | API Gateway, Redis |
| Rate Limiting | Payload size limits | Medium | Config review | nginx, API Gateway |
| Encryption | HTTPS only | Critical | SSL Labs test | SSL Labs, testssl.sh |
| Encryption | TLS 1.2+ only | High | Config scan | nmap, SSL Labs |
| Logging | Auth events logged | High | Log review | SIEM, ELK |
| Logging | No secrets in logs | Critical | Log audit | grep, log analysis |
| Monitoring | Anomaly detection | Medium | Alert review | Datadog, specialized tools |
| Inventory | All endpoints documented | High | API discovery | Swagger, API catalog |
| Inventory | Old versions deprecated | Medium | Traffic analysis | API Gateway analytics |
API security wymaga systematycznego podejścia - od designu przez development do operations. Jeden niezabezpieczony endpoint może compromisować całą aplikację. OWASP API Top 10 to dobry starting point, ale nie wszystko - każde API ma unique attack surface.
Kluczowe wnioski:
- BOLA (Broken Object Level Authorization) to najczęstsza podatność - zawsze sprawdzaj ownership
- Authentication to nie authorization - mieć token ≠ mieć prawo do zasobu
- Rate limiting chroni przed abuse i DoS - implementuj na wielu poziomach
- Input validation musi być strict - trust nothing from outside
- Monitoring jest kluczowy - nie wiesz że jesteś atakowany jeśli nie patrzysz
- API inventory - musisz wiedzieć co masz żeby to chronić
- Test regularly - automated + manual + pentest
API security to continuous process, nie one-time project. Każdy nowy endpoint to nowa surface area. Każda zmiana wymaga security review.
ARDURA Consulting dostarcza specjalistów security i DevSecOps przez body leasing z doświadczeniem w zabezpieczaniu API dla enterprise applications. Nasi eksperci pomagają projektować, implementować i testować secure APIs. Porozmawiajmy o bezpieczeństwie twoich interfejsów.