Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions src/webapp01/Pages/DevSecOps.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
@page
@model DevSecOpsModel
@{
ViewData["Title"] = "DevSecOps with GitHub Advanced Security";
}

<div class="container">
<div class="row">
<div class="col-12">
<h1 class="display-4 text-primary">@ViewData["Title"]</h1>
<p class="lead">Discover the latest features and capabilities of GitHub Advanced Security (GHAS)</p>
<hr />
</div>
</div>

<!-- Alert for TempData messages -->
@if (TempData["RegexResult"] != null)
{
<div class="alert alert-info alert-dismissible fade show" role="alert">
@TempData["RegexResult"]
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
}

@if (TempData["RegexError"] != null)
{
<div class="alert alert-danger alert-dismissible fade show" role="alert">
@TempData["RegexError"]
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
}

<div class="row">
<!-- Latest GHAS News Section -->
<div class="col-lg-8">
<div class="card mb-4">
<div class="card-header bg-dark text-white">
<h3 class="card-title mb-0">
<i class="bi bi-shield-check"></i> Latest GitHub Advanced Security News
</h3>
</div>
<div class="card-body">
@if (Model.LatestNews.Any())
{
<div class="list-group list-group-flush">
@foreach (var newsItem in Model.LatestNews)
{
<div class="list-group-item d-flex align-items-start">
<span class="badge bg-success rounded-pill me-3 mt-1">NEW</span>
<div>
<p class="mb-1">@newsItem</p>
<small class="text-muted">Updated: @DateTime.Now.ToString("MMM dd, yyyy")</small>
</div>
</div>
}
</div>
}
else
{
<p class="text-muted">No news available at this time.</p>
}
</div>
</div>

<!-- GHAS Features Overview -->
<div class="card mb-4">
<div class="card-header bg-primary text-white">
<h3 class="card-title mb-0">Core GHAS Features</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<h5><i class="bi bi-search"></i> Code Scanning</h5>
<p>Automated vulnerability detection using CodeQL semantic analysis engine.</p>

<h5><i class="bi bi-key"></i> Secret Scanning</h5>
<p>Detect and prevent secrets from being committed to repositories.</p>
</div>
<div class="col-md-6">
<h5><i class="bi bi-layers"></i> Dependency Review</h5>
<p>Understand security impact of dependency changes in pull requests.</p>

<h5><i class="bi bi-graph-up"></i> Security Overview</h5>
<p>Organization-wide security posture visibility and compliance tracking.</p>
</div>
</div>
</div>
</div>
</div>

<!-- Sidebar with Demo Tools -->
<div class="col-lg-4">
<!-- Security Demo Section -->
<div class="card mb-4">
<div class="card-header bg-warning text-dark">
<h4 class="card-title mb-0">
<i class="bi bi-exclamation-triangle"></i> Security Demo
</h4>
</div>
<div class="card-body">
<p class="text-muted small">
This page contains intentionally vulnerable code for demonstration purposes.
These vulnerabilities should be detected by GHAS code scanning.
</p>

<!-- Regex Testing Form -->
<form method="post" asp-page-handler="TestRegex" class="mt-3">
<div class="mb-3">
<label for="pattern" class="form-label">Test Regex Pattern:</label>
<input type="text" class="form-control" id="pattern" name="pattern"
placeholder="Enter pattern (e.g., aaa)" value="aaa">
<div class="form-text">
⚠️ This uses a vulnerable regex pattern susceptible to ReDoS attacks.
</div>
</div>
<button type="submit" class="btn btn-warning btn-sm">
<i class="bi bi-play"></i> Test Pattern
</button>
</form>
</div>
</div>

<!-- Quick Links -->
<div class="card">
<div class="card-header bg-info text-white">
<h4 class="card-title mb-0">Quick Links</h4>
</div>
<div class="card-body">
<div class="d-grid gap-2">
<a href="https://docs.github.com/en/code-security" class="btn btn-outline-primary btn-sm" target="_blank">
<i class="bi bi-book"></i> GHAS Documentation
</a>
<a href="https://github.com/github/codeql" class="btn btn-outline-secondary btn-sm" target="_blank">
<i class="bi bi-github"></i> CodeQL Repository
</a>
<a href="https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/about-code-scanning" class="btn btn-outline-success btn-sm" target="_blank">
<i class="bi bi-shield-check"></i> Code Scanning Guide
</a>
<a href="https://docs.github.com/en/code-security/secret-scanning" class="btn btn-outline-warning btn-sm" target="_blank">
<i class="bi bi-key"></i> Secret Scanning
</a>
</div>
</div>
</div>
</div>
</div>

