import { FormEvent, useState, useEffect } from 'react'; import { useHints } from '../contexts/HintContext'; import Link from 'next/link'; interface VulnerabilityInfo { name: string; format: string; hint: string; severity: 'Critical' | 'High' | 'Medium' | 'Low'; description: string; resources: { title: string; url: string; type: 'OWASP' | 'CWE' | 'Guide' | 'Tool' }[]; mitigation: string[]; } export default function FlagSubmit() { const [flag, setFlag] = useState(''); const [message, setMessage] = useState(null); const [loading, setLoading] = useState(false); const [selectedVuln, setSelectedVuln] = useState(null); const [submissionHistory, setSubmissionHistory] = useState<{flag: string, timestamp: string, status: string, points?: number}[]>([]); const [foundFlags, setFoundFlags] = useState>(new Set()); const { hintsVisible } = useHints(); // Cookie utility functions const setCookie = (name: string, value: string, hours: number = 24) => { const expires = new Date(); expires.setTime(expires.getTime() + (hours * 60 * 60 * 1000)); document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/;SameSite=Strict`; }; const getCookie = (name: string): string | null => { const nameEQ = name + "="; const ca = document.cookie.split(';'); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length)); } return null; }; const deleteCookie = (name: string) => { document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`; }; // Load session data on component mount from cookies and sessionStorage useEffect(() => { // Load submission history from sessionStorage (clears when browser tab closes) const savedHistory = sessionStorage.getItem('thsvwa_submission_history'); if (savedHistory) { try { setSubmissionHistory(JSON.parse(savedHistory)); } catch (e) { console.error('Failed to load submission history:', e); sessionStorage.removeItem('thsvwa_submission_history'); } } // Load found flags from cookie with fallback to sessionStorage let flagsLoaded = false; const savedFlags = getCookie('thsvwa_found_flags'); if (savedFlags) { try { const flagsArray = JSON.parse(savedFlags); setFoundFlags(new Set(flagsArray)); flagsLoaded = true; } catch (e) { console.error('Failed to load found flags from cookie:', e); deleteCookie('thsvwa_found_flags'); } } // Fallback to sessionStorage if cookie failed if (!flagsLoaded) { const sessionFlags = sessionStorage.getItem('thsvwa_found_flags'); if (sessionFlags) { try { const flagsArray = JSON.parse(sessionFlags); setFoundFlags(new Set(flagsArray)); } catch (e) { console.error('Failed to load found flags from sessionStorage:', e); sessionStorage.removeItem('thsvwa_found_flags'); } } } }, []); // Save to sessionStorage and cookies whenever data changes useEffect(() => { if (submissionHistory.length > 0) { sessionStorage.setItem('thsvwa_submission_history', JSON.stringify(submissionHistory)); } }, [submissionHistory]); useEffect(() => { if (foundFlags.size > 0) { const flagsArray = Array.from(foundFlags); // Save to sessionStorage for immediate backup sessionStorage.setItem('thsvwa_found_flags', JSON.stringify(flagsArray)); // Set cookie that expires in 8 hours (reasonable session time) setCookie('thsvwa_found_flags', JSON.stringify(flagsArray), 8); } else { // Clear both storage types when no flags sessionStorage.removeItem('thsvwa_found_flags'); deleteCookie('thsvwa_found_flags'); } }, [foundFlags]); const onSubmit = async (e: FormEvent) => { e.preventDefault(); setLoading(true); setMessage(null); try { // Check if hint mode is currently enabled const hintModeUsed = document.querySelector('[data-hints-visible="true"]') !== null; const res = await fetch('/api/flag', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ flag, hintModeUsed }), }); const data = await res.json(); const resultMessage = data.message || 'Unknown response'; setMessage(resultMessage); // Extract points from message const pointsMatch = resultMessage.match(/Score \+(\d+)/); const points = pointsMatch ? parseInt(pointsMatch[1]) : 0; // Add to submission history const newSubmission = { flag: flag, timestamp: new Date().toLocaleString(), status: res.ok ? 'success' : 'failed', points: res.ok ? points : 0 }; setSubmissionHistory(prev => [newSubmission, ...prev.slice(0, 9)]); if (res.ok) { setFlag(''); // Add to found flags set for session persistence if (flag.startsWith('FL4G{')) { setFoundFlags(prev => { const newSet = new Set(prev); newSet.add(flag); return newSet; }); } // Show vulnerability info for successful submission const vulnType = flag.match(/FL4G\{([^_]+)/)?.[1]; if (vulnType) { const vuln = vulnerabilities.find(v => v.format.includes(vulnType)); if (vuln) setSelectedVuln(vuln); } } } catch (err) { setMessage('Something went wrong'); const newSubmission = { flag: flag, timestamp: new Date().toLocaleString(), status: 'error', points: 0 }; setSubmissionHistory(prev => [newSubmission, ...prev.slice(0, 9)]); } finally { setLoading(false); } }; const vulnerabilities: VulnerabilityInfo[] = [ { name: 'Cross-Site Scripting (XSS)', format: 'FL4G{X55_*}', hint: 'Try JavaScript injection in the search functionality or login form', severity: 'High', description: 'XSS attacks inject malicious scripts into web pages viewed by other users. This can lead to session hijacking, data theft, and site defacement.', resources: [ { title: 'OWASP XSS Prevention Cheat Sheet', url: 'https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html', type: 'OWASP' }, { title: 'CWE-79: Cross-site Scripting', url: 'https://cwe.mitre.org/data/definitions/79.html', type: 'CWE' }, { title: 'XSS Hunter', url: 'https://xsshunter.com/', type: 'Tool' }, { title: 'PortSwigger XSS Guide', url: 'https://portswigger.net/web-security/cross-site-scripting', type: 'Guide' } ], mitigation: [ 'Sanitize and validate all user inputs', 'Use Content Security Policy (CSP) headers', 'Encode output data before rendering', 'Use secure frameworks that auto-escape by default' ] }, { name: 'SQL Injection', format: 'FL4G{5QL_*}', hint: 'Try SQL injection payloads in the login form', severity: 'Critical', description: 'SQL injection allows attackers to interfere with database queries, potentially accessing, modifying, or deleting sensitive data.', resources: [ { title: 'OWASP SQL Injection Prevention', url: 'https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html', type: 'OWASP' }, { title: 'CWE-89: SQL Injection', url: 'https://cwe.mitre.org/data/definitions/89.html', type: 'CWE' }, { title: 'SQLMap Tool', url: 'https://sqlmap.org/', type: 'Tool' }, { title: 'PortSwigger SQL Injection Guide', url: 'https://portswigger.net/web-security/sql-injection', type: 'Guide' } ], mitigation: [ 'Use parameterized queries/prepared statements', 'Apply input validation and sanitization', 'Use stored procedures with proper input validation', 'Implement least privilege database access' ] }, { name: 'Insecure Direct Object Reference (IDOR)', format: 'FL4G{1D0R_*}', hint: 'Try accessing product IDs you should not have access to', severity: 'High', description: 'IDOR occurs when applications provide direct access to objects based on user input without proper authorization checks.', resources: [ { title: 'OWASP IDOR Testing Guide', url: 'https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/05-Authorization_Testing/04-Testing_for_Insecure_Direct_Object_References', type: 'OWASP' }, { title: 'CWE-639: Access Control Bypass', url: 'https://cwe.mitre.org/data/definitions/639.html', type: 'CWE' }, { title: 'Burp Suite', url: 'https://portswigger.net/burp', type: 'Tool' }, { title: 'Authorization Testing Guide', url: 'https://portswigger.net/web-security/access-control', type: 'Guide' } ], mitigation: [ 'Implement proper access controls for each object', 'Use indirect object references (UUIDs)', 'Validate user authorization for each request', 'Apply role-based access control (RBAC)' ] }, { name: 'Local File Inclusion (LFI)', format: 'FL4G{LF1_*}', hint: 'Try accessing system files through directory traversal', severity: 'High', description: 'LFI allows attackers to include local files on the server, potentially exposing sensitive information or executing malicious code.', resources: [ { title: 'OWASP Path Traversal', url: 'https://owasp.org/www-community/attacks/Path_Traversal', type: 'OWASP' }, { title: 'CWE-22: Path Traversal', url: 'https://cwe.mitre.org/data/definitions/22.html', type: 'CWE' }, { title: 'LFI Testing Guide', url: 'https://book.hacktricks.xyz/pentesting-web/file-inclusion', type: 'Guide' }, { title: 'DirBuster', url: 'https://sourceforge.net/projects/dirbuster/', type: 'Tool' } ], mitigation: [ 'Validate and sanitize file paths', 'Use whitelists for allowed files', 'Implement proper access controls', 'Avoid user input in file operations' ] }, { name: 'File Upload Vulnerabilities', format: 'FL4G{*UPL04D*}', hint: 'Try uploading files with malicious extensions or content', severity: 'High', description: 'Insecure file upload can lead to remote code execution, stored XSS, or server compromise through malicious file uploads.', resources: [ { title: 'OWASP File Upload Cheat Sheet', url: 'https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html', type: 'OWASP' }, { title: 'CWE-434: Unrestricted Upload', url: 'https://cwe.mitre.org/data/definitions/434.html', type: 'CWE' }, { title: 'File Upload Testing', url: 'https://portswigger.net/web-security/file-upload', type: 'Guide' }, { title: 'Upload Scanner', url: 'https://github.com/modzero/mod0BurpUploadScanner', type: 'Tool' } ], mitigation: [ 'Validate file types and extensions', 'Scan uploaded files for malware', 'Store uploads outside web root', 'Implement file size restrictions' ] } ]; const totalPoints = submissionHistory.reduce((sum, sub) => sum + (sub.points || 0), 0); const successfulSubmissions = submissionHistory.filter(sub => sub.status === 'success').length; const uniqueFlags = foundFlags.size; return (
{/* Header */}

Vulnerability Discovery Center

Submit flags and learn about web application security vulnerabilities

{/* Stats */}
{totalPoints}
Total Points
{uniqueFlags}
Unique Flags
{vulnerabilities.length}
Total Challenges
{/* Flag Submission Form */}

Submit Flag

setFlag(e.target.value)} placeholder="FL4G{YOUR_FLAG_HERE}" className="input-field font-mono text-sm" disabled={loading} />

