From 97c331c8b8a41eff1d53d0aa2f4c1066477aeb95 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 27 Sep 2025 20:21:31 +0000 Subject: [PATCH 1/2] Initial plan From 97255d92b807d8b0d55ca3db333ef00a6a2fd4b3 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 27 Sep 2025 20:44:37 +0000 Subject: [PATCH 2/2] Enhanced SQL Injection educational demonstrations with comprehensive interactive features Co-authored-by: arhadnane <14889338+arhadnane@users.noreply.github.com> --- Modules/DefenseEngine.cs | 437 +++++++++++++++++++++++++++- Modules/InjectionTester.cs | 87 ++++++ Modules/LoginSimulator.cs | 85 ++++++ Modules/Reporter.cs | 452 ++++++++++++++++++++++++++++ Modules/UserManagerSimple.cs | 6 +- Program.cs | 550 ++++++++++++++++++++++++++++++++--- 6 files changed, 1575 insertions(+), 42 deletions(-) diff --git a/Modules/DefenseEngine.cs b/Modules/DefenseEngine.cs index a121587..e9f5050 100644 --- a/Modules/DefenseEngine.cs +++ b/Modules/DefenseEngine.cs @@ -18,7 +18,7 @@ public class DefenseEngine private readonly int _maxAttemptsPerIP = 10; private readonly int _maxAttemptsPerUser = 5; private readonly TimeSpan _timeWindow = TimeSpan.FromMinutes(5); - private readonly List _blockedIPs; + private readonly Dictionary _blockedIPs; // SQL injection detection patterns private readonly Dictionary _injectionPatterns = new() @@ -50,7 +50,7 @@ public DefenseEngine(string connectionString) _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); _ipAttemptHistory = new Dictionary>(); _userAttemptHistory = new Dictionary>(); - _blockedIPs = new List(); + _blockedIPs = new Dictionary(); _lockObject = new object(); } @@ -137,9 +137,9 @@ public BruteForceAnalysisResult AnalyzeBruteForcePatterns(string ipAddress, stri result.ShouldBlockIP = result.RecentAttemptsFromIP >= _maxAttemptsPerIP; // Auto-block if threshold exceeded - if (result.ShouldBlockIP && !_blockedIPs.Contains(ipAddress)) + if (result.ShouldBlockIP && !_blockedIPs.ContainsKey(ipAddress)) { - _blockedIPs.Add(ipAddress); + _blockedIPs[ipAddress] = DateTime.Now.AddMinutes(30); // Block for 30 minutes result.IPBlocked = true; } @@ -161,7 +161,7 @@ public async Task AnalyzeLoginAttemptAsync(string usernam }; // Check if IP is already blocked - if (_blockedIPs.Contains(ipAddress)) + if (_blockedIPs.ContainsKey(ipAddress) && _blockedIPs[ipAddress] > DateTime.Now) { result.ShouldBlock = true; result.BlockReason = "IP address is blocked due to previous suspicious activity"; @@ -453,6 +453,369 @@ private void CleanOldAttempts(DateTime now) _userAttemptHistory.Remove(user); } } + + /// + /// Advanced SQL injection pattern detection and analysis + /// + public async Task ScanForSqlInjectionAsync(string input) + { + var result = new SqlInjectionScanResult + { + Input = input, + ScanTime = DateTime.Now + }; + + if (string.IsNullOrWhiteSpace(input)) + { + result.RiskLevel = "LOW"; + result.Message = "Empty input - no risk detected"; + return result; + } + + var detectedPatterns = new List(); + var riskScore = 0; + + // Pattern 1: Classic OR injection + if (Regex.IsMatch(input, @"'\s*(OR|AND)\s*'?\w*'?\s*=\s*'?\w*'?", RegexOptions.IgnoreCase)) + { + detectedPatterns.Add("Classic OR/AND injection pattern"); + riskScore += 5; + } + + // Pattern 2: Union-based injection + if (Regex.IsMatch(input, @"UNION\s+SELECT", RegexOptions.IgnoreCase)) + { + detectedPatterns.Add("Union-based SQL injection"); + riskScore += 5; + } + + // Pattern 3: Comment injection + if (input.Contains("--") || input.Contains("/*")) + { + detectedPatterns.Add("SQL comment injection"); + riskScore += 3; + } + + // Pattern 4: Stacked queries + if (Regex.IsMatch(input, @";\s*(DROP|DELETE|INSERT|UPDATE)", RegexOptions.IgnoreCase)) + { + detectedPatterns.Add("Dangerous stacked queries"); + riskScore += 8; + } + + // Pattern 5: Time-based blind injection + if (Regex.IsMatch(input, @"WAITFOR\s+DELAY", RegexOptions.IgnoreCase)) + { + detectedPatterns.Add("Time-based blind injection"); + riskScore += 6; + } + + // Pattern 6: Error-based injection + if (Regex.IsMatch(input, @"CONVERT\s*\(|CAST\s*\(", RegexOptions.IgnoreCase)) + { + detectedPatterns.Add("Error-based injection attempt"); + riskScore += 4; + } + + // Pattern 7: System function calls + if (Regex.IsMatch(input, @"@@\w+|xp_\w+|sp_\w+", RegexOptions.IgnoreCase)) + { + detectedPatterns.Add("System function exploitation"); + riskScore += 7; + } + + result.DetectedPatterns = detectedPatterns; + result.RiskScore = riskScore; + result.RiskLevel = riskScore switch + { + 0 => "LOW", + >= 1 and <= 3 => "MEDIUM", + >= 4 and <= 7 => "HIGH", + _ => "CRITICAL" + }; + result.IsInjection = riskScore > 0; + result.Message = $"Detected {detectedPatterns.Count} injection patterns with risk score {riskScore}"; + + // Log the scan result + if (result.IsInjection) + { + await LogSecurityEventAsync("SQL_INJECTION_SCAN", result.RiskLevel, + $"SQL injection patterns detected: {string.Join(", ", detectedPatterns)}", + $"ScanForSqlInjection - Score: {riskScore}"); + } + + return result; + } + + /// + /// Detect and analyze brute force attack patterns + /// + public async Task DetectBruteForcePatternAsync(string username, string ipAddress) + { + var result = new BruteForceAnalysisResult + { + Username = username, + IpAddress = ipAddress, + AnalysisTime = DateTime.Now + }; + + using var connection = new SqlConnection(_connectionString); + await connection.OpenAsync(); + + // Check recent attempts from this IP + var ipQuery = @"SELECT COUNT(*) as AttemptCount, + MIN(AttemptTime) as FirstAttempt, + MAX(AttemptTime) as LastAttempt + FROM LoginAttempts + WHERE IpAddress = @ip AND AttemptTime >= @cutoff"; + + var cutoffTime = DateTime.Now.AddMinutes(-15); // 15-minute window + + using var command = new SqlCommand(ipQuery, connection); + command.Parameters.AddWithValue("@ip", ipAddress); + command.Parameters.AddWithValue("@cutoff", cutoffTime); + + using var reader = await command.ExecuteReaderAsync(); + + if (reader.Read()) + { + result.AttemptsInTimeWindow = reader.GetInt32(0); // AttemptCount + + if (result.AttemptsInTimeWindow > 0) + { + var firstAttempt = reader.GetDateTime(1); // FirstAttempt + var lastAttempt = reader.GetDateTime(2); // LastAttempt + var timeSpan = lastAttempt - firstAttempt; + + result.AttemptsPerMinute = result.AttemptsInTimeWindow / Math.Max(timeSpan.TotalMinutes, 1); + } + } + reader.Close(); + + // Check for rapid sequential attempts against same user + var userQuery = @"SELECT COUNT(*) as UserAttempts + FROM LoginAttempts + WHERE Username = @username AND AttemptTime >= @cutoff"; + + using var userCommand = new SqlCommand(userQuery, connection); + userCommand.Parameters.AddWithValue("@username", username); + userCommand.Parameters.AddWithValue("@cutoff", cutoffTime); + + var userAttempts = (int)(await userCommand.ExecuteScalarAsync() ?? 0); + + // Analyze patterns + result.IsBruteForce = result.AttemptsInTimeWindow >= 10 || result.AttemptsPerMinute >= 2 || userAttempts >= 5; + + result.Severity = (result.AttemptsInTimeWindow, result.AttemptsPerMinute) switch + { + (>= 50, _) or (_, >= 10) => "CRITICAL", + (>= 20, _) or (_, >= 5) => "HIGH", + (>= 10, _) or (_, >= 2) => "MEDIUM", + _ => "LOW" + }; + + result.RecommendedAction = result.Severity switch + { + "CRITICAL" => "IMMEDIATE_BLOCK", + "HIGH" => "TEMPORARY_BLOCK", + "MEDIUM" => "RATE_LIMIT", + _ => "MONITOR" + }; + + result.Message = $"IP: {result.AttemptsInTimeWindow} attempts, Rate: {result.AttemptsPerMinute:F1}/min, User: {userAttempts} attempts"; + + // Log if brute force detected + if (result.IsBruteForce) + { + await LogSecurityEventAsync("BRUTE_FORCE_DETECTION", result.Severity, + $"Brute force attack detected: {result.Message}", username); + } + + return result; + } + + /// + /// Analyze login patterns for anomaly detection + /// + public async Task AnalyzeLoginPatternsAsync(string username, TimeSpan? period = null) + { + var analysisResult = new LoginPatternAnalysisResult + { + Username = username, + AnalysisTime = DateTime.Now + }; + + var cutoffTime = DateTime.Now.Subtract(period ?? TimeSpan.FromDays(7)); + + using var connection = new SqlConnection(_connectionString); + await connection.OpenAsync(); + + // Get pattern statistics + var query = @"SELECT + COUNT(*) as TotalAttempts, + COUNT(CASE WHEN IsSuccessful = 1 THEN 1 END) as SuccessfulAttempts, + COUNT(CASE WHEN IsInjection = 1 THEN 1 END) as InjectionAttempts, + COUNT(DISTINCT IpAddress) as UniqueIPs, + COUNT(DISTINCT UserAgent) as UniqueUserAgents, + AVG(CAST(ResponseTime as FLOAT)) as AvgResponseTime, + MIN(AttemptTime) as FirstAttempt, + MAX(AttemptTime) as LastAttempt + FROM LoginAttempts + WHERE Username = @username AND AttemptTime >= @cutoff"; + + using var command = new SqlCommand(query, connection); + command.Parameters.AddWithValue("@username", username); + command.Parameters.AddWithValue("@cutoff", cutoffTime); + + using var reader = await command.ExecuteReaderAsync(); + + if (reader.Read() && !reader.IsDBNull(0)) // TotalAttempts + { + analysisResult.TotalAttempts = reader.GetInt32(0); // TotalAttempts + analysisResult.SuccessfulAttempts = reader.GetInt32(1); // SuccessfulAttempts + analysisResult.InjectionAttempts = reader.GetInt32(2); // InjectionAttempts + analysisResult.UniqueIPs = reader.GetInt32(3); // UniqueIPs + analysisResult.UniqueUserAgents = reader.GetInt32(4); // UniqueUserAgents + analysisResult.AverageResponseTime = reader.IsDBNull(5) ? 0 : reader.GetDouble(5); // AvgResponseTime + } + + // Calculate anomaly score + var anomalyScore = 0; + + // High number of failed attempts + if (analysisResult.TotalAttempts > 0) + { + var failureRate = (double)(analysisResult.TotalAttempts - analysisResult.SuccessfulAttempts) / analysisResult.TotalAttempts; + if (failureRate > 0.9) anomalyScore += 3; + else if (failureRate > 0.7) anomalyScore += 2; + else if (failureRate > 0.5) anomalyScore += 1; + } + + // Multiple IP addresses + if (analysisResult.UniqueIPs > 5) anomalyScore += 3; + else if (analysisResult.UniqueIPs > 3) anomalyScore += 2; + else if (analysisResult.UniqueIPs > 1) anomalyScore += 1; + + // Injection attempts + if (analysisResult.InjectionAttempts > 0) anomalyScore += 5; + + // Multiple user agents + if (analysisResult.UniqueUserAgents > 3) anomalyScore += 2; + + analysisResult.AnomalyScore = anomalyScore; + analysisResult.IsAnomalous = anomalyScore >= 4; + analysisResult.RiskLevel = anomalyScore switch + { + >= 8 => "CRITICAL", + >= 6 => "HIGH", + >= 4 => "MEDIUM", + >= 2 => "LOW", + _ => "MINIMAL" + }; + + return analysisResult; + } + + /// + /// Trigger security alerts based on threat analysis + /// + public async Task TriggerAlertAsync(string alertType, string severity, string details, string username = "") + { + var alertResult = new AlertResult + { + AlertType = alertType, + Severity = severity, + Details = details, + Username = username, + Timestamp = DateTime.Now, + Success = false + }; + + try + { + // Log to database + await LogSecurityEventAsync(alertType, severity, details, username); + + // Console alert for immediate visibility + var emoji = severity switch + { + "CRITICAL" => "๐Ÿšจ", + "HIGH" => "โš ๏ธ", + "MEDIUM" => "โšก", + "LOW" => "โ„น๏ธ", + _ => "๐Ÿ“Š" + }; + + Console.WriteLine($"\n{emoji} SECURITY ALERT [{severity}] - {alertType}"); + Console.WriteLine($"Time: {DateTime.Now:yyyy-MM-dd HH:mm:ss}"); + Console.WriteLine($"User: {username}"); + Console.WriteLine($"Details: {details}"); + Console.WriteLine(new string('-', 50)); + + alertResult.Success = true; + alertResult.Message = "Alert triggered successfully"; + } + catch (Exception ex) + { + alertResult.Message = $"Failed to trigger alert: {ex.Message}"; + Console.WriteLine($"โŒ Alert system error: {ex.Message}"); + } + + return alertResult; + } + + /// + /// Block suspicious activity and implement protective measures + /// + public async Task BlockSuspiciousActivityAsync(string ipAddress, string username, string reason, TimeSpan? blockDuration = null) + { + var blockResult = new BlockingResult + { + IpAddress = ipAddress, + Username = username, + Reason = reason, + BlockTime = DateTime.Now, + BlockDuration = blockDuration ?? TimeSpan.FromMinutes(30), + Success = false + }; + + try + { + // In a real implementation, this would: + // 1. Add IP to firewall block list + // 2. Update application-level blocking rules + // 3. Send alerts to security team + // 4. Log the blocking action + + Console.WriteLine($"\n๐Ÿšซ BLOCKING SUSPICIOUS ACTIVITY"); + Console.WriteLine($"IP Address: {ipAddress}"); + Console.WriteLine($"Username: {username}"); + Console.WriteLine($"Reason: {reason}"); + Console.WriteLine($"Block Duration: {blockResult.BlockDuration.TotalMinutes:F0} minutes"); + Console.WriteLine($"Expires: {blockResult.BlockTime.Add(blockResult.BlockDuration):yyyy-MM-dd HH:mm:ss}"); + + // Log the blocking action + await LogSecurityEventAsync("ACTIVITY_BLOCKED", "HIGH", + $"Blocked {ipAddress} for {reason}. Duration: {blockResult.BlockDuration.TotalMinutes:F0} minutes", + username); + + // Simulate adding to block list (in real app, this would be persistent) + if (!_blockedIPs.ContainsKey(ipAddress)) + { + _blockedIPs[ipAddress] = blockResult.BlockTime.Add(blockResult.BlockDuration); + } + + blockResult.Success = true; + blockResult.Message = "Activity blocked successfully"; + } + catch (Exception ex) + { + blockResult.Message = $"Failed to block activity: {ex.Message}"; + Console.WriteLine($"โŒ Blocking system error: {ex.Message}"); + } + + return blockResult; + } } // Data structures for analysis results @@ -477,11 +840,17 @@ public class BruteForceAnalysisResult public string IpAddress { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public DateTime Timestamp { get; set; } + public DateTime AnalysisTime { get; set; } public int RecentAttemptsFromIP { get; set; } public int RecentAttemptsForUser { get; set; } + public int AttemptsInTimeWindow { get; set; } + public double AttemptsPerMinute { get; set; } public bool IsBruteForce { get; set; } public bool ShouldBlockIP { get; set; } public bool IPBlocked { get; set; } + public string Severity { get; set; } = "LOW"; + public string RecommendedAction { get; set; } = "MONITOR"; + public string Message { get; set; } = string.Empty; } public class DefenseAnalysisResult @@ -497,13 +866,19 @@ public class DefenseAnalysisResult public ThreatLevel ThreatLevel { get; set; } public bool ShouldBlock { get; set; } public string BlockReason { get; set; } = string.Empty; + public bool IsSqlInjectionDetected { get; set; } + public bool IsBruteForceDetected { get; set; } + public string RecommendedAction { get; set; } = "ALLOW"; } public class SecurityMetrics { public int TotalAttempts { get; set; } public int SuccessfulAttempts { get; set; } + public int FailedAttempts { get; set; } public int InjectionAttempts { get; set; } + public int BruteForceAttempts { get; set; } + public int BlockedAttempts { get; set; } public int UniqueIPs { get; set; } public int UniqueUsers { get; set; } public int TotalAlerts { get; set; } @@ -513,9 +888,61 @@ public class SecurityMetrics public int LowAlerts { get; set; } public double AttackDetectionRate { get; set; } public double SuccessRate { get; set; } + public double FailureRate { get; set; } + public double InjectionRate { get; set; } + public double DetectionRate { get; set; } + public double AverageResponseTime { get; set; } public int BlockedIPs { get; set; } } + public class SqlInjectionScanResult + { + public string Input { get; set; } = string.Empty; + public DateTime ScanTime { get; set; } + public bool IsInjection { get; set; } + public List DetectedPatterns { get; set; } = new(); + public int RiskScore { get; set; } + public string RiskLevel { get; set; } = "LOW"; + public string Message { get; set; } = string.Empty; + } + + public class LoginPatternAnalysisResult + { + public string Username { get; set; } = string.Empty; + public DateTime AnalysisTime { get; set; } + public int TotalAttempts { get; set; } + public int SuccessfulAttempts { get; set; } + public int InjectionAttempts { get; set; } + public int UniqueIPs { get; set; } + public int UniqueUserAgents { get; set; } + public double AverageResponseTime { get; set; } + public int AnomalyScore { get; set; } + public bool IsAnomalous { get; set; } + public string RiskLevel { get; set; } = "LOW"; + } + + public class AlertResult + { + public string AlertType { get; set; } = string.Empty; + public string Severity { get; set; } = string.Empty; + public string Details { get; set; } = string.Empty; + public string Username { get; set; } = string.Empty; + public DateTime Timestamp { get; set; } + public bool Success { get; set; } + public string Message { get; set; } = string.Empty; + } + + public class BlockingResult + { + public string IpAddress { get; set; } = string.Empty; + public string Username { get; set; } = string.Empty; + public string Reason { get; set; } = string.Empty; + public DateTime BlockTime { get; set; } + public TimeSpan BlockDuration { get; set; } + public bool Success { get; set; } + public string Message { get; set; } = string.Empty; + } + public enum RiskLevel { Low = 1, diff --git a/Modules/InjectionTester.cs b/Modules/InjectionTester.cs index e842678..df1e314 100644 --- a/Modules/InjectionTester.cs +++ b/Modules/InjectionTester.cs @@ -291,6 +291,93 @@ public async Task RunInjectionTestSuiteAsync() Console.WriteLine($"Protection Effectiveness: {(secureProtections * 100.0 / Math.Max(injectionCount, 1)):F1}%"); } + /// + /// Show detailed query execution analysis for educational purposes + /// + public void ShowQueryExecution(string query, string description = "") + { + Console.WriteLine("\n๐Ÿ” DETAILED QUERY ANALYSIS"); + Console.WriteLine("============================"); + + if (!string.IsNullOrEmpty(description)) + { + Console.WriteLine($"๐Ÿ“ Description: {description}"); + Console.WriteLine(); + } + + Console.WriteLine($"๐Ÿ”ค Query: {query}"); + Console.WriteLine(); + + // Analyze query structure + Console.WriteLine("๐Ÿ“Š Query Analysis:"); + Console.WriteLine($" โ€ข Length: {query.Length} characters"); + Console.WriteLine($" โ€ข Contains quotes: {(query.Contains("'") ? "Yes" : "No")}"); + Console.WriteLine($" โ€ข Contains comments: {(query.Contains("--") || query.Contains("/*") ? "Yes" : "No")}"); + Console.WriteLine($" โ€ข Contains semicolons: {(query.Contains(";") ? "Yes" : "No")}"); + Console.WriteLine($" โ€ข SQL Keywords: {CountSqlKeywords(query)}"); + + // Check for injection patterns + var injectionRisk = AnalyzeInjectionRisk(query); + Console.WriteLine($" ๐Ÿšจ Injection Risk: {injectionRisk}"); + + // Show security implications + ShowSecurityImplications(query); + + Console.WriteLine(new string('-', 60)); + } + + private int CountSqlKeywords(string query) + { + var keywords = new[] { "SELECT", "FROM", "WHERE", "AND", "OR", "UNION", "INSERT", "UPDATE", "DELETE", "DROP" }; + return keywords.Count(keyword => query.ToUpper().Contains(keyword)); + } + + private string AnalyzeInjectionRisk(string query) + { + if (IsPotentialInjectionAttempt(query)) + { + return "๐Ÿ”ด HIGH - Injection patterns detected"; + } + else if (query.Contains("'")) + { + return "๐ŸŸก MEDIUM - Contains quotes but no clear injection pattern"; + } + else + { + return "๐ŸŸข LOW - No obvious injection indicators"; + } + } + + private void ShowSecurityImplications(string query) + { + Console.WriteLine("\n๐Ÿ›ก๏ธ Security Analysis:"); + + if (query.Contains("'") && !query.Contains("@")) + { + Console.WriteLine(" โš ๏ธ String concatenation detected - vulnerable to injection"); + } + if (query.Contains("@")) + { + Console.WriteLine(" โœ… Parameterized query detected - protected against injection"); + } + if (query.Contains("--")) + { + Console.WriteLine(" ๐Ÿšจ SQL comment detected - potential comment injection"); + } + if (query.ToUpper().Contains("DROP") || query.ToUpper().Contains("DELETE")) + { + Console.WriteLine(" ๐Ÿ’€ Destructive operation detected - extremely dangerous"); + } + if (query.ToUpper().Contains("UNION")) + { + Console.WriteLine(" ๐Ÿ” Union operation detected - potential data extraction"); + } + if (query.ToUpper().Contains("WAITFOR")) + { + Console.WriteLine(" โฐ Time delay detected - potential timing attack"); + } + } + /// /// Check if input contains potential SQL injection patterns /// diff --git a/Modules/LoginSimulator.cs b/Modules/LoginSimulator.cs index b6535c7..c7d646c 100644 --- a/Modules/LoginSimulator.cs +++ b/Modules/LoginSimulator.cs @@ -171,6 +171,7 @@ public async Task ExecuteLoginAttemptAsync(LoginAttempt attempt, bo return new LoginResult { Success = success, + IsSuccessful = success, Message = message, ResponseTime = stopwatch.ElapsedMilliseconds, QueryExecuted = queryExecuted @@ -187,6 +188,7 @@ public async Task ExecuteLoginAttemptAsync(LoginAttempt attempt, bo return new LoginResult { Success = false, + IsSuccessful = false, Message = $"Error: {ex.Message}", ResponseTime = stopwatch.ElapsedMilliseconds, QueryExecuted = attempt.QueryExecuted ?? "" @@ -251,6 +253,7 @@ private LoginAttempt GenerateNormalAttempt(List validUsernames) Username = username, InputPayload = username, PasswordInput = password, + Password = password, AttemptTime = DateTime.Now, IpAddress = GenerateNormalIP(), UserAgent = _userAgents[_random.Next(3)], // Use normal browsers @@ -268,6 +271,7 @@ private LoginAttempt GenerateInjectionAttempt() Username = inUsername ? payload : "admin", InputPayload = inUsername ? payload : "admin", PasswordInput = inUsername ? "password" : payload, + Password = inUsername ? "password" : payload, AttemptTime = DateTime.Now, IpAddress = GenerateSuspiciousIP(), UserAgent = _userAgents[_random.Next(3, _userAgents.Count)], // Use suspicious tools @@ -314,6 +318,85 @@ private string GenerateRandomIP() { return _random.NextDouble() > 0.7 ? GenerateSuspiciousIP() : GenerateNormalIP(); } + + /// + /// Simulate realistic user behavior patterns for educational analysis + /// + public async Task SimulateUserBehaviorAsync(int duration = 300) + { + Console.WriteLine($"\n๐ŸŽญ SIMULATING USER BEHAVIOR"); + Console.WriteLine("=============================="); + Console.WriteLine($"Duration: {duration} seconds"); + Console.WriteLine("Generating realistic mix of normal and suspicious activity...\n"); + + var startTime = DateTime.Now; + var endTime = startTime.AddSeconds(duration); + int attemptCount = 0; + + while (DateTime.Now < endTime) + { + try + { + attemptCount++; + + // Determine behavior pattern (80% normal, 15% suspicious, 5% attack) + var behaviorType = _random.NextDouble() switch + { + < 0.80 => "normal", + < 0.95 => "suspicious", + _ => "attack" + }; + + Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Attempt #{attemptCount} - {behaviorType.ToUpper()}"); + + switch (behaviorType) + { + case "normal": + var normalAttempts = await GenerateNormalAttemptsAsync(1); + foreach (var attempt in normalAttempts) + { + var result = await ExecuteLoginAttemptAsync(attempt); + Console.WriteLine($" ๐Ÿ‘ค Normal user: {attempt.Username} -> {(result.IsSuccessful ? "โœ…" : "โŒ")}"); + } + await Task.Delay(_random.Next(5000, 15000)); // Normal users take time + break; + + case "suspicious": + // Multiple rapid attempts from same IP + var targetUser = new[] { "admin", "root", "administrator" }[_random.Next(3)]; + var bruteAttempts = await GenerateBruteForceAttemptsAsync(targetUser, 3); + + foreach (var attempt in bruteAttempts) + { + var result = await ExecuteLoginAttemptAsync(attempt); + Console.WriteLine($" ๐Ÿ” Brute force: {attempt.Username}/{attempt.PasswordInput.Substring(0, Math.Min(8, attempt.PasswordInput.Length))} -> โŒ"); + await Task.Delay(_random.Next(100, 500)); // Rapid attempts + } + break; + + case "attack": + var injectionAttempts = await GenerateInjectionAttemptsAsync(1); + foreach (var attempt in injectionAttempts) + { + var result = await ExecuteLoginAttemptAsync(attempt, true); // Use vulnerable method + Console.WriteLine($" ๐Ÿšจ SQL Injection: {attempt.Username.Substring(0, Math.Min(15, attempt.Username.Length))}... -> {(result.IsSuccessful ? "๐Ÿ’€" : "๐Ÿ›ก๏ธ")}"); + } + await Task.Delay(_random.Next(1000, 3000)); + break; + } + } + catch (Exception ex) + { + Console.WriteLine($" โš ๏ธ Error in simulation: {ex.Message}"); + } + } + + var totalTime = DateTime.Now - startTime; + Console.WriteLine($"\n๐Ÿ“Š SIMULATION COMPLETE"); + Console.WriteLine($" โฑ๏ธ Duration: {totalTime.TotalSeconds:F1} seconds"); + Console.WriteLine($" ๐Ÿ”ข Total Attempts: {attemptCount}"); + Console.WriteLine($" ๐Ÿ“ˆ Average Rate: {attemptCount / totalTime.TotalMinutes:F1} attempts/minute"); + } } /// @@ -324,6 +407,7 @@ public class LoginAttempt public string Username { get; set; } = string.Empty; public string InputPayload { get; set; } = string.Empty; public string PasswordInput { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; public DateTime AttemptTime { get; set; } public bool IsSuccessful { get; set; } public bool IsInjection { get; set; } @@ -339,6 +423,7 @@ public class LoginAttempt public class LoginResult { public bool Success { get; set; } + public bool IsSuccessful { get; set; } public string Message { get; set; } = string.Empty; public long ResponseTime { get; set; } public string QueryExecuted { get; set; } = string.Empty; diff --git a/Modules/Reporter.cs b/Modules/Reporter.cs index bd69fb9..040ca2f 100644 --- a/Modules/Reporter.cs +++ b/Modules/Reporter.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using System.Text; using Microsoft.Data.SqlClient; namespace SQLInjectionSimulator.Modules @@ -97,6 +98,457 @@ private void DisplayBasicStatistics(SecurityReport report) Console.WriteLine($"โ””โ”€โ”€ Injection Attempts: {report.InjectionAttempts:N0} ({report.InjectionRate:F1}%)"); Console.WriteLine(); } + + /// + /// Generate comprehensive summary report with advanced analytics + /// + public async Task GenerateSummaryReportAsync(TimeSpan? period = null) + { + var analysisSpan = period ?? TimeSpan.FromDays(30); + var cutoffTime = DateTime.Now.Subtract(analysisSpan); + + var report = new ComprehensiveReport + { + GeneratedAt = DateTime.Now, + AnalysisPeriod = analysisSpan, + CutoffTime = cutoffTime + }; + + using var connection = new SqlConnection(_connectionString); + await connection.OpenAsync(); + + // Get basic statistics first (reuse existing method) + var basicReport = new SecurityReport(); + await PopulateBasicStatisticsAsync(connection, basicReport, cutoffTime); + report.BasicStats = basicReport; + + // Get top attack patterns + report.TopAttackPatterns = await GetTopAttackPatternsAsync(connection, cutoffTime, 10); + + // Get alert summary + report.AlertSummary = await GetAlertSummaryAsync(connection, cutoffTime); + + // Get hourly activity + report.HourlyActivity = await GetHourlyActivityAsync(connection, cutoffTime); + + return report; + } + + /// + /// Export report data to CSV format + /// + public async Task ExportToCSVAsync(SecurityReport report, string fileName = "") + { + try + { + if (string.IsNullOrEmpty(fileName)) + fileName = $"SecurityReport_{DateTime.Now:yyyyMMdd_HHmmss}.csv"; + + var csv = new StringBuilder(); + csv.AppendLine("Metric,Value,Percentage"); + csv.AppendLine($"Total Attempts,{report.TotalAttempts},100.0"); + csv.AppendLine($"Successful Attempts,{report.SuccessfulAttempts},{report.SuccessRate:F1}"); + csv.AppendLine($"Failed Attempts,{report.FailedAttempts},{report.FailureRate:F1}"); + csv.AppendLine($"Injection Attempts,{report.InjectionAttempts},{report.InjectionRate:F1}"); + csv.AppendLine($"Unique IPs,{report.UniqueIPs},-"); + csv.AppendLine($"Unique Users,{report.UniqueUsers},-"); + csv.AppendLine($"Critical Alerts,{report.CriticalAlerts},-"); + csv.AppendLine($"High Alerts,{report.HighAlerts},-"); + csv.AppendLine($"Medium Alerts,{report.MediumAlerts},-"); + csv.AppendLine($"Low Alerts,{report.LowAlerts},-"); + + // In a real application, save to file + Console.WriteLine($"๐Ÿ“„ CSV Report Generated:"); + Console.WriteLine($"Filename: {fileName}"); + Console.WriteLine($"Size: {csv.Length} characters"); + Console.WriteLine("Content preview:"); + Console.WriteLine(csv.ToString().Substring(0, Math.Min(200, csv.Length))); + + return true; + } + catch (Exception ex) + { + Console.WriteLine($"โŒ Error exporting to CSV: {ex.Message}"); + return false; + } + } + + /// + /// Display real-time security metrics dashboard + /// + public async Task DisplaySecurityMetricsDashboardAsync() + { + Console.Clear(); + Console.WriteLine("๐Ÿ“Š REAL-TIME SECURITY METRICS DASHBOARD"); + Console.WriteLine("========================================="); + Console.WriteLine($"Last Updated: {DateTime.Now:yyyy-MM-dd HH:mm:ss}"); + Console.WriteLine(); + + try + { + using var connection = new SqlConnection(_connectionString); + await connection.OpenAsync(); + + // Real-time metrics (last 24 hours) + var cutoff24h = DateTime.Now.AddDays(-1); + var metricsQuery = @" + SELECT + COUNT(*) as Total24h, + COUNT(CASE WHEN IsInjection = 1 THEN 1 END) as Injections24h, + COUNT(CASE WHEN AttemptTime >= @cutoff1h THEN 1 END) as Total1h, + COUNT(CASE WHEN IsInjection = 1 AND AttemptTime >= @cutoff1h THEN 1 END) as Injections1h, + COUNT(DISTINCT IpAddress) as UniqueIPs, + COUNT(DISTINCT CASE WHEN AttemptTime >= @cutoff1h THEN IpAddress END) as ActiveIPs + FROM LoginAttempts + WHERE AttemptTime >= @cutoff24h"; + + using var command = new SqlCommand(metricsQuery, connection); + command.Parameters.AddWithValue("@cutoff24h", cutoff24h); + command.Parameters.AddWithValue("@cutoff1h", DateTime.Now.AddHours(-1)); + + using var reader = await command.ExecuteReaderAsync(); + + if (reader.Read()) + { + Console.WriteLine("๐Ÿ”„ ACTIVITY OVERVIEW:"); + Console.WriteLine($" ๐Ÿ“ˆ Last 24 hours: {reader.GetInt32(0)} total attempts"); // Total24h + Console.WriteLine($" ๐Ÿšจ Injections (24h): {reader.GetInt32(1)} attempts"); // Injections24h + Console.WriteLine($" โšก Last 1 hour: {reader.GetInt32(2)} total attempts"); // Total1h + Console.WriteLine($" ๐Ÿ’ฅ Injections (1h): {reader.GetInt32(3)} attempts"); // Injections1h + Console.WriteLine($" ๐ŸŒ Unique IPs: {reader.GetInt32(4)} total"); // UniqueIPs + Console.WriteLine($" ๐Ÿ”ด Active IPs: {reader.GetInt32(5)} in last hour"); // ActiveIPs + } + reader.Close(); + + // Alert status + var alertQuery = @" + SELECT + COUNT(*) as TotalAlerts, + COUNT(CASE WHEN IsResolved = 0 THEN 1 END) as UnresolvedAlerts, + COUNT(CASE WHEN Severity = 'CRITICAL' AND IsResolved = 0 THEN 1 END) as CriticalOpen, + COUNT(CASE WHEN AlertTime >= @cutoff24h THEN 1 END) as Recent24h + FROM Alerts"; + + using var alertCommand = new SqlCommand(alertQuery, connection); + alertCommand.Parameters.AddWithValue("@cutoff24h", cutoff24h); + + using var alertReader = await alertCommand.ExecuteReaderAsync(); + if (alertReader.Read()) + { + Console.WriteLine("\n๐Ÿšจ ALERT STATUS:"); + Console.WriteLine($" ๐Ÿ“‹ Total Alerts: {alertReader.GetInt32(0)}"); // TotalAlerts + Console.WriteLine($" โš ๏ธ Unresolved: {alertReader.GetInt32(1)}"); // UnresolvedAlerts + Console.WriteLine($" ๐Ÿ”ด Critical Open: {alertReader.GetInt32(2)}"); // CriticalOpen + Console.WriteLine($" ๐Ÿ“… Recent (24h): {alertReader.GetInt32(3)}"); // Recent24h + } + + Console.WriteLine("\nโฑ๏ธ Auto-refresh: Dashboard updates every 30 seconds"); + Console.WriteLine("Press any key to return to main menu..."); + } + catch (Exception ex) + { + Console.WriteLine($"โŒ Dashboard error: {ex.Message}"); + } + } + + /// + /// Analyze and display top attack patterns + /// + public async Task> ShowTopAttackPatternsAsync(int topCount = 10) + { + var patterns = new List(); + + Console.WriteLine($"\n๐ŸŽฏ TOP {topCount} ATTACK PATTERNS"); + Console.WriteLine("================================"); + + try + { + using var connection = new SqlConnection(_connectionString); + await connection.OpenAsync(); + + patterns = await GetTopAttackPatternsAsync(connection, DateTime.Now.AddDays(-30), topCount); + + int rank = 1; + foreach (var pattern in patterns) + { + Console.WriteLine($"{rank,2}. Pattern: {pattern.Pattern.Substring(0, Math.Min(40, pattern.Pattern.Length))}..."); + Console.WriteLine($" Frequency: {pattern.Frequency} attempts from {pattern.UniqueIPs} IPs"); + Console.WriteLine($" Success: {pattern.SuccessCount} times | Last seen: {pattern.LastSeen:yyyy-MM-dd HH:mm}"); + Console.WriteLine(); + rank++; + } + } + catch (Exception ex) + { + Console.WriteLine($"โŒ Error analyzing attack patterns: {ex.Message}"); + } + + return patterns; + } + + /// + /// Generate security recommendations based on current threats + /// + public async Task> GenerateRecommendationsAsync() + { + var recommendations = new List(); + + Console.WriteLine("\n๐Ÿ›ก๏ธ SECURITY RECOMMENDATIONS"); + Console.WriteLine("=============================="); + + try + { + using var connection = new SqlConnection(_connectionString); + await connection.OpenAsync(); + + // Analyze recent data (last 7 days) + var cutoff = DateTime.Now.AddDays(-7); + + var analysisQuery = @" + SELECT + COUNT(*) as TotalAttempts, + COUNT(CASE WHEN IsInjection = 1 THEN 1 END) as InjectionAttempts, + COUNT(CASE WHEN IsSuccessful = 1 THEN 1 END) as SuccessfulAttempts, + COUNT(DISTINCT IpAddress) as UniqueIPs, + AVG(CAST(ResponseTime as FLOAT)) as AvgResponseTime + FROM LoginAttempts + WHERE AttemptTime >= @cutoff"; + + using var command = new SqlCommand(analysisQuery, connection); + command.Parameters.AddWithValue("@cutoff", cutoff); + + using var reader = await command.ExecuteReaderAsync(); + + if (reader.Read() && !reader.IsDBNull(0)) // TotalAttempts + { + var totalAttempts = reader.GetInt32(0); // TotalAttempts + var injectionAttempts = reader.GetInt32(1); // InjectionAttempts + var uniqueIPs = reader.GetInt32(3); // UniqueIPs + + // Generate recommendations based on analysis + if (totalAttempts > 1000) + { + recommendations.Add(new SecurityRecommendation + { + Priority = "HIGH", + Category = "Rate Limiting", + Title = "Implement Rate Limiting", + Description = $"High volume of login attempts detected ({totalAttempts} in 7 days). Implement rate limiting to slow down attackers.", + ActionItems = new[] { "Configure IP-based rate limiting", "Set up progressive delays", "Monitor for distributed attacks" } + }); + } + + if (injectionAttempts > totalAttempts * 0.1) // More than 10% injection attempts + { + recommendations.Add(new SecurityRecommendation + { + Priority = "CRITICAL", + Category = "Input Validation", + Title = "Strengthen Input Validation", + Description = $"Significant SQL injection activity ({injectionAttempts}/{totalAttempts}). Review and enhance input validation.", + ActionItems = new[] { "Implement strict input validation", "Use parameterized queries exclusively", "Deploy WAF rules" } + }); + } + + if (uniqueIPs > 100) + { + recommendations.Add(new SecurityRecommendation + { + Priority = "MEDIUM", + Category = "Monitoring", + Title = "Enhanced IP Monitoring", + Description = $"Activity from many unique IPs ({uniqueIPs}). Implement enhanced IP reputation checking.", + ActionItems = new[] { "Integrate IP reputation services", "Implement geo-blocking", "Monitor for VPN/proxy usage" } + }); + } + } + + // Always include baseline recommendations + recommendations.Add(new SecurityRecommendation + { + Priority = "HIGH", + Category = "Best Practices", + Title = "Regular Security Audits", + Description = "Maintain regular security assessments to identify new vulnerabilities.", + ActionItems = new[] { "Schedule monthly security reviews", "Conduct penetration testing", "Update security policies" } + }); + + // Display recommendations + foreach (var rec in recommendations.OrderByDescending(r => r.Priority)) + { + var emoji = rec.Priority switch + { + "CRITICAL" => "๐Ÿ”ด", + "HIGH" => "๐ŸŸก", + "MEDIUM" => "๐ŸŸ ", + _ => "๐ŸŸข" + }; + + Console.WriteLine($"{emoji} [{rec.Priority}] {rec.Category}: {rec.Title}"); + Console.WriteLine($" ๐Ÿ“ {rec.Description}"); + Console.WriteLine(" ๐Ÿ“‹ Action Items:"); + foreach (var action in rec.ActionItems) + { + Console.WriteLine($" โ€ข {action}"); + } + Console.WriteLine(); + } + } + catch (Exception ex) + { + Console.WriteLine($"โŒ Error generating recommendations: {ex.Message}"); + } + + return recommendations; + } + + private async Task> GetTopAttackPatternsAsync(SqlConnection connection, DateTime cutoffTime, int count) + { + var patterns = new List(); + + var query = @" + SELECT TOP (@count) + InputPayload, + COUNT(*) as Frequency, + COUNT(DISTINCT IpAddress) as UniqueIPs, + COUNT(CASE WHEN IsSuccessful = 1 THEN 1 END) as SuccessCount, + MAX(AttemptTime) as LastSeen + FROM LoginAttempts + WHERE IsInjection = 1 AND AttemptTime >= @cutoffTime AND InputPayload IS NOT NULL + GROUP BY InputPayload + ORDER BY COUNT(*) DESC"; + + using var command = new SqlCommand(query, connection); + command.Parameters.AddWithValue("@count", count); + command.Parameters.AddWithValue("@cutoffTime", cutoffTime); + + using var reader = await command.ExecuteReaderAsync(); + + while (reader.Read()) + { + patterns.Add(new AttackPattern + { + Pattern = reader.GetString(0), // InputPayload + Frequency = reader.GetInt32(1), // Frequency + UniqueIPs = reader.GetInt32(2), // UniqueIPs + SuccessCount = reader.GetInt32(3), // SuccessCount + LastSeen = reader.GetDateTime(4) // LastSeen + }); + } + + return patterns; + } + + private async Task GetAlertSummaryAsync(SqlConnection connection, DateTime cutoffTime) + { + var summary = new AlertSummary(); + + var query = @" + SELECT + COUNT(*) as TotalAlerts, + COUNT(CASE WHEN Severity = 'CRITICAL' THEN 1 END) as Critical, + COUNT(CASE WHEN Severity = 'HIGH' THEN 1 END) as High, + COUNT(CASE WHEN Severity = 'MEDIUM' THEN 1 END) as Medium, + COUNT(CASE WHEN Severity = 'LOW' THEN 1 END) as Low + FROM Alerts + WHERE AlertTime >= @cutoffTime"; + + using var command = new SqlCommand(query, connection); + command.Parameters.AddWithValue("@cutoffTime", cutoffTime); + + using var reader = await command.ExecuteReaderAsync(); + + if (reader.Read()) + { + summary.TotalAlerts = reader.GetInt32(0); // TotalAlerts + summary.CriticalAlerts = reader.GetInt32(1); // Critical + summary.HighAlerts = reader.GetInt32(2); // High + summary.MediumAlerts = reader.GetInt32(3); // Medium + summary.LowAlerts = reader.GetInt32(4); // Low + } + + return summary; + } + + private async Task> GetHourlyActivityAsync(SqlConnection connection, DateTime cutoffTime) + { + var activity = new List(); + + var query = @" + SELECT + DATEPART(hour, AttemptTime) as Hour, + COUNT(*) as Attempts + FROM LoginAttempts + WHERE AttemptTime >= @cutoffTime + GROUP BY DATEPART(hour, AttemptTime) + ORDER BY Hour"; + + using var command = new SqlCommand(query, connection); + command.Parameters.AddWithValue("@cutoffTime", cutoffTime); + + using var reader = await command.ExecuteReaderAsync(); + + while (reader.Read()) + { + activity.Add(new HourlyActivity + { + Hour = DateTime.Today.AddHours(reader.GetInt32(0)), // Hour + Attempts = reader.GetInt32(1) // Attempts + }); + } + + return activity; + } + } + + /// + /// Comprehensive report with advanced analytics + /// + public class ComprehensiveReport + { + public DateTime GeneratedAt { get; set; } = DateTime.Now; + public TimeSpan AnalysisPeriod { get; set; } + public DateTime CutoffTime { get; set; } + public SecurityReport BasicStats { get; set; } = new(); + public List TopAttackPatterns { get; set; } = new(); + public AlertSummary AlertSummary { get; set; } = new(); + public List HourlyActivity { get; set; } = new(); + } + + /// + /// Attack pattern analysis + /// + public class AttackPattern + { + public string Pattern { get; set; } = string.Empty; + public int Frequency { get; set; } + public int UniqueIPs { get; set; } + public int SuccessCount { get; set; } + public DateTime LastSeen { get; set; } + } + + /// + /// Alert summary statistics + /// + public class AlertSummary + { + public int TotalAlerts { get; set; } + public int CriticalAlerts { get; set; } + public int HighAlerts { get; set; } + public int MediumAlerts { get; set; } + public int LowAlerts { get; set; } + } + + /// + /// Security recommendation + /// + public class SecurityRecommendation + { + public string Priority { get; set; } = string.Empty; + public string Category { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string[] ActionItems { get; set; } = Array.Empty(); } /// diff --git a/Modules/UserManagerSimple.cs b/Modules/UserManagerSimple.cs index 124ef82..6d28ee3 100644 --- a/Modules/UserManagerSimple.cs +++ b/Modules/UserManagerSimple.cs @@ -66,7 +66,7 @@ public async Task> GetAllUsersAsync() using var connection = new SqlConnection(_connectionString); await connection.OpenAsync(); - string query = "SELECT Id, Username, IsActive FROM Users ORDER BY Username"; + string query = "SELECT UserId, Username, IsActive, LastLoginDate FROM Users ORDER BY Username"; using var command = new SqlCommand(query, connection); using var reader = await command.ExecuteReaderAsync(); @@ -77,7 +77,8 @@ public async Task> GetAllUsersAsync() { UserId = reader.GetInt32(0), Username = reader.GetString(1), - IsActive = reader.GetBoolean(2) + IsActive = reader.GetBoolean(2), + LastLoginDate = reader.IsDBNull(3) ? null : reader.GetDateTime(3) }); } @@ -120,5 +121,6 @@ public class SimpleUserInfo public int UserId { get; set; } public string Username { get; set; } = string.Empty; public bool IsActive { get; set; } + public DateTime? LastLoginDate { get; set; } } } \ No newline at end of file diff --git a/Program.cs b/Program.cs index dcd8b01..5658dba 100644 --- a/Program.cs +++ b/Program.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Configuration; using SQLInjectionSimulator.Modules; +using System.Text; namespace SQLInjectionSimulator { @@ -10,6 +11,14 @@ namespace SQLInjectionSimulator /// class Program { + private static string _connectionString = "Server=(localdb)\\MSSQLLocalDB;Database=SQLInjectionSimulator;Trusted_Connection=true;MultipleActiveResultSets=true;TrustServerCertificate=true"; + private static UserManager? _userManager; + private static UserManagerSimple? _userManagerSimple; + private static InjectionTester? _injectionTester; + private static LoginSimulator? _loginSimulator; + private static DefenseEngine? _defenseEngine; + private static Reporter? _reporter; + static async Task Main(string[] args) { try @@ -17,65 +26,536 @@ static async Task Main(string[] args) Console.WriteLine("๐Ÿ›ก๏ธ SQL Injection Cybersecurity Simulator"); Console.WriteLine("=========================================="); Console.WriteLine("โš ๏ธ FOR EDUCATIONAL PURPOSES ONLY"); + Console.WriteLine("๐ŸŽฏ Learn how SQL injection works and how to prevent it"); Console.WriteLine(); - // Simple connection string for LocalDB - string connectionString = "Server=(localdb)\\MSSQLLocalDB;Database=SQLInjectionSimulator;Trusted_Connection=true;MultipleActiveResultSets=true;TrustServerCertificate=true"; + // Initialize components + await InitializeComponentsAsync(); + + bool continueRunning = true; + while (continueRunning) + { + Console.Clear(); + ShowWelcomeHeader(); + ShowMainMenu(); + + var choice = Console.ReadLine()?.Trim(); + continueRunning = await HandleMainMenuChoice(choice); + + if (continueRunning) + { + Console.WriteLine("\nPress any key to continue..."); + Console.ReadKey(); + } + } + + Console.WriteLine("\n๐Ÿ‘‹ Thank you for using SQL Injection Cybersecurity Simulator!"); + Console.WriteLine("Stay safe and secure! ๐Ÿ›ก๏ธ"); + } + catch (Exception ex) + { + Console.WriteLine($"โŒ Critical Error: {ex.Message}"); + Console.WriteLine("Please ensure SQL Server LocalDB is installed and accessible."); + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } - // Initialize basic components - var userManager = new UserManagerSimple(connectionString); + private static async Task InitializeComponentsAsync() + { + Console.WriteLine("๐Ÿš€ Initializing application components..."); + + try + { + _userManagerSimple = new UserManagerSimple(_connectionString); + _userManager = new UserManager(_connectionString); + _injectionTester = new InjectionTester(_connectionString, _userManager); + _loginSimulator = new LoginSimulator(_connectionString, _userManager); + _defenseEngine = new DefenseEngine(_connectionString); + _reporter = new Reporter(_connectionString); - Console.WriteLine("๐Ÿš€ Initializing application..."); - Console.WriteLine("โœ… Application ready!"); + Console.WriteLine("โœ… All components initialized successfully!"); + Console.WriteLine("๐Ÿ—„๏ธ Database connection established"); + Console.WriteLine("๐Ÿ“Š Security monitoring active"); Console.WriteLine(); + } + catch (Exception ex) + { + Console.WriteLine($"โŒ Initialization failed: {ex.Message}"); + throw; + } + } - ShowMainMenu(); - var choice = Console.ReadLine()?.Trim(); + private static void ShowWelcomeHeader() + { + Console.WriteLine("๐Ÿ›ก๏ธ SQL Injection Cybersecurity Simulator"); + Console.WriteLine("=========================================="); + Console.WriteLine("โš ๏ธ FOR EDUCATIONAL PURPOSES ONLY"); + Console.WriteLine(); + } - switch (choice?.ToUpper()) + private static void ShowMainMenu() + { + Console.WriteLine("๐Ÿ“‹ Educational Menu - Choose Your Learning Path:"); + Console.WriteLine(); + Console.WriteLine("๐Ÿ—๏ธ SETUP & PREPARATION:"); + Console.WriteLine("1. Initialize Database & Create Test Users"); + Console.WriteLine("2. View Current Users & System Status"); + Console.WriteLine(); + Console.WriteLine("๐Ÿงช CORE SQL INJECTION DEMONSTRATIONS:"); + Console.WriteLine("3. Interactive Injection Testing Suite"); + Console.WriteLine("4. Compare Vulnerable vs Secure Queries"); + Console.WriteLine("5. Custom Injection Test (Enter Your Own Input)"); + Console.WriteLine(); + Console.WriteLine("โš”๏ธ ATTACK SIMULATION SCENARIOS:"); + Console.WriteLine("6. Simulate Realistic Attack Patterns"); + Console.WriteLine("7. Brute Force Attack Simulation"); + Console.WriteLine("8. Advanced Injection Patterns Demo"); + Console.WriteLine(); + Console.WriteLine("๐Ÿ›ก๏ธ DEFENSE & MONITORING:"); + Console.WriteLine("9. Real-time Defense Engine Demo"); + Console.WriteLine("10. Security Metrics Dashboard"); + Console.WriteLine("11. Generate Comprehensive Security Report"); + Console.WriteLine(); + Console.WriteLine("๐Ÿ“š EDUCATIONAL RESOURCES:"); + Console.WriteLine("12. Learn About SQL Injection Basics"); + Console.WriteLine("13. Best Practices & Prevention Guide"); + Console.WriteLine(); + Console.WriteLine("0. Exit Application"); + Console.WriteLine(); + Console.Write("Enter your choice: "); + } + + private static async Task HandleMainMenuChoice(string? choice) + { + try + { + switch (choice?.Trim()) { case "1": - Console.WriteLine("Setting up test users..."); - await userManager.CreateTestUsersAsync(); + await InitializeDatabaseAsync(); break; case "2": - Console.WriteLine("Listing users..."); - var users = await userManager.GetAllUsersAsync(); - foreach (var user in users) - { - Console.WriteLine($"- {user.Username} (Active: {user.IsActive})"); - } + await ShowSystemStatusAsync(); break; case "3": - Console.WriteLine("Testing secure authentication..."); - var result = await userManager.AuthenticateUserSecureAsync("admin", "SecureAdmin123!"); - Console.WriteLine($"Authentication result: {result.success} - {result.message}"); + await RunInteractiveInjectionTestSuiteAsync(); + break; + case "4": + await RunVulnerableVsSecureComparisonAsync(); + break; + case "5": + await RunCustomInjectionTestAsync(); + break; + case "6": + await SimulateRealisticAttackPatternsAsync(); + break; + case "7": + await SimulateBruteForceAttackAsync(); break; + case "8": + await DemonstrateAdvancedInjectionPatternsAsync(); + break; + case "9": + await RunDefenseEngineDemo(); + break; + case "10": + await ShowSecurityMetricsDashboard(); + break; + case "11": + await GenerateComprehensiveReport(); + break; + case "12": + ShowSqlInjectionBasics(); + break; + case "13": + ShowBestPracticesGuide(); + break; + case "0": + return false; default: - Console.WriteLine("Invalid choice. Exiting..."); + Console.WriteLine("โŒ Invalid choice. Please select a number from 0-13."); break; } - - Console.WriteLine("\nPress any key to exit..."); - Console.ReadKey(); } catch (Exception ex) { - Console.WriteLine($"โŒ Error: {ex.Message}"); - Console.WriteLine("Please ensure SQL Server LocalDB is installed and accessible."); - Console.WriteLine("\nPress any key to exit..."); - Console.ReadKey(); + Console.WriteLine($"โŒ Error executing option: {ex.Message}"); + Console.WriteLine("๐Ÿ“ This might be expected behavior in some injection tests."); } + + return true; } - private static void ShowMainMenu() + private static async Task InitializeDatabaseAsync() + { + Console.WriteLine("\n๐Ÿ—๏ธ DATABASE INITIALIZATION"); + Console.WriteLine("=============================="); + + if (_userManagerSimple != null) + { + Console.WriteLine("๐Ÿ“Š Setting up test users for educational demonstrations..."); + await _userManagerSimple.CreateTestUsersAsync(); + + Console.WriteLine("\nโœ… Database initialized successfully!"); + Console.WriteLine("๐Ÿ“ Test users created for educational purposes"); + Console.WriteLine("๐Ÿ”’ All passwords are securely hashed using BCrypt"); + } + } + + private static async Task ShowSystemStatusAsync() + { + Console.WriteLine("\n๐Ÿ“Š SYSTEM STATUS & USER OVERVIEW"); + Console.WriteLine("==================================="); + + if (_userManagerSimple != null) + { + Console.WriteLine("๐Ÿ‘ฅ Current Users in System:"); + var users = await _userManagerSimple.GetAllUsersAsync(); + + foreach (var user in users) + { + string status = user.IsActive ? "โœ… Active" : "โŒ Inactive"; + string lastLogin = user.LastLoginDate?.ToString("yyyy-MM-dd HH:mm") ?? "Never"; + Console.WriteLine($" ๐Ÿง‘ {user.Username,-15} | {status,-10} | Last Login: {lastLogin}"); + } + + Console.WriteLine($"\n๐Ÿ“ˆ Total Users: {users.Count()}"); + Console.WriteLine($"โœ… Active Users: {users.Count(u => u.IsActive)}"); + Console.WriteLine($"โŒ Inactive Users: {users.Count(u => !u.IsActive)}"); + } + } + + private static async Task RunInteractiveInjectionTestSuiteAsync() + { + Console.WriteLine("\n๐Ÿงช INTERACTIVE SQL INJECTION TEST SUITE"); + Console.WriteLine("=========================================="); + Console.WriteLine("This demonstration shows various SQL injection techniques"); + Console.WriteLine("and how they behave with vulnerable vs. secure implementations.\n"); + + if (_injectionTester != null) + { + await _injectionTester.RunInjectionTestSuiteAsync(); + } + } + + private static async Task RunVulnerableVsSecureComparisonAsync() + { + Console.WriteLine("\nโš–๏ธ VULNERABLE vs SECURE QUERY COMPARISON"); + Console.WriteLine("==========================================="); + Console.WriteLine("Enter test credentials to see the difference between"); + Console.WriteLine("vulnerable and secure query implementations.\n"); + + Console.Write("Enter username (try 'admin' OR '1'='1'): "); + var username = Console.ReadLine() ?? ""; + + Console.Write("Enter password (try anything): "); + var password = Console.ReadLine() ?? ""; + + if (_injectionTester != null) + { + await _injectionTester.CompareImplementationsAsync(username, password); + } + } + + private static async Task RunCustomInjectionTestAsync() + { + Console.WriteLine("\n๐ŸŽฏ CUSTOM INJECTION TEST"); + Console.WriteLine("=========================="); + Console.WriteLine("Test your own SQL injection payloads!"); + Console.WriteLine("This is a safe environment to experiment and learn.\n"); + + Console.WriteLine("๐Ÿ’ก Try these example payloads:"); + Console.WriteLine(" - admin' OR '1'='1"); + Console.WriteLine(" - admin'--"); + Console.WriteLine(" - ' UNION SELECT 1,'hacker'--"); + Console.WriteLine(" - '; DROP TABLE Users--"); + Console.WriteLine(); + + Console.Write("Enter your test username: "); + var username = Console.ReadLine() ?? ""; + + Console.Write("Enter your test password: "); + var password = Console.ReadLine() ?? ""; + + if (_injectionTester != null) + { + await _injectionTester.CompareImplementationsAsync(username, password); + } + } + + private static async Task SimulateRealisticAttackPatternsAsync() + { + Console.WriteLine("\nโš”๏ธ REALISTIC ATTACK PATTERN SIMULATION"); + Console.WriteLine("========================================"); + Console.WriteLine("Simulating a mix of normal and malicious login attempts"); + Console.WriteLine("to demonstrate how attacks might look in real scenarios.\n"); + + if (_loginSimulator != null && _defenseEngine != null) + { + // Generate normal attempts + Console.WriteLine("๐Ÿ‘ฅ Generating normal user behavior..."); + var normalAttempts = await _loginSimulator.GenerateNormalAttemptsAsync(5); + + Console.WriteLine("๐Ÿ” Analyzing normal attempts:"); + foreach (var attempt in normalAttempts) + { + var result = await _loginSimulator.ExecuteLoginAttemptAsync(attempt); + var analysis = await _defenseEngine.AnalyzeLoginAttemptAsync( + attempt.Username, attempt.Password, attempt.IpAddress, attempt.UserAgent); + + Console.WriteLine($" ๐Ÿ“ {attempt.Username}: {(result.IsSuccessful ? "โœ… Success" : "โŒ Failed")} " + + $"- Threat: {analysis.ThreatLevel}"); + } + + Console.WriteLine("\n๐Ÿšจ Generating injection attack attempts..."); + var injectionAttempts = await _loginSimulator.GenerateInjectionAttemptsAsync(3); + + Console.WriteLine("๐Ÿ” Analyzing attack attempts:"); + foreach (var attempt in injectionAttempts) + { + var result = await _loginSimulator.ExecuteLoginAttemptAsync(attempt, true); + var analysis = await _defenseEngine.AnalyzeLoginAttemptAsync( + attempt.Username, attempt.Password, attempt.IpAddress, attempt.UserAgent); + + Console.WriteLine($" ๐Ÿšจ Attack detected: {attempt.Username.Substring(0, Math.Min(20, attempt.Username.Length))}..." + + $" - Threat: {analysis.ThreatLevel}"); + } + } + } + + private static async Task SimulateBruteForceAttackAsync() + { + Console.WriteLine("\n๐Ÿ’ฅ BRUTE FORCE ATTACK SIMULATION"); + Console.WriteLine("=================================="); + Console.WriteLine("Demonstrating rapid-fire login attempts against a single account.\n"); + + Console.Write("Enter target username to attack (default: admin): "); + var targetUser = Console.ReadLine(); + if (string.IsNullOrWhiteSpace(targetUser)) + targetUser = "admin"; + + if (_loginSimulator != null && _defenseEngine != null) + { + Console.WriteLine($"๐ŸŽฏ Launching brute force attack against '{targetUser}'..."); + + var bruteForceAttempts = await _loginSimulator.GenerateBruteForceAttemptsAsync(targetUser, 5); + + Console.WriteLine("๐Ÿ” Real-time attack analysis:"); + foreach (var attempt in bruteForceAttempts) + { + var startTime = DateTime.Now; + var result = await _loginSimulator.ExecuteLoginAttemptAsync(attempt); + var analysis = await _defenseEngine.AnalyzeLoginAttemptAsync( + attempt.Username, attempt.Password, attempt.IpAddress, attempt.UserAgent); + + var responseTime = (DateTime.Now - startTime).TotalMilliseconds; + + Console.WriteLine($" โšก Attempt: {attempt.Password.Substring(0, Math.Min(10, attempt.Password.Length))} " + + $"- Result: {(result.IsSuccessful ? "โœ…" : "โŒ")} " + + $"- Threat: {analysis.ThreatLevel} " + + $"- Time: {responseTime:F0}ms"); + + // Small delay to show progression + await Task.Delay(200); + } + } + } + + private static async Task DemonstrateAdvancedInjectionPatternsAsync() + { + Console.WriteLine("\n๐ŸŽ“ ADVANCED INJECTION PATTERNS DEMONSTRATION"); + Console.WriteLine("==============================================="); + Console.WriteLine("Educational showcase of sophisticated SQL injection techniques.\n"); + + var advancedPatterns = new List<(string description, string username, string password)> + { + ("Time-Based Blind Injection", "admin", "'; WAITFOR DELAY '00:00:01'--"), + ("Union-Based Information Extraction", "test' UNION SELECT username, password FROM Users--", "anything"), + ("Error-Based SQL Injection", "admin'", "convert(int,@@version)--"), + ("Boolean-Based Blind SQL Injection", "admin' AND 1=1--", "password"), + ("Second-Order SQL Injection", "admin", "'; UPDATE Users SET password='hacked' WHERE username='admin'--"), + ("Stacked Queries Attack", "admin'; DROP TABLE IF EXISTS TempTable--", "password"), + ("Comment-Based Evasion", "admin'/**/OR/**/1=1--", "password") + }; + + Console.WriteLine("๐Ÿ”ฌ Running advanced pattern analysis:\n"); + + if (_injectionTester != null) + { + foreach (var (description, username, password) in advancedPatterns) + { + Console.WriteLine($"๐Ÿงช Testing: {description}"); + Console.WriteLine(new string('-', 50)); + + await _injectionTester.CompareImplementationsAsync(username, password); + + Console.WriteLine("\n" + new string('โ•', 80) + "\n"); + await Task.Delay(1000); // Pause between tests for readability + } + } + } + + private static async Task RunDefenseEngineDemo() + { + Console.WriteLine("\n๐Ÿ›ก๏ธ REAL-TIME DEFENSE ENGINE DEMONSTRATION"); + Console.WriteLine("============================================"); + Console.WriteLine("Watch as the defense engine analyzes and responds to threats.\n"); + + if (_defenseEngine != null) + { + var testInputs = new[] + { + ("normal_user", "valid_password", "192.168.1.100", "Mozilla/5.0"), + ("admin' OR 1=1--", "anything", "10.0.0.1", "curl/7.68.0"), + ("admin", "'; DROP TABLE Users--", "192.168.1.1", "sqlmap/1.5.2"), + ("test' UNION SELECT * FROM Users--", "password", "172.16.0.1", "Burp Suite") + }; + + Console.WriteLine("๐Ÿ” Real-time threat analysis:"); + foreach (var (username, password, ip, userAgent) in testInputs) + { + Console.WriteLine($"\n๐Ÿ“ฅ Analyzing: {username.Substring(0, Math.Min(20, username.Length))}..."); + + var analysis = await _defenseEngine.AnalyzeLoginAttemptAsync(username, password, ip, userAgent); + + Console.WriteLine($" ๐ŸŽฏ Threat Level: {analysis.ThreatLevel}"); + Console.WriteLine($" ๐Ÿšจ SQL Injection Risk: {(analysis.IsSqlInjectionDetected ? "HIGH" : "LOW")}"); + Console.WriteLine($" ๐Ÿ”„ Brute Force Risk: {(analysis.IsBruteForceDetected ? "HIGH" : "LOW")}"); + Console.WriteLine($" ๐Ÿ“ Source: {ip} via {userAgent.Substring(0, Math.Min(15, userAgent.Length))}..."); + + if (analysis.RecommendedAction != "ALLOW") + { + Console.WriteLine($" โšก Action: {analysis.RecommendedAction}"); + } + } + } + } + + private static async Task ShowSecurityMetricsDashboard() + { + Console.WriteLine("\n๐Ÿ“Š SECURITY METRICS DASHBOARD"); + Console.WriteLine("==============================="); + + if (_defenseEngine != null) + { + var metrics = await _defenseEngine.GetSecurityMetricsAsync(TimeSpan.FromDays(30)); + + Console.WriteLine("๐Ÿ“ˆ 30-Day Security Overview:"); + Console.WriteLine($" ๐Ÿ”ข Total Login Attempts: {metrics.TotalAttempts}"); + Console.WriteLine($" โœ… Successful Logins: {metrics.SuccessfulAttempts} ({metrics.SuccessRate:F1}%)"); + Console.WriteLine($" โŒ Failed Attempts: {metrics.FailedAttempts} ({metrics.FailureRate:F1}%)"); + Console.WriteLine($" ๐Ÿšจ Injection Attempts: {metrics.InjectionAttempts} ({metrics.InjectionRate:F1}%)"); + Console.WriteLine($" ๐Ÿ’ฅ Brute Force Attempts: {metrics.BruteForceAttempts}"); + Console.WriteLine($" ๐ŸŽฏ Blocked Attacks: {metrics.BlockedAttempts}"); + + Console.WriteLine("\n๐Ÿšจ Alert Summary:"); + Console.WriteLine($" ๐Ÿ”ด Critical Alerts: {metrics.CriticalAlerts}"); + Console.WriteLine($" ๐ŸŸก High Priority: {metrics.HighAlerts}"); + Console.WriteLine($" ๐ŸŸ  Medium Priority: {metrics.MediumAlerts}"); + Console.WriteLine($" ๐ŸŸข Low Priority: {metrics.LowAlerts}"); + + Console.WriteLine($"\nโšก Average Response Time: {metrics.AverageResponseTime:F1}ms"); + Console.WriteLine($"๐Ÿ›ก๏ธ Detection Rate: {metrics.DetectionRate:F1}%"); + } + } + + private static async Task GenerateComprehensiveReport() + { + Console.WriteLine("\n๐Ÿ“‹ COMPREHENSIVE SECURITY REPORT"); + Console.WriteLine("==================================="); + + if (_reporter != null) + { + Console.WriteLine("๐Ÿ”„ Generating detailed security analysis..."); + var report = await _reporter.GenerateReportAsync(); + + _reporter.DisplayReport(report); + + Console.WriteLine("\n๐Ÿ’พ Export Options:"); + Console.WriteLine("Would you like to export this report? (y/n): "); + var exportChoice = Console.ReadLine()?.ToLower(); + + if (exportChoice == "y" || exportChoice == "yes") + { + Console.WriteLine("๐Ÿ“‚ Report export functionality would be available in production version."); + Console.WriteLine("๐Ÿ“Š Data can be exported to CSV, JSON, or PDF formats."); + } + } + } + + private static void ShowSqlInjectionBasics() + { + Console.WriteLine("\n๐Ÿ“š SQL INJECTION FUNDAMENTALS"); + Console.WriteLine("==============================="); + + var basics = new StringBuilder(); + basics.AppendLine("๐ŸŽฏ What is SQL Injection?"); + basics.AppendLine("SQL injection is a code injection technique that exploits vulnerabilities"); + basics.AppendLine("in an application's software by inserting malicious SQL statements into"); + basics.AppendLine("entry fields for execution.\n"); + + basics.AppendLine("๐Ÿ” How Does It Work?"); + basics.AppendLine("1. Attacker finds input field that connects to database"); + basics.AppendLine("2. Sends malicious SQL code instead of expected data"); + basics.AppendLine("3. Application executes the malicious code"); + basics.AppendLine("4. Attacker gains unauthorized access or extracts data\n"); + + basics.AppendLine("โš ๏ธ Common Vulnerabilities:"); + basics.AppendLine("โ€ข String concatenation in SQL queries"); + basics.AppendLine("โ€ข Lack of input validation"); + basics.AppendLine("โ€ข Excessive database privileges"); + basics.AppendLine("โ€ข Poor error handling that reveals information\n"); + + basics.AppendLine("๐Ÿ›ก๏ธ Prevention Techniques:"); + basics.AppendLine("โœ… Use parameterized queries/prepared statements"); + basics.AppendLine("โœ… Implement input validation and sanitization"); + basics.AppendLine("โœ… Apply principle of least privilege"); + basics.AppendLine("โœ… Use stored procedures when appropriate"); + basics.AppendLine("โœ… Regular security testing and code reviews\n"); + + Console.WriteLine(basics.ToString()); + } + + private static void ShowBestPracticesGuide() { - Console.WriteLine("๐Ÿ“‹ Choose an option:"); - Console.WriteLine("1. Setup test users"); - Console.WriteLine("2. List users"); - Console.WriteLine("3. Test authentication"); - Console.WriteLine("4. Exit"); - Console.Write("Enter choice: "); + Console.WriteLine("\n๐Ÿ“– BEST PRACTICES & PREVENTION GUIDE"); + Console.WriteLine("======================================"); + + var guide = new StringBuilder(); + guide.AppendLine("๐Ÿ”’ Secure Coding Practices:"); + guide.AppendLine(); + guide.AppendLine("1. ๐Ÿ“ PARAMETERIZED QUERIES (Most Important!)"); + guide.AppendLine(" โŒ Bad: SELECT * FROM Users WHERE id = '" + "[userId]" + "'"); + guide.AppendLine(" โœ… Good: SELECT * FROM Users WHERE id = @userId"); + guide.AppendLine(); + guide.AppendLine("2. ๐Ÿงน INPUT VALIDATION"); + guide.AppendLine(" โ€ข Validate data type, length, format, and range"); + guide.AppendLine(" โ€ข Use allow-lists rather than block-lists"); + guide.AppendLine(" โ€ข Encode output appropriately"); + guide.AppendLine(); + guide.AppendLine("3. ๐Ÿ” DATABASE SECURITY"); + guide.AppendLine(" โ€ข Use least-privilege principle for database accounts"); + guide.AppendLine(" โ€ข Avoid using SA or administrative accounts"); + guide.AppendLine(" โ€ข Regular security updates and patches"); + guide.AppendLine(); + guide.AppendLine("4. ๐Ÿšจ ERROR HANDLING"); + guide.AppendLine(" โ€ข Don't expose database errors to users"); + guide.AppendLine(" โ€ข Log detailed errors securely for developers"); + guide.AppendLine(" โ€ข Use generic error messages for users"); + guide.AppendLine(); + guide.AppendLine("5. ๐Ÿ“Š MONITORING & LOGGING"); + guide.AppendLine(" โ€ข Log all database access attempts"); + guide.AppendLine(" โ€ข Monitor for suspicious patterns"); + guide.AppendLine(" โ€ข Implement real-time alerting"); + guide.AppendLine(); + guide.AppendLine("๐Ÿ” Testing Your Applications:"); + guide.AppendLine("โ€ข Use automated security scanning tools"); + guide.AppendLine("โ€ข Perform regular penetration testing"); + guide.AppendLine("โ€ข Conduct code reviews with security focus"); + guide.AppendLine("โ€ข Use this simulator for educational testing!"); + + Console.WriteLine(guide.ToString()); } } } \ No newline at end of file