-
Notifications
You must be signed in to change notification settings - Fork 7
Add YAML rules and tests for detecting hard-coded secrets in C# #161
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add YAML rules and tests for detecting hard-coded secrets in C# #161
Conversation
Sakshis seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
WalkthroughThe changes add several new YAML files that define security rules for detecting hard-coded secrets in C# applications. The rules specifically target the use of the Changes
Sequence Diagram(s)sequenceDiagram
participant Developer
participant StaticAnalyzer
participant RuleEngine
participant Logger
Developer->>StaticAnalyzer: Initiates code scan
StaticAnalyzer->>RuleEngine: Load C# security rule definitions
RuleEngine->>StaticAnalyzer: Evaluate matching patterns
StaticAnalyzer->>Logger: Record warnings for hardcoded secrets
Logger->>Developer: Output detected issues
Suggested reviewers
Poem
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (16)
tests/csharp/npgsqlconnectionstringbuilder-hardcoded-secret-csharp-test.yml (1)
48-48
: Trailing Spaces Detected
Trailing spaces are present on line 48. Please remove these to maintain clean formatting.- string password = "aaa"; + string password = "aaa";🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 48-48: trailing spaces
(trailing-spaces)
rules/csharp/security/npgsqlconnectionstringbuilder-hardcoded-secret-csharp.yml (7)
19-60
: Utility: Matching Hardcoded Password via String Literal
Thematch_NpgsqlConnectionStringBuilder_with_string
utility is well‑structured to detect assignment expressions where thePassword
property is directly assigned a string literal. To improve maintainability, consider adding inline comments to explain the purpose of the$U
placeholder.
61-105
: Utility: Matching Bracketed Password Assignments
Thematch_with_brackets
pattern effectively captures cases where the password is set via a bracketed argument list. Inline documentation for the role of the$U
pattern would be beneficial for future maintainers.
106-146
: Utility: Matching Instance Assignments Using Braces
Thematch_instance_with_braces
utility cleanly targets element access expressions with bracketed arguments. The use of the$C
placeholder is consistent; however, a brief comment explaining its context could help clarify its intent.
147-184
: Utility: Matching Instance Assignments Without Braces
This segment (match_instance_without_braces
) is designed to detect assignments toPassword
that do not use braces. Its structure is consistent with similar patterns. Adding a note to distinguish its behavior from the “with_braces” variant might improve clarity.
185-241
: Utility: Matching Braced Instance Patterns
Thebraces_instance
block successfully handles cases where an identifier (using$Y
and$P
) appears within an element access expression combined with a string literal. Including inline comments to document these placeholders would further improve readability.
242-299
: Utility: Matching Password Assignment with Instance
Thematch_password_with_instance
utility reliably detects assignment expressions that set thePassword
property on an instance. For added clarity, inline documentation for the$K
and$T
placeholders is recommended.
299-341
: Direct Pattern Matching for Hardcoded Password Assignment
The explicit pattern(NpgsqlConnectionStringBuilder $VALUE).Password = "$PASSWORD"
is clearly outlined and fits well within the overall rule structure. Review whether the detailed nesting within theinside
block is required for all cases and include inline comments if possible.rules/csharp/security/sqlconnectionstringbuilder-hardcoded-secret-csharp.yml (7)
18-60
: Utility: Matching Hardcoded Password for SqlConnectionStringBuilder (String Literal)
Thematch_SqlConnectionStringBuilder_with_string
utility reliably identifies assignments where thePassword
property is set to a string literal. Documenting the$U
placeholder with inline comments would be a welcome improvement for maintainability.
61-105
: Utility: Matching Bracketed Password Assignments
This utility,match_with_brackets
, efficiently captures patterns employing bracketed argument lists for password assignment. As with the similar rule in the previous file, consider adding a brief comment on the purpose of the$U
placeholder.
106-146
: Utility: Matching Instance Assignments Using Braces
Thematch_instance_with_braces
utility is written consistently to handle element access expressions with bracketed arguments, specifically forSqlConnectionStringBuilder
. A small inline note on the role of the$C
placeholder would improve clarity.
147-184
: Utility: Matching Instance Assignments Without Braces
Thematch_instance_without_braces
utility is straightforward and mirrors the functionality seen earlier, but without braces. Consider clarifying via inline remarks how this rule differs from its “with_braces” counterpart.
185-241
: Utility: Matching Braced Instance Patterns
Thebraces_instance
utility correctly targets element access expressions that include braced string literals. The use of the$Y
and$P
placeholders should be documented with inline comments for added clarity.
242-299
: Utility: Matching Password Assignment with Instance
Thematch_password_with_instance
block is effective in flagging assignments setting thePassword
property. Inline comments to explain the$K
and$T
placeholders would be useful for anyone reviewing or maintaining this rule.
299-341
: Direct Pattern Matching for Hardcoded Password Assignment
The explicit matching pattern(SqlConnectionStringBuilder $VALUE).Password = "$PASSWORD"
is clearly set up and integrates well with the overall rule structure. Consider re‑evaluating if all the nestedinside
directives are necessary and explain their purpose with inline documentation.rules/csharp/security/networkcredential-hardcoded-secret-python.yml (1)
1-15
: File Metadata and Rule Definition: Verify Naming ConsistencyThe metadata block correctly specifies the rule ID, language, severity, message, and note. However, the file name includes “python” (i.e.
networkcredential-hardcoded-secret-python.yml
), while the rule ID and language indicate C#. For clarity and consistency for future maintenance, consider renaming the file to reflect its target language (e.g.networkcredential-hardcoded-secret-csharp.yml
).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (13)
rules/csharp/security/networkcredential-hardcoded-secret-python.yml
(1 hunks)rules/csharp/security/npgsqlconnectionstringbuilder-hardcoded-secret-csharp.yml
(1 hunks)rules/csharp/security/oracleconnectionstringbuilder-hardcoded-secret-csharp.yml
(1 hunks)rules/csharp/security/sqlconnectionstringbuilder-hardcoded-secret-csharp.yml
(1 hunks)tests/__snapshots__/networkcredential-hardcoded-secret-csharp-snapshot.yml
(1 hunks)tests/__snapshots__/npgsqlconnectionstringbuilder-hardcoded-secret-csharp-snapshot.yml
(1 hunks)tests/__snapshots__/null-library-function-c-snapshot.yml
(1 hunks)tests/__snapshots__/oracleconnectionstringbuilder-hardcoded-secret-csharp-snapshot.yml
(1 hunks)tests/__snapshots__/sqlconnectionstringbuilder-hardcoded-secret-csharp-snapshot.yml
(1 hunks)tests/csharp/networkcredential-hardcoded-secret-python-test.yml
(1 hunks)tests/csharp/npgsqlconnectionstringbuilder-hardcoded-secret-csharp-test.yml
(1 hunks)tests/csharp/oracleconnectionstringbuilder-hardcoded-secret-csharp-test.yml
(1 hunks)tests/csharp/sqlconnectionstringbuilder-hardcoded-secret-csharp-test.yml
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- tests/snapshots/sqlconnectionstringbuilder-hardcoded-secret-csharp-snapshot.yml
🧰 Additional context used
🪛 YAMLlint (1.35.1)
tests/csharp/npgsqlconnectionstringbuilder-hardcoded-secret-csharp-test.yml
[error] 48-48: trailing spaces
(trailing-spaces)
🔇 Additional comments (48)
tests/csharp/networkcredential-hardcoded-secret-python-test.yml (3)
1-7
: Valid Case: Direct Usage with Dynamic Argument
The first valid example correctly demonstrates using a dynamic argument (args[1]
) for the password in theNetworkCredential
instantiation.
8-12
: Valid Case: Property Assignment with Dynamic Value
This example shows secure practice by assigning the password from a dynamic source (args[1]
) to a property rather than hardcoding it.
13-37
: Invalid Cases: Hardcoded Credentials Detection
The invalid examples comprehensively cover multiple patterns of hardcoded password assignment—whether directly in the constructor, via property assignment, or even using intermediary variables. These samples are well-constructed to trigger the detection rules for insecure credential practices.tests/__snapshots__/null-library-function-c-snapshot.yml (8)
3-7
: Snapshot Block 1: Functionf()
with Unsafestrcpy
Usage
This snapshot captures a C functionf()
that demonstrates the use ofstrcpy
with data fromgetenv("FOO")
, highlighting potential risks such as buffer overflow. It serves its purpose as a test sample for unsafe C string operations.
8-32
: Snapshot Block 1 Labels: Detailed Source Segmentation
The associated labels break down the sources for bothstrcpy
andgetenv
calls correctly by providing precise positions and styles. This detail is valuable for downstream static or security analysis.
33-36
: Snapshot Block 2:test_getc()
Function Validation
This snapshot captures a test function that usesgetc
and a file pointer fromfopen()
. It provides an example case for testing I/O function usage in C.
37-65
: Snapshot Block 2 Labels: Accurate Extraction of Function Call Elements
The labels for this block accurately identify and differentiate components such asgetc
,fopen
, and the file pointer assignment, ensuring comprehensive test documentation.
66-70
: Snapshot Block 3:fwrite
with Assigned File Pointer
This snapshot demonstrates the use offwrite
with a file pointer directly obtained fromfopen("foo.txt", "w")
. The sample is clear and its labeling further reinforces the testing parameters.
71-95
: Snapshot Block 3 Labels: Comprehensive Labeling offwrite
Usage
The detailed labels accurately map out the function call components—including parameters and sub-expressions—which is beneficial for validating security patterns.
96-99
: Snapshot Block 4: Variant offwrite
Usage Without Pointer Assignment
This block captures a slightly different coding style for invokingfwrite
(without saving the result offopen
to a variable), thereby enriching the overall snapshot suite with diverse patterns.
100-124
: Snapshot Block 4 Labels: Well-Defined Source Segments
The labels in this block clearly delineate the various parts of the function call, which supports precise test validation and analysis.tests/csharp/oracleconnectionstringbuilder-hardcoded-secret-csharp-test.yml (2)
1-5
: Valid Example: Dynamic Password Assignment
The valid test case demonstrates settingbuilder.Password
withargs[1]
, which is the recommended secure pattern.
6-30
: Invalid Examples: Detection of Hardcoded Passwords
The invalid examples effectively cover various syntaxes for hardcoded password assignments (using both property and indexer notations) in theOracleConnectionStringBuilder
. This comprehensive approach aids in testing the security rule.tests/csharp/sqlconnectionstringbuilder-hardcoded-secret-csharp-test.yml (2)
1-5
: Valid Example: Secure Dynamic Password Assignment
The valid scenario demonstrates setting the password usingargs[1]
, which fulfills the secure coding guidelines for connection string builders.
6-31
: Invalid Examples: Hardcoded Secret Patterns inSqlConnectionStringBuilder
These invalid samples illustrate different insecure patterns—whether through direct literal assignment, using indexer notation, or by first assigning to a variable. They provide a solid basis for detecting hardcoded secrets.tests/csharp/npgsqlconnectionstringbuilder-hardcoded-secret-csharp-test.yml (4)
1-6
: Valid Examples: Correct Dynamic Assignment
Both valid entries correctly use dynamic input (args[1]
) to set the password using either direct property access or indexer notation. This is in line with best practices for secure credential management.
7-22
: Invalid Example 1: Hardcoded Password via Direct Assignment
This invalid example demonstrates a direct hardcoded password assignment within theNpgsqlConnectionStringBuilder
. It effectively highlights an insecure practice that should be flagged.
23-37
: Invalid Example 2: Hardcoded Password via Indexer Notation
Here, the use of an indexer to assign a hardcoded password is clearly shown, reinforcing the pattern that the security rule should catch.
38-52
: Invalid Example 3: Hardcoded Password Assigned from a Variable
This case captures a more subtle issue where a variable (password
) is initialized with a constant string and then used to set the password, which remains insecure.🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 48-48: trailing spaces
(trailing-spaces)
tests/__snapshots__/npgsqlconnectionstringbuilder-hardcoded-secret-csharp-snapshot.yml (2)
1-17
: Snapshot for NpgsqlConnectionStringBuilder (Property Assignment)
This snapshot clearly demonstrates a hard-coded password assignment using thePassword
property (i.e.urlBuilder.Password = "aaaa"
). The example is well structured, and the labels precisely highlight the key segments.
75-89
: Snapshot for NpgsqlConnectionStringBuilder (Indexer Assignment)
This snapshot covers the alternative indexer syntax (urlBuilder["Password"] = "aaaa"
) and further confirms that the insecurity is detectable via different syntactic styles. The labels again capture the key elements accurately.tests/__snapshots__/networkcredential-hardcoded-secret-csharp-snapshot.yml (2)
1-9
: Snapshot for NetworkCredential (Direct Property Assignment)
This snapshot uses a direct assignment to thePassword
property (i.e.cre.Password = "aaaa"
) on aNetworkCredential
object. It is a straightforward insecure example that meets the rule testing needs.
66-73
: Snapshot for NetworkCredential (Assignment via Variable)
In this snapshot a local variable (password
) holding a hard-coded string is later used to setcre.Password
. This variation is useful because it shows that even an indirect assignment (via a variable) may hide a hard-coded secret.tests/__snapshots__/oracleconnectionstringbuilder-hardcoded-secret-csharp-snapshot.yml (4)
1-9
: Snapshot for OracleConnectionStringBuilder (Property Assignment)
The snapshot using direct property assignment (i.e.builder.Password = "reee!"
) efficiently illustrates the hard-coded credentials issue in an Oracle connection scenario. The labels are comprehensive and clear.
67-73
: Snapshot for OracleConnectionStringBuilder (Indexer Assignment)
This example uses indexer syntax (builder["Password"] = "reee!"
), offering another common way to set properties in C#. It provides excellent coverage and clarity.
141-147
: Snapshot with Variable Alias (Property Assignment)
Here a variable alias (cb
) is used with a direct property assignment (cb.Password = "reee!"
). This variation reinforces that the detection rule should work regardless of the variable naming.
147-153
: Snapshot with Variable Alias (Indexer Assignment)
Similarly, the snapshot using the aliascb
with indexer assignment (cb["Password"] = "reee!"
) further expands the pattern coverage.rules/csharp/security/oracleconnectionstringbuilder-hardcoded-secret-csharp.yml (4)
1-15
: OracleConnectionStringBuilder Security Rule Metadata
The rule’s metadata is well defined with clear language, severity level, and a message that cites the relevant security standards (CWE‑798 and OWASP A07:2021). The reference link is also provided.
16-60
: Utility Function Definitions for OracleConnectionStringBuilder (Part 1)
The first part of the utils section correctly sets up an AST grep pattern for finding assignments using thePassword
property via member access. The conditions are precise, and use of regex (e.g. “^OracleConnectionStringBuilder$”) increases accuracy.
61-146
: Utility Function Definitions for OracleConnectionStringBuilder (Part 2)
The subsequent definitions (e.g. for assignments using brackets, instance matching with braces/without braces) cover additional C# coding forms. They seem thorough and follow a consistent structure.
147-342
: Final Rule Aggregation for OracleConnectionStringBuilder
The rule correctly aggregates all defined match patterns, ensuring that any style of hard-coded password assignment will trigger a warning. This comprehensive approach is robust.rules/csharp/security/npgsqlconnectionstringbuilder-hardcoded-secret-csharp.yml (3)
1-15
: Metadata and Rule Definition Information
The metadata fields (id, language, severity, message, and note) are clearly defined and give a comprehensive context for this rule. Ensure that the reference URL and security guidelines remain up‑to‑date.
16-17
: Configuration Flag Confirmation
The inclusion ofast-grep-essentials: true
is correct and signals that tree‑sitter matchers are in use.
342-351
: Aggregated Rule Definition
The finalrule:
block aggregates all the individual utility patterns effectively. Verify that the ordering of the match patterns (especially the direct assignment check at the end) aligns with the intended detection priorities.rules/csharp/security/sqlconnectionstringbuilder-hardcoded-secret-csharp.yml (3)
1-15
: Metadata and Rule Definition Information
The metadata (id, language, severity, message, and note) is clearly defined, providing a solid overview for this rule. As with the other file, ensure that the provided references are kept current.
16-17
: Configuration Flag Confirmation
Theast-grep-essentials: true
flag confirms the use of tree‑sitter matchers and is appropriately set.
342-351
: Aggregated Rule Definition
The finalrule:
block aggregates the individual match patterns seamlessly. Ensure that the order in which these patterns are applied corresponds to the intended detection priority.rules/csharp/security/networkcredential-hardcoded-secret-python.yml (11)
16-17
: AST Grep Essentials Flag VerificationThe flag
ast-grep-essentials: true
is set to ensure the rule leverages essential tree-sitter patterns. Confirm that this flag is necessary and aligns with your intended matching strategies.
18-60
: Utility Function: match_NetworkCredential_with_stringThis block defines a pattern that captures assignment expressions where the
Password
member is accessed and assigned a string literal. The nested structure—especially the enforcement of the declaration of a variable with the identifier matching^NetworkCredential$
—is thorough. Ensure that this pattern covers all intended hard-coded secret scenarios in your C# code.
61-105
: Utility Function: match_with_bracketsThis snippet targets patterns using an element access expression with a bracketed argument list and validates that the corresponding variable declaration represents a
NetworkCredential
. The design is well-structured. Double-check that similar coding patterns encountered in real-world code are fully covered.
106-146
: Utility Function: match_instance_with_bracesThis utility is crafted to capture assignment expressions involving bracketed arguments (i.e. “with braces”) where a
NetworkCredential
is instantiated. The nested matching on object creation expressions is clear and consistent. Please verify with test cases that any edge cases are appropriately handled.
147-184
: Utility Function: match_instance_without_bracesThis pattern targets member access expressions on the
Password
field without the use of brackets and ensures that the assignment is associated with an instance ofNetworkCredential
. Its structure aligns with other utility patterns in the file.
185-241
: Utility Function: braces_instanceThis block matches cases where there is an element access expression with a bracketed argument list followed by a specific identifier. Although the structure is more complex, it comprehensively ties the matching to a subsequent variable declaration of
NetworkCredential
. Please ensure your snapshot tests validate these intricate matching conditions.
242-298
: Utility Function: match_password_with_instanceThis section identifies assignments where a hard-coded password is set via direct member access on a
NetworkCredential
instance. The use of two "follows" clauses to verify linked variable declarations improves reliability. The overall pattern is thorough.
299-321
: Direct Assignment Pattern for NetworkCredential PasswordThis rule explicitly targets assignment expressions of the form
(NetworkCredential $VALUE).Password = "$PASSWORD"
. The detailed matching—including the use ofnthChild
parameters and subsequent validation against a field declaration—is precise and should catch direct hard-coded assignments.
342-360
: Utility Function: match_network_credential1This pattern captures the creation of a
NetworkCredential
object with an argument list where both arguments are provided as string literals. It effectively flags hard-coded credentials during object instantiation.
361-393
: Utility Function: match_network_credential2This block extends detection to scenarios where the second constructor argument is an identifier (captured by
$J
), with a subsequent variable declaration asserting the usage of a hard-coded string literal. This layered approach is well-conceived; just ensure comprehensive test coverage to avoid false negatives.
396-406
: Aggregate Rule DefinitionThe
rule
block aggregates all the utility functions using anany
operator, which broadens the detection net. Verify that the logical OR of these patterns aligns with your intended security policy and that the combination does not produce unintended false positives.
Summary by CodeRabbit
New Features
Tests