Web Application Security Fundamentals #12: Secure Coding Practices & OWASP ASVS
Memahami principles of secure coding (defense in depth, least privilege, fail secure), OWASP ASVS levels, dan implementation checklists.
Secure coding bukan satu teknik, tapi mindset + discipline + practices. Modul ini covers konkret habits yang developer harus adopt.
Core Principles
1. Defense in Depth
Tidak ada single "magic bullet" untuk security. Berlapis-lapis controls:
Layer 1: Input validation (whitelist)
Layer 2: Parameterized queries (prevent injection)
Layer 3: Output encoding (prevent XSS)
Layer 4: Security headers (browser-level defense)
Layer 5: WAF (web application firewall)
Layer 6: Logging & monitoring (detect breaches)
Layer 7: Incident response (containment)
Jika satu layer fail, sisanya tetap protect.
2. Principle of Least Privilege
# ❌ BAD - Admin access for regular operation
def get_user_profile():
db_connection = connect(admin_credentials)
return db_connection.query("SELECT * FROM users WHERE id=?")
# ✅ GOOD - Specific database user with minimal permissions
def get_user_profile():
db_connection = connect(read_only_user_credentials)
return db_connection.query("SELECT * FROM users WHERE id=?")
3. Fail Secure
# ❌ BAD - Default allow
def has_permission(user, resource):
if not check_deny_list(user, resource):
return True # Default allow
return False
# ✅ GOOD - Default deny
def has_permission(user, resource):
if check_allow_list(user, resource):
return True
return False # Default deny
4. Don't Trust User Input
# ❌ BAD - Trust client-side validation
@app.post('/purchase')
def purchase():
price = request.json['price'] # Attacker modify price client-side
return charge_card(price)
# ✅ GOOD - Validate server-side from database
@app.post('/purchase')
def purchase():
product_id = request.json['product_id']
product = Product.query.get(product_id)
if not product:
return 'Product not found', 404
price = product.price # From DB, not client input
return charge_card(price)
OWASP ASVS (Application Security Verification Standard)
ASVS adalah checklist security requirements untuk setiap aplikasi level (Level 1, 2, 3).
Security Requirements Levels
Level 1 (Opportunistic) - Basic security
- Input validation
- Authentication exists
- Audit logging exists
Level 2 (Standard) - Industry-standard
- All Level 1 +
- Thorough authorization checks
- Strong password policy
- Rate limiting
- HTTPS for sensitive data
Level 3 (Advanced) - High-assurance
- All Level 2 +
- Threat modeling
- Secure SDLC enforced
- Penetration testing required
- Security logging comprehensive
- Incident response plan
Mapping ASVS to Requirements
Example: Online Banking Application
Requirement: User tidak dapat melihat/transfer dana milik orang lain
ASVS Mapping:
V4.1 (Access Control) - General
4.1.1: Enforce access control at every tier
4.1.2: Authorization decisions at application tier
4.1.3: Principle of least privilege
V4.2 (Access Control) - OrgOrg Dependent
4.2.1: User cannot act outside own authority
4.2.2: No elevated privileges except when needed
V4.3 (Other Access Control)
4.3.1: Administrators can audit access
4.3.2: User cannot bypass authorization
Implementation Checklist:
- [ ] Verify user owns account before showing balance
- [ ] Verify user owns account before allowing transfer
- [ ] Log all access attempts (success & failure)
- [ ] Test: User A cannot see User B's account
- [ ] Test: User A cannot transfer from User B's account
- [ ] Rate limit transfers (prevent automation)
- [ ] Require MFA for large transfers
Secure Coding Checklist
Input/Output
- [ ] All input validated server-side (whitelist preferred)
- [ ] Untrusted data escaped when output to HTML
- [ ] Parameterized queries for database (never concatenate)
- [ ] No shell commands from user input
- [ ] File uploads validated (extension, MIME, size, content)
Authentication & Authorization
- [ ] Passwords hashed with Argon2id or bcrypt
- [ ] No credentials logged or error messages
- [ ] MFA available (TOTP preferred)
- [ ] Sessions validated each request
- [ ] Session timeout implemented
- [ ] Rate limiting on login (brute force defense)
Cryptography
- [ ] Sensitive data encrypted at rest & in transit
- [ ] No weak algorithms (MD5, SHA1, DES)
- [ ] Encryption keys not hardcoded
- [ ] Use TLS 1.2+ for all HTTPS
- [ ] No insecure randomness (use crypto library)
Error Handling
- [ ] Generic error messages (don't leak internals)
- [ ] Log detailed errors server-side (not in response)
- [ ] Stack traces never shown to users
- [ ] No sensitive info in error messages
Logging & Monitoring
- [ ] Log security events (login, failed auth, privilege escalation)
- [ ] No passwords/secrets in logs
- [ ] Logs stored securely & backed up
- [ ] Monitoring alerts on anomalies
- [ ] Audit trail for compliance
Dependencies
- [ ] Regular dependency updates
- [ ] Scan dependencies for known vulnerabilities (OWASP Dependency-Check)
- [ ] Minimize dependencies (attack surface)
- [ ] Pin versions (prevent unexpected changes)
Security Code Review Checklist
When reviewing peer's code:
1. Input Validation
- Are untrusted inputs validated?
- Is validation done server-side?
- Is validation using whitelist?
2. Injection Attacks
- Any string concatenation in SQL/commands?
- Parameterized queries used?
- Output properly encoded?
3. Authentication
- Credentials ever hardcoded?
- Passwords hashed securely?
- Session tokens generated securely?
4. Authorization
- Is access control checked?
- Default deny or default allow?
- Can users escalate privileges?
5. Sensitive Data
- Any hardcoded secrets?
- Logs contain sensitive data?
- Data encrypted at rest?
6. Error Handling
- Stack traces exposed?
- Error messages leak internals?
- Errors logged for audit?
Kesimpulan
Secure coding adalah collective responsibility. Developers, testers, architects, security teams semua contribute. ASVS memberi framework untuk define standards.
Modul berikutnya (#13) membahas impact bisnis dari vulnerability.
Next: #13 - Business Impact of Vulnerabilities
Post Terkait
Malware Analysis Fundamentals #09: Teknik Evasion yang Wajib Diwaspadai Analis Malware
Penutup seri Malware Analysis Fundamentals: delapan teknik evasion yang wajib diwaspadai — packing, obfuscation, anti-de...
Malware Analysis Fundamentals #08: Bukti Digital yang Wajib Dikumpulkan Saat Analisis Malware
Checklist lengkap bukti digital yang wajib dikumpulkan saat analisis malware: hash, IOC jaringan (domain, IP, sertifikat...
Malware Analysis Fundamentals #07: Membangun Lab Analisis Malware yang Aman
Panduan membangun lab analisis malware yang aman: isolated VM, snapshot, jaringan host-only/simulasi, mematikan shared c...