Build an educational simulator in pure C# + SQL that demonstrates:
- How SQL Injection vulnerabilities work conceptually
- How malicious inputs can alter database queries
- How to detect, log, and defend against such attacks
- Best practices for secure database programming
/SQLInjectionSimulator
βββ Program.cs # Main console application entry point
βββ SQLInjectionSimulator.csproj # Project configuration
βββ Database/
β βββ schema.sql # Database table definitions
β βββ seed.sql # Initial test data
βββ Modules/
β βββ UserManager.cs # User creation & authentication
β βββ LoginSimulator.cs # Login attempt simulation
β βββ InjectionTester.cs # Vulnerability demonstration
β βββ DefenseEngine.cs # Attack detection & prevention
β βββ Reporter.cs # Results analysis & reporting
βββ copilot-instruction.md # This guide
-- User accounts for testing authentication
CREATE TABLE Users (
UserId INT PRIMARY KEY IDENTITY(1,1),
Username NVARCHAR(50) UNIQUE NOT NULL,
PasswordHash NVARCHAR(255) NOT NULL,
CreatedDate DATETIME DEFAULT GETDATE(),
IsActive BIT DEFAULT 1
);
-- Track all login attempts (normal and malicious)
CREATE TABLE LoginAttempts (
AttemptId INT PRIMARY KEY IDENTITY(1,1),
Username NVARCHAR(255), -- Might contain injection payloads
AttemptTime DATETIME DEFAULT GETDATE(),
InputPayload NVARCHAR(MAX), -- Raw input received
IsSuccessful BIT NOT NULL,
IsInjection BIT DEFAULT 0, -- Detected as injection attempt
IpAddress NVARCHAR(45) DEFAULT '127.0.0.1',
UserAgent NVARCHAR(255) DEFAULT 'SQLInjectionSimulator'
);
-- Security alerts and anomalies
CREATE TABLE Alerts (
AlertId INT PRIMARY KEY IDENTITY(1,1),
Username NVARCHAR(255),
AlertTime DATETIME DEFAULT GETDATE(),
AlertType NVARCHAR(100) NOT NULL, -- e.g., 'SQL_INJECTION', 'BRUTE_FORCE'
Severity NVARCHAR(20) DEFAULT 'MEDIUM', -- LOW, MEDIUM, HIGH, CRITICAL
Details NVARCHAR(MAX),
IsResolved BIT DEFAULT 0
);Purpose: Secure user management and authentication
// Key functionalities:
- CreateTestUsers() : void
- HashPassword(string password) : string
- VerifyPassword(string password, string hash) : bool
- AuthenticateUser(string username, string password) : bool
- GetUserByUsername(string username) : UserSecurity Features:
- Parameterized queries only
- BCrypt password hashing
- Input sanitization
Purpose: Generate realistic login scenarios
// Key functionalities:
- GenerateNormalAttempts(int count) : List<LoginAttempt>
- GenerateInjectionAttempts(int count) : List<LoginAttempt>
- SimulateUserBehavior() : void
- LogAttempt(LoginAttempt attempt) : voidSimulation Types:
- Valid user credentials
- Invalid passwords
- Non-existent usernames
- Common injection patterns (educational only)
Purpose: Demonstrate vulnerability vs. protection
// Key functionalities:
- DemonstrateVulnerableQuery(string input) : void
- DemonstrateSecureQuery(string input) : void
- CompareQueryResults(string input) : void
- ShowQueryExecution(string query) : voidEducational Demonstrations:
- String concatenation vulnerabilities
- Parameterized query protection
- Query execution logging
- Result comparison
Purpose: Attack detection and prevention
// Key functionalities:
- ScanForSqlInjection(string input) : bool
- DetectBruteForcePattern(string username) : bool
- AnalyzeLoginPatterns() : void
- TriggerAlert(string type, string details) : void
- BlockSuspiciousActivity(string username) : voidDetection Patterns:
- SQL keywords (
OR,AND,UNION,SELECT, etc.) - Comment markers (
--,/*,*/) - Quote manipulation (
',") - Multiple failed attempts
- Unusual timing patterns
Purpose: Analysis and reporting
// Key functionalities:
- GenerateSummaryReport() : void
- ExportToCSV(string filename) : void
- DisplaySecurityMetrics() : void
- ShowTopAttackPatterns() : void
- GenerateRecommendations() : voidReport Sections:
- Attack attempt statistics
- Security alerts summary
- Most common injection patterns
- Defense effectiveness metrics
- Security recommendations
// SECURE - Parameterized Query
string query = "SELECT * FROM Users WHERE Username = @username AND PasswordHash = @password";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", passwordHash);
// Execute safely...
}// Validate and sanitize inputs
public bool IsValidInput(string input)
{
if (string.IsNullOrEmpty(input)) return false;
if (input.Length > 50) return false;
// Check for suspicious patterns
string[] suspiciousPatterns = { "'", "\"", "--", "/*", "*/", "xp_", "sp_" };
return !suspiciousPatterns.Any(pattern => input.Contains(pattern, StringComparison.OrdinalIgnoreCase));
}-- Create restricted database user for application
CREATE LOGIN simulator_user WITH PASSWORD = 'SecurePassword123!';
CREATE USER simulator_user FOR LOGIN simulator_user;
-- Grant minimal necessary permissions
GRANT SELECT, INSERT ON LoginAttempts TO simulator_user;
GRANT SELECT ON Users TO simulator_user;
GRANT INSERT ON Alerts TO simulator_user;
-- NO DELETE, DROP, or administrative permissions// Log all activities for analysis
public void LogSecurityEvent(string eventType, string details, string severity = "MEDIUM")
{
string query = @"INSERT INTO Alerts (AlertType, Details, Severity, AlertTime)
VALUES (@type, @details, @severity, @time)";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("@type", eventType);
cmd.Parameters.AddWithValue("@details", details);
cmd.Parameters.AddWithValue("@severity", severity);
cmd.Parameters.AddWithValue("@time", DateTime.Now);
cmd.ExecuteNonQuery();
}
}- Database Creation: Execute
schema.sqlandseed.sql - User Setup: Create test accounts (
admin,user1,guest,testuser) - Initialize Modules: Configure defense engine and reporter
- Normal Activity: 15 legitimate login attempts (mix of success/failure)
- Attack Patterns: 10 injection-style attempts with educational payloads
- Brute Force: 5 rapid-fire attempts on same account
- Advanced Patterns: Complex injection attempts
=== SQL INJECTION SIMULATOR REPORT ===
Simulation Duration: 45 seconds
Total Login Attempts: 30
βββ Successful Logins: 8
βββ Failed Logins: 22
βββ Detected Injections: 12
βββ Security Alerts: 5
=== SECURITY ANALYSIS ===
Most Common Attack Patterns:
1. ' OR '1'='1 (5 attempts)
2. admin'-- (3 attempts)
3. ' UNION SELECT (2 attempts)
Defense Effectiveness: 95.2%
Recommended Actions:
- Account lockout after 3 failed attempts
- Enhanced monitoring for user 'admin'
- Consider implementing CAPTCHA
- Machine learning pattern recognition
- Behavioral analysis algorithms
- Geographic location tracking
- Time-based anomaly detection
- Distributed attack patterns
- Session hijacking scenarios
- Cross-site scripting (XSS) integration
- Advanced persistent threat (APT) simulation
- Interactive web dashboard
- Real-time monitoring
- Export to multiple formats (PDF, Excel, JSON)
- Integration with SIEM systems
- Step-by-step attack explanations
- Interactive tutorials
- Code comparison tools
- Best practice recommendations
- Use Repository Pattern for data access
- Implement dependency injection for modularity
- Apply SOLID principles throughout
- Include comprehensive unit tests
- Never store real credentials in code
- Use configuration files for sensitive data
- Implement proper exception handling
- Follow secure coding practices
- Use stored procedures for complex operations
- Implement database triggers for auditing
- Apply proper indexing for performance
- Design for horizontal scaling
try
{
// Database operations
}
catch (SqlException ex)
{
// Log security-relevant database errors
LogSecurityEvent("DATABASE_ERROR", ex.Message, "HIGH");
// Don't expose sensitive information to user
Console.WriteLine("Database operation failed. Check logs for details.");
}
catch (Exception ex)
{
// Handle unexpected errors gracefully
LogSecurityEvent("SYSTEM_ERROR", ex.Message, "MEDIUM");
Console.WriteLine("An unexpected error occurred.");
}- Detection Rate: Percentage of injection attempts identified
- False Positive Rate: Normal queries flagged as malicious
- Response Time: Average time to detect and respond to threats
- System Throughput: Queries processed per second
- Resource Utilization: CPU, memory, and database usage
- Detection Rate: > 95%
- False Positive Rate: < 2%
- Response Time: < 100ms
- System Throughput: > 1000 qps
- Memory Usage: < 100MB
By completing this project, developers will understand:
- How injection attacks work technically
- Common attack vectors and payloads
- Business impact of successful attacks
- Legal and ethical considerations
- Parameterized query implementation
- Input validation and sanitization
- Proper error handling and logging
- Least privilege access control
- Defense-in-depth strategies
- Threat detection and response
- Security monitoring and alerting
- Incident response procedures
- OWASP Top 10 compliance
- Data protection requirements
- Security auditing standards
- Industry best practices
This simulator is designed exclusively for educational purposes to:
- Teach secure programming practices
- Demonstrate vulnerability concepts safely
- Train security professionals
- Support cybersecurity research
DO NOT use this tool to:
- Attack real systems or applications
- Test security without explicit permission
- Harm individuals, organizations, or systems
- Violate any laws or regulations
If you discover real vulnerabilities during your learning:
- Report them through proper channels
- Follow responsible disclosure practices
- Protect sensitive information
- Respect affected organizations
- OWASP SQL Injection Prevention Cheat Sheet
- NIST Cybersecurity Framework
- ISO 27001 Information Security Management
- Follow C# naming conventions
- Include XML documentation for all public members
- Maintain minimum 80% code coverage
- Pass all security static analysis checks
- All code changes require security review
- Threat modeling for new features
- Penetration testing before releases
- Regular dependency security audits
- Update this instruction file for major changes
- Maintain comprehensive API documentation
- Include security considerations in all docs
- Provide clear setup instructions
Remember: The goal is to build a comprehensive educational tool that helps developers understand SQL injection attacks and defenses in a safe, controlled environment. Focus on clear explanations, robust security implementations, and practical learning outcomes.
Happy coding! π