Format: FL4G{'{'}VULNERABILITY_TYPE{'}'}

{/* Result Message */} {message && (
{message}
)}
{/* Recent Submissions */} {submissionHistory.length > 0 && (

Recent Activity

{submissionHistory.map((submission, index) => (
{submission.flag}
{submission.points !== undefined && submission.points > 0 && ( +{submission.points} )} {submission.status.toUpperCase()}
))}
)} {/* Found Flags Collection */} {foundFlags.size > 0 && (

Discovered Flags ({foundFlags.size})

{Array.from(foundFlags).map((discoveredFlag, index) => (
{discoveredFlag}
))}
)}
{/* Vulnerability Database */}

Vulnerability Challenges

{vulnerabilities.map((vuln, index) => (
setSelectedVuln(selectedVuln?.name === vuln.name ? null : vuln)} >

{vuln.name}

{vuln.severity}
{vuln.format}

{vuln.hint}

))}
{/* Detailed Vulnerability Info */} {selectedVuln && (

{selectedVuln.name}

Description

{selectedVuln.description}

Mitigation Strategies

    {selectedVuln.mitigation.map((item, idx) => (
  • • {item}
  • ))}

Learning Resources

{selectedVuln.resources.map((resource, idx) => ( {resource.type} {resource.title} ↗ ))}
)}
{/* Navigation */}
{/* Reset Activity Button */}
← Back to Vulnerability Testing Lab
); }