<!-- Footer Section -->
<div class="row mt-5">
<div class="col-12">
<div class="alert alert-light" role="alert">
<h5 class="alert-heading">
<i class="bi bi-lightbulb"></i> Pro Tip:
</h5>
<p>
Enable GitHub Advanced Security on your repositories to automatically detect the
security vulnerabilities demonstrated in this page's source code. GHAS will identify
issues like hardcoded credentials, vulnerable regex patterns, and potential log injection attacks.
</p>
<hr>
<p class="mb-0">
Learn more about implementing a comprehensive DevSecOps strategy with
<a href="https://github.com/features/security" target="_blank">GitHub Advanced Security</a>.
</p>
</div>
</div>
</div>
</div>

@section Scripts {
<script>
// Simple script to auto-dismiss alerts after 5 seconds
setTimeout(function() {
const alerts = document.querySelectorAll('.alert-dismissible');
alerts.forEach(alert => {
const bsAlert = new bootstrap.Alert(alert);
bsAlert.close();
});
}, 5000);
</script>
}
105 changes: 105 additions & 0 deletions src/webapp01/Pages/DevSecOps.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text.RegularExpressions;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using System.Text.Json;

namespace webapp01.Pages
{
public class DevSecOpsModel : PageModel
{
private readonly ILogger<DevSecOpsModel> _logger;

// Hardcoded credentials for demo purposes - INSECURE
private const string CONNECTION_STRING = "Server=localhost;Database=TestDB;User Id=admin;Password=SecretPassword123!;";

// Weak regex pattern - vulnerable to ReDoS
private static readonly Regex VulnerableRegex = new Regex(@"^(a+)+$", RegexOptions.Compiled);
Copy link

Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The regex pattern is vulnerable to ReDoS attacks; confirm that this insecure implementation remains only in demo environments.

Suggested change
private static readonly Regex VulnerableRegex = new Regex(@"^(a+)+$", RegexOptions.Compiled);
private static readonly Regex SecureRegex = new Regex(@"^a+$", RegexOptions.Compiled);

Copilot uses AI. Check for mistakes.

public DevSecOpsModel(ILogger<DevSecOpsModel> logger)
{
_logger = logger;
}

public List<string> LatestNews { get; set; } = new(); public void OnGet()
{
// Log forging vulnerability - user input directly in logs
string userInput = Request.Query.ContainsKey("user") ? Request.Query["user"].ToString() ?? "anonymous" : "anonymous";

Check notice

Code scanning / CodeQL

Inefficient use of ContainsKey Note

Inefficient use of 'ContainsKey' and
indexer
.

Copilot Autofix

AI 6 months ago

To fix the issue, replace the ContainsKey check and subsequent dictionary access with a single call to TryGetValue. This will combine the key existence check and value retrieval into one operation, improving efficiency. Specifically:

  • Replace Request.Query.ContainsKey("user") ? Request.Query["user"].ToString() ?? "anonymous" : "anonymous" with a TryGetValue call that retrieves the value if the key exists or defaults to "anonymous" otherwise.

Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -27,3 +27,3 @@
             // Log forging vulnerability - user input directly in logs
-            string userInput = Request.Query.ContainsKey("user") ? Request.Query["user"].ToString() ?? "anonymous" : "anonymous";
+            string userInput = Request.Query.TryGetValue("user", out var userValue) ? userValue.ToString() ?? "anonymous" : "anonymous";
             _logger.LogInformation($"User accessed DevSecOps page: {userInput}");
EOF
@@ -27,3 +27,3 @@
// Log forging vulnerability - user input directly in logs
string userInput = Request.Query.ContainsKey("user") ? Request.Query["user"].ToString() ?? "anonymous" : "anonymous";
string userInput = Request.Query.TryGetValue("user", out var userValue) ? userValue.ToString() ?? "anonymous" : "anonymous";
_logger.LogInformation($"User accessed DevSecOps page: {userInput}");
Copilot is powered by AI and may make mistakes. Always verify output.
_logger.LogInformation($"User accessed DevSecOps page: {userInput}");

Check failure

Code scanning / CodeQL

Log entries created from user input High

This log entry depends on a
user-provided value
.

Copilot Autofix

AI 6 months ago

To fix the issue, sanitize the userInput variable before logging it. Since the logs are plain text, remove newline characters and other potentially harmful characters from the user input using String.Replace or similar methods. This ensures that malicious input cannot forge log entries or cause confusion.

The fix involves:

  1. Replacing newline characters (\r\n, \n, \r) in userInput with an empty string.
  2. Optionally, encoding or escaping other special characters to further reduce the risk of log manipulation.
Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -28,2 +28,3 @@
             string userInput = Request.Query.ContainsKey("user") ? Request.Query["user"].ToString() ?? "anonymous" : "anonymous";
+            userInput = userInput.Replace("\r", "").Replace("\n", "").Replace(Environment.NewLine, "");
             _logger.LogInformation($"User accessed DevSecOps page: {userInput}");
@@ -38,2 +39,3 @@
                 bool isMatch = VulnerableRegex.IsMatch(testPattern);
+                testPattern = testPattern.Replace("\r", "").Replace("\n", "").Replace(Environment.NewLine, "");
                 _logger.LogInformation($"Regex pattern match result: {isMatch} for input: {testPattern}");
@@ -43,2 +45,3 @@
                 // Log forging in exception handling
+                testPattern = testPattern.Replace("\r", "").Replace("\n", "").Replace(Environment.NewLine, "");
                 _logger.LogError($"Regex evaluation failed for pattern: {testPattern}. Error: {ex.Message}");
@@ -86,2 +89,3 @@
             // Log forging vulnerability in POST handler
+            pattern = pattern.Replace("\r", "").Replace("\n", "").Replace(Environment.NewLine, "");
             _logger.LogInformation($"Testing regex pattern submitted by user: {pattern}");
EOF
@@ -28,2 +28,3 @@
string userInput = Request.Query.ContainsKey("user") ? Request.Query["user"].ToString() ?? "anonymous" : "anonymous";
userInput = userInput.Replace("\r", "").Replace("\n", "").Replace(Environment.NewLine, "");
_logger.LogInformation($"User accessed DevSecOps page: {userInput}");
@@ -38,2 +39,3 @@
bool isMatch = VulnerableRegex.IsMatch(testPattern);
testPattern = testPattern.Replace("\r", "").Replace("\n", "").Replace(Environment.NewLine, "");
_logger.LogInformation($"Regex pattern match result: {isMatch} for input: {testPattern}");
@@ -43,2 +45,3 @@
// Log forging in exception handling
testPattern = testPattern.Replace("\r", "").Replace("\n", "").Replace(Environment.NewLine, "");
_logger.LogError($"Regex evaluation failed for pattern: {testPattern}. Error: {ex.Message}");
@@ -86,2 +89,3 @@
// Log forging vulnerability in POST handler
pattern = pattern.Replace("\r", "").Replace("\n", "").Replace(Environment.NewLine, "");
_logger.LogInformation($"Testing regex pattern submitted by user: {pattern}");
Copilot is powered by AI and may make mistakes. Always verify output.
Copy link

Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logging user input directly may lead to log forging; ensure that this practice is strictly confined to the controlled demo context.

Suggested change
_logger.LogInformation($"User accessed DevSecOps page: {userInput}");
string sanitizedUserInput = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(userInput);
_logger.LogInformation($"User accessed DevSecOps page: {sanitizedUserInput}");

Copilot uses AI. Check for mistakes.

// Simulate getting latest news about GitHub Advanced Security
LoadLatestGHASNews();

// Demonstrate potential ReDoS vulnerability
string testPattern = Request.Query.ContainsKey("pattern") ? Request.Query["pattern"].ToString() ?? "aaa" : "aaa";

Check notice

Code scanning / CodeQL

Inefficient use of ContainsKey Note

Inefficient use of 'ContainsKey' and
indexer
.

Copilot Autofix

AI 6 months ago

To fix the issue, replace the ContainsKey check and subsequent indexer access with a single call to the TryGetValue method. This will combine the key existence check and value retrieval into one operation, improving efficiency. Specifically, on line 35, replace the Request.Query.ContainsKey("pattern") check with a TryGetValue call, and handle the result accordingly.


Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -34,3 +34,3 @@
             // Demonstrate potential ReDoS vulnerability
-            string testPattern = Request.Query.ContainsKey("pattern") ? Request.Query["pattern"].ToString() ?? "aaa" : "aaa";
+            string testPattern = Request.Query.TryGetValue("pattern", out var patternValue) ? patternValue.ToString() ?? "aaa" : "aaa";
             try
EOF
@@ -34,3 +34,3 @@
// Demonstrate potential ReDoS vulnerability
string testPattern = Request.Query.ContainsKey("pattern") ? Request.Query["pattern"].ToString() ?? "aaa" : "aaa";
string testPattern = Request.Query.TryGetValue("pattern", out var patternValue) ? patternValue.ToString() ?? "aaa" : "aaa";
try
Copilot is powered by AI and may make mistakes. Always verify output.
try
{
bool isMatch = VulnerableRegex.IsMatch(testPattern);

Check failure

Code scanning / CodeQL

Denial of Service from comparison of user input against expensive regex High

This regex operation with dangerous complexity depends on a
user-provided value
.

Copilot Autofix

AI 6 months ago

To address the vulnerability, we will modify the regex operation to include a timeout. This ensures that the regex evaluation is canceled if it exceeds a specified duration, preventing the application from hanging indefinitely. The timeout will be set using the Regex constructor that accepts a TimeSpan parameter.

Additionally, we will replace the vulnerable regex pattern ^(a+)+$ with a safer alternative that avoids exponential worst-case complexity. If a safer alternative is not feasible, the timeout will serve as a fallback mitigation.

Changes will be made to:

  1. The definition of VulnerableRegex to include a timeout.
  2. The regex operations in both the OnGet and OnPostTestRegex methods to use the updated regex.
Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -17,3 +17,3 @@
         // Weak regex pattern - vulnerable to ReDoS
-        private static readonly Regex VulnerableRegex = new Regex(@"^(a+)+$", RegexOptions.Compiled);
+        private static readonly Regex VulnerableRegex = new Regex(@"^a+$", RegexOptions.Compiled, TimeSpan.FromSeconds(1));
 
@@ -37,3 +37,12 @@
             {
-                bool isMatch = VulnerableRegex.IsMatch(testPattern);
+                bool isMatch;
+                try
+                {
+                    isMatch = VulnerableRegex.IsMatch(testPattern);
+                }
+                catch (RegexMatchTimeoutException)
+                {
+                    _logger.LogWarning($"Regex evaluation timed out for input: {testPattern}");
+                    isMatch = false;
+                }
                 _logger.LogInformation($"Regex pattern match result: {isMatch} for input: {testPattern}");
@@ -91,3 +100,12 @@
                 // Vulnerable regex that could cause ReDoS
-                bool result = VulnerableRegex.IsMatch(pattern);
+                bool result;
+                try
+                {
+                    result = VulnerableRegex.IsMatch(pattern);
+                }
+                catch (RegexMatchTimeoutException)
+                {
+                    _logger.LogWarning($"Regex evaluation timed out for pattern: {pattern}");
+                    result = false;
+                }
                 TempData["RegexResult"] = $"Pattern '{pattern}' match result: {result}";
EOF
@@ -17,3 +17,3 @@
// Weak regex pattern - vulnerable to ReDoS
private static readonly Regex VulnerableRegex = new Regex(@"^(a+)+$", RegexOptions.Compiled);
private static readonly Regex VulnerableRegex = new Regex(@"^a+$", RegexOptions.Compiled, TimeSpan.FromSeconds(1));

@@ -37,3 +37,12 @@
{
bool isMatch = VulnerableRegex.IsMatch(testPattern);
bool isMatch;
try
{
isMatch = VulnerableRegex.IsMatch(testPattern);
}
catch (RegexMatchTimeoutException)
{
_logger.LogWarning($"Regex evaluation timed out for input: {testPattern}");
isMatch = false;
}
_logger.LogInformation($"Regex pattern match result: {isMatch} for input: {testPattern}");
@@ -91,3 +100,12 @@
// Vulnerable regex that could cause ReDoS
bool result = VulnerableRegex.IsMatch(pattern);
bool result;
try
{
result = VulnerableRegex.IsMatch(pattern);
}
catch (RegexMatchTimeoutException)
{
_logger.LogWarning($"Regex evaluation timed out for pattern: {pattern}");
result = false;
}
TempData["RegexResult"] = $"Pattern '{pattern}' match result: {result}";
Copilot is powered by AI and may make mistakes. Always verify output.
_logger.LogInformation($"Regex pattern match result: {isMatch} for input: {testPattern}");

Check failure

Code scanning / CodeQL

Log entries created from user input High

This log entry depends on a
user-provided value
.

Copilot Autofix

AI 6 months ago

To fix the issue, the user-provided input (testPattern) should be sanitized before being logged. Since the log is likely stored as plain text, newline characters and other control characters should be removed from the input. This can be achieved using String.Replace or a similar method. Additionally, the sanitized input should be clearly marked in the log message to prevent confusion.

The fix involves:

  1. Sanitizing the testPattern variable by removing newline characters and other control characters.
  2. Updating the log message on line 39 to use the sanitized version of testPattern.

Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -35,6 +35,7 @@
             string testPattern = Request.Query.ContainsKey("pattern") ? Request.Query["pattern"].ToString() ?? "aaa" : "aaa";
+            string sanitizedPattern = testPattern.Replace("\r", "").Replace("\n", "").Replace("\t", "");
             try
             {
-                bool isMatch = VulnerableRegex.IsMatch(testPattern);
-                _logger.LogInformation($"Regex pattern match result: {isMatch} for input: {testPattern}");
+                bool isMatch = VulnerableRegex.IsMatch(sanitizedPattern);
+                _logger.LogInformation($"Regex pattern match result: {isMatch} for sanitized input: {sanitizedPattern}");
             }
EOF
@@ -35,6 +35,7 @@
string testPattern = Request.Query.ContainsKey("pattern") ? Request.Query["pattern"].ToString() ?? "aaa" : "aaa";
string sanitizedPattern = testPattern.Replace("\r", "").Replace("\n", "").Replace("\t", "");
try
{
bool isMatch = VulnerableRegex.IsMatch(testPattern);
_logger.LogInformation($"Regex pattern match result: {isMatch} for input: {testPattern}");
bool isMatch = VulnerableRegex.IsMatch(sanitizedPattern);
_logger.LogInformation($"Regex pattern match result: {isMatch} for sanitized input: {sanitizedPattern}");
}
Copilot is powered by AI and may make mistakes. Always verify output.
}
catch (Exception ex)
{
// Log forging in exception handling
_logger.LogError($"Regex evaluation failed for pattern: {testPattern}. Error: {ex.Message}");

Check failure

Code scanning / CodeQL

Log entries created from user input High

This log entry depends on a
user-provided value
.

Copilot Autofix

AI 6 months ago

To fix the issue, the user-provided input (testPattern) should be sanitized before being included in the log message. Since the logs are plain text, we can remove newline characters and other potentially problematic characters from the input using String.Replace or similar methods. This ensures that the log entry cannot be manipulated by malicious input.

The fix involves:

  1. Sanitizing testPattern before it is used in the log message on line 44.
  2. Applying the same sanitization to other log messages that use testPattern (e.g., line 39).
Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -35,6 +35,7 @@
             string testPattern = Request.Query.ContainsKey("pattern") ? Request.Query["pattern"].ToString() ?? "aaa" : "aaa";
+            string sanitizedPattern = testPattern.Replace(Environment.NewLine, "").Replace("\r", "").Replace("\n", "");
             try
             {
-                bool isMatch = VulnerableRegex.IsMatch(testPattern);
-                _logger.LogInformation($"Regex pattern match result: {isMatch} for input: {testPattern}");
+                bool isMatch = VulnerableRegex.IsMatch(sanitizedPattern);
+                _logger.LogInformation($"Regex pattern match result: {isMatch} for input: {sanitizedPattern}");
             }
@@ -43,3 +44,3 @@
                 // Log forging in exception handling
-                _logger.LogError($"Regex evaluation failed for pattern: {testPattern}. Error: {ex.Message}");
+                _logger.LogError($"Regex evaluation failed for pattern: {sanitizedPattern}. Error: {ex.Message}");
             }
@@ -86,3 +87,4 @@
             // Log forging vulnerability in POST handler
-            _logger.LogInformation($"Testing regex pattern submitted by user: {pattern}");
+            string sanitizedPattern = pattern.Replace(Environment.NewLine, "").Replace("\r", "").Replace("\n", "");
+            _logger.LogInformation($"Testing regex pattern submitted by user: {sanitizedPattern}");
 
EOF
@@ -35,6 +35,7 @@
string testPattern = Request.Query.ContainsKey("pattern") ? Request.Query["pattern"].ToString() ?? "aaa" : "aaa";
string sanitizedPattern = testPattern.Replace(Environment.NewLine, "").Replace("\r", "").Replace("\n", "");
try
{
bool isMatch = VulnerableRegex.IsMatch(testPattern);
_logger.LogInformation($"Regex pattern match result: {isMatch} for input: {testPattern}");
bool isMatch = VulnerableRegex.IsMatch(sanitizedPattern);
_logger.LogInformation($"Regex pattern match result: {isMatch} for input: {sanitizedPattern}");
}
@@ -43,3 +44,3 @@
// Log forging in exception handling
_logger.LogError($"Regex evaluation failed for pattern: {testPattern}. Error: {ex.Message}");
_logger.LogError($"Regex evaluation failed for pattern: {sanitizedPattern}. Error: {ex.Message}");
}
@@ -86,3 +87,4 @@
// Log forging vulnerability in POST handler
_logger.LogInformation($"Testing regex pattern submitted by user: {pattern}");
string sanitizedPattern = pattern.Replace(Environment.NewLine, "").Replace("\r", "").Replace("\n", "");
_logger.LogInformation($"Testing regex pattern submitted by user: {sanitizedPattern}");

Copilot is powered by AI and may make mistakes. Always verify output.
}
Comment on lines +41 to +45

Check notice

Code scanning / CodeQL

Generic catch clause Note

Generic catch clause.

Copilot Autofix

AI 6 months ago

To fix the issue, we will replace the generic catch (Exception ex) block with specific exception types that are relevant to the regex operation. The most appropriate exception to catch here is RegexMatchTimeoutException, which occurs when a regex operation exceeds its timeout. This ensures that only anticipated exceptions are handled, and other unexpected exceptions are allowed to propagate.

Additionally, we will update the log message to avoid exposing sensitive information unnecessarily.


Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -40,6 +40,6 @@
             }
-            catch (Exception ex)
+            catch (RegexMatchTimeoutException ex)
             {
-                // Log forging in exception handling
-                _logger.LogError($"Regex evaluation failed for pattern: {testPattern}. Error: {ex.Message}");
+                // Log regex timeout error
+                _logger.LogError($"Regex evaluation timed out for pattern: {testPattern}. Error: {ex.Message}");
             }
@@ -94,7 +94,7 @@
             }
-            catch (Exception ex)
+            catch (RegexMatchTimeoutException ex)
             {
-                // Logging sensitive information
-                _logger.LogError($"Regex test failed for pattern: {pattern}. Exception: {ex}");
-                TempData["RegexError"] = "Pattern evaluation failed";
+                // Log regex timeout error
+                _logger.LogError($"Regex test timed out for pattern: {pattern}. Error: {ex.Message}");
+                TempData["RegexError"] = "Pattern evaluation timed out";
             }
EOF
@@ -40,6 +40,6 @@
}
catch (Exception ex)
catch (RegexMatchTimeoutException ex)
{
// Log forging in exception handling
_logger.LogError($"Regex evaluation failed for pattern: {testPattern}. Error: {ex.Message}");
// Log regex timeout error
_logger.LogError($"Regex evaluation timed out for pattern: {testPattern}. Error: {ex.Message}");
}
@@ -94,7 +94,7 @@
}
catch (Exception ex)
catch (RegexMatchTimeoutException ex)
{
// Logging sensitive information
_logger.LogError($"Regex test failed for pattern: {pattern}. Exception: {ex}");
TempData["RegexError"] = "Pattern evaluation failed";
// Log regex timeout error
_logger.LogError($"Regex test timed out for pattern: {pattern}. Error: {ex.Message}");
TempData["RegexError"] = "Pattern evaluation timed out";
}
Copilot is powered by AI and may make mistakes. Always verify output.

