883 lines
26 KiB
C#
Executable File
883 lines
26 KiB
C#
Executable File
using MarketAlly.AIPlugin;
|
||
using MarketAlly.AIPlugin.Security.Plugins;
|
||
using Microsoft.Extensions.DependencyInjection;
|
||
using Microsoft.Extensions.Logging;
|
||
using Microsoft.Extensions.Http;
|
||
using NuGet.Protocol.Plugins;
|
||
using System.Text.Json;
|
||
|
||
namespace MarketAlly.AIPlugin.Security.TestApp;
|
||
|
||
/// <summary>
|
||
/// Test console application for MarketAlly.AIPlugin.Security package
|
||
/// Demonstrates all security plugins with sample files and comprehensive testing
|
||
/// </summary>
|
||
class Program
|
||
{
|
||
private static AIPluginRegistry _registry;
|
||
private static ILogger<Program> _logger;
|
||
private static readonly string TestDataPath = Path.Combine(Directory.GetCurrentDirectory(), "TestData");
|
||
|
||
static async Task Main(string[] args)
|
||
{
|
||
Console.WriteLine("=".PadRight(80, '='));
|
||
Console.WriteLine("MarketAlly.AIPlugin.Security - Comprehensive Test Suite");
|
||
Console.WriteLine("=".PadRight(80, '='));
|
||
Console.WriteLine();
|
||
|
||
// Setup logging and services
|
||
SetupServices();
|
||
|
||
// Setup test environment
|
||
await SetupTestEnvironment();
|
||
|
||
// Register all security plugins
|
||
RegisterSecurityPlugins();
|
||
|
||
ShowMainMenu();
|
||
|
||
while (true)
|
||
{
|
||
Console.Write("Enter your choice (0-5): ");
|
||
var choice = Console.ReadLine();
|
||
|
||
try
|
||
{
|
||
switch (choice)
|
||
{
|
||
case "1":
|
||
await RunAllSecurityTests();
|
||
break;
|
||
case "2":
|
||
await RunIndividualPluginTests();
|
||
break;
|
||
case "3":
|
||
await RunQuickSecurityAudit();
|
||
break;
|
||
case "4":
|
||
await CreateSampleVulnerableFiles();
|
||
break;
|
||
case "5":
|
||
CleanupTestData();
|
||
break;
|
||
case "0":
|
||
break;
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.WriteLine($"❌ Error cleaning up test data: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
/// Test result container
|
||
/// </summary>
|
||
public class TestResult
|
||
{
|
||
public string PluginName { get; set; }
|
||
public bool Success { get; set; }
|
||
public string Message { get; set; }
|
||
public string Details { get; set; }
|
||
public DateTime ExecutionTime { get; set; }
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// Setup dependency injection and logging
|
||
/// </summary>
|
||
private static void SetupServices()
|
||
{
|
||
var services = new ServiceCollection();
|
||
|
||
// Add logging
|
||
services.AddLogging(builder =>
|
||
{
|
||
builder.AddConsole();
|
||
builder.SetMinimumLevel(LogLevel.Information);
|
||
});
|
||
|
||
// Add HTTP client for vulnerability analysis
|
||
services.AddHttpClient();
|
||
|
||
// Build service provider
|
||
var serviceProvider = services.BuildServiceProvider();
|
||
|
||
// Get logger
|
||
_logger = serviceProvider.GetRequiredService<ILogger<Program>>();
|
||
|
||
// Create plugin registry
|
||
_registry = new AIPluginRegistry(serviceProvider.GetRequiredService<ILogger<AIPluginRegistry>>());
|
||
}
|
||
|
||
/// <summary>
|
||
/// Register all security plugins
|
||
/// </summary>
|
||
private static void RegisterSecurityPlugins()
|
||
{
|
||
Console.WriteLine("📦 Registering Security Plugins...");
|
||
|
||
_registry.RegisterPlugin(new SecurityScanPlugin());
|
||
_registry.RegisterPlugin(new VulnerabilityAnalyzerPlugin());
|
||
_registry.RegisterPlugin(new InputValidationPlugin());
|
||
_registry.RegisterPlugin(new AuthenticationAnalyzerPlugin());
|
||
_registry.RegisterPlugin(new SecureConfigurationPlugin());
|
||
|
||
var pluginCount = _registry.GetAllPlugins().Count;
|
||
Console.WriteLine($"✅ Registered {pluginCount} security plugins successfully!");
|
||
Console.WriteLine();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Setup test environment with sample files
|
||
/// </summary>
|
||
private static async Task SetupTestEnvironment()
|
||
{
|
||
Console.WriteLine("🔧 Setting up test environment...");
|
||
|
||
// Create test data directory
|
||
if (!Directory.Exists(TestDataPath))
|
||
{
|
||
Directory.CreateDirectory(TestDataPath);
|
||
}
|
||
|
||
await CreateSampleVulnerableFiles();
|
||
Console.WriteLine("✅ Test environment ready!");
|
||
Console.WriteLine();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Show main menu
|
||
/// </summary>
|
||
private static void ShowMainMenu()
|
||
{
|
||
Console.WriteLine("🔐 Security Plugins Test Suite");
|
||
Console.WriteLine("Choose an option:");
|
||
Console.WriteLine("1. Run All Security Tests");
|
||
Console.WriteLine("2. Test Individual Plugins");
|
||
Console.WriteLine("3. Run Quick Security Audit");
|
||
Console.WriteLine("4. Create Sample Vulnerable Files");
|
||
Console.WriteLine("5. Cleanup Test Data");
|
||
Console.WriteLine("0. Exit");
|
||
Console.WriteLine();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Run comprehensive security tests for all plugins
|
||
/// </summary>
|
||
private static async Task RunAllSecurityTests()
|
||
{
|
||
Console.WriteLine("🚀 Running Comprehensive Security Test Suite");
|
||
Console.WriteLine("=".PadRight(60, '='));
|
||
|
||
var startTime = DateTime.Now;
|
||
var testResults = new List<TestResult>();
|
||
|
||
// Test 1: Security Scan
|
||
Console.WriteLine("\n1️⃣ Testing SecurityScanPlugin...");
|
||
var securityResult = await TestSecurityScanPlugin();
|
||
testResults.Add(securityResult);
|
||
|
||
// Test 2: Vulnerability Analysis
|
||
Console.WriteLine("\n2️⃣ Testing VulnerabilityAnalyzerPlugin...");
|
||
var vulnResult = await TestVulnerabilityAnalyzerPlugin();
|
||
testResults.Add(vulnResult);
|
||
|
||
// Test 3: Input Validation
|
||
Console.WriteLine("\n3️⃣ Testing InputValidationPlugin...");
|
||
var inputResult = await TestInputValidationPlugin();
|
||
testResults.Add(inputResult);
|
||
|
||
// Test 4: Authentication Analysis
|
||
Console.WriteLine("\n4️⃣ Testing AuthenticationAnalyzerPlugin...");
|
||
var authResult = await TestAuthenticationAnalyzerPlugin();
|
||
testResults.Add(authResult);
|
||
|
||
// Test 5: Configuration Security
|
||
Console.WriteLine("\n5️⃣ Testing SecureConfigurationPlugin...");
|
||
var configResult = await TestSecureConfigurationPlugin();
|
||
testResults.Add(configResult);
|
||
|
||
// Generate comprehensive report
|
||
var endTime = DateTime.Now;
|
||
await GenerateComprehensiveReport(testResults, startTime, endTime);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Run individual plugin tests with menu selection
|
||
/// </summary>
|
||
private static async Task RunIndividualPluginTests()
|
||
{
|
||
Console.WriteLine("🔍 Individual Plugin Testing");
|
||
Console.WriteLine("Select a plugin to test:");
|
||
Console.WriteLine("1. SecurityScan - Comprehensive security analysis");
|
||
Console.WriteLine("2. VulnerabilityAnalyzer - Dependency vulnerability scanning");
|
||
Console.WriteLine("3. InputValidation - Input validation security analysis");
|
||
Console.WriteLine("4. AuthenticationAnalyzer - Authentication/authorization review");
|
||
Console.WriteLine("5. SecureConfiguration - Configuration security validation");
|
||
Console.WriteLine("0. Back to main menu");
|
||
|
||
Console.Write("\nEnter your choice (0-5): ");
|
||
var choice = Console.ReadLine();
|
||
|
||
switch (choice)
|
||
{
|
||
case "1":
|
||
await TestSecurityScanPlugin(verbose: true);
|
||
break;
|
||
case "2":
|
||
await TestVulnerabilityAnalyzerPlugin(verbose: true);
|
||
break;
|
||
case "3":
|
||
await TestInputValidationPlugin(verbose: true);
|
||
break;
|
||
case "4":
|
||
await TestAuthenticationAnalyzerPlugin(verbose: true);
|
||
break;
|
||
case "5":
|
||
await TestSecureConfigurationPlugin(verbose: true);
|
||
break;
|
||
case "0":
|
||
return;
|
||
default:
|
||
Console.WriteLine("Invalid choice.");
|
||
break;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Run quick security audit on test files
|
||
/// </summary>
|
||
private static async Task RunQuickSecurityAudit()
|
||
{
|
||
Console.WriteLine("⚡ Quick Security Audit");
|
||
Console.WriteLine("=".PadRight(40, '='));
|
||
|
||
var issues = new List<string>();
|
||
|
||
// Quick scan with SecurityScanPlugin
|
||
var scanResult = await _registry.CallFunctionAsync("SecurityScan", new Dictionary<string, object>
|
||
{
|
||
["path"] = TestDataPath,
|
||
["severityLevel"] = "high"
|
||
});
|
||
|
||
if (scanResult.Success)
|
||
{
|
||
var scanData = JsonSerializer.Serialize(scanResult.Data, new JsonSerializerOptions { WriteIndented = true });
|
||
var scanObj = JsonSerializer.Deserialize<JsonElement>(scanData);
|
||
|
||
if (scanObj.TryGetProperty("secrets", out var secrets))
|
||
{
|
||
issues.Add($"🔑 {secrets.GetArrayLength()} secrets found");
|
||
}
|
||
|
||
if (scanObj.TryGetProperty("vulnerabilities", out var vulns))
|
||
{
|
||
issues.Add($"🛡️ {vulns.GetArrayLength()} vulnerabilities found");
|
||
}
|
||
}
|
||
|
||
// Quick config check
|
||
var configFiles = Directory.GetFiles(TestDataPath, "*.json", SearchOption.AllDirectories);
|
||
if (configFiles.Any())
|
||
{
|
||
var configResult = await _registry.CallFunctionAsync("SecureConfiguration", new Dictionary<string, object>
|
||
{
|
||
["configPath"] = configFiles.First()
|
||
});
|
||
|
||
if (configResult.Success)
|
||
{
|
||
var configData = JsonSerializer.Serialize(configResult.Data, new JsonSerializerOptions { WriteIndented = true });
|
||
var configObj = JsonSerializer.Deserialize<JsonElement>(configData);
|
||
|
||
if (configObj.TryGetProperty("exposedSecrets", out var exposedSecrets))
|
||
{
|
||
issues.Add($"⚙️ {exposedSecrets.GetArrayLength()} configuration secrets exposed");
|
||
}
|
||
}
|
||
}
|
||
|
||
// Display results
|
||
Console.WriteLine("📊 Quick Audit Results:");
|
||
Console.WriteLine($" • Files scanned: {Directory.GetFiles(TestDataPath, "*", SearchOption.AllDirectories).Length}");
|
||
|
||
if (issues.Any())
|
||
{
|
||
Console.WriteLine(" • Issues found:");
|
||
foreach (var issue in issues)
|
||
{
|
||
Console.WriteLine($" - {issue}");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine(" • ✅ No major security issues found");
|
||
}
|
||
|
||
Console.WriteLine("\n💡 Recommendations:");
|
||
Console.WriteLine(" • Run full security scan for detailed analysis");
|
||
Console.WriteLine(" • Check individual plugins for specific vulnerabilities");
|
||
Console.WriteLine(" • Review configuration files for hardcoded secrets");
|
||
}
|
||
|
||
/// <summary>
|
||
/// Test SecurityScanPlugin
|
||
/// </summary>
|
||
private static async Task<TestResult> TestSecurityScanPlugin(bool verbose = false)
|
||
{
|
||
if (verbose) Console.WriteLine("Testing SecurityScanPlugin with comprehensive analysis...");
|
||
|
||
var result = await _registry.CallFunctionAsync("SecurityScan", new Dictionary<string, object>
|
||
{
|
||
["path"] = TestDataPath,
|
||
["scanSecrets"] = true,
|
||
["scanSqlInjection"] = true,
|
||
["scanXss"] = true,
|
||
["scanConfigurations"] = true,
|
||
["severityLevel"] = "medium"
|
||
});
|
||
|
||
var testResult = new TestResult
|
||
{
|
||
PluginName = "SecurityScan",
|
||
Success = result.Success,
|
||
Message = result.Message,
|
||
ExecutionTime = DateTime.Now
|
||
};
|
||
|
||
if (result.Success)
|
||
{
|
||
if (verbose)
|
||
{
|
||
var data = JsonSerializer.Serialize(result.Data, new JsonSerializerOptions { WriteIndented = true });
|
||
var obj = JsonSerializer.Deserialize<JsonElement>(data);
|
||
|
||
Console.WriteLine("📊 Security Scan Results:");
|
||
if (obj.TryGetProperty("secrets", out var secrets))
|
||
{
|
||
Console.WriteLine($" 🔑 Secrets found: {secrets.GetArrayLength()}");
|
||
}
|
||
if (obj.TryGetProperty("vulnerabilities", out var vulns))
|
||
{
|
||
Console.WriteLine($" 🛡️ Vulnerabilities: {vulns.GetArrayLength()}");
|
||
}
|
||
if (obj.TryGetProperty("overallRisk", out var risk))
|
||
{
|
||
Console.WriteLine($" ⚠️ Risk Level: {risk.GetString()}");
|
||
}
|
||
}
|
||
|
||
testResult.Details = "SecurityScan completed successfully";
|
||
Console.WriteLine("✅ SecurityScan test passed");
|
||
}
|
||
else
|
||
{
|
||
testResult.Details = $"SecurityScan failed: {result.Message}";
|
||
Console.WriteLine($"❌ SecurityScan test failed: {result.Message}");
|
||
}
|
||
|
||
return testResult;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Test VulnerabilityAnalyzerPlugin
|
||
/// </summary>
|
||
private static async Task<TestResult> TestVulnerabilityAnalyzerPlugin(bool verbose = false)
|
||
{
|
||
if (verbose) Console.WriteLine("Testing VulnerabilityAnalyzerPlugin with sample project...");
|
||
|
||
var packageJsonPath = Path.Combine(TestDataPath, "package.json");
|
||
|
||
var result = await _registry.CallFunctionAsync("VulnerabilityAnalyzer", new Dictionary<string, object>
|
||
{
|
||
["projectPath"] = File.Exists(packageJsonPath) ? packageJsonPath : TestDataPath,
|
||
["includeTransitive"] = true,
|
||
["checkOutdated"] = true,
|
||
["vulnerabilitySource"] = "nvd",
|
||
["generateRecommendations"] = true
|
||
});
|
||
|
||
var testResult = new TestResult
|
||
{
|
||
PluginName = "VulnerabilityAnalyzer",
|
||
Success = result.Success,
|
||
Message = result.Message,
|
||
ExecutionTime = DateTime.Now
|
||
};
|
||
|
||
if (result.Success)
|
||
{
|
||
if (verbose)
|
||
{
|
||
var data = JsonSerializer.Serialize(result.Data, new JsonSerializerOptions { WriteIndented = true });
|
||
var obj = JsonSerializer.Deserialize<JsonElement>(data);
|
||
|
||
Console.WriteLine("📊 Vulnerability Analysis Results:");
|
||
if (obj.TryGetProperty("dependencies", out var deps))
|
||
{
|
||
Console.WriteLine($" 📦 Dependencies analyzed: {deps.GetArrayLength()}");
|
||
}
|
||
if (obj.TryGetProperty("vulnerablePackages", out var vulnPkgs))
|
||
{
|
||
Console.WriteLine($" 🚨 Vulnerable packages: {vulnPkgs.GetArrayLength()}");
|
||
}
|
||
if (obj.TryGetProperty("outdatedPackages", out var outdated))
|
||
{
|
||
Console.WriteLine($" 📅 Outdated packages: {outdated.GetArrayLength()}");
|
||
}
|
||
}
|
||
|
||
testResult.Details = "VulnerabilityAnalyzer completed successfully";
|
||
Console.WriteLine("✅ VulnerabilityAnalyzer test passed");
|
||
}
|
||
else
|
||
{
|
||
testResult.Details = $"VulnerabilityAnalyzer failed: {result.Message}";
|
||
Console.WriteLine($"❌ VulnerabilityAnalyzer test failed: {result.Message}");
|
||
}
|
||
|
||
return testResult;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Test InputValidationPlugin
|
||
/// </summary>
|
||
private static async Task<TestResult> TestInputValidationPlugin(bool verbose = false)
|
||
{
|
||
if (verbose) Console.WriteLine("Testing InputValidationPlugin with vulnerable code samples...");
|
||
|
||
var vulnerableFile = Path.Combine(TestDataPath, "VulnerableController.cs");
|
||
|
||
var result = await _registry.CallFunctionAsync("InputValidation", new Dictionary<string, object>
|
||
{
|
||
["filePath"] = vulnerableFile,
|
||
["checkSqlInjection"] = true,
|
||
["checkXssProtection"] = true,
|
||
["checkCsrfProtection"] = true,
|
||
["analyzeSanitization"] = true,
|
||
["generateSuggestions"] = true
|
||
});
|
||
|
||
var testResult = new TestResult
|
||
{
|
||
PluginName = "InputValidation",
|
||
Success = result.Success,
|
||
Message = result.Message,
|
||
ExecutionTime = DateTime.Now
|
||
};
|
||
|
||
if (result.Success)
|
||
{
|
||
if (verbose)
|
||
{
|
||
var data = JsonSerializer.Serialize(result.Data, new JsonSerializerOptions { WriteIndented = true });
|
||
var obj = JsonSerializer.Deserialize<JsonElement>(data);
|
||
|
||
Console.WriteLine("📊 Input Validation Results:");
|
||
if (obj.TryGetProperty("validationIssues", out var issues))
|
||
{
|
||
Console.WriteLine($" 🔍 Validation issues: {issues.GetArrayLength()}");
|
||
}
|
||
if (obj.TryGetProperty("securityScore", out var score))
|
||
{
|
||
Console.WriteLine($" 📊 Security score: {score.GetInt32()}/100");
|
||
}
|
||
if (obj.TryGetProperty("goodPractices", out var practices))
|
||
{
|
||
Console.WriteLine($" ✅ Good practices found: {practices.GetArrayLength()}");
|
||
}
|
||
}
|
||
|
||
testResult.Details = "InputValidation completed successfully";
|
||
Console.WriteLine("✅ InputValidation test passed");
|
||
}
|
||
else
|
||
{
|
||
testResult.Details = $"InputValidation failed: {result.Message}";
|
||
Console.WriteLine($"❌ InputValidation test failed: {result.Message}");
|
||
}
|
||
|
||
return testResult;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Test AuthenticationAnalyzerPlugin
|
||
/// </summary>
|
||
private static async Task<TestResult> TestAuthenticationAnalyzerPlugin(bool verbose = false)
|
||
{
|
||
if (verbose) Console.WriteLine("Testing AuthenticationAnalyzerPlugin with authentication code...");
|
||
|
||
var authFile = Path.Combine(TestDataPath, "AuthController.cs");
|
||
|
||
var result = await _registry.CallFunctionAsync("AuthenticationAnalyzer", new Dictionary<string, object>
|
||
{
|
||
["path"] = File.Exists(authFile) ? authFile : TestDataPath,
|
||
["checkJwt"] = true,
|
||
["checkOAuth"] = true,
|
||
["checkSessions"] = true,
|
||
["checkAuthorization"] = true,
|
||
["checkPasswords"] = true
|
||
});
|
||
|
||
var testResult = new TestResult
|
||
{
|
||
PluginName = "AuthenticationAnalyzer",
|
||
Success = result.Success,
|
||
Message = result.Message,
|
||
ExecutionTime = DateTime.Now
|
||
};
|
||
|
||
if (result.Success)
|
||
{
|
||
if (verbose)
|
||
{
|
||
var data = JsonSerializer.Serialize(result.Data, new JsonSerializerOptions { WriteIndented = true });
|
||
var obj = JsonSerializer.Deserialize<JsonElement>(data);
|
||
|
||
Console.WriteLine("📊 Authentication Analysis Results:");
|
||
if (obj.TryGetProperty("authenticationIssues", out var authIssues))
|
||
{
|
||
Console.WriteLine($" 🔐 Authentication issues: {authIssues.GetArrayLength()}");
|
||
}
|
||
if (obj.TryGetProperty("authorizationIssues", out var authzIssues))
|
||
{
|
||
Console.WriteLine($" 🛡️ Authorization issues: {authzIssues.GetArrayLength()}");
|
||
}
|
||
if (obj.TryGetProperty("complianceScore", out var compliance))
|
||
{
|
||
Console.WriteLine($" 📊 Compliance score: {compliance.GetInt32()}/100");
|
||
}
|
||
}
|
||
|
||
testResult.Details = "AuthenticationAnalyzer completed successfully";
|
||
Console.WriteLine("✅ AuthenticationAnalyzer test passed");
|
||
}
|
||
else
|
||
{
|
||
testResult.Details = $"AuthenticationAnalyzer failed: {result.Message}";
|
||
Console.WriteLine($"❌ AuthenticationAnalyzer test failed: {result.Message}");
|
||
}
|
||
|
||
return testResult;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Test SecureConfigurationPlugin
|
||
/// </summary>
|
||
private static async Task<TestResult> TestSecureConfigurationPlugin(bool verbose = false)
|
||
{
|
||
if (verbose) Console.WriteLine("Testing SecureConfigurationPlugin with configuration files...");
|
||
|
||
var configFile = Path.Combine(TestDataPath, "appsettings.json");
|
||
|
||
var result = await _registry.CallFunctionAsync("SecureConfiguration", new Dictionary<string, object>
|
||
{
|
||
["configPath"] = File.Exists(configFile) ? configFile : TestDataPath,
|
||
["checkSecrets"] = true,
|
||
["checkTls"] = true,
|
||
["checkDatabase"] = true,
|
||
["checkCors"] = true,
|
||
["checkEnvironments"] = true
|
||
});
|
||
|
||
var testResult = new TestResult
|
||
{
|
||
PluginName = "SecureConfiguration",
|
||
Success = result.Success,
|
||
Message = result.Message,
|
||
ExecutionTime = DateTime.Now
|
||
};
|
||
|
||
if (result.Success)
|
||
{
|
||
if (verbose)
|
||
{
|
||
var data = JsonSerializer.Serialize(result.Data, new JsonSerializerOptions { WriteIndented = true });
|
||
var obj = JsonSerializer.Deserialize<JsonElement>(data);
|
||
|
||
Console.WriteLine("📊 Configuration Security Results:");
|
||
if (obj.TryGetProperty("exposedSecrets", out var secrets))
|
||
{
|
||
Console.WriteLine($" 🔑 Exposed secrets: {secrets.GetArrayLength()}");
|
||
}
|
||
if (obj.TryGetProperty("securityIssues", out var issues))
|
||
{
|
||
Console.WriteLine($" ⚠️ Security issues: {issues.GetArrayLength()}");
|
||
}
|
||
if (obj.TryGetProperty("securityRating", out var rating))
|
||
{
|
||
Console.WriteLine($" 📊 Security rating: {rating.GetString()}");
|
||
}
|
||
}
|
||
|
||
testResult.Details = "SecureConfiguration completed successfully";
|
||
Console.WriteLine("✅ SecureConfiguration test passed");
|
||
}
|
||
else
|
||
{
|
||
testResult.Details = $"SecureConfiguration failed: {result.Message}";
|
||
Console.WriteLine($"❌ SecureConfiguration test failed: {result.Message}");
|
||
}
|
||
|
||
return testResult;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Create sample vulnerable files for testing
|
||
/// </summary>
|
||
private static async Task CreateSampleVulnerableFiles()
|
||
{
|
||
Console.WriteLine("📝 Creating sample vulnerable files for testing...");
|
||
|
||
// Create vulnerable C# controller
|
||
var controllerContent = @"using Microsoft.AspNetCore.Mvc;
|
||
using System.Data.SqlClient;
|
||
|
||
namespace TestApp.Controllers
|
||
{
|
||
public class VulnerableController : ControllerBase
|
||
{
|
||
private string connectionString = ""Server=localhost;Database=test;User=sa;Password=password123;"";
|
||
private string jwtSecret = ""mysecretkey"";
|
||
|
||
[HttpPost]
|
||
public IActionResult Login(string username, string password)
|
||
{
|
||
// SQL Injection vulnerability
|
||
string sql = ""SELECT * FROM Users WHERE Username = '"" + username + ""' AND Password = '"" + password + ""'"";
|
||
using var connection = new SqlConnection(connectionString);
|
||
// ... vulnerable code
|
||
|
||
return Ok();
|
||
}
|
||
|
||
[HttpGet]
|
||
public IActionResult GetUser(string id)
|
||
{
|
||
// XSS vulnerability
|
||
return Content(""<h1>User: "" + id + ""</h1>"", ""text/html"");
|
||
}
|
||
|
||
public string GetApiKey()
|
||
{
|
||
return ""sk_live_abcd1234567890abcdef1234567890ab""; // Hardcoded Stripe key
|
||
}
|
||
}
|
||
}";
|
||
|
||
await File.WriteAllTextAsync(Path.Combine(TestDataPath, "VulnerableController.cs"), controllerContent);
|
||
|
||
// Create vulnerable auth controller
|
||
var authContent = @"using Microsoft.AspNetCore.Mvc;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
|
||
namespace TestApp.Controllers
|
||
{
|
||
public class AuthController : ControllerBase
|
||
{
|
||
[HttpPost]
|
||
public IActionResult Authenticate(string password)
|
||
{
|
||
// Weak password hashing
|
||
var hash = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
|
||
|
||
// Hardcoded salt
|
||
string salt = ""fixedsalt123"";
|
||
|
||
return Ok();
|
||
}
|
||
|
||
public string GenerateJwtToken()
|
||
{
|
||
var secret = ""weak""; // Weak JWT secret
|
||
// JWT with no expiration and 'none' algorithm
|
||
return ""eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0..."";
|
||
}
|
||
}
|
||
}";
|
||
|
||
await File.WriteAllTextAsync(Path.Combine(TestDataPath, "AuthController.cs"), authContent);
|
||
|
||
// Create vulnerable configuration
|
||
var configContent = @"{
|
||
""ConnectionStrings"": {
|
||
""DefaultConnection"": ""Server=localhost;Database=MyApp;User Id=sa;Password=Admin123!;""
|
||
},
|
||
""JwtSettings"": {
|
||
""SecretKey"": ""MyJwtSecretKey123"",
|
||
""Issuer"": ""MyApp"",
|
||
""Audience"": ""MyAppUsers""
|
||
},
|
||
""ApiKeys"": {
|
||
""StripeKey"": ""sk_live_1234567890abcdef1234567890abcdef"",
|
||
""GoogleMapsKey"": ""AIzaSyBk7J8F5G2H9I3J4K5L6M7N8O9P0Q1R2S3T""
|
||
},
|
||
""Logging"": {
|
||
""LogLevel"": {
|
||
""Default"": ""Debug"",
|
||
""Microsoft"": ""Trace""
|
||
}
|
||
},
|
||
""Environment"": ""Development"",
|
||
""DebugMode"": true,
|
||
""DetailedErrors"": true,
|
||
""Cors"": {
|
||
""AllowedOrigins"": [""*""],
|
||
""AllowCredentials"": true
|
||
}
|
||
}";
|
||
|
||
await File.WriteAllTextAsync(Path.Combine(TestDataPath, "appsettings.json"), configContent);
|
||
|
||
// Create package.json with vulnerable dependencies
|
||
var packageContent = @"{
|
||
""name"": ""vulnerable-app"",
|
||
""version"": ""1.0.0"",
|
||
""dependencies"": {
|
||
""lodash"": ""4.17.15"",
|
||
""jquery"": ""3.4.1"",
|
||
""express"": ""4.16.0"",
|
||
""moment"": ""2.19.3""
|
||
},
|
||
""devDependencies"": {
|
||
""webpack"": ""4.29.0"",
|
||
""babel-core"": ""6.26.0""
|
||
}
|
||
}";
|
||
|
||
await File.WriteAllTextAsync(Path.Combine(TestDataPath, "package.json"), packageContent);
|
||
|
||
// Create project file
|
||
var projectContent = @"<Project Sdk=""Microsoft.NET.Sdk.Web"">
|
||
<PropertyGroup>
|
||
<TargetFramework>net6.0</TargetFramework>
|
||
</PropertyGroup>
|
||
|
||
<ItemGroup>
|
||
<PackageReference Include=""Microsoft.AspNetCore.Authentication.JwtBearer"" Version=""6.0.0"" />
|
||
<PackageReference Include=""System.Data.SqlClient"" Version=""4.8.0"" />
|
||
<PackageReference Include=""Newtonsoft.Json"" Version=""12.0.1"" />
|
||
</ItemGroup>
|
||
</Project>";
|
||
|
||
await File.WriteAllTextAsync(Path.Combine(TestDataPath, "TestApp.csproj"), projectContent);
|
||
|
||
Console.WriteLine($"✅ Created sample vulnerable files in: {TestDataPath}");
|
||
Console.WriteLine(" • VulnerableController.cs - SQL injection, XSS, hardcoded secrets");
|
||
Console.WriteLine(" • AuthController.cs - Weak authentication, JWT issues");
|
||
Console.WriteLine(" • appsettings.json - Configuration secrets, insecure settings");
|
||
Console.WriteLine(" • package.json - Vulnerable Node.js dependencies");
|
||
Console.WriteLine(" • TestApp.csproj - .NET project file");
|
||
}
|
||
|
||
/// <summary>
|
||
/// Generate comprehensive test report
|
||
/// </summary>
|
||
private static async Task GenerateComprehensiveReport(List<TestResult> results, DateTime startTime, DateTime endTime)
|
||
{
|
||
Console.WriteLine("\n" + "=".PadRight(80, '='));
|
||
Console.WriteLine("📊 COMPREHENSIVE SECURITY TEST REPORT");
|
||
Console.WriteLine("=".PadRight(80, '='));
|
||
|
||
var duration = endTime - startTime;
|
||
var successCount = results.Count(r => r.Success);
|
||
var failCount = results.Count(r => !r.Success);
|
||
|
||
Console.WriteLine($"🕒 Execution Time: {duration.TotalSeconds:F2} seconds");
|
||
Console.WriteLine($"✅ Successful Tests: {successCount}/{results.Count}");
|
||
Console.WriteLine($"❌ Failed Tests: {failCount}/{results.Count}");
|
||
Console.WriteLine($"📈 Success Rate: {(successCount * 100.0 / results.Count):F1}%");
|
||
Console.WriteLine();
|
||
|
||
Console.WriteLine("📋 Test Results Summary:");
|
||
Console.WriteLine("-".PadRight(60, '-'));
|
||
|
||
foreach (var result in results)
|
||
{
|
||
var status = result.Success ? "✅ PASS" : "❌ FAIL";
|
||
Console.WriteLine($"{status} | {result.PluginName,-20} | {result.Details}");
|
||
}
|
||
|
||
Console.WriteLine();
|
||
Console.WriteLine("🔐 Security Analysis Summary:");
|
||
Console.WriteLine("-".PadRight(60, '-'));
|
||
Console.WriteLine("The security plugins have been tested with intentionally vulnerable");
|
||
Console.WriteLine("sample files to ensure they can detect common security issues:");
|
||
Console.WriteLine();
|
||
Console.WriteLine("• SQL Injection vulnerabilities");
|
||
Console.WriteLine("• Cross-Site Scripting (XSS) flaws");
|
||
Console.WriteLine("• Hardcoded secrets and API keys");
|
||
Console.WriteLine("• Weak authentication mechanisms");
|
||
Console.WriteLine("• Insecure configuration settings");
|
||
Console.WriteLine("• Vulnerable dependencies");
|
||
Console.WriteLine();
|
||
|
||
if (successCount == results.Count)
|
||
{
|
||
Console.WriteLine("🎉 ALL TESTS PASSED! The security plugin suite is working correctly.");
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine("⚠️ Some tests failed. Please review the error messages above.");
|
||
}
|
||
|
||
// Save detailed report to file
|
||
var reportPath = Path.Combine(TestDataPath, $"SecurityTestReport_{DateTime.Now:yyyyMMdd_HHmmss}.json");
|
||
var reportData = new
|
||
{
|
||
Timestamp = DateTime.Now,
|
||
Duration = duration.TotalSeconds,
|
||
TestResults = results,
|
||
Summary = new
|
||
{
|
||
TotalTests = results.Count,
|
||
Successful = successCount,
|
||
Failed = failCount,
|
||
SuccessRate = successCount * 100.0 / results.Count
|
||
}
|
||
};
|
||
|
||
var reportJson = JsonSerializer.Serialize(reportData, new JsonSerializerOptions { WriteIndented = true });
|
||
await File.WriteAllTextAsync(reportPath, reportJson);
|
||
|
||
Console.WriteLine($"📄 Detailed report saved to: {reportPath}");
|
||
}
|
||
|
||
/// <summary>
|
||
/// Cleanup test data
|
||
/// </summary>
|
||
private static void CleanupTestData()
|
||
{
|
||
Console.WriteLine("🧹 Cleaning up test data...");
|
||
|
||
try
|
||
{
|
||
if (Directory.Exists(TestDataPath))
|
||
{
|
||
Directory.Delete(TestDataPath, true);
|
||
Console.WriteLine("✅ Test data cleaned up successfully!");
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine("Goodbye!");
|
||
return;
|
||
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.WriteLine($"❌ Error: {ex.Message}");
|
||
_logger.LogError(ex, "Test execution failed");
|
||
}
|
||
|
||
Console.WriteLine("\nPress any key to continue...");
|
||
Console.ReadKey();
|
||
Console.Clear();
|
||
ShowMainMenu();
|
||
}
|
||
} |