Add demo files with intentional security vulnerabilities for GitHub A…#142
Add demo files with intentional security vulnerabilities for GitHub A…#142
Conversation
…dvanced Security training - Created Terraform configuration for Azure resources including a VM, network security group, and public IP. - Added insecure JavaScript and Python scripts demonstrating vulnerabilities such as eval injection and exception handling issues. - Introduced an ARM template with insecure configurations, including hardcoded credentials and CORS misconfigurations. - Developed a Flask application with SQL injection risks and insecure regex patterns. - Implemented a Razor page with hardcoded API keys, log forging vulnerabilities, and insecure database connections.
Dependency ReviewThe following issues were found:
Snapshot WarningsEnsure that dependencies are being submitted on PR branches and consider enabling retry-on-snapshot-warnings. See the documentation for more information and troubleshooting advice. Vulnerabilitiesdevsecops-demo/Pipfile.lockOnly included vulnerabilities with severity moderate or higher. License Issuesdevsecops-demo/Pipfile.lock
OpenSSF Scorecard
Scanned Files
|
| resource "azurerm_network_security_group" "catapp-sg" { | ||
| name = "${var.prefix}-sg" | ||
| location = var.location | ||
| resource_group_name = azurerm_resource_group.myresourcegroup.name | ||
|
|
||
| security_rule { | ||
| name = "HTTP" | ||
| priority = 100 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "80" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
|
|
||
| security_rule { | ||
| name = "HTTPS" | ||
| priority = 102 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "443" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
|
|
||
| security_rule { | ||
| name = "SSH" | ||
| priority = 101 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "22" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
| } |
Check failure
Code scanning / defsec
An inbound network security rule allows traffic from /0. Error
| resource "azurerm_network_security_group" "catapp-sg" { | ||
| name = "${var.prefix}-sg" | ||
| location = var.location | ||
| resource_group_name = azurerm_resource_group.myresourcegroup.name | ||
|
|
||
| security_rule { | ||
| name = "HTTP" | ||
| priority = 100 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "80" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
|
|
||
| security_rule { | ||
| name = "HTTPS" | ||
| priority = 102 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "443" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
|
|
||
| security_rule { | ||
| name = "SSH" | ||
| priority = 101 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "22" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
| } |
Check failure
Code scanning / defsec
An inbound network security rule allows traffic from /0. Error
| resource "azurerm_network_security_group" "catapp-sg" { | ||
| name = "${var.prefix}-sg" | ||
| location = var.location | ||
| resource_group_name = azurerm_resource_group.myresourcegroup.name | ||
|
|
||
| security_rule { | ||
| name = "HTTP" | ||
| priority = 100 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "80" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
|
|
||
| security_rule { | ||
| name = "HTTPS" | ||
| priority = 102 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "443" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
|
|
||
| security_rule { | ||
| name = "SSH" | ||
| priority = 101 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "22" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
| } |
Check failure
Code scanning / defsec
An inbound network security rule allows traffic from /0. Error
| resource "azurerm_network_security_group" "catapp-sg" { | ||
| name = "${var.prefix}-sg" | ||
| location = var.location | ||
| resource_group_name = azurerm_resource_group.myresourcegroup.name | ||
|
|
||
| security_rule { | ||
| name = "HTTP" | ||
| priority = 100 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "80" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
|
|
||
| security_rule { | ||
| name = "HTTPS" | ||
| priority = 102 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "443" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
|
|
||
| security_rule { | ||
| name = "SSH" | ||
| priority = 101 | ||
| direction = "Inbound" | ||
| access = "Allow" | ||
| protocol = "Tcp" | ||
| source_port_range = "*" | ||
| destination_port_range = "22" | ||
| source_address_prefix = "*" | ||
| destination_address_prefix = "*" | ||
| } | ||
| } |
Check failure
Code scanning / defsec
SSH access should not be accessible from the Internet, should be blocked on port 22 Error
| resource "azurerm_virtual_machine" "catapp" { | ||
| name = "${var.prefix}-meow" | ||
| location = var.location | ||
| resource_group_name = azurerm_resource_group.myresourcegroup.name | ||
| vm_size = var.vm_size | ||
|
|
||
| network_interface_ids = [azurerm_network_interface.catapp-nic.id] | ||
| delete_os_disk_on_termination = "true" | ||
|
|
||
| storage_image_reference { | ||
| publisher = var.image_publisher | ||
| offer = var.image_offer | ||
| sku = var.image_sku | ||
| version = var.image_version | ||
| } | ||
|
|
||
| storage_os_disk { | ||
| name = "${var.prefix}-osdisk" | ||
| managed_disk_type = "Standard_LRS" | ||
| caching = "ReadWrite" | ||
| create_option = "FromImage" | ||
| } | ||
|
|
||
| os_profile { | ||
| computer_name = var.prefix | ||
| admin_username = var.admin_username | ||
| admin_password = var.admin_password | ||
| } | ||
|
|
||
| os_profile_linux_config { | ||
| disable_password_authentication = false | ||
| } | ||
|
|
||
| tags = {} | ||
|
|
||
| # Added to allow destroy to work correctly. | ||
| depends_on = [azurerm_network_interface_security_group_association.catapp-nic-sg-ass] | ||
| } |
Check failure
Code scanning / defsec
Password authentication should be disabled on Azure virtual machines Error
| try: | ||
| print(xs[7]) | ||
| print(xs[8]) | ||
| except: pass |
Check notice
Code scanning / CodeQL
Except block handles 'BaseException' Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, to fix this issue you should avoid bare except: clauses and avoid catching BaseException directly. Instead, catch the specific exception types you actually expect, and allow KeyboardInterrupt and SystemExit (and other unexpected critical exceptions) to propagate.
For this specific file, the first try block at lines 7–10 is at risk. Accessing xs[7] and xs[8] can raise IndexError. We can make the handling explicit by replacing except: with except IndexError: so that only index errors are caught and quietly ignored, while KeyboardInterrupt and SystemExit continue to propagate normally. This preserves existing behavior (ignoring index errors) but removes the overly broad exception handling. The second try block on lines 14–16 is not part of the reported finding; it also uses except: but its behavior (continuing on any error while iterating) depends on catching TypeError. Changing that could alter behavior, and CodeQL did not flag that line in the prompt, so we will leave it unchanged.
No new imports or helper methods are required. The only change is narrowing the exception type in the first except clause in devsecops-demo/insecure-01.py.
| @@ -7,7 +7,7 @@ | ||
| try: | ||
| print(xs[7]) | ||
| print(xs[8]) | ||
| except: pass | ||
| except IndexError: pass | ||
|
|
||
| ys=[1, 2, None, None] | ||
| for y in ys: |
| try: | ||
| print(xs[7]) | ||
| print(xs[8]) | ||
| except: pass |
Check notice
Code scanning / CodeQL
Empty except Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, empty except blocks should be replaced with handlers that (a) catch specific exception types instead of bare except:, and (b) do something meaningful: log the error, clean up resources, re‑raise, or otherwise handle the condition. Swallowing all exceptions with pass hides failures and complicates debugging.
For this snippet, the code inside the first try block is indexing into a fixed list xs. The likely error is IndexError when accessing xs[8]. To fix the issue without changing the observable functionality too much, we can:
- Replace the bare
except:withexcept IndexError as exc:. - Inside the handler, print an informative message including the exception, instead of silently passing.
This preserves that the program continues after an indexing failure but no longer hides the reason. No new imports are required, and only lines around the except statement in devsecops-demo/insecure-01.py need to be changed.
| @@ -7,7 +7,8 @@ | ||
| try: | ||
| print(xs[7]) | ||
| print(xs[8]) | ||
| except: pass | ||
| except IndexError as exc: | ||
| print(f"Index error while accessing xs: {exc}") | ||
|
|
||
| ys=[1, 2, None, None] | ||
| for y in ys: |
| for y in ys: | ||
| try: | ||
| print(str(y+3)) #TypeErrors ahead | ||
| except: continue #not how to handle them |
Check notice
Code scanning / CodeQL
Except block handles 'BaseException' Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, to fix this issue, replace bare except: (or except BaseException:) with handlers for more specific exception classes, most commonly except Exception: or a narrower subset, and handle SystemExit/KeyboardInterrupt separately if they truly need to be caught. This ensures that program termination and user interrupts are not silently swallowed.
For this file, there are two bare except: blocks:
- Lines 7–10: accesses
xs[7]andxs[8], which may raiseIndexError. - Lines 14–16: does
str(y+3)whereymay beNone, which may raiseTypeError.
To preserve behaviour (ignore the error and continue) while avoiding catching KeyboardInterrupt/SystemExit, we should:
- Narrow the first handler to
except Exception:(or even more specificIndexError:). Since the intent is simply “ignore indexing errors”,Exceptionis sufficient and safer than a bareexcept:. - Narrow the second handler to
except Exception:(or more specificTypeError:) so thatKeyboardInterruptandSystemExitare not caught, but type errors still cause the loop tocontinueas before.
No new imports or helper functions are needed. Only the two except: lines must be changed in devsecops-demo/insecure-01.py.
| @@ -7,13 +7,13 @@ | ||
| try: | ||
| print(xs[7]) | ||
| print(xs[8]) | ||
| except: pass | ||
| except Exception: pass | ||
|
|
||
| ys=[1, 2, None, None] | ||
| for y in ys: | ||
| try: | ||
| print(str(y+3)) #TypeErrors ahead | ||
| except: continue #not how to handle them | ||
| except Exception: continue #not how to handle them | ||
|
|
||
| #some imports | ||
| import telnetlib |
| except: continue #not how to handle them | ||
|
|
||
| #some imports | ||
| import telnetlib |
Check notice
Code scanning / CodeQL
Unused import Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
To fix an unused import, you remove the import statement for the module that is not referenced anywhere in the file. This reduces clutter and avoids misleading readers about dependencies.
In this case, within devsecops-demo/insecure-01.py, the line import telnetlib at line 19 is unused. The best fix that does not change existing functionality is simply to delete this line and leave the rest of the file intact. No additional methods, imports, or definitions are required, and no other code needs to be updated because nothing references telnetlib.
Concretely:
- Edit
devsecops-demo/insecure-01.py. - Remove line 19 (
import telnetlib), leaving the surrounding code unchanged. - Keep
import ftplibas-is, since that import is not part of this specific report.
| @@ -16,7 +16,6 @@ | ||
| except: continue #not how to handle them | ||
|
|
||
| #some imports | ||
| import telnetlib | ||
| import ftplib | ||
|
|
||
| #B303 and B324 |
|
|
||
| #some imports | ||
| import telnetlib | ||
| import ftplib |
Check notice
Code scanning / CodeQL
Unused import Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
To fix an unused import, the general approach is to remove the import statement for any module that is not referenced in the file. This reduces unnecessary dependencies and makes the code clearer.
In this case, the single best fix without changing functionality is to delete the import ftplib line on line 20 in devsecops-demo/insecure-01.py. No other code changes are needed, since nothing in the snippet uses ftplib. The existing hashlib usages and other code remain untouched.
| @@ -17,7 +17,6 @@ | ||
|
|
||
| #some imports | ||
| import telnetlib | ||
| import ftplib | ||
|
|
||
| #B303 and B324 | ||
| s = b"I am a string" |
| @@ -0,0 +1,30 @@ | |||
|
|
|||
| from flask import request, render_template, make_response | |||
Check notice
Code scanning / CodeQL
Unused import Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
To fix an unused import, remove only the unused name from the import statement while leaving the used ones intact. This preserves all existing behavior while cleaning up the dependency list.
In devsecops-demo/routes-01.py, on line 2, make_response is imported but never used. The best fix is to edit that line to import only request and render_template. No other code changes are needed because there are no references to make_response elsewhere in the snippet.
Concretely:
- Edit
devsecops-demo/routes-01.py, line 2. - Change
from flask import request, render_template, make_responsetofrom flask import request, render_template. - No additional methods, imports, or definitions are required.
| @@ -1,5 +1,5 @@ | ||
|
|
||
| from flask import request, render_template, make_response | ||
| from flask import request, render_template | ||
|
|
||
| from server.webapp import flaskapp, cursor | ||
| from server.models import Book |
| def index(): | ||
| name = request.args.get('name') | ||
| author = request.args.get('author') | ||
| read = bool(request.args.get('read')) |
Check notice
Code scanning / CodeQL
Unused local variable Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
To fix the problem, remove the unused local variable read while preserving all existing behavior. Because the value is never used and reading a query argument has no necessary side effects, dropping the assignment is safe and keeps the function semantics unchanged.
Concretely, in devsecops-demo/routes-01.py, inside the index view, delete line 12: read = bool(request.args.get('read')). No other lines need to change, and no new imports or definitions are required.
| @@ -9,7 +9,6 @@ | ||
| def index(): | ||
| name = request.args.get('name') | ||
| author = request.args.get('author') | ||
| read = bool(request.args.get('read')) | ||
|
|
||
| if name: | ||
| cursor.execute( |
There was a problem hiding this comment.
templateanalyzer found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.
| string drive = Request.Query.ContainsKey("drive") ? Request.Query["drive"] : "C"; | ||
| var str = $"/C fsutil volume diskfree {drive}:"; | ||
|
|
||
| _logger.LogInformation($"Executing command: {str}"); |
Check failure
Code scanning / CodeQL
Log entries created from user input High
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, to fix log forging you should ensure any user-controlled data included in log messages is normalized before logging. For plain-text logs, this usually means removing or replacing newline and other control characters so that an attacker cannot break the log format or create additional fake log entries. For logs that may be rendered as HTML, HTML-encode user input first.
Here, the vulnerable value is str, which includes drive from Request.Query. We can preserve the current behavior of the application while preventing log forging by sanitizing drive (or str) before it is logged. The simplest, non-invasive change is to create a sanitized version of str that removes \r and \n (and optionally other control characters) and log that instead. This leaves command execution behavior (if any) untouched and only affects the representation in the logs.
Concretely, in src/webapp01/Pages/Privacy.cshtml.cs, inside OnGet:
- After computing
str, introduce a new variable, e.g.sanitizedStr, that is derived fromstrwith newline characters removed usingstring.Replace("\r", "").Replace("\n", ""). This matches the pattern from the recommendation. - Change the call
_logger.LogInformation($"Executing command: {str}");to logsanitizedStrinstead. - No new namespaces are needed, since
string.Replaceis fromSystem, which is already implicitly available.
No other lines (23–25) use tainted input, so they do not need modification.
| @@ -18,8 +18,8 @@ | ||
| { | ||
| string drive = Request.Query.ContainsKey("drive") ? Request.Query["drive"] : "C"; | ||
| var str = $"/C fsutil volume diskfree {drive}:"; | ||
|
|
||
| _logger.LogInformation($"Executing command: {str}"); | ||
| var sanitizedStr = str.Replace("\r", string.Empty).Replace("\n", string.Empty); | ||
| _logger.LogInformation($"Executing command: {sanitizedStr}"); | ||
| _logger.LogInformation($"User: {User.Identity?.Name}"); | ||
| _logger.LogInformation($"Admin: {User.IsInRole("Admin")}"); | ||
| _logger.LogInformation("Admin" + adminUserName); |
| // SECURITY ISSUE: SQL connection with hardcoded credentials | ||
| try | ||
| { | ||
| using var sqlConnection = new SqlConnection(DB_CONNECTION); |
Check failure
Code scanning / CodeQL
Insecure SQL connection High
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, the fix is to ensure the SQL connection string explicitly enforces encryption by including Encrypt=True (or Encrypt=true) in the connection string used to create SqlConnection. This makes the client require transport encryption rather than silently falling back to an unencrypted session if a man-in-the-middle or misconfiguration disables encryption.
The best targeted fix here is to update the DB_CONNECTION constant in DevSecOps-7492.cshtml.cs so that the literal connection string gains an Encrypt=True; segment, keeping the rest of the behavior unchanged. No code using DB_CONNECTION needs to change; the SqlConnection call will simply inherit the updated connection string. A minimal, clear change is to append Encrypt=True; to the existing constant:
"Server=demo-server;Database=SecurityDemo;User Id=demouser;Password=DemoPass2026!;Encrypt=True;";
This only requires editing the constant declaration on line 21 in src/webapp01/Pages/DevSecOps-7492.cshtml.cs. No additional imports or methods are needed.
| @@ -18,7 +18,7 @@ | ||
| private readonly ILogger<DevSecOps7492Model> _logger; | ||
|
|
||
| // SECURITY ISSUE: Hardcoded database credentials - for demo purposes only! | ||
| private const string DB_CONNECTION = "Server=demo-server;Database=SecurityDemo;User Id=demouser;Password=DemoPass2026!;"; | ||
| private const string DB_CONNECTION = "Server=demo-server;Database=SecurityDemo;User Id=demouser;Password=DemoPass2026!;Encrypt=True;"; | ||
|
|
||
| // SECURITY ISSUE: Vulnerable regex pattern susceptible to ReDoS (Regular Expression Denial of Service) | ||
| private static readonly Regex InsecureRegex = new Regex(@"^(([a-z])+.)+[A-Z]([a-z])+$", RegexOptions.None); |
| catch (Exception ex) | ||
| { | ||
| // SECURITY ISSUE: Logging sensitive exception details | ||
| _logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex.ToString()}"); |
Check failure
Code scanning / CodeQL
Log entries created from user input High
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
To fix the problem, user-provided data must be sanitized or encoded before being logged so that it cannot inject new lines or control characters that alter the structure of the log. For typical plain-text logs, this means stripping or replacing newline and carriage-return characters from the untrusted input before interpolation. The rest of the log message (static text and exception details) can remain as is.
The best minimally invasive fix here is to create a sanitized version of testInput inside the catch block before logging, using Replace to remove \r and \n. This keeps existing behavior (the same data content minus dangerous control characters) and does not require changes to the logging configuration or other code paths. We only modify the log line on 68 inside OnGet in DevSecOps-7492.cshtml.cs.
Concretely:
- In the
catch (Exception ex)block starting at line 65, introduce a new local variable, e.g.safeTestInput, that is derived fromtestInputwith line breaks removed:testInput.Replace("\r", "").Replace("\n", ""). - Update the
_logger.LogErrorcall on line 68 to usesafeTestInputinstead oftestInput. - We do not need new imports;
string.Replaceis available inSystem, which is already implicitly available in C#.
| @@ -65,7 +65,8 @@ | ||
| catch (Exception ex) | ||
| { | ||
| // SECURITY ISSUE: Logging sensitive exception details | ||
| _logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex.ToString()}"); | ||
| var safeTestInput = (testInput ?? string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty); | ||
| _logger.LogError($"Regex evaluation failed for user input: {safeTestInput}. Exception details: {ex.ToString()}"); | ||
| } | ||
| } | ||
|
|
| // This regex is vulnerable to ReDoS attacks | ||
| var match = InsecureRegex.IsMatch(testInput); | ||
| // Log forging in conditional logic | ||
| _logger.LogInformation($"Regex test performed on input: {testInput}, result: {match}"); |
Check failure
Code scanning / CodeQL
Log entries created from user input High
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, to prevent log forging when logging user-provided values, you should sanitize or encode the input before logging it. For plain-text logs, remove or normalize newline and other control characters so an attacker cannot inject additional log lines or confuse log parsers. For logs that will be rendered as HTML, HTML-encode the user input before logging.
In this specific case, the best fix that preserves existing functionality is to sanitize testInput before including it in the log message. Since the log format is unspecified but typical ASP.NET Core logging goes to plain text or structured logs, we can defensively strip out \r and \n characters from testInput before logging. We will do this right before the _logger.LogInformation call on line 63 by introducing a local sanitizedTestInput that uses Replace to remove newlines, and then log that variable instead of the raw testInput. This change is localized to the OnGet method in src/webapp01/Pages/DevSecOps-7492.cshtml.cs and does not require any new imports or changes to behavior beyond removing line breaks from the logged representation of the query parameter.
Concretely:
- In the
if (!string.IsNullOrEmpty(testInput))block, add a line to createsanitizedTestInput, e.g.var sanitizedTestInput = testInput.Replace("\r", string.Empty).Replace("\n", string.Empty);. - Update the
_logger.LogInformationmessage on line 63 to interpolatesanitizedTestInputrather thantestInput.
| @@ -59,8 +59,9 @@ | ||
| { | ||
| // This regex is vulnerable to ReDoS attacks | ||
| var match = InsecureRegex.IsMatch(testInput); | ||
| // Log forging in conditional logic | ||
| _logger.LogInformation($"Regex test performed on input: {testInput}, result: {match}"); | ||
| // Sanitize user input before logging to prevent log forging | ||
| var sanitizedTestInput = testInput.Replace("\r", string.Empty).Replace("\n", string.Empty); | ||
| _logger.LogInformation($"Regex test performed on input: {sanitizedTestInput}, result: {match}"); | ||
| } | ||
| catch (Exception ex) | ||
| { |
| try | ||
| { | ||
| // This regex is vulnerable to ReDoS attacks | ||
| var match = InsecureRegex.IsMatch(testInput); |
Check failure
Code scanning / CodeQL
Denial of Service from comparison of user input against expensive regex High
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, there are two complementary ways to fix this issue: (1) change the regex to avoid constructs that cause catastrophic backtracking (e.g., avoid nested or overlapping quantified groups), and/or (2) ensure that any regex evaluated on untrusted input has a timeout, so that even if the pattern is expensive, it cannot tie up the server for long. In .NET, this is done by using the Regex constructor overload that accepts a TimeSpan match timeout or by setting a default regex timeout application-wide.
To fix this specific case without changing existing functionality, we should preserve the intended matching behavior as much as possible while eliminating the ReDoS risk. The simplest and safest change, given we must not assume broader context, is to re-create the InsecureRegex with a finite timeout using the constructor overload new Regex(pattern, options, matchTimeout). This changes only performance characteristics and error behavior (throwing a RegexMatchTimeoutException on overly complex matches) but leaves the logical pattern unchanged. Concretely, in src/webapp01/Pages/DevSecOps-7492.cshtml.cs, update the InsecureRegex field declaration at line 24 to use a timeout, for example TimeSpan.FromMilliseconds(500) or TimeSpan.FromSeconds(1). Since System is not yet imported in this file, we must add using System; at the top so TimeSpan is available. No other logic changes are necessary, because the existing try/catch (Exception ex) around the match will also catch any timeout exceptions and log them.
| @@ -10,6 +10,7 @@ | ||
| using Microsoft.Data.SqlClient; | ||
| using Newtonsoft.Json; | ||
| using System.Text.Json; | ||
| using System; | ||
|
|
||
| namespace webapp01.Pages | ||
| { | ||
| @@ -21,7 +22,8 @@ | ||
| private const string DB_CONNECTION = "Server=demo-server;Database=SecurityDemo;User Id=demouser;Password=DemoPass2026!;"; | ||
|
|
||
| // SECURITY ISSUE: Vulnerable regex pattern susceptible to ReDoS (Regular Expression Denial of Service) | ||
| private static readonly Regex InsecureRegex = new Regex(@"^(([a-z])+.)+[A-Z]([a-z])+$", RegexOptions.None); | ||
| private static readonly Regex InsecureRegex = | ||
| new Regex(@"^(([a-z])+.)+[A-Z]([a-z])+$", RegexOptions.None, TimeSpan.FromSeconds(1)); | ||
|
|
||
| // SECURITY ISSUE: API key hardcoded | ||
| private const string API_KEY = "ghp_demo1234567890abcdefghijklmnopqrst"; |
| catch (Exception ex) | ||
| { | ||
| _logger.LogError($"Database connection attempt failed: {ex.Message}"); | ||
| } |
Check notice
Code scanning / CodeQL
Generic catch clause Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
General fix: Replace the generic catch (Exception) with one or more specific exception types that are reasonably expected from the code in the try block (here, database-related failures). Optionally, add a secondary catch or catch-all that rethrows unexpected exceptions instead of silently logging them, so that truly abnormal situations are not masked.
Best minimal fix here without changing outward behavior: change the catch (Exception ex) surrounding the SqlConnection usage to catch SqlException, which is the primary exception thrown by Microsoft.Data.SqlClient. Keep logging behavior the same (still log ex.Message). Since the code inside the try is only instantiating SqlConnection and not opening it, in practice the only realistic failures are SQL provider issues (SqlException) or other configuration/runtime bugs; constraining the catch to SqlException addresses CodeQL’s concern while preserving the “log and continue” flow.
Edits needed:
-
In
src/webapp01/Pages/DevSecOps-7492.cshtml.cs, within theOnGetmethod’s SQL connection section (lines 72–83), update:catch (Exception ex)→catch (SqlException ex)
No new imports are required because using Microsoft.Data.SqlClient; is already present at line 10.
| @@ -77,7 +77,7 @@ | ||
| // Note: Not actually opening connection for demo safety | ||
| // sqlConnection.Open(); | ||
| } | ||
| catch (Exception ex) | ||
| catch (SqlException ex) | ||
| { | ||
| _logger.LogError($"Database connection attempt failed: {ex.Message}"); | ||
| } |
| catch (Exception ex) | ||
| { | ||
| // SECURITY ISSUE: Logging sensitive exception details | ||
| _logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex.ToString()}"); |
Check notice
Code scanning / CodeQL
Redundant ToString() call Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
To fix redundant ToString() calls in interpolated strings, pass the object directly into the interpolation and let the language invoke ToString() implicitly. This keeps behavior identical while simplifying the code.
In this file, the only flagged instance is on line 68 in OnGet, where the catch block logs an error with $"Regex evaluation failed ... Exception details: {ex.ToString()}". The best fix is to remove the .ToString() call and interpolate ex directly: $"... Exception details: {ex}". No additional methods, imports, or definitions are required, and no behavior change occurs because Exception.ToString() is what interpolation would call anyway.
Concretely, in src/webapp01/Pages/DevSecOps-7492.cshtml.cs, replace the line:
_logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex.ToString()}");with:
_logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex}");| @@ -65,7 +65,7 @@ | ||
| catch (Exception ex) | ||
| { | ||
| // SECURITY ISSUE: Logging sensitive exception details | ||
| _logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex.ToString()}"); | ||
| _logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex}"); | ||
| } | ||
| } | ||
|
|
| catch (Exception ex) | ||
| { | ||
| // SECURITY ISSUE: Logging sensitive exception details | ||
| _logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex.ToString()}"); | ||
| } |
Check notice
Code scanning / CodeQL
Generic catch clause Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, to fix a “generic catch clause” you should catch the specific exception types that the protected code can reasonably throw and that you actually intend to handle, letting all other exceptions propagate so that higher-level handlers or the framework can deal with them appropriately.
For this specific block (lines 58–69), the risky operation is InsecureRegex.IsMatch(testInput). Typical, expected exceptions here are:
RegexMatchTimeoutExceptionwhen regex evaluation times out.ArgumentExceptionif something about the pattern or options is invalid (even though the pattern is static, this is still the most relevant specific type for regex-related argument issues).
The best minimal fix without changing visible behavior is to:
- Replace
catch (Exception ex)with two specific catch blocks: one forRegexMatchTimeoutExceptionand one forArgumentException. - Keep the existing logging behavior inside each, so functionality (logging the failure plus exception details) remains the same.
- Leave any other unexpected exceptions unhandled here so they can bubble up.
No new imports are needed if System is already in scope via implicit usings (typical for ASP.NET Core). If it isn’t, then the fully qualified names System.Text.RegularExpressions.RegexMatchTimeoutException and System.ArgumentException can be used, but given we already have using System.Text.RegularExpressions;, RegexMatchTimeoutException is available directly, and ArgumentException is part of System, which is usually imported implicitly in ASP.NET Core projects.
Concretely, in src/webapp01/Pages/DevSecOps-7492.cshtml.cs, adjust the try/catch that wraps the regex evaluation (around line 58–69) to replace the generic catch (Exception ex) with two specific catch blocks.
| @@ -62,9 +62,14 @@ | ||
| // Log forging in conditional logic | ||
| _logger.LogInformation($"Regex test performed on input: {testInput}, result: {match}"); | ||
| } | ||
| catch (Exception ex) | ||
| catch (RegexMatchTimeoutException ex) | ||
| { | ||
| // SECURITY ISSUE: Logging sensitive exception details | ||
| _logger.LogError($"Regex evaluation timed out for user input: {testInput}. Exception details: {ex.ToString()}"); | ||
| } | ||
| catch (ArgumentException ex) | ||
| { | ||
| // SECURITY ISSUE: Logging sensitive exception details | ||
| _logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex.ToString()}"); | ||
| } | ||
| } |
| LoadLatestGHASNews(); | ||
|
|
||
| // SECURITY ISSUE: Vulnerable regex testing | ||
| string testInput = Request.Query.ContainsKey("test") ? Request.Query["test"].ToString() ?? "" : ""; |
Check notice
Code scanning / CodeQL
Inefficient use of ContainsKey Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, to fix this issue you should replace the pattern “check ContainsKey then access via indexer” with a single call to TryGetValue, which both tests for existence and retrieves the value in one operation. This reduces redundant lookups and aligns with recommended usage for dictionary-like collections.
For this specific file, on line 55 you should remove the ternary expression that calls Request.Query.ContainsKey("test") and indexer access Request.Query["test"], and instead call Request.Query.TryGetValue("test", out var testValues) and use the resulting StringValues to build testInput. A concise way that preserves the current behavior (defaulting to "" when the parameter is absent or null-ish) is:
- Use
TryGetValueinto a local variable (e.g.,var testInputRaw). - If
TryGetValuefails, settestInputto"". - Otherwise, call
ToString()ontestInputRawand coalesce to"".
IQueryCollection.TryGetValue is in Microsoft.AspNetCore.Http, but you don’t need a new using because you’re already accessing Request.Query. No new methods or external dependencies are needed; only the single line that currently uses ContainsKey must be replaced with a small block using TryGetValue.
| @@ -52,7 +52,7 @@ | ||
| LoadLatestGHASNews(); | ||
|
|
||
| // SECURITY ISSUE: Vulnerable regex testing | ||
| string testInput = Request.Query.ContainsKey("test") ? Request.Query["test"].ToString() ?? "" : ""; | ||
| string testInput = Request.Query.TryGetValue("test", out var testValues) ? (testValues.ToString() ?? "") : ""; | ||
| if (!string.IsNullOrEmpty(testInput)) | ||
| { | ||
| try |
| // SECURITY ISSUE: Log forging - unsanitized user input directly written to logs | ||
| string userAgent = Request.Headers["User-Agent"].ToString(); | ||
| string remoteIp = Request.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"; | ||
| string userName = Request.Query.ContainsKey("user") ? Request.Query["user"].ToString() ?? "anonymous" : "anonymous"; |
Check notice
Code scanning / CodeQL
Inefficient use of ContainsKey Note
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 1 day ago
In general, to fix “inefficient use of ContainsKey and indexer,” replace sequences like if (dict.ContainsKey(k)) { var v = dict[k]; ... } with a single call to dict.TryGetValue(k, out var v) and use the v from the out parameter. This avoids performing two dictionary lookups.
For this specific case in src/webapp01/Pages/DevSecOps-7492.cshtml.cs, line 42 computes userName by first checking Request.Query.ContainsKey("user") and then accessing Request.Query["user"]. We should instead call Request.Query.TryGetValue("user", out var userValues) once, and then, if successful, take the first value (or .ToString()) from userValues. Since the existing code returns "anonymous" both when the key is missing and when the value is null, we must preserve that behavior.
Request.Query.TryGetValue returns a bool and outputs an IEnumerable<string>-like StringValues (from Microsoft.Extensions.Primitives), which already has a meaningful .ToString() implementation that concatenates values. Therefore, we can safely write:
string userName = Request.Query.TryGetValue("user", out var userValues)
? userValues.ToString() ?? "anonymous"
: "anonymous";This change is confined to the OnGet method, around line 42. No new imports or additional methods are required, because TryGetValue is already available on IQueryCollection in ASP.NET Core and StringValues is already in scope via existing framework references.
| @@ -39,7 +39,7 @@ | ||
| // SECURITY ISSUE: Log forging - unsanitized user input directly written to logs | ||
| string userAgent = Request.Headers["User-Agent"].ToString(); | ||
| string remoteIp = Request.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"; | ||
| string userName = Request.Query.ContainsKey("user") ? Request.Query["user"].ToString() ?? "anonymous" : "anonymous"; | ||
| string userName = Request.Query.TryGetValue("user", out var userValues) ? userValues.ToString() ?? "anonymous" : "anonymous"; | ||
|
|
||
| // Log forging vulnerability - attacker can inject newlines and fake log entries | ||
| _logger.LogInformation($"DevSecOps-7492 page accessed by: {userName} from IP: {remoteIp}"); |
There was a problem hiding this comment.
checkov found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.
| try: | ||
| print(xs[7]) | ||
| print(xs[8]) | ||
| except: pass |
Check warning
Code scanning / Bandit
Try, Except, Pass detected. Warning
| for y in ys: | ||
| try: | ||
| print(str(y+3)) #TypeErrors ahead | ||
| except: continue #not how to handle them |
Check warning
Code scanning / Bandit
Try, Except, Continue detected. Warning
|
|
||
| #B303 and B324 | ||
| s = b"I am a string" | ||
| print("MD5: " +hashlib.md5(s).hexdigest()) |
Check warning
Code scanning / Bandit
Use of weak MD5 hash for security. Consider usedforsecurity=False Warning
| #B303 and B324 | ||
| s = b"I am a string" | ||
| print("MD5: " +hashlib.md5(s).hexdigest()) | ||
| print("SHA1: " +hashlib.sha1(s).hexdigest()) |
Check warning
Code scanning / Bandit
Use of weak SHA1 hash for security. Consider usedforsecurity=False Warning
| "flask": { | ||
| "hashes": [ | ||
| "sha256:7b2fb8e934ddd50731893bdcdb00fc8c0315916f9fcd50d22c7cc1a95ab634e2", | ||
| "sha256:cb90f62f1d8e4dc4621f52106613488b5ba826b2e1e10a33eac92f723093ab6a" | ||
| ], | ||
| "index": "pypi", | ||
| "version": "==2.0.2" | ||
| }, |
Check failure
Code scanning / Trivy
flask: Possible disclosure of permanent session cookie due to missing Vary: Cookie header High
| "jinja2": { | ||
| "hashes": [ | ||
| "sha256:827a0e32839ab1600d4eb1c4c33ec5a8edfbc5cb42dafa13b81f182f97784b45", | ||
| "sha256:8569982d3f0889eed11dd620c706d39b60c36d6d25843961f33f77fb6bc6b20c" | ||
| ], | ||
| "markers": "python_version >= '3.6'", | ||
| "version": "==3.0.2" | ||
| }, |
Check failure
Code scanning / Trivy
jinja2: Jinja has a sandbox breakout through malicious filenames High
| "jinja2": { | ||
| "hashes": [ | ||
| "sha256:827a0e32839ab1600d4eb1c4c33ec5a8edfbc5cb42dafa13b81f182f97784b45", | ||
| "sha256:8569982d3f0889eed11dd620c706d39b60c36d6d25843961f33f77fb6bc6b20c" | ||
| ], | ||
| "markers": "python_version >= '3.6'", | ||
| "version": "==3.0.2" | ||
| }, |
Check failure
Code scanning / Trivy
jinja2: Jinja has a sandbox breakout through indirect reference to format method High
| "werkzeug": { | ||
| "hashes": [ | ||
| "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f", | ||
| "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a" | ||
| ], | ||
| "markers": "python_version >= '3.6'", | ||
| "version": "==2.0.2" | ||
| } |
Check failure
Code scanning / Trivy
python-werkzeug: high resource usage when parsing multipart form data with many fields High
| "werkzeug": { | ||
| "hashes": [ | ||
| "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f", | ||
| "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a" | ||
| ], | ||
| "markers": "python_version >= '3.6'", | ||
| "version": "==2.0.2" | ||
| } |
Check failure
Code scanning / Trivy
python-werkzeug: user may execute code on a developer's machine High
| "werkzeug": { | ||
| "hashes": [ | ||
| "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f", | ||
| "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a" | ||
| ], | ||
| "markers": "python_version >= '3.6'", | ||
| "version": "==2.0.2" | ||
| } |
Check warning
Code scanning / Trivy
python-werkzeug: high resource consumption leading to denial of service Medium
| "werkzeug": { | ||
| "hashes": [ | ||
| "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f", | ||
| "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a" | ||
| ], | ||
| "markers": "python_version >= '3.6'", | ||
| "version": "==2.0.2" | ||
| } |
Check warning
Code scanning / Trivy
werkzeug: python-werkzeug: Werkzeug safe_join not safe on Windows Medium
| "werkzeug": { | ||
| "hashes": [ | ||
| "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f", | ||
| "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a" | ||
| ], | ||
| "markers": "python_version >= '3.6'", | ||
| "version": "==2.0.2" | ||
| } |
Check warning
Code scanning / Trivy
Werkzeug: Werkzeug: Denial of service via Windows device names in path segments Medium
| "werkzeug": { | ||
| "hashes": [ | ||
| "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f", | ||
| "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a" | ||
| ], | ||
| "markers": "python_version >= '3.6'", | ||
| "version": "==2.0.2" | ||
| } |
Check warning
Code scanning / Trivy
Werkzeug safe_join() allows Windows special device names with compound extensions Medium
| "werkzeug": { | ||
| "hashes": [ | ||
| "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f", | ||
| "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a" | ||
| ], | ||
| "markers": "python_version >= '3.6'", | ||
| "version": "==2.0.2" | ||
| } |
Check notice
Code scanning / Trivy
python-werkzeug: cookie prefixed with = can shadow unprefixed cookie Low
| // SECURITY ISSUE: Potential JSON deserialization vulnerability | ||
| // Using older Newtonsoft.Json version (12.0.2) which has known vulnerabilities | ||
| string jsonData = JsonConvert.SerializeObject(LatestGHASNews); | ||
| var deserializedNews = JsonConvert.DeserializeObject<List<string>>(jsonData); |
| // SECURITY ISSUE: Log forging - unsanitized user input directly written to logs | ||
| string userAgent = Request.Headers["User-Agent"].ToString(); | ||
| string remoteIp = Request.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"; | ||
| string userName = Request.Query.ContainsKey("user") ? Request.Query["user"].ToString() ?? "anonymous" : "anonymous"; |
| LoadLatestGHASNews(); | ||
|
|
||
| // SECURITY ISSUE: Vulnerable regex testing | ||
| string testInput = Request.Query.ContainsKey("test") ? Request.Query["test"].ToString() ?? "" : ""; |
|
|
||
| public void OnGet() | ||
| { | ||
| string drive = Request.Query.ContainsKey("drive") ? Request.Query["drive"] : "C"; |
| catch (Exception ex) | ||
| { | ||
| // SECURITY ISSUE: Logging sensitive exception details | ||
| _logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex.ToString()}"); | ||
| } |
| catch (Exception ex) | ||
| { | ||
| _logger.LogError($"Database connection attempt failed: {ex.Message}"); | ||
| } |
| catch (Exception ex) | ||
| { | ||
| // SECURITY ISSUE: Logging full exception with potentially sensitive information | ||
| _logger.LogError($"Pattern test failed for input: {pattern} | Exception: {ex.ToString()}"); | ||
| TempData["Error"] = "Pattern evaluation encountered an error"; | ||
| } |
|
|
||
| public class PrivacyModel : PageModel | ||
| { | ||
| string adminUserName = "demouser@example.com"; |
| catch (Exception ex) | ||
| { | ||
| // SECURITY ISSUE: Logging sensitive exception details | ||
| _logger.LogError($"Regex evaluation failed for user input: {testInput}. Exception details: {ex.ToString()}"); |
| catch (Exception ex) | ||
| { | ||
| // SECURITY ISSUE: Logging full exception with potentially sensitive information | ||
| _logger.LogError($"Pattern test failed for input: {pattern} | Exception: {ex.ToString()}"); |
…dvanced Security training