// Simulate database connection with hardcoded credentials
try
{
using var connection = new SqlConnection(CONNECTION_STRING);
_logger.LogInformation("Attempting database connection...");
// Don't actually open connection for demo purposes
}
catch (Exception ex)
{
_logger.LogError($"Database connection failed: {ex.Message}");
}
Comment on lines +54 to +57

Check notice

Code scanning / CodeQL

Generic catch clause Note

Generic catch clause.

Copilot Autofix

AI 6 months ago

To fix the issue, replace the generic catch clause catch (Exception ex) with a specific catch clause for SqlException, which is the most relevant exception type for database connection errors. This ensures that only database-related exceptions are caught and logged, while other exceptions are allowed to propagate. Additionally, if there is a need to handle other specific exceptions, they can be added as separate catch blocks.

Steps to implement the fix:

  1. Replace the generic catch (Exception ex) block with catch (SqlException ex).
  2. Ensure that the logging logic remains unchanged to log the details of the SqlException.

Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -53,3 +53,3 @@
             }
-            catch (Exception ex)
+            catch (SqlException ex)
             {
EOF
@@ -53,3 +53,3 @@
}
catch (Exception ex)
catch (SqlException ex)
{
Copilot is powered by AI and may make mistakes. Always verify output.
}

private void LoadLatestGHASNews()
{
LatestNews = new List<string>
{
"GitHub Advanced Security now supports enhanced code scanning with CodeQL 2.20",
"New secret scanning patterns added for over 200 service providers",
"Dependency review alerts now include detailed remediation guidance",
"Security advisories integration improved for better vulnerability management",
"Custom CodeQL queries can now be shared across organizations",
"AI-powered security suggestions available in GitHub Copilot for Security",
"New compliance frameworks supported in security overview dashboard",
"Enhanced SARIF support for third-party security tools integration"
};

// Potential JSON deserialization vulnerability
string jsonData = JsonConvert.SerializeObject(LatestNews);
Copy link

Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although used for demo purposes, consider validating JSON serialization/deserialization to prevent potential security issues in less controlled environments.

Copilot uses AI. Check for mistakes.
var deserializedData = JsonConvert.DeserializeObject<List<string>>(jsonData);

Check warning

Code scanning / CodeQL

Useless assignment to local variable Warning

This assignment to
deserializedData
is useless, since its value is never read.

Copilot Autofix

AI 6 months ago

To fix the issue, the assignment to deserializedData on line 76 should be removed entirely, as the variable is not used anywhere in the code. This will eliminate the unnecessary assignment and improve code clarity. The deserialization operation itself can also be removed unless it serves a purpose beyond assigning a value to deserializedData.


Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -75,3 +75,2 @@
             string jsonData = JsonConvert.SerializeObject(LatestNews);
-            var deserializedData = JsonConvert.DeserializeObject<List<string>>(jsonData);
             
EOF
@@ -75,3 +75,2 @@
string jsonData = JsonConvert.SerializeObject(LatestNews);
var deserializedData = JsonConvert.DeserializeObject<List<string>>(jsonData);

Copilot is powered by AI and may make mistakes. Always verify output.

_logger.LogInformation($"Loaded {LatestNews.Count} news items about GitHub Advanced Security");
}

