diff --git a/internal/services/engines/csharp/rule_manager.go b/internal/services/engines/csharp/rule_manager.go index 2c0a79212..e884c1f3e 100644 --- a/internal/services/engines/csharp/rule_manager.go +++ b/internal/services/engines/csharp/rule_manager.go @@ -68,7 +68,7 @@ func Rules() []engine.Rule { NewCookieWithoutHttpOnlyFlag(), NewSQLInjectionEnterpriseLibraryData(), NewCQLInjectionCassandra(), - NewPasswordComplexity(), + NewPasswordComplexityDefault(), NewNoInputVariable(), NewIdentityWeakPasswordComplexity(), diff --git a/internal/services/engines/csharp/rules.go b/internal/services/engines/csharp/rules.go index 385e8ac2f..3a28eb88a 100644 --- a/internal/services/engines/csharp/rules.go +++ b/internal/services/engines/csharp/rules.go @@ -28,11 +28,13 @@ import ( func NewCommandInjection() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-1", - Name: "Command Injection", - Description: "If a malicious user controls either the FileName or Arguments, he might be able to execute unwanted commands or add unwanted argument. This behavior would not be possible if input parameter are validate against a white-list of characters. For more information access: (https://security-code-scan.github.io/#SCS0001).", - Severity: severities.Medium.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-1", + Name: "Command Injection", + Description: "If a malicious user controls either the FileName or Arguments, he might be able to execute unwanted commands or add unwanted argument. This behavior would not be possible if input parameter are validate against a white-list of characters. For more information access: (https://security-code-scan.github.io/#SCS0001).", + Severity: severities.Medium.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP1, + UnsafeExample: SampleVulnerableHSCSHARP1, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ @@ -46,11 +48,13 @@ func NewCommandInjection() *text.Rule { func NewXPathInjection() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-2", - Name: "XPath Injection", - Description: "If the user input is not properly filtered, a malicious user could extend the XPath query. For more information access: (https://security-code-scan.github.io/#SCS0003).", - Severity: severities.Medium.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-2", + Name: "XPath Injection", + Description: "If the user input is not properly filtered, a malicious user could extend the XPath query. For more information access: (https://security-code-scan.github.io/#SCS0003).", + Severity: severities.Medium.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP2, + UnsafeExample: SampleVulnerableHSCSHARP2, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ @@ -64,20 +68,18 @@ func NewXPathInjection() *text.Rule { func NewExternalEntityInjection() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-3", - Name: "XML eXternal Entity Injection (XXE)", - Description: "The XML parser is configured incorrectly. The operation could be vulnerable to XML eXternal Entity (XXE) processing. For more information access: (https://security-code-scan.github.io/#SCS0007).", - Severity: severities.Medium.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-3", + Name: "XML eXternal Entity Injection (XXE)", + Description: "The XML parser is configured incorrectly. The operation could be vulnerable to XML eXternal Entity (XXE) processing. For more information access: (https://security-code-scan.github.io/#SCS0007).", + Severity: severities.Medium.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP3, + UnsafeExample: SampleVulnerableHSCSHARP3, }, - Type: text.AndMatch, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`new XmlReaderSettings\(\)`), - regexp.MustCompile(`XmlReader.Create\(.*\)`), - regexp.MustCompile(`new XmlDocument\(.*\)`), - regexp.MustCompile(`Load\(.*\)`), - regexp.MustCompile(`ProhibitDtd = false`), - regexp.MustCompile(`(new XmlReaderSettings\(\))(([^P]|P[^r]|Pr[^o]|Pro[^h]|Proh[^i]|Prohi[^b]|Prohib[^i]|Prohibi[^t]|Prohibit[^D]|ProhibitD[^t]|ProhibitDt[^d])*)(\.Load\(.*\))`), + regexp.MustCompile(`(new XmlReaderSettings\(\))(.|\s)*(ProhibitDtd\s*=\s*false)(.|\s)*(XmlReader.Create\(.*\))`), + regexp.MustCompile(`(new XmlReaderSettings\(\))(.|\s)*(DtdProcessing\s*=\s*DtdProcessing.Parse)(.|\s)*(XmlReader.Create\(.*\))`), }, } } @@ -85,17 +87,19 @@ func NewExternalEntityInjection() *text.Rule { func NewPathTraversal() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-4", - Name: "Path Traversal", - Description: "A path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the expected directory.By manipulating variables that reference files with “dot-dot-slash (../)” sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system including application source code or configuration and critical system files. For more information access: (https://security-code-scan.github.io/#SCS0018).", - Severity: severities.Medium.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-4", + Name: "Path Traversal", + Description: "A path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the expected directory.By manipulating variables that reference files with “dot-dot-slash (../)” sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system including application source code or configuration and critical system files. For more information access: (https://security-code-scan.github.io/#SCS0018).", + Severity: severities.Medium.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP4, + UnsafeExample: SampleVulnerableHSCSHARP4, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`ActionResult`), regexp.MustCompile(`System.IO.File.ReadAllBytes\(Server.MapPath\(.*\) \+ .*\)`), - regexp.MustCompile(`File\(.*, System.Net.Mime.MediaTypeNames.Application.Octet, .*\)`), + regexp.MustCompile(`(private|public|protected|internal|var)(([^G]|G[^e]|Ge[^t]|Get[^I]|GetI[^n]|GetIn[^v]|GetInv[^a]|GetInva[^l]|GetInval[^i]|GetInvali[^d]|GetInvalid[^F]|GetInvalidF[^i]|GetInvalidFi[^l]|GetInvalidFil[^e]|GetInvalidFile[^N]|GetInvalidFileN[^a]|GetInvalidFileNa[^m]|GetInvalidFileNam[^e]|GetInvalidFileName[^C]|GetInvalidFileNameC[^h]|GetInvalidFileNameCh[^a]|GetInvalidFileNameCha[^r]|GetInvalidFileNameChar[^s])*)(\s*File\(.*,\s*System\.Net\.Mime\.MediaTypeNames\.Application\.Octet\s*,.*\))`), }, } } @@ -103,16 +107,17 @@ func NewPathTraversal() *text.Rule { func NewSQLInjectionWebControls() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-5", - Name: "SQL Injection WebControls", - Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0014).", - Severity: severities.High.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-5", + Name: "SQL Injection WebControls", + Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0002).", + Severity: severities.High.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP5, + UnsafeExample: SampleVulnerableHSCSHARP5, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`"Select .* From .* where .*" & .*`), - regexp.MustCompile(`System\.Web\.UI\.WebControls\.SqlDataSource | System\.Web\.UI\.WebControls\.SqlDataSourceView | Microsoft\.Whos\.Framework\.Data\.SqlUtility`), + regexp.MustCompile(`(?i)['|"]Select .* From .* where .*['|"]\s*\+\s*\w+[[:print:]]*\s*\+\s*['|"]`), }, } } @@ -120,11 +125,13 @@ func NewSQLInjectionWebControls() *text.Rule { func NewWeakCipherOrCBCOrECBMode() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-6", - Name: "Weak Cipher Mode", - Description: "The cipher provides no way to detect that the data has been tampered with. If the cipher text can be controlled by an attacker, it could be altered without detection. The use of AES in CBC mode with a HMAC is recommended guaranteeing integrity and confidentiality. For more information access: (https://security-code-scan.github.io/#SCS0013).", - Severity: severities.Medium.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-6", + Name: "Weak Cipher Mode", + Description: "The cipher provides no way to detect that the data has been tampered with. If the cipher text can be controlled by an attacker, it could be altered without detection. The use of AES in CBC mode with a HMAC is recommended guaranteeing integrity and confidentiality. For more information access: (https://security-code-scan.github.io/#SCS0013).", + Severity: severities.Medium.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP6, + UnsafeExample: SampleVulnerableHSCSHARP6, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ @@ -140,16 +147,18 @@ func NewWeakCipherOrCBCOrECBMode() *text.Rule { func NewFormsAuthenticationCookielessMode() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-7", - Name: "Forms Authentication Cookieless Mode", - Description: "Authentication cookies should not be sent in the URL. Doing so allows attackers to gain unauthorized access to authentication tokens (web server logs, referrer headers, and browser history) and more easily perform session fixation / hijacking attacks. For more information checkout the CWE-598 (https://cwe.mitre.org/data/definitions/598.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-7", + Name: "Forms Authentication Cookieless Mode", + Description: "Authentication cookies should not be sent in the URL. Doing so allows attackers to gain unauthorized access to authentication tokens (web server logs, referrer headers, and browser history) and more easily perform session fixation / hijacking attacks. For more information checkout the CWE-598 (https://cwe.mitre.org/data/definitions/598.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP7, + UnsafeExample: SampleVulnerableHSCSHARP7, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`\)`), + regexp.MustCompile(`\ true;`), regexp.MustCompile(`new WebRequestHandler\(\)`), - regexp.MustCompile(`ServerCertificateValidationCallback \+= \(.*\) => true;`), }, } } @@ -400,16 +437,18 @@ func NewCertificateValidationDisabledAndMatch() *text.Rule { func NewActionRequestValidationDisabled() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-22", - Name: "Action Request Validation Disabled", - Description: "Request validation performs blacklist input validation for XSS payloads found in form and URL request parameters. Request validation has known bypass issues and does not prevent all XSS attacks, but it does provide a strong countermeasure for most payloads targeting a HTML context. For more information checkout the CWE-20 (https://cwe.mitre.org/data/definitions/20.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-22", + Name: "Action Request Validation Disabled", + Description: "Request validation performs blacklist input validation for XSS payloads found in form and URL request parameters. Request validation has known bypass issues and does not prevent all XSS attacks, but it does provide a strong countermeasure for most payloads targeting a HTML context. For more information checkout the CWE-20 (https://cwe.mitre.org/data/definitions/20.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP22, + UnsafeExample: SampleVulnerableHSCSHARP22, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`(\[HttpGet\(.*\)\]|\[HttpPost\(.*\)\]|\[HttpPut\(.*\)\]|\[HttpDelete\(.*\)\]|\[HttpGet\]|\[HttpPost\]|\[HttpPut\]|\[HttpDelete\])`), regexp.MustCompile(`\[ValidateInput\(false\)\]`), + regexp.MustCompile(`(\[HttpGet(\(.*\))?\]|\[HttpPost(\(.*\))?\]|\[HttpPut(\(.*\))?\]|\[HttpDelete(\(.*\))?\])`), }, } } @@ -417,16 +456,18 @@ func NewActionRequestValidationDisabled() *text.Rule { func NewXmlDocumentExternalEntityExpansion() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-23", - Name: "Xml Document External Entity Expansion", - Description: "XML External Entity (XXE) vulnerabilities occur when applications process untrusted XML data without disabling external entities and DTD processing. Processing untrusted XML data with a vulnerable parser can allow attackers to extract data from the server, perform denial of service attacks, and in some cases gain remote code execution. The XmlDocument class is vulnerable to XXE attacks when setting the XmlResolver property to resolve external entities. To prevent XmlDocument XXE attacks, set the XmlResolver property to null. For more information checkout the CWE-611 (https://cwe.mitre.org/data/definitions/611.html) advisory.", - Severity: severities.High.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-23", + Name: "Xml Document External Entity Expansion", + Description: "XML External Entity (XXE) vulnerabilities occur when applications process untrusted XML data without disabling external entities and DTD processing. Processing untrusted XML data with a vulnerable parser can allow attackers to extract data from the server, perform denial of service attacks, and in some cases gain remote code execution. The XmlDocument class is vulnerable to XXE attacks when setting the XmlResolver property to resolve external entities. To prevent XmlDocument XXE attacks, set the XmlResolver property to null. For more information checkout the CWE-611 (https://cwe.mitre.org/data/definitions/611.html) advisory.", + Severity: severities.High.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP23, + UnsafeExample: SampleVulnerableHSCSHARP23, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ + regexp.MustCompile(`(?i)(\.XmlResolver\s*=\s*)(([^n]|n[^u]|nu[^l]|nul[^l])*)(\.LoadXml\()`), regexp.MustCompile(`new\sXmlDocument`), - regexp.MustCompile(`(XmlResolver)(([^n]|n[^u]|nu[^l]|nul[^l])*)(;)`), }, } } @@ -434,17 +475,19 @@ func NewXmlDocumentExternalEntityExpansion() *text.Rule { func NewLdapInjectionFilterAssignment() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-24", - Name: "Ldap Injection Filter Assignment", - Description: "LDAP Injection vulnerabilities occur when untrusted data is concatenated into a LDAP Path or Filter expression without properly escaping control characters. This can allow attackers to change the meaning of an LDAP query and gain access to resources for which they are not authorized. For more information checkout the CWE-90 (https://cwe.mitre.org/data/definitions/90.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-24", + Name: "Ldap Injection Filter Assignment", + Description: "LDAP Injection vulnerabilities occur when untrusted data is concatenated into a LDAP Path or Filter expression without properly escaping control characters. This can allow attackers to change the meaning of an LDAP query and gain access to resources for which they are not authorized. Fixing the LDAP Injection Filter Assignment vulnerability requires untrusted data to be encoded using the Web Protection Library (aka AntiXSS) LDAP encoding method 'Encoder.LdapFilterEncode()'. For more information checkout the CWE-90 (https://cwe.mitre.org/data/definitions/90.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP24, + UnsafeExample: SampleVulnerableHSCSHARP24, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ + regexp.MustCompile(`(\.Filter)(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r]|Encoder[^.]|Encoder\.[^L]|Encoder\.L[^d]|Encoder\.Ld[^a]|Encoder\.Lda[^p]|Encoder\.Ldap[^F]|Encoder\.LdapF[^i]|Encoder\.LdapFi[^l]|Encoder\.LdapFil[^t]|Encoder\.LdapFilt[^e]|Encoder\.LdapFilte[^r]|Encoder\.LdapFilter[^E]|Encoder\.LdapFilterE[^n]|Encoder\.LdapFilterEn[^c]|Encoder\.LdapFilterEnc[^o]|Encoder\.LdapFilterEnco[^d]|Encoder\.LdapFilterEncod[^e])*)(\);)`), regexp.MustCompile(`new DirectoryEntry\(.*\)`), regexp.MustCompile(`new DirectorySearcher\(.*\)`), - regexp.MustCompile(`(\.Filter)(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r]|Encoder[^.]|Encoder\.[^L]|Encoder\.L[^d]|Encoder\.Ld[^a]|Encoder\.Lda[^p]|Encoder\.Ldap[^F]|Encoder\.LdapF[^i]|Encoder\.LdapFi[^l]|Encoder\.LdapFil[^t]|Encoder\.LdapFilt[^e]|Encoder\.LdapFilte[^r]|Encoder\.LdapFilter[^E]|Encoder\.LdapFilterE[^n]|Encoder\.LdapFilterEn[^c]|Encoder\.LdapFilterEnc[^o]|Encoder\.LdapFilterEnco[^d]|Encoder\.LdapFilterEncod[^e])*)(\);)`), }, } } @@ -452,11 +495,13 @@ func NewLdapInjectionFilterAssignment() *text.Rule { func NewSqlInjectionDynamicNHibernateQuery() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-25", - Name: "Sql Injection: Dynamic NHibernate Query", - Description: "Concatenating untrusted data into a dynamic SQL string and calling vulnerable NHibernate Framework methods can allow SQL Injection. To ensure calls to vulnerable NHibernate Framework methods are parameterized, pass positional or named parameters in the statement. The following NHibernate methods allow for raw SQL queries to be executed: CreateQuery CreateSqlQuery To ensure calls to vulnerable NHibernate methods are parameterized, use named parameters in the raw SQL query. Then, set the named parameter values when executing the query. For more information checkout the CWE-89 (https://cwe.mitre.org/data/definitions/89.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-25", + Name: "Sql Injection: Dynamic NHibernate Query", + Description: "Concatenating untrusted data into a dynamic SQL string and calling vulnerable NHibernate Framework methods can allow SQL Injection. To ensure calls to vulnerable NHibernate Framework methods are parameterized, pass positional or named parameters in the statement. The following NHibernate methods allow for raw SQL queries to be executed: CreateQuery CreateSqlQuery To ensure calls to vulnerable NHibernate methods are parameterized, use named parameters in the raw SQL query. Then, set the named parameter values when executing the query. For more information checkout the CWE-89 (https://cwe.mitre.org/data/definitions/89.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP25, + UnsafeExample: SampleVulnerableHSCSHARP25, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ @@ -469,16 +514,18 @@ func NewSqlInjectionDynamicNHibernateQuery() *text.Rule { func NewLdapInjectionDirectorySearcher() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-26", - Name: "Ldap Injection Directory Searcher", - Description: "LDAP Injection vulnerabilities occur when untrusted data is concatenated into a LDAP Path or Filter expression without properly escaping control characters. This can allow attackers to change the meaning of an LDAP query and gain access to resources for which they are not authorized. For more information checkout the CWE-90 (https://cwe.mitre.org/data/definitions/90.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-26", + Name: "Ldap Injection Directory Searcher", + Description: "LDAP Injection vulnerabilities occur when untrusted data is concatenated into a LDAP Path or Filter expression without properly escaping control characters. This can allow attackers to change the meaning of an LDAP query and gain access to resources for which they are not authorized. Fixing the LDAP Injection Directory Searcher vulnerability requires untrusted data to be encoded using the Web Protection Library (aka AntiXSS) LDAP encoding method 'Encoder.LdapFilterEncode'. For more information checkout the CWE-90 (https://cwe.mitre.org/data/definitions/90.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP26, + UnsafeExample: SampleVulnerableHSCSHARP26, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ + regexp.MustCompile(`(new DirectorySearcher\s*\(\s*.*\s*,\s*.*\s*,\s*)(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r]|Encoder[^.]|Encoder\.[^L]|Encoder\.L[^d]|Encoder\.Ld[^a]|Encoder\.Lda[^p]|Encoder\.Ldap[^F]|Encoder\.LdapF[^i]|Encoder\.LdapFi[^l]|Encoder\.LdapFil[^t]|Encoder\.LdapFilt[^e]|Encoder\.LdapFilte[^r]|Encoder\.LdapFilter[^E]|Encoder\.LdapFilterE[^n]|Encoder\.LdapFilterEn[^c]|Encoder\.LdapFilterEnc[^o]|Encoder\.LdapFilterEnco[^d]|Encoder\.LdapFilterEncod[^e])*)(\);)`), regexp.MustCompile(`new DirectoryEntry\(.*\)`), - regexp.MustCompile(`(new DirectorySearcher)(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r]|Encoder[^.]|Encoder\.[^L]|Encoder\.L[^d]|Encoder\.Ld[^a]|Encoder\.Lda[^p]|Encoder\.Ldap[^F]|Encoder\.LdapF[^i]|Encoder\.LdapFi[^l]|Encoder\.LdapFil[^t]|Encoder\.LdapFilt[^e]|Encoder\.LdapFilte[^r]|Encoder\.LdapFilter[^E]|Encoder\.LdapFilterE[^n]|Encoder\.LdapFilterEn[^c]|Encoder\.LdapFilterEnc[^o]|Encoder\.LdapFilterEnco[^d]|Encoder\.LdapFilterEncod[^e])*)(\);)`), }, } } @@ -486,16 +533,18 @@ func NewLdapInjectionDirectorySearcher() *text.Rule { func NewLdapInjectionPathAssignment() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-27", - Name: "Ldap Injection Path Assignment", - Description: "LDAP Injection vulnerabilities occur when untrusted data is concatenated into a LDAP Path or Filter expression without properly escaping control characters. This can allow attackers to change the meaning of an LDAP query and gain access to resources for which they are not authorized. For more information checkout the CWE-90 (https://cwe.mitre.org/data/definitions/90.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-27", + Name: "Ldap Injection Path Assignment", + Description: "LDAP Injection vulnerabilities occur when untrusted data is concatenated into a LDAP Path or Filter expression without properly escaping control characters. This can allow attackers to change the meaning of an LDAP query and gain access to resources for which they are not authorized. Fixing the LDAP Injection Path Assignment vulnerability requires untrusted data to be encoded using the appropriate Web Protection Library (aka AntiXSS) LDAP encoding method 'Encoder.LdapDistinguishedNameEncode'. For more information checkout the CWE-90 (https://cwe.mitre.org/data/definitions/90.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP27, + UnsafeExample: SampleVulnerableHSCSHARP27, }, Type: text.AndMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`new DirectoryEntry\(\)`), regexp.MustCompile(`(\.Path)(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r]|Encoder[^.]|Encoder\.[^L]|Encoder\.L[^d]|Encoder\.Ld[^a]|Encoder\.Lda[^p]|Encoder\.Ldap[^D]|Encoder\.LdapD[^i]|Encoder\.LdapDi[^s]|Encoder\.LdapDis[^t]|Encoder\.LdapDist[^i]|Encoder\.LdapDisti[^n]|Encoder\.LdapDistin[^g]|Encoder\.LdapDisting[^u]|Encoder\.LdapDistingu[^i]|Encoder\.LdapDistingui[^s]|Encoder\.LdapDistinguis[^h]|Encoder\.LdapDistinguish[^e]|Encoder\.LdapDistinguishe[^d]|Encoder\.LdapDistinguished[^N]|Encoder\.LdapDistinguishedN[^a]|Encoder\.LdapDistinguishedNa[^m]|Encoder\.LdapDistinguishedNam[^e]|Encoder\.LdapDistinguishedName[^E]|Encoder\.LdapDistinguishedNameE[^n]|Encoder\.LdapDistinguishedNameEn[^c]|Encoder\.LdapDistinguishedNameEnc[^o]|Encoder\.LdapDistinguishedNameEnco[^d]|Encoder\.LdapDistinguishedNameEncod[^e])*)(\);)`), + regexp.MustCompile(`new DirectoryEntry\(\)`), }, } } @@ -503,16 +552,18 @@ func NewLdapInjectionPathAssignment() *text.Rule { func NewLDAPInjection() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-28", - Name: "LDAP Injection", - Description: "The dynamic value passed to the LDAP query should be validated. For more information access: (https://security-code-scan.github.io/#SCS0031).", - Severity: severities.High.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-28", + Name: "LDAP Injection", + Description: "The dynamic value passed to the LDAP query should be validated. Risk: If the user input is not properly filtered, a malicious user could extend the LDAP query. Solution: Use proper encoder (LdapFilterEncode or LdapDistinguishedNameEncode) from AntiXSS library:. For more information access: (https://security-code-scan.github.io/#SCS0031) or (https://security-code-scan.github.io/#SCS0026) or CWE-90 (https://cwe.mitre.org/data/definitions/90.html) advisory.", + Severity: severities.High.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP28, + UnsafeExample: SampleVulnerableHSCSHARP28, }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`(new DirectorySearcher\(\))(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r]|Encoder[^.]|Encoder\.[^L]|Encoder\.L[^d]|Encoder\.Ld[^a]|Encoder\.Lda[^p]|Encoder\.Ldap[^F]|Encoder\.LdapF[^i]|Encoder\.LdapFi[^l]|Encoder\.LdapFil[^t]|Encoder\.LdapFilt[^e]|Encoder\.LdapFilte[^r]|Encoder\.LdapFilter[^E]|Encoder\.LdapFilterE[^n]|Encoder\.LdapFilterEn[^c]|Encoder\.LdapFilterEnc[^o]|Encoder\.LdapFilterEnco[^d]|Encoder\.LdapFilterEncod[^e])*)(\)";)`), - regexp.MustCompile(`(new DirectoryEntry\(\))(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r]|Encoder[^.]|Encoder\.[^L]|Encoder\.L[^d]|Encoder\.Ld[^a]|Encoder\.Lda[^p]|Encoder\.Ldap[^D]|Encoder\.LdapD[^i]|Encoder\.LdapDi[^s]|Encoder\.LdapDis[^t]|Encoder\.LdapDist[^i]|Encoder\.LdapDisti[^n]|Encoder\.LdapDistin[^g]|Encoder\.LdapDisting[^u]|Encoder\.LdapDistingu[^i]|Encoder\.LdapDistingui[^s]|Encoder\.LdapDistinguis[^h]|Encoder\.LdapDistinguish[^e]|Encoder\.LdapDistinguishe[^d]|Encoder\.LdapDistinguished[^N]|Encoder\.LdapDistinguishedN[^a]|Encoder\.LdapDistinguishedNa[^m]|Encoder\.LdapDistinguishedNam[^e]|Encoder\.LdapDistinguishedName[^E]|Encoder\.LdapDistinguishedNameE[^n]|Encoder\.LdapDistinguishedNameEn[^c]|Encoder\.LdapDistinguishedNameEnc[^o]|Encoder\.LdapDistinguishedNameEnco[^d]|Encoder\.LdapDistinguishedNameEncod[^e])*)(,.*";)`), + regexp.MustCompile(`(.Filter\s*=\s*)(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r]|Encoder[^.]|Encoder\.[^L]|Encoder\.L[^d]|Encoder\.Ld[^a]|Encoder\.Lda[^p]|Encoder\.Ldap[^F]|Encoder\.LdapF[^i]|Encoder\.LdapFi[^l]|Encoder\.LdapFil[^t]|Encoder\.LdapFilt[^e]|Encoder\.LdapFilte[^r]|Encoder\.LdapFilter[^E]|Encoder\.LdapFilterE[^n]|Encoder\.LdapFilterEn[^c]|Encoder\.LdapFilterEnc[^o]|Encoder\.LdapFilterEnco[^d]|Encoder\.LdapFilterEncod[^e])*)(\)['|"])`), + regexp.MustCompile(`(.Path\s*=\s*)(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r]|Encoder[^.]|Encoder\.[^L]|Encoder\.L[^d]|Encoder\.Ld[^a]|Encoder\.Lda[^p]|Encoder\.Ldap[^D]|Encoder\.LdapD[^i]|Encoder\.LdapDi[^s]|Encoder\.LdapDis[^t]|Encoder\.LdapDist[^i]|Encoder\.LdapDisti[^n]|Encoder\.LdapDistin[^g]|Encoder\.LdapDisting[^u]|Encoder\.LdapDistingu[^i]|Encoder\.LdapDistingui[^s]|Encoder\.LdapDistinguis[^h]|Encoder\.LdapDistinguish[^e]|Encoder\.LdapDistinguishe[^d]|Encoder\.LdapDistinguished[^N]|Encoder\.LdapDistinguishedN[^a]|Encoder\.LdapDistinguishedNa[^m]|Encoder\.LdapDistinguishedNam[^e]|Encoder\.LdapDistinguishedName[^E]|Encoder\.LdapDistinguishedNameE[^n]|Encoder\.LdapDistinguishedNameEn[^c]|Encoder\.LdapDistinguishedNameEnc[^o]|Encoder\.LdapDistinguishedNameEnco[^d]|Encoder\.LdapDistinguishedNameEncod[^e])*)(,.*['|"])`), }, } } @@ -520,11 +571,13 @@ func NewLDAPInjection() *text.Rule { func NewSQLInjectionLinq() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-29", - Name: "SQL Injection LINQ", - Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database.. For more information access: (https://security-code-scan.github.io/#SCS0002).", - Severity: severities.High.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-29", + Name: "SQL Injection LINQ", + Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database.. For more information access: (https://security-code-scan.github.io/#SCS0002).", + Severity: severities.High.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP29, + UnsafeExample: SampleVulnerableHSCSHARP29, }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ @@ -536,11 +589,25 @@ func NewSQLInjectionLinq() *text.Rule { func NewInsecureDeserialization() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-30", - Name: "Insecure Deserialization", - Description: "Arbitrary code execution, full application compromise or denial of service. An attacker may pass specially crafted serialized .NET object of specific class that will execute malicious code during the construction of the object. For more information access: (https://security-code-scan.github.io/#SCS0028).", - Severity: severities.Low.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-30", + Name: "Insecure Deserialization", + Description: `Arbitrary code execution, full application compromise or denial of service. An attacker may pass specially crafted serialized .NET object of specific class that will execute malicious code during the construction of the object. +Solution: +There is no simple fix. Do not deserialize untrusted data: user input, cookies or data that crosses trust boundaries. + +In case it is unavoidable: +1) If serialization is done on the server side, then crosses trust boundary, but is not modified and is returned back (like cookie for example) - use signed cryptography (HMAC for instance) to ensure it wasn’t tampered. +2) Do not get the type to deserialize into from untrusted source: the serialized stream itself or other untrusted parameter. BinaryFormatter for example reads type information from serialized stream itself and can’t be used with untrusted streams: + +// DO NOT DO THIS! +var thing = (MyType)new BinaryFormatter().Deserialize(untrustedStream); + +JavaScriptSerializer for instance without a JavaScriptTypeResolver is safe because it doesn’t resolve types at all: +3) If the library supports implement a callback that verifies if the object and its properties are of expected type (don’t blacklist, use whitelist!) +4) Serialize simple Data Transfer Objects (DTO) only. Do not serialize/deserialize type information. For example, use only TypeNameHandling.None (the default) in Json.net +For more information access: (https://security-code-scan.github.io/#SCS0028).`, + Severity: severities.Low.ToString(), + Confidence: confidence.Low.ToString(), }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ @@ -553,11 +620,13 @@ func NewInsecureDeserialization() *text.Rule { func NewSQLInjectionEnterpriseLibraryData() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-31", - Name: "SQL Injection Enterprise Library Data", - Description: "Arbitrary code execution, full application compromise or denial of service. An attacker may pass specially crafted serialized .NET object of specific class that will execute malicious code during the construction of the object. For more information access: (https://security-code-scan.github.io/#SCS0036).", - Severity: severities.High.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-31", + Name: "SQL Injection Enterprise Library Data", + Description: "Arbitrary code execution, full application compromise or denial of service. An attacker may pass specially crafted serialized .NET object of specific class that will execute malicious code during the construction of the object. For more information access: (https://security-code-scan.github.io/#SCS0036).", + Severity: severities.High.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP31, + UnsafeExample: SampleVulnerableHSCSHARP31, }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ @@ -570,35 +639,37 @@ func NewSQLInjectionEnterpriseLibraryData() *text.Rule { func NewCQLInjectionCassandra() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-32", - Name: "CQL Injection Cassandra", - Description: "Arbitrary code execution, full application compromise or denial of service. An attacker may pass specially crafted serialized .NET object of specific class that will execute malicious code during the construction of the object. For more information access: (https://security-code-scan.github.io/#SCS0038).", - Severity: severities.High.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-32", + Name: "CQL Injection Cassandra", + Description: "Arbitrary code execution, full application compromise or denial of service. An attacker may pass specially crafted serialized .NET object of specific class that will execute malicious code during the construction of the object. For more information access: (https://security-code-scan.github.io/#SCS0038).", + Severity: severities.High.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP32, + UnsafeExample: SampleVulnerableHSCSHARP32, }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`(Prepare\("(SELECT|select).*(FROM|from).*(WHERE|where).*\))(([^B]|B[^i]|Bi[^n]|Bin[^d])*)(Execute\(.*\))`), - regexp.MustCompile(`Execute\("(SELECT|select).*(FROM|from).*(WHERE|where).*"\)`), + regexp.MustCompile(`(?i)(PreparedStatement.*Prepare\(['|"]select.*from.*where.*\))(([^B]|B[^i]|Bi[^n]|Bin[^d])*)(Execute\(.*\))`), + regexp.MustCompile(`(?i)Execute\(['|"]select.*from.*where.*['|"]\s*\+.*\)`), }, } } -func NewPasswordComplexity() *text.Rule { +func NewPasswordComplexityDefault() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-33", - Name: "Password Complexity", - Description: "PasswordValidator should have at least two requirements for better security, the RequiredLength property must be set with a minimum value of 8. For more information access: (https://security-code-scan.github.io/#SCS0027).", - Severity: severities.Low.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-33", + Name: "Password Complexity Default", + Description: "PasswordValidator should have at least two requirements for better security, the RequiredLength property must be set with a minimum value of 8. For more information access: (https://security-code-scan.github.io/#SCS0027).", + Severity: severities.Low.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP33, + UnsafeExample: SampleVulnerableHSCSHARP33, }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`new\sPasswordValidator\(\)`), regexp.MustCompile(`new\sPasswordValidator(\n?\s*{)(\n*.*=.*,?)(\s|\n)*[^a-z]}`), - regexp.MustCompile(`new\sPasswordValidator(\n?\s*{)((\n|.*)*RequiredLength=[0-7][^\d])`), - regexp.MustCompile(`(new\sPasswordValidator)(([^R]|R[^e]|Re[^q]|Req[^u]|Requ[^i]|Requi[^r]|Requir[^e]|Require[^d]|Required[^L]|RequiredL[^e]|RequiredLe[^n]|RequiredLen[^g]|RequiredLeng[^t]|RequiredLengt[^h])*)(})`), }, } } @@ -606,11 +677,13 @@ func NewPasswordComplexity() *text.Rule { func NewCookieWithoutSSLFlag() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-34", - Name: "Cookie Without SSL Flag", - Description: "It is recommended to specify the Secure flag to new cookie. The Secure flag is a directive to the browser to make sure that the cookie is not sent by unencrypted channel. For more information access: (https://security-code-scan.github.io/#SCS0008) and (https://cwe.mitre.org/data/definitions/614.html).", - Severity: severities.Low.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-34", + Name: "Cookie Without SSL Flag", + Description: "It is recommended to specify the Secure flag to new cookie. The Secure flag is a directive to the browser to make sure that the cookie is not sent by unencrypted channel. For more information access: (https://security-code-scan.github.io/#SCS0008) and (https://cwe.mitre.org/data/definitions/614.html).", + Severity: severities.Low.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP34, + UnsafeExample: SampleVulnerableHSCSHARP34, }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ @@ -625,11 +698,13 @@ func NewCookieWithoutSSLFlag() *text.Rule { func NewCookieWithoutHttpOnlyFlag() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-35", - Name: "Cookie Without HttpOnly Flag", - Description: "It is recommended to specify the HttpOnly flag to new cookie. For more information access: (https://security-code-scan.github.io/#SCS0009) or (https://cwe.mitre.org/data/definitions/1004.html).", - Severity: severities.Low.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-35", + Name: "Cookie Without HttpOnly Flag", + Description: "It is recommended to specify the HttpOnly flag to new cookie. For more information access: (https://security-code-scan.github.io/#SCS0009) or (https://cwe.mitre.org/data/definitions/1004.html).", + Severity: severities.Low.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP35, + UnsafeExample: SampleVulnerableHSCSHARP35, }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ @@ -643,11 +718,13 @@ func NewCookieWithoutHttpOnlyFlag() *text.Rule { func NewNoInputVariable() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-36", - Name: "No input variable", - Description: "The application appears to allow XSS through an unencrypted / unauthorized input variable. https://owasp.org/www-community/attacks/xss/. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", - Severity: severities.High.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-36", + Name: "No input variable", + Description: "The application appears to allow XSS through an unencrypted / unauthorized input variable. https://owasp.org/www-community/attacks/xss/. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", + Severity: severities.High.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP36, + UnsafeExample: SampleVulnerableHSCSHARP36, }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ @@ -660,11 +737,13 @@ func NewNoInputVariable() *text.Rule { func NewIdentityWeakPasswordComplexity() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-37", - Name: "Identity Weak Password Complexity", - Description: "Weak passwords can allow attackers to easily guess user passwords using wordlist or brute force attacks. Enforcing a strict password complexity policy mitigates these attacks by significantly increasing the time to guess a user’s valid password. For more information checkout the CWE-521 (https://cwe.mitre.org/data/definitions/521.html) advisory.", - Severity: severities.Critical.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-37", + Name: "Identity Weak Password Complexity", + Description: "Weak passwords can allow attackers to easily guess user passwords using wordlist or brute force attacks. Enforcing a strict password complexity policy mitigates these attacks by significantly increasing the time to guess a user’s valid password. For more information checkout the CWE-521 (https://cwe.mitre.org/data/definitions/521.html) advisory.", + Severity: severities.Critical.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP37, + UnsafeExample: SampleVulnerableHSCSHARP37, }, Type: text.OrMatch, Expressions: []*regexp.Regexp{ @@ -682,13 +761,15 @@ func NewIdentityWeakPasswordComplexity() *text.Rule { func NewNoLogSensitiveInformationInConsole() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-38", - Name: "No Log Sensitive Information in console", - Description: "The App logs information. Sensitive information should never be logged. For more information checkout the CWE-532 (https://cwe.mitre.org/data/definitions/532.html) advisory.", - Severity: severities.Info.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-38", + Name: "No Log Sensitive Information in console", + Description: "The App logs information. Sensitive information should never be logged. For more information checkout the CWE-532 (https://cwe.mitre.org/data/definitions/532.html) advisory.", + Severity: severities.Info.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP38, + UnsafeExample: SampleVulnerableHSCSHARP38, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(?i)(((Log|log).*\.(Verbose|Debug|Info|Warn|Erro|ForContext|FromLogContext|Seq))|(Console.Write))`), }, @@ -698,13 +779,15 @@ func NewNoLogSensitiveInformationInConsole() *text.Rule { func NewOutputCacheConflict() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-39", - Name: "OutputCache Conflict", - Description: "Having the annotation [OutputCache] will disable the annotation [Authorize] for the requests following the first one. For more information access: (https://security-code-scan.github.io/#SCS0019).", - Severity: severities.Medium.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-39", + Name: "OutputCache Conflict", + Description: "Having the annotation [OutputCache] will disable the annotation [Authorize] for the requests following the first one. For more information access: (https://security-code-scan.github.io/#SCS0019).", + Severity: severities.Medium.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP39, + UnsafeExample: SampleVulnerableHSCSHARP39, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(\[Authorize\])(.*|\n)*(\[OutputCache\])`), }, @@ -714,13 +797,15 @@ func NewOutputCacheConflict() *text.Rule { func NewOpenRedirect() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-40", - Name: "Open Redirect", - Description: "Your site may be used in phishing attacks. An attacker may craft a trustworthy looking link to your site redirecting a victim to a similar looking malicious site: 'http://yourdomain.com?redirect=https://urdomain.com/login'. For more information access: (https://security-code-scan.github.io/#SCS0027).", - Severity: severities.Low.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-40", + Name: "Open Redirect", + Description: "Your site may be used in phishing attacks. An attacker may craft a trustworthy looking link to your site redirecting a victim to a similar looking malicious site: 'http://yourdomain.com?redirect=https://urdomain.com/login'. For more information access: (https://security-code-scan.github.io/#SCS0027).", + Severity: severities.Low.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP40, + UnsafeExample: SampleVulnerableHSCSHARP40, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`String.IsNullOrEmpty.*\n?.*{?\n?.*return\sRedirect\(.*\);`), }, @@ -730,13 +815,15 @@ func NewOpenRedirect() *text.Rule { func NewRequestValidationDisabledAttribute() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-41", - Name: "Request Validation Disabled (Attribute)", - Description: "Request validation is disabled. Request validation allows the filtering of some XSS patterns submitted to the application. For more information access: (https://security-code-scan.github.io/#SCS0017).", - Severity: severities.High.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-41", + Name: "Request Validation Disabled (Attribute)", + Description: "Request validation is disabled. Request validation allows the filtering of some XSS patterns submitted to the application. For more information access: (https://security-code-scan.github.io/#SCS0017).", + Severity: severities.High.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP41, + UnsafeExample: SampleVulnerableHSCSHARP41, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`\[ValidateInput\(false\)\]`), }, @@ -746,13 +833,15 @@ func NewRequestValidationDisabledAttribute() *text.Rule { func NewSQLInjectionOLEDB() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-42", - Name: "SQL Injection OLE DB", - Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0020).", - Severity: severities.High.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-42", + Name: "SQL Injection OLE DB", + Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0020).", + Severity: severities.High.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP42, + UnsafeExample: SampleVulnerableHSCSHARP42, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(new OleDbConnection\(.*\))(([^P]|P[^a]|Pa[^r]|Par[^a]|Para[^m]|Param[^e]|Parame[^t]|Paramet[^e]|Paramete[^r]|Parameter[^s]|Parameters[^.]|Parameters\.[^A]|Parameters\.A[^d]|Parameters\.Ad[^d])*)(\.ExecuteReader\(.*\))`), }, @@ -762,13 +851,15 @@ func NewSQLInjectionOLEDB() *text.Rule { func NewRequestValidationDisabledConfigurationFile() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-43", - Name: "Request Validation Disabled (Configuration File)", - Description: "The validateRequest which provides additional protection against XSS is disabled in configuration file. For more information access: (https://security-code-scan.github.io/#SCS0017) or (https://cwe.mitre.org/data/definitions/20.html).", - Severity: severities.High.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-43", + Name: "Request Validation Disabled (Configuration File)", + Description: "The validateRequest which provides additional protection against XSS is disabled in configuration file. For more information access: (https://security-code-scan.github.io/#SCS0017) or (https://cwe.mitre.org/data/definitions/20.html).", + Severity: severities.High.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP43, + UnsafeExample: SampleVulnerableHSCSHARP43, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`validateRequest\s*=\s*['|"]false['|"]`), }, @@ -778,15 +869,17 @@ func NewRequestValidationDisabledConfigurationFile() *text.Rule { func NewSQLInjectionMsSQLDataProvider() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-44", - Name: "SQL Injection MsSQL Data Provider", - Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0026).", - Severity: severities.High.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-44", + Name: "SQL Injection MsSQL Data Provider", + Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0026).", + Severity: severities.High.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP44, + UnsafeExample: SampleVulnerableHSCSHARP44, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`(new SqlCommand\(.*\))(([^P]|P[^a]|Pa[^r]|Par[^a]|Para[^m]|Param[^e]|Parame[^t]|Paramet[^e]|Paramete[^r]|Parameter[^s]|Parameters[^.]|Parameters\.[^A]|Parameters\.A[^d]|Parameters\.Ad[^d]|Parameters\.Add[^W]|Parameters\.AddW[^i]|Parameters\.AddWi[^t]|Parameters\.AddWit[^h]|Parameters\.AddWith[^V]|Parameters\.AddWithV[^a]|Parameters\.AddWithVa[^l]|Parameters\.AddWithVal[^u]|Parameters\.AddWithValu[^e])*)(Open\(\)|ExecuteReader\(\))`), + regexp.MustCompile(`(new SqlCommand\(.*\))(([^P]|P[^a]|Pa[^r]|Par[^a]|Para[^m]|Param[^e]|Parame[^t]|Paramet[^e]|Paramete[^r]|Parameter[^s]|Parameters[^.]|Parameters\.[^A]|Parameters\.A[^d]|Parameters\.Ad[^d]|Parameters\.Add[^W]|Parameters\.AddW[^i]|Parameters\.AddWi[^t]|Parameters\.AddWit[^h]|Parameters\.AddWith[^V]|Parameters\.AddWithV[^a]|Parameters\.AddWithVa[^l]|Parameters\.AddWithVal[^u]|F[^e])*)(Open\(\)|ExecuteReader\(\))`), }, } } @@ -794,13 +887,15 @@ func NewSQLInjectionMsSQLDataProvider() *text.Rule { func NewRequestValidationIsEnabledOnlyForPages() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-45", - Name: "Request validation is enabled only for pages", - Description: "The requestValidationMode which provides additional protection against XSS is enabled only for pages, not for all HTTP requests in configuration file. For more information access: (https://security-code-scan.github.io/#SCS0030).", - Severity: severities.High.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-45", + Name: "Request validation is enabled only for pages", + Description: "The requestValidationMode which provides additional protection against XSS is enabled only for pages, not for all HTTP requests in configuration file. For more information access: (https://security-code-scan.github.io/#SCS0030).", + Severity: severities.High.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP45, + UnsafeExample: SampleVulnerableHSCSHARP45, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`requestValidationMode\s*=\s*['|"][0-3][^\d].*['|"]`), }, @@ -810,13 +905,15 @@ func NewRequestValidationIsEnabledOnlyForPages() *text.Rule { func NewSQLInjectionEntityFramework() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-46", - Name: "SQL Injection Entity Framework", - Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database, please use SqlParameter to create query with parameters. For more information access: (https://security-code-scan.github.io/#SCS0035) or (https://cwe.mitre.org/data/definitions/89.html) .", - Severity: severities.High.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-46", + Name: "SQL Injection Entity Framework", + Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database, please use SqlParameter to create query with parameters. For more information access: (https://security-code-scan.github.io/#SCS0035) or (https://cwe.mitre.org/data/definitions/89.html) .", + Severity: severities.High.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP46, + UnsafeExample: SampleVulnerableHSCSHARP46, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(Database\.ExecuteSqlCommand)(([^S]|S[^q]|Sq[^l]|Sql[^P]|SqlP[^a]|SqlPa[^r]|SqlPar[^a]|SqlPara[^m]|SqlParam[^e]|SqlParame[^t]|SqlParamet[^e]|SqlParamete[^r])*)(\);)`), }, @@ -826,13 +923,15 @@ func NewSQLInjectionEntityFramework() *text.Rule { func NewViewStateNotEncrypted() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-47", - Name: "View State Not Encrypted", - Description: "The viewStateEncryptionMode is not set to Always in configuration file. Web Forms controls use hidden base64 encoded fields to store state information. If sensitive information is stored there it may be leaked to the client side. For more information access: (https://security-code-scan.github.io/#SCS0023) or (https://cwe.mitre.org/data/definitions/200.html).", - Severity: severities.High.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-47", + Name: "View State Not Encrypted", + Description: "The viewStateEncryptionMode is not set to Always in configuration file. Web Forms controls use hidden base64 encoded fields to store state information. If sensitive information is stored there it may be leaked to the client side. For more information access: (https://security-code-scan.github.io/#SCS0023) or (https://cwe.mitre.org/data/definitions/200.html).", + Severity: severities.High.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP47, + UnsafeExample: SampleVulnerableHSCSHARP47, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`viewStateEncryptionMode\s*=\s*['|"](Auto|Never)['|"]`), }, @@ -842,15 +941,17 @@ func NewViewStateNotEncrypted() *text.Rule { func NewSQLInjectionNhibernate() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-48", - Name: "SQL Injection Nhibernate", - Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0037).", - Severity: severities.High.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-48", + Name: "SQL Injection Nhibernate", + Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0037).", + Severity: severities.High.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP48, + UnsafeExample: SampleVulnerableHSCSHARP48, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`(CreateSQLQuery)(([^S]|S[^e]|Se[^t]|Set[^P]|SetP[^a]|SetPa[^r]|SetPar[^a]|SetPara[^m]|SetParam[^e]|SetParame[^t]|SetParamet[^e]|SetParamete[^r])*)(\);)`), + regexp.MustCompile(`(?i)(\.CreateQuery|\.CreateSqlQuery)(([^S]|S[^e]|Se[^t]|Set[^P]|SetP[^a]|SetPa[^r]|SetPar[^a]|SetPara[^m]|SetParam[^e]|SetParame[^t]|SetParamet[^e]|SetParamete[^r])*)((FirstOrDefault|open|execute|all|list).*\);)`), }, } } @@ -858,13 +959,15 @@ func NewSQLInjectionNhibernate() *text.Rule { func NewViewStateMacDisabled() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-49", - Name: "View State MAC Disabled", - Description: "The enableViewStateMac is disabled in configuration file. (This feature cannot be disabled starting .NET 4.5.1). The view state could be altered by an attacker. For more information access: (https://security-code-scan.github.io/#SCS0024) or (https://cwe.mitre.org/data/definitions/807.html).", - Severity: severities.High.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-49", + Name: "View State MAC Disabled", + Description: "The enableViewStateMac is disabled in configuration file. (This feature cannot be disabled starting .NET 4.5.1). The view state could be altered by an attacker. For more information access: (https://security-code-scan.github.io/#SCS0024) or (https://cwe.mitre.org/data/definitions/807.html).", + Severity: severities.High.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP49, + UnsafeExample: SampleVulnerableHSCSHARP49, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`enableViewStateMac\s*=\s*['|"]false['|"]`), }, @@ -874,15 +977,17 @@ func NewViewStateMacDisabled() *text.Rule { func NewSQLInjectionNpgsql() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-50", - Name: "SQL Injection Npgsql", - Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0039).", - Severity: severities.High.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-50", + Name: "SQL Injection Npgsql", + Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information access: (https://security-code-scan.github.io/#SCS0039).", + Severity: severities.High.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP50, + UnsafeExample: SampleVulnerableHSCSHARP50, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`(NpgsqlCommand\(.*\))(([^P]|P[^a]|Pa[^r]|Par[^a]|Para[^m]|Param[^e]|Parame[^t]|Paramet[^e]|Paramete[^r]|Parameter[^s]|Parameters[^.]|Parameters\.[^A]|Parameters\.A[^d]|Parameters\.Ad[^d]|Parameters\.Add[^W]|Parameters\.AddW[^i]|Parameters\.AddWi[^t]|Parameters\.AddWit[^h]|Parameters\.AddWith[^V]|Parameters\.AddWithV[^a]|Parameters\.AddWithVa[^l]|Parameters\.AddWithVal[^u]|Parameters\.AddWithValu[^e])*)(ExecuteNonQuery\(.*\)|ExecuteReader\(.*\))`), + regexp.MustCompile(`(NpgsqlCommand\()(([^P]|P[^a]|Pa[^r]|Par[^a]|Para[^m]|Param[^e]|Parame[^t]|Paramet[^e]|Paramete[^r]|Parameter[^s]|Parameters[^.]|Parameters\.[^A]|Parameters\.A[^d]|Parameters\.Ad[^d]|Parameters\.Add[^W]|Parameters\.AddW[^i]|Parameters\.AddWi[^t]|Parameters\.AddWit[^h]|Parameters\.AddWith[^V]|Parameters\.AddWithV[^a]|Parameters\.AddWithVa[^l]|Parameters\.AddWithVal[^u]|Parameters\.AddWithValu[^e])*)(ExecuteNonQuery\(.*\)|ExecuteReader\(.*\))`), }, } } @@ -890,15 +995,17 @@ func NewSQLInjectionNpgsql() *text.Rule { func NewCertificateValidationDisabled() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-51", - Name: "Certificate Validation Disabled", - Description: "Disabling certificate validation is often used to connect easily to a host that is not signed by a root certificate authority. As a consequence, this is vulnerable to Man-in-the-middle attacks since the client will trust any certificate. For more information access: (https://security-code-scan.github.io/#SCS0004).", - Severity: severities.Medium.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-51", + Name: "Certificate Validation Disabled", + Description: "Disabling certificate validation is often used to connect easily to a host that is not signed by a root certificate authority. As a consequence, this is vulnerable to Man-in-the-middle attacks since the client will trust any certificate. For more information access: (https://security-code-scan.github.io/#SCS0004).", + Severity: severities.Medium.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP51, + UnsafeExample: SampleVulnerableHSCSHARP51, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`ServicePointManager\.ServerCertificateValidationCallback \+= (.*) => true;`), + regexp.MustCompile(`(ServicePointManager)?\.ServerCertificateValidationCallback \+= (.*) => true;`), }, } } @@ -906,13 +1013,15 @@ func NewCertificateValidationDisabled() *text.Rule { func NewWeakCipherAlgorithm() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-52", - Name: "Weak cipher algorithm", - Description: "Broken or deprecated ciphers have typically known weakness. A attacker might be able to brute force the secret key use for the encryption. The confidentiality and integrity of the information encrypted is at risk. For more information access: (https://security-code-scan.github.io/#SCS0010).", - Severity: severities.Medium.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-52", + Name: "Weak cipher algorithm", + Description: "Broken or deprecated ciphers have typically known weakness. A attacker might be able to brute force the secret key use for the encryption. The confidentiality and integrity of the information encrypted is at risk. For more information access: (https://security-code-scan.github.io/#SCS0010).", + Severity: severities.Medium.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP52, + UnsafeExample: SampleVulnerableHSCSHARP52, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(DES.Create\(\))(([^A]|A[^e]|Ae[^s]|Aes[^M]|AesM[^a]|AesMa[^n]|AesMan[^a]|AesMana[^g]|AesManag[^e]|AesManage[^d])*)(Write\(.*\))`), }, @@ -922,13 +1031,15 @@ func NewWeakCipherAlgorithm() *text.Rule { func NewNoUseHtmlRaw() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-53", - Name: "No use Html.Raw", - Description: "The application uses the potentially dangerous Html.Raw construct in conjunction with a user-supplied variable. The recommendation is to avoid using HTML assembly, but if it is extremely necessary to allow Html, we suggest the following: support only a fixed subset of Html, after the user submits content, analyze the Html and filter it in a whitelist of allowed tags and attributes. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", - Severity: severities.High.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-53", + Name: "No use Html.Raw", + Description: "The application uses the potentially dangerous Html.Raw construct in conjunction with a user-supplied variable. The recommendation is to avoid using HTML assembly, but if it is extremely necessary to allow Html, we suggest the following: support only a fixed subset of Html, after the user submits content, analyze the Html and filter it in a whitelist of allowed tags and attributes. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", + Severity: severities.High.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP53, + UnsafeExample: SampleVulnerableHSCSHARP53, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`Html\.Raw\(`), }, @@ -938,15 +1049,17 @@ func NewNoUseHtmlRaw() *text.Rule { func NewNoLogSensitiveInformation() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-54", - Name: "No log sensitive information debug mode", - Description: "The application is configured to display standard .NET errors. This can provide the attacker with useful information and should not be used in a production application. https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-getting-started/deploying-web-site-projects/displaying-a-custom-error-page-cs. For more information checkout the CWE-12 (https://cwe.mitre.org/data/definitions/12.html) advisory.", - Severity: severities.Low.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-54", + Name: "No log sensitive information debug mode", + Description: "The application is configured to display standard .NET errors. This can provide the attacker with useful information and should not be used in a production application. https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-getting-started/deploying-web-site-projects/displaying-a-custom-error-page-cs. For more information checkout the CWE-12 (https://cwe.mitre.org/data/definitions/12.html) advisory.", + Severity: severities.Low.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP54, + UnsafeExample: SampleVulnerableHSCSHARP54, }, - Type: text.Regular, + Type: text.AndMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`<\s*customErrors\s+mode\s*=\s*\"Off\"\s*/?>`), + regexp.MustCompile(`<\s*customErrors\s+mode\s*=\s*['|"]Off['|"](.|\n)*/>`), }, } } @@ -954,15 +1067,17 @@ func NewNoLogSensitiveInformation() *text.Rule { func NewNoReturnStringConcatInController() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-55", - Name: "No return string concat in controller", - Description: "A potential Cross-Site Scripting (XSS) was found. The endpoint returns a variable from the client entry that has not been coded. Always encode untrusted input before output, regardless of validation or cleaning performed. https://docs.microsoft.com/en-us/aspnet/core/security/cross-site-scripting?view=aspnetcore-3.1. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", - Severity: severities.Low.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-55", + Name: "No return string concat in controller", + Description: "A potential Cross-Site Scripting (XSS) was found. The endpoint returns a variable from the client entry that has not been coded. Always encode untrusted input before output, regardless of validation or cleaning performed. https://docs.microsoft.com/en-us/aspnet/core/security/cross-site-scripting?view=aspnetcore-3.1. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", + Severity: severities.Low.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP55, + UnsafeExample: SampleVulnerableHSCSHARP55, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ - regexp.MustCompile(`(?:public\sclass\s.*Controller|.*\s+:\s+Controller)(?:\n*.*)*return\s+.*\".*\+`), + regexp.MustCompile(`(?i)(?:public\sclass\s.*Controller|.*\s+:\s+Controller)(\n|.)*return\s*['|"](<|\\>).*['|"]\s*\+\s*\w+\s*\+\s*['|"]`), }, } } @@ -970,13 +1085,15 @@ func NewNoReturnStringConcatInController() *text.Rule { func NewSQLInjectionOdbcCommand() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-56", - Name: "SQL Injection OdbcCommand", - Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", - Severity: severities.High.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-56", + Name: "SQL Injection OdbcCommand", + Description: "Malicious user might get direct read and/or write access to the database. If the database is poorly configured the attacker might even get Remote Code Execution (RCE) on the machine running the database. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", + Severity: severities.High.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP56, + UnsafeExample: SampleVulnerableHSCSHARP56, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`.*\s*new\sOdbcCommand\(.*\".*\+(?:.*\n*)*.ExecuteReader\(`), }, @@ -986,13 +1103,15 @@ func NewSQLInjectionOdbcCommand() *text.Rule { func NewWeakHashingFunctionMd5OrSha1() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-57", - Name: "Weak hashing function md5 or sha1", - Description: "MD5 or SHA1 have known collision weaknesses and are no longer considered strong hashing algorithms. For more information checkout the CWE-326 (https://cwe.mitre.org/data/definitions/326.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-57", + Name: "Weak hashing function md5 or sha1", + Description: "MD5 or SHA1 have known collision weaknesses and are no longer considered strong hashing algorithms. For more information checkout the CWE-326 (https://cwe.mitre.org/data/definitions/326.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP57, + UnsafeExample: SampleVulnerableHSCSHARP57, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`new\sSHA1CryptoServiceProvider\(`), regexp.MustCompile(`new\sMD5CryptoServiceProvider\(`), @@ -1003,13 +1122,15 @@ func NewWeakHashingFunctionMd5OrSha1() *text.Rule { func NewWeakHashingFunctionDESCrypto() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-58", - Name: "Weak hashing function DES Crypto", - Description: "DES Crypto have known collision weaknesses and are no longer considered strong hashing algorithms. For more information checkout the CWE-326 (https://cwe.mitre.org/data/definitions/326.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-58", + Name: "Weak hashing function DES Crypto", + Description: "DES Crypto have known collision weaknesses and are no longer considered strong hashing algorithms. For more information checkout the CWE-326 (https://cwe.mitre.org/data/definitions/326.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP58, + UnsafeExample: SampleVulnerableHSCSHARP58, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`new\sTripleDESCryptoServiceProvider\(`), regexp.MustCompile(`new\sDESCryptoServiceProvider\(`), @@ -1022,13 +1143,15 @@ func NewWeakHashingFunctionDESCrypto() *text.Rule { func NewNoUseCipherMode() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-59", - Name: "No Use Cipher mode", - Description: "This mode is not recommended because it opens the door to various security exploits. If the plain text to be encrypted contains substantial repetitions, it is possible that the cipher text will be broken one block at a time. You can also use block analysis to determine the encryption key. In addition, an active opponent can replace and exchange individual blocks without detection, which allows the blocks to be saved and inserted into the stream at other points without detection. ECB and OFB mode will produce the same result for identical blocks. The use of AES in CBC mode with an HMAC is recommended, ensuring integrity and confidentiality. https://docs.microsoft.com/en-us/visualstudio/code-quality/ca5358?view=vs-2019. For more information checkout the CWE-326 (https://cwe.mitre.org/data/definitions/326.html) and CWE-327 (https://cwe.mitre.org/data/definitions/327.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-59", + Name: "No Use Cipher mode", + Description: "This mode is not recommended because it opens the door to various security exploits. If the plain text to be encrypted contains substantial repetitions, it is possible that the cipher text will be broken one block at a time. You can also use block analysis to determine the encryption key. In addition, an active opponent can replace and exchange individual blocks without detection, which allows the blocks to be saved and inserted into the stream at other points without detection. ECB and OFB mode will produce the same result for identical blocks. The use of AES in CBC mode with an HMAC is recommended, ensuring integrity and confidentiality. https://docs.microsoft.com/en-us/visualstudio/code-quality/ca5358?view=vs-2019. For more information checkout the CWE-326 (https://cwe.mitre.org/data/definitions/326.html) and CWE-327 (https://cwe.mitre.org/data/definitions/327.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP59, + UnsafeExample: SampleVulnerableHSCSHARP59, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`CipherMode\.ECB`), regexp.MustCompile(`CipherMode\.OFB`), @@ -1041,13 +1164,15 @@ func NewNoUseCipherMode() *text.Rule { func NewDebugBuildEnabled() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-60", - Name: "Debug Build Enabled", - Description: "Binaries compiled in debug mode can leak detailed stack traces and debugging messages to attackers. Disable debug builds by setting the debug attribute to false. For more information checkout the CWE-11 (https://cwe.mitre.org/data/definitions/11.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-60", + Name: "Debug Build Enabled", + Description: "Binaries compiled in debug mode can leak detailed stack traces and debugging messages to attackers. Disable debug builds by setting the debug attribute to false. For more information checkout the CWE-11 (https://cwe.mitre.org/data/definitions/11.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP60, + UnsafeExample: SampleVulnerableHSCSHARP60, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`\`), + regexp.MustCompile(` builder\.AllowAnyOrigin\(\)\);`), }, @@ -1089,13 +1218,15 @@ func NewCorsAllowOriginWildCard() *text.Rule { func NewMissingAntiForgeryTokenAttribute() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-63", - Name: "Missing Anti Forgery Token Attribute", - Description: "Cross Site Request Forgery attacks occur when a victim authenticates to a target web site and then visits a malicious web page. The malicious web page then sends a fake HTTP request (GET, POST, etc.) back to the target website. The victim’s valid authentication cookie from the target web site is automatically included in the malicious request, sent to the target web site, and processed as a valid transaction under the victim’s identity. For more information checkout the CWE-352 (https://cwe.mitre.org/data/definitions/352.html) advisory.", - Severity: severities.Info.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-63", + Name: "Missing Anti Forgery Token Attribute", + Description: "Cross Site Request Forgery attacks occur when a victim authenticates to a target web site and then visits a malicious web page. The malicious web page then sends a fake HTTP request (GET, POST, etc.) back to the target website. The victim’s valid authentication cookie from the target web site is automatically included in the malicious request, sent to the target web site, and processed as a valid transaction under the victim’s identity.This rule searches for all actions decorated with HTTP verbs that typically modify data (POST, PUT, DELETE, and PATCH). Actions containing the [AllowAnonymous] attribute are not reported as CSRF attacks target authenticated users. Any identified actions that are missing the ValidateAntiForgeryToken attribute raise a diagnostic warning. In ASP.NET MVC, the ValidateAntiForgeryToken attribute protects applications using authentication cookies from CSRF attacks. Actions with this attribute search the request parameters for the __RequestVerificationToken and validate the value prior to executing the request. For more information checkout the CWE-352 (https://cwe.mitre.org/data/definitions/352.html) advisory.", + Severity: severities.Info.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP63, + UnsafeExample: SampleVulnerableHSCSHARP63, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(\[HttpGet\]|\[HttpPost\]|\[HttpPut\]|\[HttpDelete\])(([^V]|V[^a]|Va[^l]|Val[^i]|Vali[^d]|Valid[^a]|Valida[^t]|Validat[^e]|Validate[^A]|ValidateA[^n]|ValidateAn[^t]|ValidateAnt[^i]|ValidateAnti[^F]|ValidateAntiF[^o]|ValidateAntiFo[^r]|ValidateAntiFor[^g]|ValidateAntiForg[^e]|ValidateAntiForge[^r]|ValidateAntiForger[^y]|ValidateAntiForgery[^T]|ValidateAntiForgeryT[^o]|ValidateAntiForgeryTo[^k]|ValidateAntiForgeryTok[^e]|ValidateAntiForgeryToke[^n])*)(ActionResult)`), }, @@ -1105,13 +1236,15 @@ func NewMissingAntiForgeryTokenAttribute() *text.Rule { func NewUnvalidatedWebFormsRedirect() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-64", - Name: "Unvalidated Web Forms Redirect", - Description: "Passing unvalidated redirect locations to the Response.Redirect method can allow attackers to send users to malicious web sites. This can allow attackers to perform phishing attacks and distribute malware to victims. For more information checkout the CWE-601 (https://cwe.mitre.org/data/definitions/601.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Low.ToString(), + ID: "HS-CSHARP-64", + Name: "Unvalidated Web Forms Redirect", + Description: "Passing unvalidated redirect locations to the Response.Redirect method can allow attackers to send users to malicious web sites. This can allow attackers to perform phishing attacks and distribute malware to victims. For more information checkout the CWE-601 (https://cwe.mitre.org/data/definitions/601.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Low.ToString(), + SafeExample: SampleSafeHSCSHARP64, + UnsafeExample: SampleVulnerableHSCSHARP64, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`Response\.Redirect\(Request\.QueryString\[".*"\]\)`), }, @@ -1121,13 +1254,15 @@ func NewUnvalidatedWebFormsRedirect() *text.Rule { func NewIdentityPasswordLockoutDisabled() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-65", - Name: "Identity Password Lockout Disabled", - Description: "Password lockout mechanisms help prevent continuous brute force attacks again user accounts by disabling an account for a period of time after a number of invalid attempts. The ASP.NET Identity SignInManager protects against brute force attacks if the lockout parameter is set to true. For more information checkout the CWE-307 (https://cwe.mitre.org/data/definitions/307.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-65", + Name: "Identity Password Lockout Disabled", + Description: "Password lockout mechanisms help prevent continuous brute force attacks again user accounts by disabling an account for a period of time after a number of invalid attempts. The ASP.NET Identity SignInManager protects against brute force attacks if the lockout parameter is set to true. For more information checkout the CWE-307 (https://cwe.mitre.org/data/definitions/307.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP65, + UnsafeExample: SampleVulnerableHSCSHARP65, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`CheckPasswordSignInAsync\(.*, .*, false\)`), }, @@ -1137,13 +1272,15 @@ func NewIdentityPasswordLockoutDisabled() *text.Rule { func NewRawInlineExpression() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-66", - Name: "Raw Inline Expression", - Description: "Data is written to the browser using a raw write: <%= var %>. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). Instead of using a raw write, use the inline HTML encoded shortcut (<%: var %>) to automatically HTML encode data before writing it to the browser. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-66", + Name: "Raw Inline Expression", + Description: "Data is written to the browser using a raw write: <%= var %>. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). Instead of using a raw write, use the inline HTML encoded shortcut (<%: var %>) to automatically HTML encode data before writing it to the browser. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP66, + UnsafeExample: SampleVulnerableHSCSHARP66, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`\<\%=.*\%\>`), }, @@ -1153,13 +1290,15 @@ func NewRawInlineExpression() *text.Rule { func NewRawBindingExpression() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-67", - Name: "Raw Binding Expression", - Description: "Data is written to the browser using a raw binding expression: <%# Item.Variable %>. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). Instead of using a raw binding expression, use the HTML encoded binding shortcut (<%#: Item.Variable %>) to automatically HTML encode data before writing it to the browser. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-67", + Name: "Raw Binding Expression", + Description: "Data is written to the browser using a raw binding expression: <%# Item.Variable %>. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). Instead of using a raw binding expression, use the HTML encoded binding shortcut (<%#: Item.Variable %>) to automatically HTML encode data before writing it to the browser. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP67, + UnsafeExample: SampleVulnerableHSCSHARP67, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`\<\%#[^:].*\%\>`), }, @@ -1169,13 +1308,15 @@ func NewRawBindingExpression() *text.Rule { func NewRawWriteLiteralMethod() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-68", - Name: "Raw Write Literal Method", - Description: "Data is written to the browser using the raw WriteLiteral method. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). Instead of using the raw WriteLiteral method, use a Razor helper that performs automatic HTML encoding before writing it to the browser. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-68", + Name: "Raw Write Literal Method", + Description: "Data is written to the browser using the raw WriteLiteral method. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). Instead of using the raw WriteLiteral method, use a Razor helper that performs automatic HTML encoding before writing it to the browser. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP68, + UnsafeExample: SampleVulnerableHSCSHARP68, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`WriteLiteral\(`), }, @@ -1185,13 +1326,15 @@ func NewRawWriteLiteralMethod() *text.Rule { func NewUnencodedWebFormsProperty() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-69", - Name: "Unencoded Web Forms Property", - Description: "Data is written to the browser using a WebForms property that does not perform output encoding. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). WebForms controls are often found in HTML contexts, but can also appear in other contexts such as JavaScript, HTML Attribute, or URL. Fixing the vulnerability requires the appropriate Web Protection Library (aka AntiXSS) context-specific method to encode the data before setting the WebForms property. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-69", + Name: "Unencoded Web Forms Property", + Description: "Data is written to the browser using a WebForms property that does not perform output encoding. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). WebForms controls are often found in HTML contexts, but can also appear in other contexts such as JavaScript, HTML Attribute, or URL. Fixing the vulnerability requires the appropriate Web Protection Library (aka AntiXSS) context-specific method to encode the data before setting the WebForms property. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP69, + UnsafeExample: SampleVulnerableHSCSHARP69, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(litDetails\.Text)(([^H]|H[^t]|Ht[^m]|Htm[^l]|Html[^E]|HtmlE[^n]|HtmlEn[^c]|HtmlEnc[^o]|HtmlEnco[^d]|HtmlEncod[^e])*)(;)`), }, @@ -1201,13 +1344,15 @@ func NewUnencodedWebFormsProperty() *text.Rule { func NewUnencodedLabelText() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-70", - Name: "Unencoded Label Text", - Description: "Data is written to the browser using the raw Label.Text method. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). Label controls are often found in HTML contexts, but can also appear in other contexts such as JavaScript, HTML Attribute, or URL. Fixing the vulnerability requires the appropriate Web Protection Library (aka AntiXSS) context-specific method to encode the data before setting the Label.Text property. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", - Severity: severities.Medium.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-70", + Name: "Unencoded Label Text", + Description: "Data is written to the browser using the raw Label.Text method. This can result in Cross-Site Scripting (XSS) vulnerabilities if the data source is considered untrusted or dynamic (request parameters, database, web service, etc.). Label controls are often found in HTML contexts, but can also appear in other contexts such as JavaScript, HTML Attribute, or URL. Fixing the vulnerability requires the appropriate Web Protection Library (aka AntiXSS) context-specific method to encode the data before setting the Label.Text property. For more information checkout the CWE-79 (https://cwe.mitre.org/data/definitions/79.html) advisory.", + Severity: severities.Medium.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP70, + UnsafeExample: SampleVulnerableHSCSHARP70, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(lblDetails\.Text)(([^H]|H[^t]|Ht[^m]|Htm[^l]|Html[^E]|HtmlE[^n]|HtmlEn[^c]|HtmlEnc[^o]|HtmlEnco[^d]|HtmlEncod[^e])*)(;)`), }, @@ -1217,13 +1362,15 @@ func NewUnencodedLabelText() *text.Rule { func NewWeakRandomNumberGenerator() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-71", - Name: "Weak Random Number Generator", - Description: "The use of a predictable random value can lead to vulnerabilities when used in certain security critical contexts. For more information access: (https://security-code-scan.github.io/#SCS0005) or (https://cwe.mitre.org/data/definitions/338.html).", - Severity: severities.Low.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-71", + Name: "Weak Random Number Generator", + Description: "The use of a predictable random value can lead to vulnerabilities when used in certain security critical contexts. For more information access: (https://security-code-scan.github.io/#SCS0005) or (https://cwe.mitre.org/data/definitions/338.html).", + Severity: severities.Low.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP71, + UnsafeExample: SampleVulnerableHSCSHARP71, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`new Random\(\)`), }, @@ -1233,13 +1380,15 @@ func NewWeakRandomNumberGenerator() *text.Rule { func NewWeakRsaKeyLength() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-72", - Name: "Weak Rsa Key Length", - Description: "Due to advances in cryptanalysis attacks and cloud computing capabilities, the National Institute of Standards and Technology (NIST) deprecated 1024-bit RSA keys on January 1, 2011. The Certificate Authority Browser Forum, along with the latest version of all browsers, currently mandates a minimum key size of 2048-bits for all RSA keys. For more information checkout the CWE-326 (https://cwe.mitre.org/data/definitions/326.html) advisory.", - Severity: severities.Critical.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-72", + Name: "Weak Rsa Key Length", + Description: "Due to advances in cryptanalysis attacks and cloud computing capabilities, the National Institute of Standards and Technology (NIST) deprecated 1024-bit RSA keys on January 1, 2011. The Certificate Authority Browser Forum, along with the latest version of all browsers, currently mandates a minimum key size of 2048-bits for all RSA keys. For more information checkout the CWE-326 (https://cwe.mitre.org/data/definitions/326.html) advisory.", + Severity: severities.Critical.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP72, + UnsafeExample: SampleVulnerableHSCSHARP72, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(new RSACryptoServiceProvider\()(\)|[0-9][^\d]|[0-9]{2}[^\d]|[0-9]{3}[^\d]|[0-1][0-9]{3}[^\d]|20[0-3][0-9]|204[0-7])`), }, @@ -1249,13 +1398,15 @@ func NewWeakRsaKeyLength() *text.Rule { func NewXmlReaderExternalEntityExpansion() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-73", - Name: "Xml Reader External Entity Expansion", - Description: "XML External Entity (XXE) vulnerabilities occur when applications process untrusted XML data without disabling external entities and DTD processing. Processing untrusted XML data with a vulnerable parser can allow attackers to extract data from the server, perform denial of service attacks, and in some cases gain remote code execution. The XmlReaderSettings and XmlTextReader classes are vulnerable to XXE attacks when setting the DtdProcessing property to DtdProcessing.Parse or the ProhibitDtd property to false. To prevent XmlReader XXE attacks, avoid using the deprecated ProhibitDtd property. Set the DtdProcessing property to DtdProcessing.Prohibit. For more information checkout the CWE-611 (https://cwe.mitre.org/data/definitions/611.html) advisory.", - Severity: severities.High.ToString(), - Confidence: confidence.High.ToString(), + ID: "HS-CSHARP-73", + Name: "Xml Reader External Entity Expansion", + Description: "XML External Entity (XXE) vulnerabilities occur when applications process untrusted XML data without disabling external entities and DTD processing. Processing untrusted XML data with a vulnerable parser can allow attackers to extract data from the server, perform denial of service attacks, and in some cases gain remote code execution. The XmlReaderSettings and XmlTextReader classes are vulnerable to XXE attacks when setting the DtdProcessing property to DtdProcessing.Parse or the ProhibitDtd property to false. To prevent XmlReader XXE attacks, avoid using the deprecated ProhibitDtd property. Set the DtdProcessing property to DtdProcessing.Prohibit. For more information checkout the CWE-611 (https://cwe.mitre.org/data/definitions/611.html) advisory.", + Severity: severities.High.ToString(), + Confidence: confidence.High.ToString(), + SafeExample: SampleSafeHSCSHARP73, + UnsafeExample: SampleVulnerableHSCSHARP73, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(new\sXmlReaderSettings)(([^P]|P[^r]|Pr[^o]|Pro[^h]|Proh[^i]|Prohi[^b]|Prohib[^i]|Prohibi[^t])*)(})`), }, @@ -1265,13 +1416,15 @@ func NewXmlReaderExternalEntityExpansion() *text.Rule { func NewLdapInjectionDirectoryEntry() *text.Rule { return &text.Rule{ Metadata: engine.Metadata{ - ID: "HS-CSHARP-74", - Name: "Ldap Injection Directory Entry", - Description: "LDAP Injection vulnerabilities occur when untrusted data is concatenated into a LDAP Path or Filter expression without properly escaping control characters. This can allow attackers to change the meaning of an LDAP query and gain access to resources for which they are not authorized. Fixing the LDAP Injection Directory Entry vulnerability requires untrusted data to be encoded using the appropriate Web Protection Library (aka AntiXSS) LDAP encoding method: Encoder.LdapDistinguishedNameEncode(). For more information checkout the CWE-90 (https://cwe.mitre.org/data/definitions/90.html) advisory.", - Severity: severities.High.ToString(), - Confidence: confidence.Medium.ToString(), + ID: "HS-CSHARP-74", + Name: "Ldap Injection Directory Entry", + Description: "LDAP Injection vulnerabilities occur when untrusted data is concatenated into a LDAP Path or Filter expression without properly escaping control characters. This can allow attackers to change the meaning of an LDAP query and gain access to resources for which they are not authorized. Fixing the LDAP Injection Directory Entry vulnerability requires untrusted data to be encoded using the appropriate Web Protection Library (aka AntiXSS) LDAP encoding method: Encoder.LdapDistinguishedNameEncode(). For more information checkout the CWE-90 (https://cwe.mitre.org/data/definitions/90.html) advisory.", + Severity: severities.High.ToString(), + Confidence: confidence.Medium.ToString(), + SafeExample: SampleSafeHSCSHARP74, + UnsafeExample: SampleVulnerableHSCSHARP74, }, - Type: text.Regular, + Type: text.OrMatch, Expressions: []*regexp.Regexp{ regexp.MustCompile(`(new\sDirectoryEntry\(.*LDAP.*\{)(([^E]|E[^n]|En[^c]|Enc[^o]|Enco[^d]|Encod[^e]|Encode[^r])*)(;)`), }, diff --git a/internal/services/engines/csharp/rules_test.go b/internal/services/engines/csharp/rules_test.go index 2d3d42927..58c0922ac 100644 --- a/internal/services/engines/csharp/rules_test.go +++ b/internal/services/engines/csharp/rules_test.go @@ -15,7 +15,6 @@ package csharp import ( - "fmt" "path/filepath" "testing" @@ -31,12 +30,12 @@ func TestRulesVulnerableCode(t *testing.T) { Name: "HS-CSHARP-1", Rule: NewCommandInjection(), Src: SampleVulnerableHSCSHARP1, - Filename: filepath.Join(tempDir, fmt.Sprintf("%s%s", "HS-CSHARP-1", ".test")), + Filename: filepath.Join(tempDir, "HS-CSHARP-1.test"), Findings: []engine.Finding{ { CodeSample: "var p = new Process();", SourceLocation: engine.Location{ - Filename: filepath.Join(tempDir, fmt.Sprintf("%s%s", "HS-CSHARP-1", ".test")), + Filename: filepath.Join(tempDir, "HS-CSHARP-1.test"), Line: 2, Column: 10, }, @@ -47,18 +46,1218 @@ func TestRulesVulnerableCode(t *testing.T) { Name: "HS-CSHARP-2", Rule: NewXPathInjection(), Src: SampleVulnerableHSCSHARP2, - Filename: filepath.Join(tempDir, fmt.Sprintf("%s%s", "HS-CSHARP-2", ".test")), + Filename: filepath.Join(tempDir, "HS-CSHARP-2.test"), Findings: []engine.Finding{ { CodeSample: "var doc = new XmlDocument {XmlResolver = null};", SourceLocation: engine.Location{ - Filename: filepath.Join(tempDir, fmt.Sprintf("%s%s", "HS-CSHARP-2", ".test")), + Filename: filepath.Join(tempDir, "HS-CSHARP-2.test"), Line: 2, Column: 12, }, }, }, }, + { + Name: "HS-CSHARP-3", + Rule: NewExternalEntityInjection(), + Src: SampleVulnerableHSCSHARP3, + Filename: filepath.Join(tempDir, "HS-CSHARP-3.test"), + Findings: []engine.Finding{ + { + CodeSample: "XmlReaderSettings settings = new XmlReaderSettings();", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-3.test"), + Line: 2, + Column: 29, + }, + }, + }, + }, + { + Name: "HS-CSHARP-4", + Rule: NewPathTraversal(), + Src: SampleVulnerableHSCSHARP4, + Filename: filepath.Join(tempDir, "HS-CSHARP-4.test"), + Findings: []engine.Finding{ + { + CodeSample: "public ActionResult Download(string fileName)", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-4.test"), + Line: 3, + Column: 7, + }, + }, + }, + }, + { + Name: "HS-CSHARP-5", + Rule: NewSQLInjectionWebControls(), + Src: SampleVulnerableHSCSHARP5, + Filename: filepath.Join(tempDir, "HS-CSHARP-5.test"), + Findings: []engine.Finding{ + { + CodeSample: "var cmd = \"SELECT * FROM Users WHERE username = '\" + input + \"' and role='user'\";", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-5.test"), + Line: 2, + Column: 10, + }, + }, + }, + }, + { + Name: "HS-CSHARP-6", + Rule: NewWeakCipherOrCBCOrECBMode(), + Src: SampleVulnerableHSCSHARP6, + Filename: filepath.Join(tempDir, "HS-CSHARP-6.test"), + Findings: []engine.Finding{ + { + CodeSample: "using (var aes = new AesManaged {", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-6.test"), + Line: 2, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-7", + Rule: NewFormsAuthenticationCookielessMode(), + Src: SampleVulnerableHSCSHARP7, + Filename: filepath.Join(tempDir, "HS-CSHARP-7.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-7.test"), + Line: 4, + Column: 4, + }, + }, + }, + }, + { + Name: "HS-CSHARP-8", + Rule: NewFormsAuthenticationCrossAppRedirects(), + Src: SampleVulnerableHSCSHARP8, + Filename: filepath.Join(tempDir, "HS-CSHARP-8.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-8.test"), + Line: 3, + Column: 2, + }, + }, + }, + }, + { + Name: "HS-CSHARP-9", + Rule: NewFormsAuthenticationWeakCookieProtection(), + Src: SampleVulnerableHSCSHARP9, + Filename: filepath.Join(tempDir, "HS-CSHARP-9.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-9.test"), + Line: 3, + Column: 2, + }, + }, + }, + }, + { + Name: "HS-CSHARP-10", + Rule: NewFormsAuthenticationWeakTimeout(), + Src: SampleVulnerableHSCSHARP10, + Filename: filepath.Join(tempDir, "HS-CSHARP-10.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-10.test"), + Line: 3, + Column: 2, + }, + }, + }, + }, + { + Name: "HS-CSHARP-11", + Rule: NewHeaderCheckingDisabled(), + Src: SampleVulnerableHSCSHARP11, + Filename: filepath.Join(tempDir, "HS-CSHARP-11.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-11.test"), + Line: 2, + Column: 13, + }, + }, + }, + }, + { + Name: "HS-CSHARP-12", + Rule: NewVersionHeaderEnabled(), + Src: SampleVulnerableHSCSHARP12, + Filename: filepath.Join(tempDir, "HS-CSHARP-12.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-12.test"), + Line: 2, + Column: 13, + }, + }, + }, + }, + { + Name: "HS-CSHARP-13", + Rule: NewEventValidationDisabled(), + Src: SampleVulnerableHSCSHARP13, + Filename: filepath.Join(tempDir, "HS-CSHARP-13.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-13.test"), + Line: 2, + Column: 7, + }, + }, + }, + }, + { + Name: "HS-CSHARP-14", + Rule: NewWeakSessionTimeout(), + Src: SampleVulnerableHSCSHARP14, + Filename: filepath.Join(tempDir, "HS-CSHARP-14.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-14.test"), + Line: 2, + Column: 14, + }, + }, + }, + }, + { + Name: "HS-CSHARP-15", + Rule: NewStateServerMode(), + Src: SampleVulnerableHSCSHARP15, + Filename: filepath.Join(tempDir, "HS-CSHARP-15.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-15.test"), + Line: 2, + Column: 14, + }, + }, + }, + }, + { + Name: "HS-CSHARP-16", + Rule: NewJwtSignatureValidationDisabled(), + Src: SampleVulnerableHSCSHARP16, + Filename: filepath.Join(tempDir, "HS-CSHARP-16.test"), + Findings: []engine.Finding{ + { + CodeSample: "services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-16.test"), + Line: 2, + Column: 9, + }, + }, + }, + }, + { + Name: "HS-CSHARP-17", + Rule: NewInsecureHttpCookieTransport(), + Src: SampleVulnerableHSCSHARP17, + Filename: filepath.Join(tempDir, "HS-CSHARP-17.test"), + Findings: []engine.Finding{ + { + CodeSample: "Secure = false,", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-17.test"), + Line: 4, + Column: 4, + }, + }, + }, + }, + { + Name: "HS-CSHARP-18", + Rule: NewHttpCookieAccessibleViaScript(), + Src: SampleVulnerableHSCSHARP18, + Filename: filepath.Join(tempDir, "HS-CSHARP-18.test"), + Findings: []engine.Finding{ + { + CodeSample: "HttpOnly = false,", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-18.test"), + Line: 4, + Column: 4, + }, + }, + }, + }, + { + Name: "HS-CSHARP-19", + Rule: NewDirectoryListingEnabled(), + Src: SampleVulnerableHSCSHARP19, + Filename: filepath.Join(tempDir, "HS-CSHARP-19.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-19.test"), + Line: 3, + Column: 19, + }, + }, + }, + }, + { + Name: "HS-CSHARP-20", + Rule: NewLdapAuthenticationDisabled(), + Src: SampleVulnerableHSCSHARP20, + Filename: filepath.Join(tempDir, "HS-CSHARP-20.test"), + Findings: []engine.Finding{ + { + CodeSample: "entry.AuthenticationType = AuthenticationTypes.Anonymous;", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-20.test"), + Line: 3, + Column: 27, + }, + }, + }, + }, + { + Name: "HS-CSHARP-21", + Rule: NewCertificateValidationDisabledAndMatch(), + Src: SampleVulnerableHSCSHARP21, + Filename: filepath.Join(tempDir, "HS-CSHARP-21.test"), + Findings: []engine.Finding{ + { + CodeSample: "handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-21.test"), + Line: 4, + Column: 12, + }, + }, + }, + }, + { + Name: "HS-CSHARP-22", + Rule: NewActionRequestValidationDisabled(), + Src: SampleVulnerableHSCSHARP22, + Filename: filepath.Join(tempDir, "HS-CSHARP-22.test"), + Findings: []engine.Finding{ + { + CodeSample: "[ValidateInput(false)]", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-22.test"), + Line: 3, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-23", + Rule: NewXmlDocumentExternalEntityExpansion(), + Src: SampleVulnerableHSCSHARP23, + Filename: filepath.Join(tempDir, "HS-CSHARP-23.test"), + Findings: []engine.Finding{ + { + CodeSample: "xmlDoc.XmlResolver = resolver;", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-23.test"), + Line: 6, + Column: 6, + }, + }, + }, + }, + { + Name: "HS-CSHARP-24", + Rule: NewLdapInjectionFilterAssignment(), + Src: SampleVulnerableHSCSHARP24, + Filename: filepath.Join(tempDir, "HS-CSHARP-24.test"), + Findings: []engine.Finding{ + { + CodeSample: "searcher.Filter = string.Format(\"(name={0})\", model.UserName);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-24.test"), + Line: 5, + Column: 8, + }, + }, + }, + }, + { + Name: "HS-CSHARP-25", + Rule: NewSqlInjectionDynamicNHibernateQuery(), + Src: SampleVulnerableHSCSHARP25, + Filename: filepath.Join(tempDir, "HS-CSHARP-25.test"), + Findings: []engine.Finding{ + { + CodeSample: "string q = \"SELECT * FROM Items WHERE ProductCode = '\" + model.ProductCode + \"'\";", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-25.test"), + Line: 2, + Column: 11, + }, + }, + }, + }, + { + Name: "HS-CSHARP-26", + Rule: NewLdapInjectionDirectorySearcher(), + Src: SampleVulnerableHSCSHARP26, + Filename: filepath.Join(tempDir, "HS-CSHARP-26.test"), + Findings: []engine.Finding{ + { + CodeSample: "DirectorySearcher searcher = new DirectorySearcher(entry, string.Format(\"(name={0})\", model.UserName);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-26.test"), + Line: 3, + Column: 29, + }, + }, + }, + }, + { + Name: "HS-CSHARP-27", + Rule: NewLdapInjectionPathAssignment(), + Src: SampleVulnerableHSCSHARP27, + Filename: filepath.Join(tempDir, "HS-CSHARP-27.test"), + Findings: []engine.Finding{ + { + CodeSample: "entry.Path = string.Format(\"LDAP://DC={0},DC=COM,CN=Users\", model.Domain);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-27.test"), + Line: 3, + Column: 5, + }, + }, + }, + }, + { + Name: "HS-CSHARP-28", + Rule: NewLDAPInjection(), + Src: SampleVulnerableHSCSHARP28, + Filename: filepath.Join(tempDir, "HS-CSHARP-28.test"), + Findings: []engine.Finding{ + { + CodeSample: "searcher.Filter = \"(cn=\" + input + \")\";", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-28.test"), + Line: 3, + Column: 8, + }, + }, + }, + }, + { + Name: "HS-CSHARP-29", + Rule: NewSQLInjectionLinq(), + Src: SampleVulnerableHSCSHARP29, + Filename: filepath.Join(tempDir, "HS-CSHARP-29.test"), + Findings: []engine.Finding{ + { + CodeSample: "var cmd = \"SELECT * FROM Users WHERE username = '\" + input + \"' and role='user'\";", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-29.test"), + Line: 2, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-30", + Rule: NewInsecureDeserialization(), + Src: SampleVulnerableHSCSHARP30, + Filename: filepath.Join(tempDir, "HS-CSHARP-30.test"), + Findings: []engine.Finding{ + { + CodeSample: "var mySerializer = new JavaScriptSerializer(new SimpleTypeResolver());", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-30.test"), + Line: 4, + Column: 23, + }, + }, + }, + }, + { + Name: "HS-CSHARP-31", + Rule: NewSQLInjectionEnterpriseLibraryData(), + Src: SampleVulnerableHSCSHARP31, + Filename: filepath.Join(tempDir, "HS-CSHARP-31.test"), + Findings: []engine.Finding{ + { + CodeSample: "DbCommand dbCommand = db.GetSqlStringCommand(\"select * from v_Comments WITH(NOLOCK) where CommentsID=\" + CommentsID);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-31.test"), + Line: 6, + Column: 37, + }, + }, + }, + }, + { + Name: "HS-CSHARP-32", + Rule: NewCQLInjectionCassandra(), + Src: SampleVulnerableHSCSHARP32, + Filename: filepath.Join(tempDir, "HS-CSHARP-32.test"), + Findings: []engine.Finding{ + { + CodeSample: "PreparedStatement ps = session.prepare(\"SELECT * FROM users WHERE uname=\"+filter);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-32.test"), + Line: 3, + Column: 1, + }, + }, + }, + }, + { + Name: "HS-CSHARP-33", + Rule: NewPasswordComplexityDefault(), + Src: SampleVulnerableHSCSHARP33, + Filename: filepath.Join(tempDir, "HS-CSHARP-33.test"), + Findings: []engine.Finding{ + { + CodeSample: "manager.PasswordValidator = new PasswordValidator();", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-33.test"), + Line: 9, + Column: 28, + }, + }, + { + CodeSample: "manager.PasswordValidator = new PasswordValidator", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-33.test"), + Line: 2, + Column: 28, + }, + }, + }, + }, + { + Name: "HS-CSHARP-34", + Rule: NewCookieWithoutSSLFlag(), + Src: SampleVulnerableHSCSHARP34, + Filename: filepath.Join(tempDir, "HS-CSHARP-34.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-34.test"), + Line: 4, + Column: 17, + }, + }, + }, + }, + { + Name: "HS-CSHARP-35", + Rule: NewCookieWithoutHttpOnlyFlag(), + Src: SampleVulnerableHSCSHARP35, + Filename: filepath.Join(tempDir, "HS-CSHARP-35.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-35.test"), + Line: 4, + Column: 17, + }, + }, + }, + }, + { + Name: "HS-CSHARP-36", + Rule: NewNoInputVariable(), + Src: SampleVulnerableHSCSHARP36, + Filename: filepath.Join(tempDir, "HS-CSHARP-36.test"), + Findings: []engine.Finding{ + { + CodeSample: "element.innerHTML = executableXss", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-36.test"), + Line: 4, + Column: 9, + }, + }, + }, + }, + { + Name: "HS-CSHARP-37", + Rule: NewIdentityWeakPasswordComplexity(), + Src: SampleVulnerableHSCSHARP37, + Filename: filepath.Join(tempDir, "HS-CSHARP-37.test"), + Findings: []engine.Finding{ + { + CodeSample: "RequiredLength = 6", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-37.test"), + Line: 4, + Column: 4, + }, + }, + { + CodeSample: "manager.PasswordValidator = new PasswordValidator", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-37.test"), + Line: 2, + Column: 28, + }, + }, + { + CodeSample: "manager.PasswordValidator = new PasswordValidator", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-37.test"), + Line: 2, + Column: 28, + }, + }, + { + CodeSample: "manager.PasswordValidator = new PasswordValidator", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-37.test"), + Line: 2, + Column: 28, + }, + }, + { + CodeSample: "manager.PasswordValidator = new PasswordValidator", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-37.test"), + Line: 2, + Column: 28, + }, + }, + }, + }, + { + Name: "HS-CSHARP-38", + Rule: NewNoLogSensitiveInformationInConsole(), + Src: SampleVulnerableHSCSHARP38, + Filename: filepath.Join(tempDir, "HS-CSHARP-38.test"), + Findings: []engine.Finding{ + { + CodeSample: "Console.WriteLine(\"The user logged is: \" + user);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-38.test"), + Line: 4, + Column: 1, + }, + }, + }, + }, + { + Name: "HS-CSHARP-39", + Rule: NewOutputCacheConflict(), + Src: SampleVulnerableHSCSHARP39, + Filename: filepath.Join(tempDir, "HS-CSHARP-39.test"), + Findings: []engine.Finding{ + { + CodeSample: "[Authorize]", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-39.test"), + Line: 2, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-40", + Rule: NewOpenRedirect(), + Src: SampleVulnerableHSCSHARP40, + Filename: filepath.Join(tempDir, "HS-CSHARP-40.test"), + Findings: []engine.Finding{ + { + CodeSample: "if (!String.IsNullOrEmpty(returnUrl))", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-40.test"), + Line: 10, + Column: 17, + }, + }, + }, + }, + { + Name: "HS-CSHARP-41", + Rule: NewRequestValidationDisabledAttribute(), + Src: SampleVulnerableHSCSHARP41, + Filename: filepath.Join(tempDir, "HS-CSHARP-41.test"), + Findings: []engine.Finding{ + { + CodeSample: "[ValidateInput(false)]", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-41.test"), + Line: 4, + Column: 4, + }, + }, + }, + }, + { + Name: "HS-CSHARP-42", + Rule: NewSQLInjectionOLEDB(), + Src: SampleVulnerableHSCSHARP42, + Filename: filepath.Join(tempDir, "HS-CSHARP-42.test"), + Findings: []engine.Finding{ + { + CodeSample: "OleDbConnection oconnection = new OleDbConnection(ModGloVariable.RasmusConn);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-42.test"), + Line: 3, + Column: 50, + }, + }, + }, + }, + { + Name: "HS-CSHARP-43", + Rule: NewRequestValidationDisabledConfigurationFile(), + Src: SampleVulnerableHSCSHARP43, + Filename: filepath.Join(tempDir, "HS-CSHARP-43.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-43.test"), + Line: 4, + Column: 11, + }, + }, + }, + }, + { + Name: "HS-CSHARP-44", + Rule: NewSQLInjectionMsSQLDataProvider(), + Src: SampleVulnerableHSCSHARP44, + Filename: filepath.Join(tempDir, "HS-CSHARP-44.test"), + Findings: []engine.Finding{ + { + CodeSample: "SqlCommand cmd = new SqlCommand(\"Select * from GridViewDynamicData where Field1= '\" + txtSearch.Text +\"'\", conn);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-44.test"), + Line: 4, + Column: 18, + }, + }, + }, + }, + { + Name: "HS-CSHARP-45", + Rule: NewRequestValidationIsEnabledOnlyForPages(), + Src: SampleVulnerableHSCSHARP45, + Filename: filepath.Join(tempDir, "HS-CSHARP-45.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-45.test"), + Line: 4, + Column: 21, + }, + }, + }, + }, + { + Name: "HS-CSHARP-46", + Rule: NewSQLInjectionEntityFramework(), + Src: SampleVulnerableHSCSHARP46, + Filename: filepath.Join(tempDir, "HS-CSHARP-46.test"), + Findings: []engine.Finding{ + { + CodeSample: "ctx.Database.ExecuteSqlCommand(", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-46.test"), + Line: 3, + Column: 4, + }, + }, + }, + }, + { + Name: "HS-CSHARP-47", + Rule: NewViewStateNotEncrypted(), + Src: SampleVulnerableHSCSHARP47, + Filename: filepath.Join(tempDir, "HS-CSHARP-47.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-47.test"), + Line: 4, + Column: 15, + }, + }, + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-47.test"), + Line: 13, + Column: 15, + }, + }, + }, + }, + { + Name: "HS-CSHARP-48", + Rule: NewSQLInjectionNhibernate(), + Src: SampleVulnerableHSCSHARP48, + Filename: filepath.Join(tempDir, "HS-CSHARP-48.test"), + Findings: []engine.Finding{ + { + CodeSample: "var query = session.CreateSqlQuery(q);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-48.test"), + Line: 8, + Column: 19, + }, + }, + }, + }, + { + Name: "HS-CSHARP-49", + Rule: NewViewStateMacDisabled(), + Src: SampleVulnerableHSCSHARP49, + Filename: filepath.Join(tempDir, "HS-CSHARP-49.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-49.test"), + Line: 4, + Column: 11, + }, + }, + }, + }, + { + Name: "HS-CSHARP-50", + Rule: NewSQLInjectionNpgsql(), + Src: SampleVulnerableHSCSHARP50, + Filename: filepath.Join(tempDir, "HS-CSHARP-50.test"), + Findings: []engine.Finding{ + { + CodeSample: "using (var cmd = new NpgsqlCommand(", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-50.test"), + Line: 14, + Column: 41, + }, + }, + }, + }, + { + Name: "HS-CSHARP-51", + Rule: NewCertificateValidationDisabled(), + Src: SampleVulnerableHSCSHARP51, + Filename: filepath.Join(tempDir, "HS-CSHARP-51.test"), + Findings: []engine.Finding{ + { + CodeSample: "handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-51.test"), + Line: 4, + Column: 11, + }, + }, + }, + }, + { + Name: "HS-CSHARP-52", + Rule: NewWeakCipherAlgorithm(), + Src: SampleVulnerableHSCSHARP52, + Filename: filepath.Join(tempDir, "HS-CSHARP-52.test"), + Findings: []engine.Finding{ + { + CodeSample: "DES DESalg = DES.Create();", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-52.test"), + Line: 2, + Column: 13, + }, + }, + }, + }, + { + Name: "HS-CSHARP-53", + Rule: NewNoUseHtmlRaw(), + Src: SampleVulnerableHSCSHARP53, + Filename: filepath.Join(tempDir, "HS-CSHARP-53.test"), + Findings: []engine.Finding{ + { + CodeSample: "@Html.Raw(string.Format(\"Welcome {0}!\", Model.UserName))", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-53.test"), + Line: 3, + Column: 5, + }, + }, + }, + }, + { + Name: "HS-CSHARP-54", + Rule: NewNoLogSensitiveInformation(), + Src: SampleVulnerableHSCSHARP54, + Filename: filepath.Join(tempDir, "HS-CSHARP-54.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-54.test"), + Line: 4, + Column: 4, + }, + }, + }, + }, + { + Name: "HS-CSHARP-55", + Rule: NewNoReturnStringConcatInController(), + Src: SampleVulnerableHSCSHARP55, + Filename: filepath.Join(tempDir, "HS-CSHARP-55.test"), + Findings: []engine.Finding{ + { + CodeSample: "public class AdminController : Controller", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-55.test"), + Line: 2, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-56", + Rule: NewSQLInjectionOdbcCommand(), + Src: SampleVulnerableHSCSHARP56, + Filename: filepath.Join(tempDir, "HS-CSHARP-56.test"), + Findings: []engine.Finding{ + { + CodeSample: "OdbcCommand cmd = new OdbcCommand(\"SELECT a.id, a.image FROM auspiciante a Where a.name = \" + name, con);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-56.test"), + Line: 9, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-57", + Rule: NewWeakHashingFunctionMd5OrSha1(), + Src: SampleVulnerableHSCSHARP57, + Filename: filepath.Join(tempDir, "HS-CSHARP-57.test"), + Findings: []engine.Finding{ + { + CodeSample: "HashAlgorithm hash = new SHA1CryptoServiceProvider();", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-57.test"), + Line: 2, + Column: 21, + }, + }, + }, + }, + { + Name: "HS-CSHARP-58", + Rule: NewWeakHashingFunctionDESCrypto(), + Src: SampleVulnerableHSCSHARP58, + Filename: filepath.Join(tempDir, "HS-CSHARP-58.test"), + Findings: []engine.Finding{ + { + CodeSample: "SymmetricAlgorithm alg = new DESCryptoServiceProvider();", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-58.test"), + Line: 7, + Column: 29, + }, + }, + }, + }, + { + Name: "HS-CSHARP-59", + Rule: NewNoUseCipherMode(), + Src: SampleVulnerableHSCSHARP59, + Filename: filepath.Join(tempDir, "HS-CSHARP-59.test"), + Findings: []engine.Finding{ + { + CodeSample: "alg.Mode = CipherMode.ECB;", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-59.test"), + Line: 8, + Column: 15, + }, + }, + }, + }, + { + Name: "HS-CSHARP-60", + Rule: NewDebugBuildEnabled(), + Src: SampleVulnerableHSCSHARP60, + Filename: filepath.Join(tempDir, "HS-CSHARP-60.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-60.test"), + Line: 4, + Column: 4, + }, + }, + }, + }, + { + Name: "HS-CSHARP-61", + Rule: NewVulnerablePackageReference(), + Src: SampleVulnerableHSCSHARP61, + Filename: filepath.Join(tempDir, "HS-CSHARP-61.test"), + Findings: []engine.Finding{ + { + CodeSample: "", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-61.test"), + Line: 2, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-62", + Rule: NewCorsAllowOriginWildCard(), + Src: SampleVulnerableHSCSHARP62, + Filename: filepath.Join(tempDir, "HS-CSHARP-62.test"), + Findings: []engine.Finding{ + { + CodeSample: "app.UseCors(builder => builder.AllowAnyOrigin());", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-62.test"), + Line: 5, + Column: 4, + }, + }, + }, + }, + { + Name: "HS-CSHARP-63", + Rule: NewMissingAntiForgeryTokenAttribute(), + Src: SampleVulnerableHSCSHARP63, + Filename: filepath.Join(tempDir, "HS-CSHARP-63.test"), + Findings: []engine.Finding{ + { + CodeSample: "[HttpPost]", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-63.test"), + Line: 2, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-64", + Rule: NewUnvalidatedWebFormsRedirect(), + Src: SampleVulnerableHSCSHARP64, + Filename: filepath.Join(tempDir, "HS-CSHARP-64.test"), + Findings: []engine.Finding{ + { + CodeSample: "Response.Redirect(Request.QueryString[\"ReturnUrl\"]);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-64.test"), + Line: 5, + Column: 8, + }, + }, + }, + }, + { + Name: "HS-CSHARP-65", + Rule: NewIdentityPasswordLockoutDisabled(), + Src: SampleVulnerableHSCSHARP65, + Filename: filepath.Join(tempDir, "HS-CSHARP-65.test"), + Findings: []engine.Finding{ + { + CodeSample: "var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-65.test"), + Line: 6, + Column: 38, + }, + }, + }, + }, + { + Name: "HS-CSHARP-66", + Rule: NewRawInlineExpression(), + Src: SampleVulnerableHSCSHARP66, + Filename: filepath.Join(tempDir, "HS-CSHARP-66.test"), + Findings: []engine.Finding{ + { + CodeSample: "Welcome <%= Request[\"UserName\"].ToString() %>", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-66.test"), + Line: 3, + Column: 12, + }, + }, + }, + }, + { + Name: "HS-CSHARP-67", + Rule: NewRawBindingExpression(), + Src: SampleVulnerableHSCSHARP67, + Filename: filepath.Join(tempDir, "HS-CSHARP-67.test"), + Findings: []engine.Finding{ + { + CodeSample: "<%# Item.ProductName %>", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-67.test"), + Line: 6, + Column: 16, + }, + }, + }, + }, + { + Name: "HS-CSHARP-68", + Rule: NewRawWriteLiteralMethod(), + Src: SampleVulnerableHSCSHARP68, + Filename: filepath.Join(tempDir, "HS-CSHARP-68.test"), + Findings: []engine.Finding{ + { + CodeSample: "WriteLiteral(string.Format(\"Welcome {0}!\", Model.UserName));", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-68.test"), + Line: 4, + Column: 4, + }, + }, + }, + }, + { + Name: "HS-CSHARP-69", + Rule: NewUnencodedWebFormsProperty(), + Src: SampleVulnerableHSCSHARP69, + Filename: filepath.Join(tempDir, "HS-CSHARP-69.test"), + Findings: []engine.Finding{ + { + CodeSample: "litDetails.Text = product.ProductDescription;", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-69.test"), + Line: 2, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-70", + Rule: NewUnencodedLabelText(), + Src: SampleVulnerableHSCSHARP70, + Filename: filepath.Join(tempDir, "HS-CSHARP-70.test"), + Findings: []engine.Finding{ + { + CodeSample: "lblDetails.Text = product.ProductDescription;", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-70.test"), + Line: 2, + Column: 0, + }, + }, + }, + }, + { + Name: "HS-CSHARP-71", + Rule: NewWeakRandomNumberGenerator(), + Src: SampleVulnerableHSCSHARP71, + Filename: filepath.Join(tempDir, "HS-CSHARP-71.test"), + Findings: []engine.Finding{ + { + CodeSample: "var random = new Random();", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-71.test"), + Line: 4, + Column: 17, + }, + }, + }, + }, + { + Name: "HS-CSHARP-72", + Rule: NewWeakRsaKeyLength(), + Src: SampleVulnerableHSCSHARP72, + Filename: filepath.Join(tempDir, "HS-CSHARP-72.test"), + Findings: []engine.Finding{ + { + CodeSample: "RSACryptoServiceProvider alg = new RSACryptoServiceProvider(1024);", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-72.test"), + Line: 2, + Column: 31, + }, + }, + }, + }, + { + Name: "HS-CSHARP-73", + Rule: NewXmlReaderExternalEntityExpansion(), + Src: SampleVulnerableHSCSHARP73, + Filename: filepath.Join(tempDir, "HS-CSHARP-73.test"), + Findings: []engine.Finding{ + { + CodeSample: "XmlReaderSettings rs = new XmlReaderSettings", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-73.test"), + Line: 2, + Column: 23, + }, + }, + }, + }, + { + Name: "HS-CSHARP-74", + Rule: NewLdapInjectionDirectoryEntry(), + Src: SampleVulnerableHSCSHARP74, + Filename: filepath.Join(tempDir, "HS-CSHARP-74.test"), + Findings: []engine.Finding{ + { + CodeSample: "DirectoryEntry entry = new DirectoryEntry(string.Format(\"LDAP://DC={0}, DC=COM/\", model.Domain));", + SourceLocation: engine.Location{ + Filename: filepath.Join(tempDir, "HS-CSHARP-74.test"), + Line: 2, + Column: 23, + }, + }, + }, + }, } testutil.TestVulnerableCode(t, testcases) } @@ -70,13 +1269,445 @@ func TestRulesSafeCode(t *testing.T) { Name: "HS-CSHARP-1", Rule: NewCommandInjection(), Src: SampleSafeHSCSHARP1, - Filename: filepath.Join(tempDir, fmt.Sprintf("%s%s", "HS-CSHARP-1", ".test")), + Filename: filepath.Join(tempDir, "HS-CSHARP11.test"), }, { Name: "HS-CSHARP-2", Rule: NewXPathInjection(), Src: SampleSafeHSCSHARP2, - Filename: filepath.Join(tempDir, fmt.Sprintf("%s%s", "HS-CSHARP-2", ".test")), + Filename: filepath.Join(tempDir, "HS-CSHARP22.test"), + }, + { + Name: "HS-CSHARP-3", + Rule: NewExternalEntityInjection(), + Src: SampleSafeHSCSHARP3, + Filename: filepath.Join(tempDir, "HS-CSHARP32.test"), + }, + { + Name: "HS-CSHARP-4", + Rule: NewPathTraversal(), + Src: SampleSafeHSCSHARP4, + Filename: filepath.Join(tempDir, "HS-CSHARP42.test"), + }, + { + Name: "HS-CSHARP-5", + Rule: NewSQLInjectionWebControls(), + Src: SampleSafeHSCSHARP5, + Filename: filepath.Join(tempDir, "HS-CSHARP52.test"), + }, + { + Name: "HS-CSHARP-6", + Rule: NewWeakCipherOrCBCOrECBMode(), + Src: SampleSafeHSCSHARP6, + Filename: filepath.Join(tempDir, "HS-CSHARP62.test"), + }, + { + Name: "HS-CSHARP-7", + Rule: NewFormsAuthenticationCookielessMode(), + Src: SampleSafeHSCSHARP7, + Filename: filepath.Join(tempDir, "HS-CSHARP72.test"), + }, + { + Name: "HS-CSHARP-8", + Rule: NewFormsAuthenticationCrossAppRedirects(), + Src: SampleSafeHSCSHARP8, + Filename: filepath.Join(tempDir, "HS-CSHARP82.test"), + }, + { + Name: "HS-CSHARP-9", + Rule: NewFormsAuthenticationWeakCookieProtection(), + Src: SampleSafeHSCSHARP9, + Filename: filepath.Join(tempDir, "HS-CSHARP92.test"), + }, + { + Name: "HS-CSHARP-10", + Rule: NewFormsAuthenticationWeakTimeout(), + Src: SampleSafeHSCSHARP10, + Filename: filepath.Join(tempDir, "HS-CSHARP-10.test"), + }, + { + Name: "HS-CSHARP-11", + Rule: NewHeaderCheckingDisabled(), + Src: SampleSafeHSCSHARP11, + Filename: filepath.Join(tempDir, "HS-CSHARP-11.test"), + }, + { + Name: "HS-CSHARP-12", + Rule: NewVersionHeaderEnabled(), + Src: SampleSafeHSCSHARP12, + Filename: filepath.Join(tempDir, "HS-CSHARP-12.test"), + }, + { + Name: "HS-CSHARP-13", + Rule: NewEventValidationDisabled(), + Src: SampleSafeHSCSHARP13, + Filename: filepath.Join(tempDir, "HS-CSHARP-13.test"), + }, + { + Name: "HS-CSHARP-14", + Rule: NewWeakSessionTimeout(), + Src: SampleSafeHSCSHARP14, + Filename: filepath.Join(tempDir, "HS-CSHARP-14.test"), + }, + { + Name: "HS-CSHARP-15", + Rule: NewStateServerMode(), + Src: SampleSafeHSCSHARP15, + Filename: filepath.Join(tempDir, "HS-CSHARP-15.test"), + }, + { + Name: "HS-CSHARP-16", + Rule: NewJwtSignatureValidationDisabled(), + Src: SampleSafeHSCSHARP16, + Filename: filepath.Join(tempDir, "HS-CSHARP-16.test"), + }, + { + Name: "HS-CSHARP-17", + Rule: NewInsecureHttpCookieTransport(), + Src: SampleSafeHSCSHARP17, + Filename: filepath.Join(tempDir, "HS-CSHARP-17.test"), + }, + { + Name: "HS-CSHARP-18", + Rule: NewHttpCookieAccessibleViaScript(), + Src: SampleSafeHSCSHARP18, + Filename: filepath.Join(tempDir, "HS-CSHARP-18.test"), + }, + { + Name: "HS-CSHARP-19", + Rule: NewDirectoryListingEnabled(), + Src: SampleSafeHSCSHARP19, + Filename: filepath.Join(tempDir, "HS-CSHARP-19.test"), + }, + { + Name: "HS-CSHARP-20", + Rule: NewLdapAuthenticationDisabled(), + Src: SampleSafeHSCSHARP20, + Filename: filepath.Join(tempDir, "HS-CSHARP-20.test"), + }, + { + Name: "HS-CSHARP-21", + Rule: NewCertificateValidationDisabledAndMatch(), + Src: SampleSafeHSCSHARP21, + Filename: filepath.Join(tempDir, "HS-CSHARP-21.test"), + }, + { + Name: "HS-CSHARP-22", + Rule: NewActionRequestValidationDisabled(), + Src: SampleSafeHSCSHARP22, + Filename: filepath.Join(tempDir, "HS-CSHARP-22.test"), + }, + { + Name: "HS-CSHARP-23", + Rule: NewXmlDocumentExternalEntityExpansion(), + Src: SampleSafeHSCSHARP23, + Filename: filepath.Join(tempDir, "HS-CSHARP-23.test"), + }, + { + Name: "HS-CSHARP-24", + Rule: NewLdapInjectionFilterAssignment(), + Src: SampleSafeHSCSHARP24, + Filename: filepath.Join(tempDir, "HS-CSHARP-24.test"), + }, + { + Name: "HS-CSHARP-25", + Rule: NewSqlInjectionDynamicNHibernateQuery(), + Src: SampleSafeHSCSHARP25, + Filename: filepath.Join(tempDir, "HS-CSHARP-25.test"), + }, + { + Name: "HS-CSHARP-26", + Rule: NewLdapInjectionDirectorySearcher(), + Src: SampleSafeHSCSHARP26, + Filename: filepath.Join(tempDir, "HS-CSHARP-26.test"), + }, + { + Name: "HS-CSHARP-27", + Rule: NewLdapInjectionPathAssignment(), + Src: SampleSafeHSCSHARP27, + Filename: filepath.Join(tempDir, "HS-CSHARP-27.test"), + }, + { + Name: "HS-CSHARP-28", + Rule: NewLDAPInjection(), + Src: SampleSafeHSCSHARP28, + Filename: filepath.Join(tempDir, "HS-CSHARP-28.test"), + }, + { + Name: "HS-CSHARP-29", + Rule: NewSQLInjectionLinq(), + Src: SampleSafeHSCSHARP29, + Filename: filepath.Join(tempDir, "HS-CSHARP-29.test"), + }, + { + Name: "HS-CSHARP-30", + Rule: NewInsecureDeserialization(), + Src: SampleSafeHSCSHARP30, + Filename: filepath.Join(tempDir, "HS-CSHARP-30.test"), + }, + { + Name: "HS-CSHARP-31", + Rule: NewSQLInjectionEnterpriseLibraryData(), + Src: SampleSafeHSCSHARP31, + Filename: filepath.Join(tempDir, "HS-CSHARP-31.test"), + }, + { + Name: "HS-CSHARP-32", + Rule: NewCQLInjectionCassandra(), + Src: SampleSafeHSCSHARP32, + Filename: filepath.Join(tempDir, "HS-CSHARP-32.test"), + }, + { + Name: "HS-CSHARP-33", + Rule: NewPasswordComplexityDefault(), + Src: SampleSafeHSCSHARP33, + Filename: filepath.Join(tempDir, "HS-CSHARP-33.test"), + }, + { + Name: "HS-CSHARP-34", + Rule: NewCookieWithoutSSLFlag(), + Src: SampleSafeHSCSHARP34, + Filename: filepath.Join(tempDir, "HS-CSHARP-34.test"), + }, + { + Name: "HS-CSHARP-35", + Rule: NewCookieWithoutHttpOnlyFlag(), + Src: SampleSafeHSCSHARP35, + Filename: filepath.Join(tempDir, "HS-CSHARP-35.test"), + }, + { + Name: "HS-CSHARP-36", + Rule: NewNoInputVariable(), + Src: SampleSafeHSCSHARP36, + Filename: filepath.Join(tempDir, "HS-CSHARP-36.test"), + }, + { + Name: "HS-CSHARP-37", + Rule: NewIdentityWeakPasswordComplexity(), + Src: SampleSafeHSCSHARP37, + Filename: filepath.Join(tempDir, "HS-CSHARP-37.test"), + }, + { + Name: "HS-CSHARP-38", + Rule: NewNoLogSensitiveInformationInConsole(), + Src: SampleSafeHSCSHARP38, + Filename: filepath.Join(tempDir, "HS-CSHARP-38.test"), + }, + { + Name: "HS-CSHARP-39", + Rule: NewOutputCacheConflict(), + Src: SampleSafeHSCSHARP39, + Filename: filepath.Join(tempDir, "HS-CSHARP-39.test"), + }, + { + Name: "HS-CSHARP-40", + Rule: NewOpenRedirect(), + Src: SampleSafeHSCSHARP40, + Filename: filepath.Join(tempDir, "HS-CSHARP-40.test"), + }, + { + Name: "HS-CSHARP-41", + Rule: NewRequestValidationDisabledAttribute(), + Src: SampleSafeHSCSHARP41, + Filename: filepath.Join(tempDir, "HS-CSHARP-41.test"), + }, + { + Name: "HS-CSHARP-42", + Rule: NewSQLInjectionOLEDB(), + Src: SampleSafeHSCSHARP42, + Filename: filepath.Join(tempDir, "HS-CSHARP-42.test"), + }, + { + Name: "HS-CSHARP-43", + Rule: NewRequestValidationDisabledConfigurationFile(), + Src: SampleSafeHSCSHARP43, + Filename: filepath.Join(tempDir, "HS-CSHARP-43.test"), + }, + { + Name: "HS-CSHARP-44", + Rule: NewSQLInjectionMsSQLDataProvider(), + Src: SampleSafeHSCSHARP44, + Filename: filepath.Join(tempDir, "HS-CSHARP-44.test"), + }, + { + Name: "HS-CSHARP-45", + Rule: NewRequestValidationIsEnabledOnlyForPages(), + Src: SampleSafeHSCSHARP45, + Filename: filepath.Join(tempDir, "HS-CSHARP-45.test"), + }, + { + Name: "HS-CSHARP-46", + Rule: NewSQLInjectionEntityFramework(), + Src: SampleSafeHSCSHARP46, + Filename: filepath.Join(tempDir, "HS-CSHARP-46.test"), + }, + { + Name: "HS-CSHARP-47", + Rule: NewViewStateNotEncrypted(), + Src: SampleSafeHSCSHARP47, + Filename: filepath.Join(tempDir, "HS-CSHARP-47.test"), + }, + { + Name: "HS-CSHARP-48", + Rule: NewSQLInjectionNhibernate(), + Src: SampleSafeHSCSHARP48, + Filename: filepath.Join(tempDir, "HS-CSHARP-48.test"), + }, + { + Name: "HS-CSHARP-49", + Rule: NewViewStateMacDisabled(), + Src: SampleSafeHSCSHARP49, + Filename: filepath.Join(tempDir, "HS-CSHARP-49.test"), + }, + { + Name: "HS-CSHARP-50", + Rule: NewSQLInjectionNpgsql(), + Src: SampleSafeHSCSHARP50, + Filename: filepath.Join(tempDir, "HS-CSHARP-50.test"), + }, + { + Name: "HS-CSHARP-51", + Rule: NewCertificateValidationDisabled(), + Src: SampleSafeHSCSHARP51, + Filename: filepath.Join(tempDir, "HS-CSHARP-51.test"), + }, + { + Name: "HS-CSHARP-52", + Rule: NewWeakCipherAlgorithm(), + Src: SampleSafeHSCSHARP52, + Filename: filepath.Join(tempDir, "HS-CSHARP-52.test"), + }, + { + Name: "HS-CSHARP-53", + Rule: NewNoUseHtmlRaw(), + Src: SampleSafeHSCSHARP53, + Filename: filepath.Join(tempDir, "HS-CSHARP-53.test"), + }, + { + Name: "HS-CSHARP-54", + Rule: NewNoLogSensitiveInformation(), + Src: SampleSafeHSCSHARP54, + Filename: filepath.Join(tempDir, "HS-CSHARP-54.test"), + }, + { + Name: "HS-CSHARP-55", + Rule: NewNoReturnStringConcatInController(), + Src: SampleSafeHSCSHARP55, + Filename: filepath.Join(tempDir, "HS-CSHARP-55.test"), + }, + { + Name: "HS-CSHARP-56", + Rule: NewSQLInjectionOdbcCommand(), + Src: SampleSafeHSCSHARP56, + Filename: filepath.Join(tempDir, "HS-CSHARP-56.test"), + }, + { + Name: "HS-CSHARP-57", + Rule: NewWeakHashingFunctionMd5OrSha1(), + Src: SampleSafeHSCSHARP57, + Filename: filepath.Join(tempDir, "HS-CSHARP-57.test"), + }, + { + Name: "HS-CSHARP-58", + Rule: NewWeakHashingFunctionDESCrypto(), + Src: SampleSafeHSCSHARP58, + Filename: filepath.Join(tempDir, "HS-CSHARP-58.test"), + }, + { + Name: "HS-CSHARP-59", + Rule: NewNoUseCipherMode(), + Src: SampleSafeHSCSHARP59, + Filename: filepath.Join(tempDir, "HS-CSHARP-59.test"), + }, + { + Name: "HS-CSHARP-60", + Rule: NewDebugBuildEnabled(), + Src: SampleSafeHSCSHARP60, + Filename: filepath.Join(tempDir, "HS-CSHARP-60.test"), + }, + { + Name: "HS-CSHARP-61", + Rule: NewVulnerablePackageReference(), + Src: SampleSafeHSCSHARP61, + Filename: filepath.Join(tempDir, "HS-CSHARP-61.test"), + }, + { + Name: "HS-CSHARP-62", + Rule: NewCorsAllowOriginWildCard(), + Src: SampleSafeHSCSHARP62, + Filename: filepath.Join(tempDir, "HS-CSHARP-62.test"), + }, + { + Name: "HS-CSHARP-63", + Rule: NewMissingAntiForgeryTokenAttribute(), + Src: SampleSafeHSCSHARP63, + Filename: filepath.Join(tempDir, "HS-CSHARP-63.test"), + }, + { + Name: "HS-CSHARP-64", + Rule: NewUnvalidatedWebFormsRedirect(), + Src: SampleSafeHSCSHARP64, + Filename: filepath.Join(tempDir, "HS-CSHARP-64.test"), + }, + { + Name: "HS-CSHARP-65", + Rule: NewIdentityPasswordLockoutDisabled(), + Src: SampleSafeHSCSHARP65, + Filename: filepath.Join(tempDir, "HS-CSHARP-65.test"), + }, + { + Name: "HS-CSHARP-66", + Rule: NewRawInlineExpression(), + Src: SampleSafeHSCSHARP66, + Filename: filepath.Join(tempDir, "HS-CSHARP-66.test"), + }, + { + Name: "HS-CSHARP-67", + Rule: NewRawBindingExpression(), + Src: SampleSafeHSCSHARP67, + Filename: filepath.Join(tempDir, "HS-CSHARP-67.test"), + }, + { + Name: "HS-CSHARP-68", + Rule: NewRawWriteLiteralMethod(), + Src: SampleSafeHSCSHARP68, + Filename: filepath.Join(tempDir, "HS-CSHARP-68.test"), + }, + { + Name: "HS-CSHARP-69", + Rule: NewUnencodedWebFormsProperty(), + Src: SampleSafeHSCSHARP69, + Filename: filepath.Join(tempDir, "HS-CSHARP-69.test"), + }, + { + Name: "HS-CSHARP-70", + Rule: NewUnencodedLabelText(), + Src: SampleSafeHSCSHARP70, + Filename: filepath.Join(tempDir, "HS-CSHARP-70.test"), + }, + { + Name: "HS-CSHARP-71", + Rule: NewWeakRandomNumberGenerator(), + Src: SampleSafeHSCSHARP71, + Filename: filepath.Join(tempDir, "HS-CSHARP-71.test"), + }, + { + Name: "HS-CSHARP-72", + Rule: NewWeakRsaKeyLength(), + Src: SampleSafeHSCSHARP72, + Filename: filepath.Join(tempDir, "HS-CSHARP-72.test"), + }, + { + Name: "HS-CSHARP-73", + Rule: NewXmlReaderExternalEntityExpansion(), + Src: SampleSafeHSCSHARP73, + Filename: filepath.Join(tempDir, "HS-CSHARP-73.test"), + }, + { + Name: "HS-CSHARP-74", + Rule: NewLdapInjectionDirectoryEntry(), + Src: SampleSafeHSCSHARP74, + Filename: filepath.Join(tempDir, "HS-CSHARP-74.test"), }, } diff --git a/internal/services/engines/csharp/samples.go b/internal/services/engines/csharp/samples.go new file mode 100644 index 000000000..e6e9b5778 --- /dev/null +++ b/internal/services/engines/csharp/samples.go @@ -0,0 +1,1436 @@ +// Copyright 2021 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package csharp + +const ( + SampleVulnerableHSCSHARP1 = ` + var p = new Process(); + p.StartInfo.FileName = "exportLegacy.exe"; + p.StartInfo.Arguments = " -user " + input + " -role user"; + p.Start(); + ` + + SampleSafeHSCSHARP1 = ` + var p = new Process(); + p.StartInfo.FileName = "exportLegacy.exe"; + p.Start(); + ` + + SampleVulnerableHSCSHARP2 = ` + var doc = new XmlDocument {XmlResolver = null}; + doc.Load("/config.xml"); + var results = doc.SelectNodes("/Config/Devices/Device[id='" + input + "']"); + ` + + SampleSafeHSCSHARP2 = ` + XmlDocument doc = new XmlDocument { XmlResolver = null }; + doc.Load("/config.xml"); + var results = doc.SelectSingleNode("/Config/Devices/Device"); + ` + SampleVulnerableHSCSHARP3 = ` +XmlReaderSettings settings = new XmlReaderSettings(); +settings.ProhibitDtd = false; +XmlReader reader = XmlReader.Create(inputXml, settings); +` + SampleSafeHSCSHARP3 = ` +XmlReaderSettings settings = new XmlReaderSettings(); +settings.ProhibitDtd = true; +XmlReader reader = XmlReader.Create(inputXml, settings);` + SampleVulnerableHSCSHARP4 = ` +[RedirectingAction] +public ActionResult Download(string fileName) +{ + byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/ClientDocument/") + fileName); + return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); +} +` + SampleSafeHSCSHARP4 = ` +[RedirectingAction] +public ActionResult Download(string fileName) +{ + private static readonly char[] InvalidFilenameChars = Path.GetInvalidFileNameChars(); + + if (fileName.IndexOfAny(InvalidFilenameChars) >= 0) + return new HttpStatusCodeResult(HttpStatusCode.BadRequest); + + byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/ClientDocument/") + fileName); + return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); +} +` + SampleVulnerableHSCSHARP5 = ` +var cmd = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; +ctx.Database.ExecuteSqlCommand( + cmd); +` + SampleSafeHSCSHARP5 = ` +var cmd = "SELECT * FROM Users WHERE username = @username and role='user'"; +ctx.Database.ExecuteSqlCommand( + cmd, + new SqlParameter("@username", input)); +` + SampleVulnerableHSCSHARP6 = ` +using (var aes = new AesManaged { + KeySize = KeyBitSize, + BlockSize = BlockBitSize, + Mode = CipherMode.OFB, + Padding = PaddingMode.PKCS7 +}) +{ + using (var encrypter = aes.CreateEncryptor(cryptKey, new byte[16])) + using (var cipherStream = new MemoryStream()) + { + using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) + using (var binaryWriter = new BinaryWriter(cryptoStream)) + { + //Encrypt Data + binaryWriter.Write(secretMessage); + } + cipherText = cipherStream.ToArray(); + } +} +//Missing HMAC suffix to assure integrity +` + SampleSafeHSCSHARP6 = ` +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Engines; +using Org.BouncyCastle.Crypto.Generators; +using Org.BouncyCastle.Crypto.Modes; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Security; + +public static readonly int BlockBitSize = 128; +public static readonly int KeyBitSize = 256; + +public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key) +{ + //User Error Checks + if (key == null || key.Length != KeyBitSize / 8) + throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key"); + + if (secretMessage == null || secretMessage.Length == 0) + throw new ArgumentException("Secret Message Required!", "secretMessage"); + + //Using random nonce large enough not to repeat + var nonce = new byte[NonceBitSize / 8]; + Random.NextBytes(nonce, 0, nonce.Length); + + var cipher = new GcmBlockCipher(new AesFastEngine()); + var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, new byte[0]); + cipher.Init(true, parameters); + + //Generate Cipher Text With Auth Tag + var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)]; + var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0); + cipher.DoFinal(cipherText, len); + + //Assemble Message + using (var combinedStream = new MemoryStream()) + { + using (var binaryWriter = new BinaryWriter(combinedStream)) + { + //Prepend Nonce + binaryWriter.Write(nonce); + //Write Cipher Text + binaryWriter.Write(cipherText); + } + return combinedStream.ToArray(); + } +}` + SampleVulnerableHSCSHARP7 = ` + + + + + +` + SampleSafeHSCSHARP7 = ` + + + + + +` + SampleVulnerableHSCSHARP8 = ` + + + + + +` + SampleSafeHSCSHARP8 = ` + + + + + +` + SampleVulnerableHSCSHARP9 = ` + + + + + +` + SampleSafeHSCSHARP9 = ` + + + + + +` + SampleVulnerableHSCSHARP10 = ` + + + + + +` + SampleSafeHSCSHARP10 = ` + + + + + +` + SampleVulnerableHSCSHARP11 = ` + +` + SampleSafeHSCSHARP11 = ` + +` + SampleVulnerableHSCSHARP12 = ` + +` + SampleSafeHSCSHARP12 = ` + +` + SampleVulnerableHSCSHARP13 = ` + +` + SampleSafeHSCSHARP13 = ` + +` + SampleVulnerableHSCSHARP14 = ` + +` + SampleSafeHSCSHARP14 = ` + +` + SampleVulnerableHSCSHARP15 = ` + +` + SampleSafeHSCSHARP15 = ` + +` + SampleVulnerableHSCSHARP16 = ` +services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + [...] + RequireSignedTokens = false, + }; + }); +` + SampleSafeHSCSHARP16 = ` +services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + [...] + RequireSignedTokens = true, + }; + }); +` + SampleVulnerableHSCSHARP17 = ` +CookieOptions options = new CookieOptions() +{ + Secure = false, +}; +` + SampleSafeHSCSHARP17 = ` +CookieOptions options = new CookieOptions() +{ + Secure = true, +}; +` + SampleVulnerableHSCSHARP18 = ` +CookieOptions options = new CookieOptions() +{ + HttpOnly = false, +}; +` + SampleSafeHSCSHARP18 = ` + CookieOptions options = new CookieOptions() +{ + HttpOnly = true, +}; +` + SampleVulnerableHSCSHARP19 = ` + + + +` + SampleSafeHSCSHARP19 = ` + + + +` + SampleVulnerableHSCSHARP20 = ` +DirectoryEntry entry = new DirectoryEntry("LDAP://DC=PUMA}, DC=COM/"); +entry.AuthenticationType = AuthenticationTypes.Anonymous; +` + SampleSafeHSCSHARP20 = ` +DirectoryEntry entry = new DirectoryEntry("LDAP://DC=PUMA}, DC=COM/"); +entry.AuthenticationType = AuthenticationTypes.Secure; +` + SampleVulnerableHSCSHARP21 = ` +using (var handler = new WebRequestHandler()) +{ + handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; + + using (var client = new HttpClient(handler)) + { + var request = client.GetAsync(string.Format("{0}{1}", BASE_URL, endpoint)).ContinueWith((response) => + { + var result = response.Result; + var json = result.Content.ReadAsStringAsync(); + json.Wait(); + item = JsonConvert.DeserializeObject(json.Result); + } + ); + request.Wait(); + } +} +` + SampleSafeHSCSHARP21 = ` +using (var handler = new WebRequestHandler()) +{ + using (var client = new HttpClient(handler)) + { + var request = client.GetAsync(string.Format("{0}{1}", BASE_URL, endpoint)).ContinueWith((response) => + { + var result = response.Result; + var json = result.Content.ReadAsStringAsync(); + json.Wait(); + item = JsonConvert.DeserializeObject(json.Result); + } + ); + request.Wait(); + } +} +` + SampleVulnerableHSCSHARP22 = ` +[HttpPost] +[ValidateInput(false)] +public ActionResult Save(int id, ProductFeedbackModel model) +{ + ... +} +` + SampleSafeHSCSHARP22 = ` +[HttpPost] +public ActionResult Save(int id, ProductFeedbackModel model) +{ + ... +} +` + SampleVulnerableHSCSHARP23 = ` +XmlUrlResolver resolver = new XmlUrlResolver(); +resolver.Credentials = CredentialCache.DefaultCredentials; + +XmlDocument xmlDoc = new XmlDocument(); +xmlDoc.XmlResolver = resolver; +xmlDoc.LoadXml(xml); +` + SampleSafeHSCSHARP23 = ` +XmlDocument xmlDoc = new XmlDocument(); +xmlDoc.XmlResolver = null; +xmlDoc.LoadXml(xml); +` + SampleVulnerableHSCSHARP24 = ` +DirectoryEntry entry = new DirectoryEntry("LDAP://DC=example.com, DC=COM"); +DirectorySearcher searcher = new DirectorySearcher(entry); +searcher.SearchScope = SearchScope.Subtree; +searcher.Filter = string.Format("(name={0})", model.UserName); +SearchResultCollection resultCollection = searcher.FindAll(); +` + SampleSafeHSCSHARP24 = ` +DirectoryEntry entry = new DirectoryEntry("LDAP://DC=example.com, DC=COM"); +DirectorySearcher searcher = new DirectorySearcher(entry); +searcher.SearchScope = SearchScope.Subtree; +searcher.Filter = string.Format("(name={0})", Encoder.LdapFilterEncode(model.UserName)); +SearchResultCollection resultCollection = searcher.FindAll(); +` + SampleVulnerableHSCSHARP25 = ` +string q = "SELECT * FROM Items WHERE ProductCode = '" + model.ProductCode + "'"; + +var cfg = new Configuration(); +ISessionFactory sessions = cfg.BuildSessionFactory(); +ISession session = sessions.OpenSession(); + +var query = session.CreateQuery(q); +var product = query.List().FirstOrDefault(); +` + SampleSafeHSCSHARP25 = ` +string q = "SELECT * FROM Items WHERE ProductCode = :productCode"; + +var cfg = new Configuration(); +ISessionFactory sessions = cfg.BuildSessionFactory(); +ISession session = sessions.OpenSession(); + +var query = session.CreateQuery(q); +var product = query + .SetString("productCode", model.ProductCode) + .List().FirstOrDefault(); +` + SampleVulnerableHSCSHARP26 = ` +DirectoryEntry entry = new DirectoryEntry("LDAP://DC=example.com, DC=COM/"); +DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(name={0})", model.UserName); +searcher.SearchScope = SearchScope.Subtree; +SearchResultCollection resultCollection = searcher.FindAll(); +` + SampleSafeHSCSHARP26 = ` +DirectoryEntry entry = new DirectoryEntry("LDAP://DC=example.com, DC=COM/"); +DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(name={0})", Encoder.LdapFilterEncode(model.UserName))); +searcher.SearchScope = SearchScope.Subtree; +SearchResultCollection resultCollection = searcher.FindAll(); +` + SampleVulnerableHSCSHARP27 = ` +DirectoryEntry entry = new DirectoryEntry(); +entry.Path = string.Format("LDAP://DC={0},DC=COM,CN=Users", model.Domain); +entry.Username = model.UserName; +entry.Password = model.Password; +DirectorySearcher searcher = new DirectorySearcher(entry); +searcher.SearchScope = SearchScope.Subtree; +searcher.Filter = $"(samaccountname=DOMAIN\\BobbyTables)"; +SearchResult result = searcher.FindOne(); +` + SampleSafeHSCSHARP27 = ` +DirectoryEntry entry = new DirectoryEntry(); +entry.Path = string.Format("LDAP://DC={0},DC=COM,CN=Users", Encoder.LdapDistinguishedNameEncode(model.Domain)); +entry.Username = model.UserName; +entry.Password = model.Password; +DirectorySearcher searcher = new DirectorySearcher(entry); +searcher.SearchScope = SearchScope.Subtree; +searcher.Filter = $"(samaccountname=DOMAIN\\BobbyTables)"; +SearchResult result = searcher.FindOne(); +` + SampleVulnerableHSCSHARP28 = ` +var searcher = new DirectorySearcher(); +searcher.Filter = "(cn=" + input + ")"; +` + SampleSafeHSCSHARP28 = ` +var searcher = new DirectorySearcher(); +searcher.Filter = "(cn=" + Encoder.LdapFilterEncode(input) + ")"; +` + SampleVulnerableHSCSHARP29 = ` +var cmd = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; +ctx.Database.ExecuteSqlCommand( + cmd); +` + SampleSafeHSCSHARP29 = ` +var cmd = "SELECT * FROM Users WHERE username = @username and role='user'"; +ctx.Database.ExecuteSqlCommand( + cmd, + new SqlParameter("@username", input)); +` + SampleVulnerableHSCSHARP30 = ` +private void ConvertData(string json) +{ + var mySerializer = new JavaScriptSerializer(new SimpleTypeResolver()); + Object mything = mySerializer.Deserialize(json, typeof(SomeDataClass)/* the type doesn't matter */); +} +` + SampleSafeHSCSHARP30 = ` +private void ConvertData(string json) +{ + /* no resolver in JavaScriptSerializer parameter's */ + var mySerializer = new JavaScriptSerializer(); + Object mything = mySerializer.Deserialize(json, typeof(SomeDataClass)); +} +` + SampleVulnerableHSCSHARP31 = ` +public XCLCMS.Data.Model.View.v_Comments GetModel(long CommentsID) + { + XCLCMS.Data.Model.View.v_Comments model = new XCLCMS.Data.Model.View.v_Comments(); + Database db = base.CreateDatabase(); + DbCommand dbCommand = db.GetSqlStringCommand("select * from v_Comments WITH(NOLOCK) where CommentsID=" + CommentsID); + using (var dr = db.ExecuteDataSet(dbCommand)) + { + return XCLNetTools.DataSource.DataReaderHelper.DataReaderToEntity(dr); + } + } +` + SampleSafeHSCSHARP31 = ` +public XCLCMS.Data.Model.View.v_Comments GetModel(long CommentsID) + { + XCLCMS.Data.Model.View.v_Comments model = new XCLCMS.Data.Model.View.v_Comments(); + Database db = base.CreateDatabase(); + DbCommand dbCommand = db.GetSqlStringCommand("select * from v_Comments WITH(NOLOCK) where CommentsID=@CommentsID"); + db.AddInParameter(dbCommand, "CommentsID", DbType.Int64, CommentsID); + using (var dr = db.ExecuteDataSet(dbCommand)) + { + return XCLNetTools.DataSource.DataReaderHelper.DataReaderToEntity(dr); + } + } +` + SampleVulnerableHSCSHARP32 = ` +public void query(string filter) { + PreparedStatement ps = session.prepare("SELECT * FROM users WHERE uname="+filter); + session.execute(ps); +} +` + SampleSafeHSCSHARP32 = ` +public void query(string filter) { + PreparedStatement ps = session.prepare("SELECT * FROM users WHERE uname=?"); + ps = ps.bind('uname', filter) + session.execute(ps); +} +` + SampleVulnerableHSCSHARP33 = ` +manager.PasswordValidator = new PasswordValidator +{ + RequiredLength = 6 +}; + +or + +manager.PasswordValidator = new PasswordValidator(); +` + SampleSafeHSCSHARP33 = ` +manager.PasswordValidator = new PasswordValidator +{ + RequiredLength = 12, // greater than 8 + RequireDigit = true, // required + RequireLowercase = true, // required + RequireNonLetterOrDigit = true, // required + RequireUppercase = true // required +}; +` + SampleVulnerableHSCSHARP34 = ` + + ... + + ... + +` + SampleSafeHSCSHARP34 = ` + + ... + + ... + +` + SampleVulnerableHSCSHARP35 = ` + + ... + + ... + +` + SampleSafeHSCSHARP35 = ` + + ... + + ... + +` + SampleVulnerableHSCSHARP36 = ` + let executableXss = "" + + element.innerHTML = executableXss +` + SampleSafeHSCSHARP36 = ` + let executableXss = "" + + element.textContent = executableXss +` + + SampleVulnerableHSCSHARP37 = ` +manager.PasswordValidator = new PasswordValidator +{ + RequiredLength = 6 +}; +` + SampleSafeHSCSHARP37 = ` +manager.PasswordValidator = new PasswordValidator +{ + RequiredLength = 12, // greater than 8 + RequireDigit = true, // required + RequireLowercase = true, // required + RequireNonLetterOrDigit = true, // required + RequireUppercase = true // required +}; +` + + SampleVulnerableHSCSHARP38 = ` +public void OnGet() +{ + Console.WriteLine("The user logged is: " + user); +} + +or + +public void OnGet() +{ + Message = $"The user logged is: {user}"; + _logger.LogInformation(Message); +} + +or + +public void OnGet() +{ + Message = $"The user logged is: {user}"; + _logger.LogError(Message); +} +` + SampleSafeHSCSHARP38 = ` +// It is recommended not to use any logs on your system. +` + SampleVulnerableHSCSHARP39 = ` +[Authorize] +public class AdminController : Controller +{ + [OutputCache] + public ActionResult Index() + { + return View(); + } +} +` + SampleSafeHSCSHARP39 = ` +[Authorize] +public class AdminController : Controller +{ + public ActionResult Index() + { + return View(); + } +} +` + SampleVulnerableHSCSHARP40 = ` +[HttpPost] +public ActionResult LogOn(LogOnModel model, string returnUrl) +{ + if (ModelState.IsValid) + { + if (MembershipService.ValidateUser(model.UserName, model.Password)) + { + FormsService.SignIn(model.UserName, model.RememberMe); + if (!String.IsNullOrEmpty(returnUrl)) + { + return Redirect(returnUrl); + } + else + { + return RedirectToAction("Index", "Home"); + } + } + else + { + ModelState.AddModelError("", "The user name or password provided is incorrect."); + } + } + + // If we got this far, something failed, redisplay form + return View(model); +} +` + SampleSafeHSCSHARP40 = ` +[HttpPost] +public ActionResult LogOn(LogOnModel model, string returnUrl) +{ + if (ModelState.IsValid) + { + if (MembershipService.ValidateUser(model.UserName, model.Password)) + { + FormsService.SignIn(model.UserName, model.RememberMe); + if (Url.IsLocalUrl(returnUrl)) // Make sure the url is relative, not absolute path + { + return Redirect(returnUrl); + } + else + { + return RedirectToAction("Index", "Home"); + } + } + else + { + ModelState.AddModelError("", "The user name or password provided is incorrect."); + } + } + + // If we got this far, something failed, redisplay form + return View(model); +} +` + SampleVulnerableHSCSHARP41 = `public class TestController +{ + [HttpPost] + [ValidateInput(false)] + public ActionResult ControllerMethod(string input) { + return f(input); + } +} +` + SampleSafeHSCSHARP41 = ` +public class TestController +{ + [HttpPost] + public ActionResult ControllerMethod(string input) { + return f(input); + } +} +` + SampleVulnerableHSCSHARP42 = ` +sql = "select sr_scenman_hid, name, remark from ras_sr_scenman_head where name = " + ScenmanName; + OleDbConnection oconnection = new OleDbConnection(ModGloVariable.RasmusConn); + oconnection.Open(); + OleDbCommand cmd = new OleDbCommand(sql, oconnection); + cmd.CommandType = System.Data.CommandType.Text; + OleDbDataReader reader = cmd.ExecuteReader(); +` + SampleSafeHSCSHARP42 = ` +sql = "select sr_scenman_hid, name, remark from ras_sr_scenman_head where name = @ScenmanName"; + OleDbConnection oconnection = new OleDbConnection(ModGloVariable.RasmusConn); + oconnection.Open(); + OleDbCommand cmd = new OleDbCommand(sql, oconnection); + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@ScenmanName", OleDbType.Char, 50).Value = ScenmanName; + OleDbDataReader reader = cmd.ExecuteReader(); +` + SampleVulnerableHSCSHARP43 = ` + + ... + + ... + +` + SampleSafeHSCSHARP43 = ` + + ... + + ... + +` + SampleVulnerableHSCSHARP44 = ` +protected void btnSearch_Click(object sender, EventArgs e) { + SqlConnection conn = new SqlConnection(@"Data Source=ServerName\SQLEXPRESS;Initial Catalog=DemoDB;Integrated Security=SSPI;"); + SqlCommand cmd = new SqlCommand("Select * from GridViewDynamicData where Field1= '" + txtSearch.Text +"'", conn); + conn.Open(); + SqlDataAdapter ad = new SqlDataAdapter(cmd); + DataTable dt = new DataTable(); + ad.Fill(dt); + if(dt.Rows.Count > 0) + { + GridView1.DataSource = dt; + GridView1.DataBind(); + } + conn.Close(); +} +` + SampleSafeHSCSHARP44 = ` +protected void btnSearch_Click(object sender, EventArgs e) { + DataTable dt = new DataTable(); + using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString)){ + string sql = "SELECT * FROM GridViewDynamicData WHERE Field1 = @SearchText"; + using(SqlCommand sqlCmd = new SqlCommand(sql,sqlConn)){ + sqlCmd.Parameters.AddWithValue("@SearchText", txtSearch.Text); + sqlConn.Open(); + using(SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd)){ + sqlAdapter.Fill(dt); + } + } + } + + if(dt.Rows.Count > 0){ + GridView1.DataSource = dt; + GridView1.DataBind(); + } +} + +` + SampleVulnerableHSCSHARP45 = ` + + ... + + ... + +` + SampleSafeHSCSHARP45 = ` + + ... + + ... + +` + SampleVulnerableHSCSHARP46 = ` +var cmd = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; +ctx.Database.ExecuteSqlCommand( + cmd); +` + SampleSafeHSCSHARP46 = ` +var cmd = "SELECT * FROM Users WHERE username = @username and role='user'"; +ctx.Database.ExecuteSqlCommand( + cmd, + new SqlParameter("@username", input)); +` + SampleVulnerableHSCSHARP47 = ` + + ... + + ... + + +or + + + + ... + + ... + +` + SampleSafeHSCSHARP47 = ` + + ... + + ... + +` + SampleVulnerableHSCSHARP48 = ` +string q = "SELECT * FROM Items WHERE ProductCode = '" + model.ProductCode + "'"; + +var cfg = new Configuration(); +ISessionFactory sessions = cfg.BuildSessionFactory(); +ISession session = sessions.OpenSession(); + +var query = session.CreateSqlQuery(q); +var product = query.List().FirstOrDefault(); +` + SampleSafeHSCSHARP48 = ` +string q = "SELECT * FROM Items WHERE ProductCode = :productCode"; + +var cfg = new Configuration(); +ISessionFactory sessions = cfg.BuildSessionFactory(); +ISession session = sessions.OpenSession(); + +var query = session.CreateSqlQuery(q); +var product = query + .SetParameter("productCode", model.ProductCode) + .List().FirstOrDefault(); +` + SampleVulnerableHSCSHARP49 = ` + + ... + + ... + +` + SampleSafeHSCSHARP49 = ` + + ... + + ... + +` + SampleVulnerableHSCSHARP50 = ` + public void Append(string name, byte[] data, long expectedVersion) + { + using (var conn = new NpgsqlConnection(_connectionString)) + { + conn.Open(); + using (var tx = conn.BeginTransaction()) + { + var version = MakeSureLastVersionMatches(name, expectedVersion, conn, tx); + + const string txt = + @""; + + using (var cmd = new NpgsqlCommand( + "INSERT INTO ES_Events2 (CustomerId, Name, Version, Data) + VALUES("+customerId+","+name+","+(version+1)+","+data+")", + conn, tx)) + { + cmd.ExecuteNonQuery(); + } + tx.Commit(); + } + } + } +` + SampleSafeHSCSHARP50 = ` + public void Append(string name, byte[] data, long expectedVersion) + { + using (var conn = new NpgsqlConnection(_connectionString)) + { + conn.Open(); + using (var tx = conn.BeginTransaction()) + { + var version = MakeSureLastVersionMatches(name, expectedVersion, conn, tx); + + const string txt = + @"INSERT INTO ES_Events2 (CustomerId, Name, Version, Data) + VALUES(:customerId, :name, :version, :data)"; + + using (var cmd = new NpgsqlCommand(txt, conn, tx)) + { + cmd.Parameters.AddWithValue(":name", name); + cmd.Parameters.AddWithValue(":version", version+1); + cmd.Parameters.AddWithValue(":data", data); + cmd.Parameters.AddWithValue(":customerId", customerId); + cmd.ExecuteNonQuery(); + } + tx.Commit(); + } + } + } +` + SampleVulnerableHSCSHARP51 = ` +using (var handler = new WebRequestHandler()) +{ + handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; + + using (var client = new HttpClient(handler)) + { + var request = client.GetAsync(string.Format("{0}{1}", BASE_URL, endpoint)).ContinueWith((response) => + { + var result = response.Result; + var json = result.Content.ReadAsStringAsync(); + json.Wait(); + item = JsonConvert.DeserializeObject(json.Result); + } + ); + request.Wait(); + } +} +` + SampleSafeHSCSHARP51 = ` +using (var handler = new WebRequestHandler()) +{ + using (var client = new HttpClient(handler)) + { + var request = client.GetAsync(string.Format("{0}{1}", BASE_URL, endpoint)).ContinueWith((response) => + { + var result = response.Result; + var json = result.Content.ReadAsStringAsync(); + json.Wait(); + item = JsonConvert.DeserializeObject(json.Result); + } + ); + request.Wait(); + } +} +` + SampleVulnerableHSCSHARP52 = ` +DES DESalg = DES.Create(); + +// Create a string to encrypt. +byte[] encrypted; +ICryptoTransform encryptor = DESalg.CreateEncryptor(key, zeroIV); + +// Create the streams used for encryption. +using (MemoryStream msEncrypt = new MemoryStream()) +{ + using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, + encryptor, + CryptoStreamMode.Write)) + { + using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) + { + //Write all data to the stream. + swEncrypt.Write(Data); + } + encrypted = msEncrypt.ToArray(); + return encrypted; + } +} +` + SampleSafeHSCSHARP52 = ` +// Create a string to encrypt. +byte[] encrypted; +var encryptor = new AesManaged(); +encryptor.Key = key; +encryptor.GenerateIV(); +var iv = encryptor.IV; + +// Create the streams used for encryption. +using (MemoryStream msEncrypt = new MemoryStream()) +{ + using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, + encryptor.CreateEncryptor(), + CryptoStreamMode.Write)) + { + using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) + { + //Write all data to the stream. + swEncrypt.Write(Data); + } + encrypted = msEncrypt.ToArray(); + return encrypted; + } +} +` + SampleVulnerableHSCSHARP53 = ` +
+ @Html.Raw(string.Format("Welcome {0}!", Model.UserName)) +
+` + SampleSafeHSCSHARP53 = ` +
+ Welcome @Model.UserName! +
+` + SampleVulnerableHSCSHARP54 = ` + + ... + + ... + +` + SampleSafeHSCSHARP54 = ` + + ... + + ... + +` + SampleVulnerableHSCSHARP55 = ` +public class AdminController : Controller +{ + public string GetScript(string param) { + return "" + } +} +` + SampleSafeHSCSHARP55 = ` +public class AdminController : Controller +{ + public string GetScript() { + return "" + } +} +` + SampleVulnerableHSCSHARP56 = ` + public static List getAllAuspiciantes(string name) + { + OdbcConnection con = ConexionBD.ObtenerConexion(); + DataSet ds = new DataSet(); + List listaAuspiciantes = new List(); + try + { + OdbcCommand cmd = new OdbcCommand("SELECT a.id, a.image FROM auspiciante a Where a.name = " + name, con); + cmd.CommandType = CommandType.Text; + OdbcDataReader dr = cmd.ExecuteReader(); + + while (dr.Read()) + { + Auspiciante a = new Auspiciante(); + a.IdAuspiciante = dr.GetInt32(dr.GetOrdinal("id")); + a.ImagenAuspiciante = ImagenDAL.getImagen(con,dr.GetInt32(dr.GetOrdinal("imagen"))); + + listaAuspiciantes.Add(a); + } + } + catch (Exception e) + { + throw new SportingException("Ocurrio un problema al intentar obtener los auspiciantes. " + e.Message); + } + return listaAuspiciantes; + } +` + SampleSafeHSCSHARP56 = ` +public static List getAllAuspiciantes(string name) +{ + OdbcConnection con = ConexionBD.ObtenerConexion(); + DataSet ds = new DataSet(); + List listaAuspiciantes = new List(); + try + { + OdbcCommand cmd = new OdbcCommand("SELECT a.id, a.image FROM auspiciante a Where a.name = ?", con); + command.Parameters.Add(new OdbcParameter("name", name)); + cmd.CommandType = CommandType.Text; + OdbcDataReader dr = cmd.ExecuteReader(); + + while (dr.Read()) + { + Auspiciante a = new Auspiciante(); + a.IdAuspiciante = dr.GetInt32(dr.GetOrdinal("id")); + a.ImagenAuspiciante = ImagenDAL.getImagen(con,dr.GetInt32(dr.GetOrdinal("imagen"))); + + listaAuspiciantes.Add(a); + } + } + catch (Exception e) + { + throw new SportingException("Ocurrio un problema al intentar obtener los auspiciantes. " + e.Message); + } + return listaAuspiciantes; +} +` + SampleVulnerableHSCSHARP57 = ` +HashAlgorithm hash = new SHA1CryptoServiceProvider(); +byte[] bytes = hash.ComputeHash(input); +` + SampleSafeHSCSHARP57 = ` +HashAlgorithm hash = new SHA512Managed(); +byte[] bytes = hash.ComputeHash(input); +` + SampleVulnerableHSCSHARP58 = ` +using (MemoryStream mStream = new MemoryStream()) +{ + //Input bytes + byte[] inputBytes = Encoding.UTF8.GetBytes(plainText); + + SymmetricAlgorithm alg = new DESCryptoServiceProvider(); + + //Set key and iv + alg.Key = GetKey(); + alg.IV = GetIv(); + + //Create the crypto stream + CryptoStream cStream = new CryptoStream(mStream, alg.CreateEncryptor(), CryptoStreamMode.Write); + cStream.Write(inputBytes, 0, inputBytes.Length); + cStream.FlushFinalBlock(); + cStream.Close(); + + //Get the output + output = mStream.ToArray(); + + //Close resources + mStream.Close(); + alg.Clear(); +} +` + SampleSafeHSCSHARP58 = ` +using (MemoryStream mStream = new MemoryStream()) +{ + //Input bytes + byte[] inputBytes = Encoding.UTF8.GetBytes(plainText); + + SymmetricAlgorithm alg = new AesManaged(); + + //Set key and iv + alg.Key = GetKey(); + alg.IV = GetIv(); + + //Create the crypto stream + CryptoStream cStream = new CryptoStream(mStream, alg.CreateEncryptor(), CryptoStreamMode.Write); + cStream.Write(inputBytes, 0, inputBytes.Length); + cStream.FlushFinalBlock(); + cStream.Close(); + + //Get the output + output = mStream.ToArray(); + + //Close resources + mStream.Close(); + alg.Clear(); +} +` + SampleVulnerableHSCSHARP59 = ` +using (MemoryStream mStream = new MemoryStream()) +{ + //Input bytes + byte[] inputBytes = Encoding.UTF8.GetBytes(plainText); + + SymmetricAlgorithm alg = Aes.Create(); + alg.Mode = CipherMode.ECB; + + //Set key and iv + alg.Key = GetKey(); + alg.IV = GetIv(); + + //Create the crypto stream + CryptoStream cStream = new CryptoStream(mStream + , alg.CreateEncryptor() + , CryptoStreamMode.Write); + cStream.Write(inputBytes, 0, inputBytes.Length); + cStream.FlushFinalBlock(); + cStream.Close(); + + //Get the output + output = mStream.ToArray(); + + //Close resources + mStream.Close(); + alg.Clear(); +} +` + SampleSafeHSCSHARP59 = ` +//Perform integrity check on incoming data +string[] args = model.ProtectedData.Split('.'); +byte[] ciphertext = Convert.FromBase64String(args[0]); +byte[] hmac = Convert.FromBase64String(args[1]); + +HMACSHA256 hmac = new HMACSHA256(_KEY); +byte[] verification = hmac.ComputeHash(ciphertext); + +if (!verification.SequenceEqual(hmac)) + throw new ArgumentException("Invalid signature detected."); + +using (MemoryStream mStream = new MemoryStream()) +{ + SymmetricAlgorithm alg = Aes.Create(); + alg.Mode = CipherMode.CBC; + + //Set key and iv + alg.Key = GetKey(); + alg.IV = GetIv(); + + //Create the crypto stream + CryptoStream cStream = new CryptoStream(mStream + , alg.CreateDecryptor() + , CryptoStreamMode.Write); + cStream.Write(ciphertext, 0, inputBytes.Length); + cStream.FlushFinalBlock(); + cStream.Close(); + + //Get the cleartext + byte[] cleartext = mStream.ToArray(); + + //Close resources + mStream.Close(); + alg.Clear(); +} +` + SampleVulnerableHSCSHARP60 = ` + + ... + + ... + +` + SampleSafeHSCSHARP60 = ` + + ... + + ... + +` + SampleVulnerableHSCSHARP61 = ` + +` + SampleSafeHSCSHARP61 = ` + +` + SampleVulnerableHSCSHARP62 = ` +public void Configure(IApplicationBuilder app, IHostingEnvironment env) +{ + ... + app.UseCors(builder => builder.AllowAnyOrigin()); + ... +} +` + SampleSafeHSCSHARP62 = ` +private readonly string secureOrigin = "_secureOrigin"; + +public void ConfigureServices(IServiceCollection services) +{ + services.AddCors(options => + { + options.AddPolicy(MyAllowSpecificOrigins, + builder => + { + builder.WithOrigins("https://www.pumasecurity.io", + "https://www.pumascan.com"); + }); + }); +} + +public void Configure(IApplicationBuilder app, IHostingEnvironment env) +{ + ... + app.UseCors(secureOrigin); + ... +} +` + SampleVulnerableHSCSHARP63 = ` +[HttpPost] +public ActionResult Enter(int id, ContestEntryModel model) +{ + if (ModelState.IsValid) + { + submitContestEntry(id, model); + } +} +` + SampleSafeHSCSHARP63 = ` +[HttpPost] +[ValidateAntiForgeryToken] +public ActionResult Enter(int id, ContestEntryModel model) +{ + if (ModelState.IsValid) + { + submitContestEntry(id, model); + } +} +` + SampleVulnerableHSCSHARP64 = ` +protected void LoginUser_LoggedIn(object sender, EventArgs e) +{ + if (Request.QueryString["ReturnUrl"] != null) + Response.Redirect(Request.QueryString["ReturnUrl"]); +} +` + SampleSafeHSCSHARP64 = ` +protected void LoginUser_LoggedIn(object sender, EventArgs e) +{ + Uri targetUri = null; + + if (Uri.TryCreate(Request.QueryString["ReturnUrl"], UriKind.Relative, out targetUri)) + { + Response.Redirect(targetUri.ToString()); + } + else + { + Response.Redirect("~/default.aspx"); + } +} +` + SampleVulnerableHSCSHARP65 = ` +public async Task Login(LoginViewModel model, string returnUrl) +{ + var user = await _userManager.FindByNameAsync(model.Username); + [...] + var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); + [...] +}; +` + SampleSafeHSCSHARP65 = ` +{ + var user = await _userManager.FindByNameAsync(model.Username); + [...] + var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true); + [...] +}; +` + SampleVulnerableHSCSHARP66 = ` +

+ Welcome <%= Request["UserName"].ToString() %> +

+` + SampleSafeHSCSHARP66 = ` +

+ Welcome <%: Request["UserName"].ToString() %> +

+` + SampleVulnerableHSCSHARP67 = ` + + + + + <%# Item.ProductName %> + + + + +` + SampleSafeHSCSHARP67 = ` + + + + + <%#: Item.ProductName %> + + + + +` + SampleVulnerableHSCSHARP68 = ` +
+@{ + WriteLiteral(string.Format("Welcome {0}!", Model.UserName)); +} +
+` + SampleSafeHSCSHARP68 = ` +
+ Welcome @Model.UserName! +
+` + SampleVulnerableHSCSHARP69 = ` +litDetails.Text = product.ProductDescription; +` + SampleSafeHSCSHARP69 = ` +litDetails.Text = Encoder.HtmlEncode(product.ProductDescription); +` + SampleVulnerableHSCSHARP70 = ` +lblDetails.Text = product.ProductDescription; +` + SampleSafeHSCSHARP70 = ` +lblDetails.Text = Encoder.HtmlEncode(product.ProductDescription); +` + SampleVulnerableHSCSHARP71 = ` +public static byte[] GenerateRandomBytes(int length) +{ + var random = new Random(); + byte[] bytes = new byte[length]; + random.NextBytes(bytes); + return bytes; +} +` + SampleSafeHSCSHARP71 = ` +public static byte[] GenerateSecureRandomBytes(int length) +{ + var random = new RNGCryptoServiceProvider(); + byte[] bytes = new byte[length]; + random.GetNonZeroBytes(bytes); + return bytes; +} +` + SampleVulnerableHSCSHARP72 = ` +RSACryptoServiceProvider alg = new RSACryptoServiceProvider(1024); +` + SampleSafeHSCSHARP72 = ` +RSACryptoServiceProvider alg = new RSACryptoServiceProvider(2048); +` + SampleVulnerableHSCSHARP73 = ` +XmlReaderSettings rs = new XmlReaderSettings +{ + DtdProcessing = DtdProcessing.Parse, +}; + +XmlReader reader = XmlReader.Create("evil.xml", rs); +while (reader.Read()) +` + SampleSafeHSCSHARP73 = ` +XmlReaderSettings rs = new XmlReaderSettings +{ + DtdProcessing = DtdProcessing.Prohibit, +}; + +XmlReader reader = XmlReader.Create("evil.xml", rs); +while (reader.Read()) +` + SampleVulnerableHSCSHARP74 = ` +DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://DC={0}, DC=COM/", model.Domain)); +DirectorySearcher searcher = new DirectorySearcher(entry); +searcher.SearchScope = SearchScope.Subtree; +searcher.Filter = "(name={BobbyTables})"; +SearchResultCollection resultCollection = searcher.FindAll(); +` + SampleSafeHSCSHARP74 = ` +DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://DC={0}, DC=COM/", Encoder.LdapDistinguishedNameEncode(model.Domain)); +DirectorySearcher searcher = new DirectorySearcher(entry); +searcher.SearchScope = SearchScope.Subtree; +searcher.Filter = "(name={BobbyTables})"; +SearchResultCollection resultCollection = searcher.FindAll(); +` +) diff --git a/internal/services/engines/csharp/samples_test.go b/internal/services/engines/csharp/samples_test.go deleted file mode 100644 index 4153b7faf..000000000 --- a/internal/services/engines/csharp/samples_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2021 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package csharp - -const ( - SampleVulnerableHSCSHARP1 = ` - var p = new Process(); - p.StartInfo.FileName = "exportLegacy.exe"; - p.StartInfo.Arguments = " -user " + input + " -role user"; - p.Start(); - ` - - SampleVulnerableHSCSHARP2 = ` - var doc = new XmlDocument {XmlResolver = null}; - doc.Load("/config.xml"); - var results = doc.SelectNodes("/Config/Devices/Device[id='" + input + "']"); - ` - - SampleSafeHSCSHARP1 = ` - var p = new Process(); - p.StartInfo.FileName = "exportLegacy.exe"; - p.Start(); - ` - - SampleSafeHSCSHARP2 = ` - XmlDocument doc = new XmlDocument { XmlResolver = null }; - doc.Load("/config.xml"); - var results = doc.SelectSingleNode("/Config/Devices/Device"); - ` -)