public IActionResult OnPostTestRegex(string pattern)
{
if (string.IsNullOrEmpty(pattern))
return BadRequest("Pattern cannot be empty");

// Log forging vulnerability in POST handler
_logger.LogInformation($"Testing regex pattern submitted by user: {pattern}");

try
{
// Vulnerable regex that could cause ReDoS
bool result = VulnerableRegex.IsMatch(pattern);
TempData["RegexResult"] = $"Pattern '{pattern}' match result: {result}";
}
catch (Exception ex)
{
// Logging sensitive information
_logger.LogError($"Regex test failed for pattern: {pattern}. Exception: {ex}");
Comment on lines +97 to +98
Copy link

Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logging detailed exception data alongside user input might expose sensitive information; consider masking details in production logs.

Suggested change
// Logging sensitive information
_logger.LogError($"Regex test failed for pattern: {pattern}. Exception: {ex}");
// Log a generic error message without exposing sensitive details
_logger.LogError("Regex test failed due to an unexpected error.");

Copilot uses AI. Check for mistakes.
TempData["RegexError"] = "Pattern evaluation failed";
}
Comment on lines +95 to +100

Check notice

Code scanning / CodeQL

Generic catch clause Note

Generic catch clause.

Copilot Autofix

AI 6 months ago

To fix the issue, the generic catch (Exception ex) clause should be replaced with specific exception types that are relevant to the regex operation. In this case, the RegexMatchTimeoutException is the most appropriate exception to catch, as it is specifically related to regex evaluation timeouts. This ensures that only expected exceptions are handled, while other unexpected exceptions propagate up the call stack for proper handling elsewhere.

Additionally, sensitive information from the exception object should not be logged directly. Instead, a generic error message should be logged to avoid exposing internal details.


Suggested changeset 1
src/webapp01/Pages/DevSecOps.cshtml.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/webapp01/Pages/DevSecOps.cshtml.cs b/src/webapp01/Pages/DevSecOps.cshtml.cs
--- a/src/webapp01/Pages/DevSecOps.cshtml.cs
+++ b/src/webapp01/Pages/DevSecOps.cshtml.cs
@@ -94,7 +94,7 @@
             }
-            catch (Exception ex)
+            catch (RegexMatchTimeoutException)
             {
-                // Logging sensitive information
-                _logger.LogError($"Regex test failed for pattern: {pattern}. Exception: {ex}");
-                TempData["RegexError"] = "Pattern evaluation failed";
+                // Log a generic error message without exposing sensitive details
+                _logger.LogError($"Regex test failed for pattern: {pattern} due to a timeout.");
+                TempData["RegexError"] = "Pattern evaluation timed out";
             }
EOF
@@ -94,7 +94,7 @@
}
catch (Exception ex)
catch (RegexMatchTimeoutException)
{
// Logging sensitive information
_logger.LogError($"Regex test failed for pattern: {pattern}. Exception: {ex}");
TempData["RegexError"] = "Pattern evaluation failed";
// Log a generic error message without exposing sensitive details
_logger.LogError($"Regex test failed for pattern: {pattern} due to a timeout.");
TempData["RegexError"] = "Pattern evaluation timed out";
}
Copilot is powered by AI and may make mistakes. Always verify output.

return RedirectToPage();
}
}
}
4 changes: 4 additions & 0 deletions src/webapp01/Pages/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,9 @@
<h5 class="card-title">.NET 💜 Azure v5</h5>
<p class="card-text">Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
<p class="card-text">Visit our <a asp-page="/About">About GHAS</a> page to learn about GitHub Advanced Security features.</p>
<p class="card-text">
<strong>New!</strong> Check out our <a asp-page="/DevSecOps" class="btn btn-primary btn-sm">DevSecOps Demo</a>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All great :)

page to see the latest GHAS features and security demonstrations.
</p>
</div>
</div>
6 changes: 4 additions & 2 deletions src/webapp01/Pages/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/About">About GHAS</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/DevSecOps">DevSecOps Demo</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
Expand Down
6 changes: 3 additions & 3 deletions src/webapp01/webapp01.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.13.2" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="6.0.2" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.0.2" />
Copy link

Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The dependency version with known vulnerabilities is intentionally used for the demo; ensure that such versions are isolated to non-production environments.

Suggested change
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.0.2" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.0" />

Copilot uses AI. Check for mistakes.
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="System.Text.Json" Version="9.0.4" />
<PackageReference Include="System.Text.Json" Version="8.0.4" />
Copy link

Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure this downgraded version is confined to demo use, as it has a known high severity vulnerability.

Suggested change
<PackageReference Include="System.Text.Json" Version="8.0.4" />
<PackageReference Include="System.Text.Json" Version="8.0.5" />

Copilot uses AI. Check for mistakes.
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
Copy link

Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The addition of this package version with known vulnerabilities should be clearly limited to demo scenarios to prevent production misuse.

Suggested change
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />

Copilot uses AI. Check for mistakes.
</ItemGroup>

</Project>
Loading