From d406741907cd4da23e8cb6a9a1282d135bd60370 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Tue, 6 Oct 2026 12:22:50 +0000 Subject: [PATCH] feat(sast): vendored MIT semgrep packs and a guard against registry rules (#492) (#504) Our ~35 own rules left whole languages without SAST findings. Three permissively licensed community packs now run next to them, on the same semgrep invocation (--metrics=off, local files only): - GitLab sast-rules v2.10.1 (53bf5cf6): 148 rules for C#, Java, JavaScript/TypeScript, Python and one Go rule; only files whose header says "License: MIT (c) GitLab Inc.". Not vendored: c/ (every file GPL-2.0, generated from flawfinder), go/ apart from one file (Apache-2.0 gosec ports), scala/, rules/lgpl, rules/lgpl-cc (Commons Clause), rules/gitlab (EE). - 0xdea semgrep-rules (dae50da6, MIT): 35 C/C++ rules. - elttam semgrep-rules (24426856, MIT; its LICENSE carries the Semgrep template's copyright line): 34 rules for Java, Go and Struts/Spring XML. Each pack lives in compliance-agent/rules/vendor// with LICENSE, NOTICE (provenance, what was left out and why) and UPSTREAM (pinned commit): upstream/ holds the selected files unchanged with their tests, pack.yaml the rules the agent runs, ids prefixed per source (gitlab-, 0xdea-, elttam-), rules.json an index for the tests. scripts/vendor-semgrep-rules.py regenerates all of it deterministically. Provenance: every candidate rule was compared with the Semgrep registry (semgrep/semgrep-rules, read only for the comparison). Eight GitLab Python/JS rules with the same message or the same patterns are not vendored, nor are elttam's Kubernetes rules (registry-derived). Also left out: elttam's entrypoint enumerators, its ORM-leak hints, three files whose upstream tests fail on semgrep 1.177 and a join-mode rule. Noise budget: run over the nightly fixtures, the public samples and FreeRTOS-Kernel, lwIP, OpenRA, eShopOnWeb, requests, express and spring-petclinic. 15 rules that flood real code (0xdea missing-return 1514 hits, typos 989, interesting-api-calls 718, signed-unsigned-conversion 221, suspicious-assert 176, format-string-bugs 61 ...; GitLab assert-used) are dropped from the pack, each listed with its reason in NOTICE. CPU time of the semgrep run roughly doubles on C-heavy trees (FreeRTOS-Kernel 70 s -> 136 s, lwIP 18 s -> 68 s), well inside the 10-minute stage timeout. Ids stay bare (#473 logic covers the vendored ids, fingerprint() unchanged). The control map gets one vendored semgrep binding per control, by CWE (by rule id for the few elttam rules without one), with exactly the languages of the rules behind it; a test checks every vendored rule maps to a control that claims its languages. Guard: semgrep_args() builds the one invocation; a test fails if any --config is not a staged local pack, or is auto, p/, r/ or a URL, and another scans the agent source, scripts, docker/, CI and Dockerfile.agent for a registry config. Nightly baselines with C, Python, C# or JS code change and need a bless run after the image is deployed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- compliance-agent/rules/vendor/0xdea/LICENSE | 21 + compliance-agent/rules/vendor/0xdea/NOTICE | 38 + compliance-agent/rules/vendor/0xdea/UPSTREAM | 1 + compliance-agent/rules/vendor/0xdea/pack.yaml | 2187 ++++ .../rules/vendor/0xdea/rules.json | 281 + .../0xdea/upstream/rules/c/argv-envp-access.c | 28 + .../upstream/rules/c/argv-envp-access.yaml | 31 + .../upstream/rules/c/command-injection.c | 103 + .../upstream/rules/c/command-injection.yaml | 40 + .../0xdea/upstream/rules/c/double-free.c | 96 + .../0xdea/upstream/rules/c/double-free.yaml | 55 + .../upstream/rules/c/format-string-bugs.c | 108 + .../upstream/rules/c/format-string-bugs.yaml | 122 + .../rules/c/high-entropy-assignment.c | 20 + .../rules/c/high-entropy-assignment.yaml | 34 + .../rules/c/incorrect-order-setuid-setgid.c | 101 + .../c/incorrect-order-setuid-setgid.yaml | 94 + .../rules/c/incorrect-unsigned-comparison.c | 42 + .../c/incorrect-unsigned-comparison.yaml | 52 + .../upstream/rules/c/incorrect-use-of-free.c | 55 + .../rules/c/incorrect-use-of-free.yaml | 86 + .../rules/c/incorrect-use-of-memset.c | 55 + .../rules/c/incorrect-use-of-memset.yaml | 37 + .../rules/c/incorrect-use-of-sizeof.c | 184 + .../rules/c/incorrect-use-of-sizeof.cpp | 121 + .../rules/c/incorrect-use-of-sizeof.yaml | 78 + .../rules/c/incorrect-use-of-strncat.c | 62 + .../rules/c/incorrect-use-of-strncat.yaml | 50 + .../rules/c/insecure-api-access-stat.c | 150 + .../rules/c/insecure-api-access-stat.yaml | 39 + .../upstream/rules/c/insecure-api-alloca.c | 42 + .../upstream/rules/c/insecure-api-alloca.yaml | 32 + .../0xdea/upstream/rules/c/insecure-api-ato.c | 22 + .../upstream/rules/c/insecure-api-ato.yaml | 39 + .../upstream/rules/c/insecure-api-gets.c | 43 + .../upstream/rules/c/insecure-api-gets.yaml | 30 + .../c/insecure-api-mktemp-tmpnam-tempnam.c | 28 + .../c/insecure-api-mktemp-tmpnam-tempnam.yaml | 37 + .../rules/c/insecure-api-rand-srand.c | 56 + .../rules/c/insecure-api-rand-srand.yaml | 44 + .../upstream/rules/c/insecure-api-scanf.c | 236 + .../upstream/rules/c/insecure-api-scanf.yaml | 61 + .../upstream/rules/c/insecure-api-signal.c | 47 + .../upstream/rules/c/insecure-api-signal.yaml | 35 + .../rules/c/insecure-api-sprintf-vsprintf.c | 72 + .../c/insecure-api-sprintf-vsprintf.yaml | 38 + .../rules/c/insecure-api-strcpy-strcat.c | 150 + .../rules/c/insecure-api-strcpy-strcat.yaml | 47 + .../upstream/rules/c/integer-truncation.c | 53 + .../upstream/rules/c/integer-truncation.yaml | 133 + .../upstream/rules/c/integer-wraparound.c | 310 + .../upstream/rules/c/integer-wraparound.yaml | 214 + .../upstream/rules/c/interesting-api-calls.c | 340 + .../rules/c/interesting-api-calls.yaml | 263 + .../rules/c/memory-address-exposure.c | 51 + .../rules/c/memory-address-exposure.yaml | 77 + .../c/mismatched-memory-management-cpp.cpp | 81 + .../c/mismatched-memory-management-cpp.yaml | 67 + .../rules/c/mismatched-memory-management.c | 28 + .../rules/c/mismatched-memory-management.yaml | 51 + .../rules/c/missing-break-in-switch.c | 141 + .../rules/c/missing-break-in-switch.yaml | 66 + .../rules/c/missing-default-in-switch.c | 128 + .../rules/c/missing-default-in-switch.yaml | 36 + .../0xdea/upstream/rules/c/missing-return.c | 28 + .../upstream/rules/c/missing-return.yaml | 43 + .../0xdea/upstream/rules/c/off-by-one.c | 390 + .../0xdea/upstream/rules/c/off-by-one.yaml | 107 + .../rules/c/overlapping-source-destination.c | 74 + .../c/overlapping-source-destination.yaml | 80 + .../upstream/rules/c/pointer-subtraction.c | 63 + .../upstream/rules/c/pointer-subtraction.yaml | 65 + .../0xdea/upstream/rules/c/putenv-stack-var.c | 49 + .../upstream/rules/c/putenv-stack-var.yaml | 85 + .../vendor/0xdea/upstream/rules/c/regex-dos.c | 57 + .../0xdea/upstream/rules/c/regex-dos.yaml | 55 + .../upstream/rules/c/ret-stack-address.c | 85 + .../upstream/rules/c/ret-stack-address.yaml | 141 + .../rules/c/signed-unsigned-conversion.c | 239 + .../rules/c/signed-unsigned-conversion.cpp | 22 + .../rules/c/signed-unsigned-conversion.yaml | 145 + .../upstream/rules/c/suspicious-assert.c | 107 + .../upstream/rules/c/suspicious-assert.yaml | 41 + .../vendor/0xdea/upstream/rules/c/typos.c | 283 + .../vendor/0xdea/upstream/rules/c/typos.yaml | 105 + .../upstream/rules/c/unchecked-ret-malloc.c | 99 + .../rules/c/unchecked-ret-malloc.yaml | 77 + .../upstream/rules/c/unchecked-ret-scanf.c | 68 + .../upstream/rules/c/unchecked-ret-scanf.yaml | 65 + .../rules/c/unchecked-ret-setuid-seteuid.c | 42 + .../rules/c/unchecked-ret-setuid-seteuid.yaml | 49 + .../rules/c/unsafe-ret-snprintf-vsnprintf.c | 297 + .../c/unsafe-ret-snprintf-vsnprintf.yaml | 48 + .../rules/c/unsafe-ret-strlcpy-strlcat.c | 61 + .../rules/c/unsafe-ret-strlcpy-strlcat.yaml | 46 + .../0xdea/upstream/rules/c/unsafe-strlen.c | 30 + .../0xdea/upstream/rules/c/unsafe-strlen.yaml | 52 + .../rules/c/unterminated-string-strncpy.c | 124 + .../rules/c/unterminated-string-strncpy.yaml | 56 + .../0xdea/upstream/rules/c/use-after-free.c | 360 + .../upstream/rules/c/use-after-free.yaml | 63 + .../rules/c/use-of-source-size-in-copy.c | 1143 ++ .../rules/c/use-of-source-size-in-copy.yaml | 100 + .../rules/c/write-into-stack-buffer.c | 70 + .../rules/c/write-into-stack-buffer.yaml | 189 + compliance-agent/rules/vendor/elttam/LICENSE | 21 + compliance-agent/rules/vendor/elttam/NOTICE | 94 + compliance-agent/rules/vendor/elttam/UPSTREAM | 1 + .../rules/vendor/elttam/pack.yaml | 1610 +++ .../rules/vendor/elttam/rules.json | 241 + ...rilla-cookiestore-default-samesite-none.go | 71 + ...lla-cookiestore-default-samesite-none.yaml | 59 + .../json-decode-without-content-type-check.go | 84 + ...son-decode-without-content-type-check.yaml | 119 + .../audit/json-marshaler-pointer-receiver.go | 41 + .../json-marshaler-pointer-receiver.yaml | 41 + .../audit/len-cast-to-narrow-int-overflow.go | 104 + .../len-cast-to-narrow-int-overflow.yaml | 97 + ...ssing-null-byte-check-at-trust-boundary.go | 91 + ...ing-null-byte-check-at-trust-boundary.yaml | 113 + .../audit/net-url-pointer-alias-mutation.go | 91 + .../audit/net-url-pointer-alias-mutation.yaml | 112 + .../java/jackson/polymorphic-typing.java | 54 + .../java/jackson/polymorphic-typing.yml | 36 + .../java/jackson/type-resolver-override.java | 50 + .../java/jackson/type-resolver-override.yml | 32 + .../default-properties-devmode.properties | 286 + .../devmode/default-properties-devmode.yml | 30 + .../audit/devmode/struts-xml-devmode.xml | 37 + .../audit/devmode/struts-xml-devmode.yml | 53 + .../audit/devmode/web-xml-devmode.xml | 31 + .../audit/devmode/web-xml-devmode.yml | 37 + .../audit/dmi/struts-xml-action-dmi.xml | 38 + .../audit/dmi/struts-xml-action-dmi.yml | 34 + .../security/audit/dmi/struts-xml-dmi.xml | 51 + .../security/audit/dmi/struts-xml-dmi.yml | 49 + .../security/audit/dmi/taglib-action-dmi.jsp | 22 + .../security/audit/dmi/taglib-action-dmi.yml | 177 + ...truts-xml-always-select-full-namespace.xml | 40 + ...truts-xml-always-select-full-namespace.yml | 51 + .../java/xstream/security/audit/fromxml.java | 123 + .../java/xstream/security/audit/fromxml.yml | 22 + .../express/security/audit/mongodb-nosqli.js | 25 + .../express/security/audit/mongodb-nosqli.yml | 58 + .../lang/security/audit/executable-symlink.go | 62 + .../security/audit/executable-symlink.yaml | 23 + .../security/audit/sprintf-plain-string.go | 44 + .../security/audit/sprintf-plain-string.yaml | 38 + .../lang/security/audit/uintptr-nonatomic.go | 22 + .../security/audit/uintptr-nonatomic.yaml | 24 + .../jakarta-mail-email-primitives.yml | 303 + .../jakarta-mail-email-primitives.java | 76 + .../security/audit/crypto/gcm-static-iv.java | 117 + .../security/audit/crypto/gcm-static-iv.yml | 46 + .../audit/crypto/randomstringutils.java | 12 + .../audit/crypto/randomstringutils.yml | 25 + .../UnsafeHttpInvokerServiceExporterXml.xml | 15 + .../UnsafeHttpInvokerServiceExporterXml.yml | 31 + compliance-agent/rules/vendor/gitlab/LICENSE | 28 + compliance-agent/rules/vendor/gitlab/NOTICE | 38 + compliance-agent/rules/vendor/gitlab/UPSTREAM | 1 + .../rules/vendor/gitlab/pack.yaml | 9453 +++++++++++++++++ .../rules/vendor/gitlab/rules.json | 1045 ++ .../cookies/rule-CookieWithoutHttpOnlyFlag.cs | 22 + .../rule-CookieWithoutHttpOnlyFlag.yml | 49 + .../cookies/rule-CookieWithoutSSLFlag.cs | 22 + .../cookies/rule-CookieWithoutSSLFlag.yml | 47 + .../rule-CertificateValidationDisabled.cs | 22 + .../rule-CertificateValidationDisabled.yml | 45 + .../csharp/crypto/rule-WeakCipherAlgorithm.cs | 32 + .../crypto/rule-WeakCipherAlgorithm.yml | 93 + .../csharp/crypto/rule-WeakCipherMode.cs | 25 + .../csharp/crypto/rule-WeakCipherMode.yml | 88 + .../csharp/crypto/rule-WeakHashingFunction.cs | 34 + .../crypto/rule-WeakHashingFunction.yml | 65 + .../upstream/csharp/crypto/rule-WeakRNG.cs | 27 + .../upstream/csharp/crypto/rule-WeakRNG.yml | 39 + .../gitlab/upstream/csharp/csrf/rule-Csrf.cs | 193 + .../gitlab/upstream/csharp/csrf/rule-Csrf.yml | 73 + .../rule-InsecureDeserialization.cs | 172 + .../rule-InsecureDeserialization.yml | 87 + .../endpoint/rule-UnvalidatedRedirect.cs | 81 + .../endpoint/rule-UnvalidatedRedirect.yml | 89 + .../csharp/injection/rule-CommandInjection.cs | 155 + .../injection/rule-CommandInjection.yml | 105 + .../csharp/injection/rule-LdapInjection.cs | 169 + .../csharp/injection/rule-LdapInjection.yml | 105 + .../csharp/injection/rule-SQLInjection.cs | 164 + .../csharp/injection/rule-SQLInjection.yml | 153 + .../csharp/injection/rule-XPathInjection.cs | 87 + .../csharp/injection/rule-XPathInjection.yml | 91 + .../injection/rule-XmlDocumentXXEInjection.cs | 54 + .../rule-XmlDocumentXXEInjection.yml | 54 + .../injection/rule-XmlReaderXXEInjection.cs | 104 + .../injection/rule-XmlReaderXXEInjection.yml | 53 + .../other/rule-UnsafeXSLTSettingUsed.cs | 56 + .../other/rule-UnsafeXSLTSettingUsed.yml | 87 + .../password/rule-PasswordComplexity.cs | 66 + .../password/rule-PasswordComplexity.yml | 54 + .../csharp/path/rule-PathTraversal.cs | 24 + .../csharp/path/rule-PathTraversal.yml | 153 + .../csharp/validation/rule-InputValidation.cs | 18 + .../validation/rule-InputValidation.yml | 52 + .../csharp/xss/rule-HtmlElementXss.cs | 94 + .../csharp/xss/rule-HtmlElementXss.yml | 102 + .../upstream/csharp/xss/rule-ScriptXss.cs | 102 + .../upstream/csharp/xss/rule-ScriptXss.yml | 89 + .../upstream/go/crypto/rule-tlsversion.go | 308 + .../upstream/go/crypto/rule-tlsversion.yml | 75 + .../java/cookie/rule-CookieInsecure.java | 53 + .../java/cookie/rule-CookieInsecure.yml | 53 + .../cookie/rule-HttpResponseSplitting.java | 232 + .../cookie/rule-HttpResponseSplitting.yml | 91 + .../cookie/rule-RequestParamToHeader.java | 97 + .../java/cookie/rule-RequestParamToHeader.yml | 93 + .../cors/rule-PermissiveCORSInjection.java | 123 + .../cors/rule-PermissiveCORSInjection.yml | 80 + .../java/crypto/rule-BlowfishKeySize.java | 13 + .../java/crypto/rule-BlowfishKeySize.yml | 75 + .../java/crypto/rule-CipherDESInsecure.java | 2 + .../java/crypto/rule-CipherDESInsecure.yml | 118 + .../crypto/rule-CipherDESedeInsecure.java | 2 + .../java/crypto/rule-CipherDESedeInsecure.yml | 114 + .../java/crypto/rule-CipherECBMode.java | 29 + .../java/crypto/rule-CipherECBMode.yml | 129 + .../java/crypto/rule-CipherIntegrity.java | 2 + .../java/crypto/rule-CipherIntegrity.yml | 139 + .../java/crypto/rule-CipherPaddingOracle.java | 2 + .../java/crypto/rule-CipherPaddingOracle.yml | 132 + .../java/crypto/rule-CustomMessageDigest.java | 42 + .../java/crypto/rule-CustomMessageDigest.yml | 43 + .../rule-HazelcastSymmetricEncryption.java | 51 + .../rule-HazelcastSymmetricEncryption.yml | 28 + .../crypto/rule-InsufficientKeySizeRsa.java | 107 + .../crypto/rule-InsufficientKeySizeRsa.yml | 67 + .../upstream/java/crypto/rule-NullCipher.java | 50 + .../upstream/java/crypto/rule-NullCipher.yml | 107 + .../java/crypto/rule-RsaNoPadding.java | 47 + .../java/crypto/rule-RsaNoPadding.yml | 65 + .../java/crypto/rule-WeakMessageDigest.java | 62 + .../java/crypto/rule-WeakMessageDigest.yml | 65 + ...rule-WeakTLSProtocolDefaultHttpClient.java | 18 + .../rule-WeakTLSProtocolDefaultHttpClient.yml | 45 + .../rule-WeakTLSProtocolSSLContext.java | 59 + .../crypto/rule-WeakTLSProtocolSSLContext.yml | 40 + .../crypto/rule-WeakTLSProtocolVersion.java | 2 + .../crypto/rule-WeakTLSProtocolVersion.yml | 90 + .../java/endpoint/rule-HostnameVerifier.java | 120 + .../java/endpoint/rule-HostnameVerifier.yml | 69 + .../endpoint/rule-UnvalidatedRedirect.java | 87 + .../endpoint/rule-UnvalidatedRedirect.yml | 71 + .../java/endpoint/rule-X509TrustManager.java | 312 + .../java/endpoint/rule-X509TrustManager.yml | 81 + .../java/file/rule-FileUploadFileName.java | 77 + .../java/file/rule-FileUploadFileName.yml | 82 + .../java/file/rule-FilenameUtils.java | 238 + .../upstream/java/file/rule-FilenameUtils.yml | 95 + .../java/inject/rule-CommandInjection.java | 105 + .../java/inject/rule-CommandInjection.yml | 122 + .../java/inject/rule-ELInjection.java | 124 + .../upstream/java/inject/rule-ELInjection.yml | 93 + .../rule-FileDisclosureRequestDispatcher.java | 50 + .../rule-FileDisclosureRequestDispatcher.yml | 62 + .../rule-FileDisclosureSpringFramework.java | 53 + .../rule-FileDisclosureSpringFramework.yml | 86 + .../inject/rule-HttpParameterPollution.java | 35 + .../inject/rule-HttpParameterPollution.yml | 102 + .../java/inject/rule-LDAPInjection.java | 196 + .../java/inject/rule-LDAPInjection.yml | 173 + .../java/inject/rule-OgnlInjection.java | 117 + .../java/inject/rule-OgnlInjection.yml | 165 + .../rule-SpotbugsPathTraversalAbsolute.java | 167 + .../rule-SpotbugsPathTraversalAbsolute.yml | 161 + .../java/ldap/rule-AnonymousLDAP.java | 36 + .../upstream/java/ldap/rule-AnonymousLDAP.yml | 70 + .../password/rule-ConstantDBPassword.java | 29 + .../java/password/rule-ConstantDBPassword.yml | 42 + .../java/password/rule-EmptyDBPassword.java | 26 + .../java/password/rule-EmptyDBPassword.yml | 45 + .../java/password/rule-HardcodePassword.java | 67 + .../java/password/rule-HardcodePassword.yml | 51 + .../java/perm/rule-DangerousPermissions.java | 39 + .../java/perm/rule-DangerousPermissions.yml | 46 + ...-OverlyPermissiveFilePermissionInline.java | 26 + ...e-OverlyPermissiveFilePermissionInline.yml | 51 + .../rules/vendor/gitlab/upstream/java/pom.xml | 346 + .../java/script/rule-ScriptInjection.java | 95 + .../java/script/rule-ScriptInjection.yml | 74 + .../rule-SpringSpelExpressionParser.java | 92 + .../rule-SpringSpelExpressionParser.yml | 65 + .../upstream/java/smtp/rule-InsecureSmtp.java | 81 + .../upstream/java/smtp/rule-InsecureSmtp.yml | 78 + .../upstream/java/smtp/rule-SmtpClient.java | 86 + .../upstream/java/smtp/rule-SmtpClient.yml | 90 + .../gitlab/upstream/java/ssrf/rule-SSRF.java | 57 + .../gitlab/upstream/java/ssrf/rule-SSRF.yml | 142 + .../java/strings/rule-BadHexConversion.java | 119 + .../java/strings/rule-BadHexConversion.yml | 88 + .../rule-FormatStringManipulation.java | 46 + .../strings/rule-FormatStringManipulation.yml | 76 + .../strings/rule-ModifyAfterValidation.java | 133 + .../strings/rule-ModifyAfterValidation.yml | 67 + .../rule-NormalizeAfterValidation.java | 20 + .../strings/rule-NormalizeAfterValidation.yml | 54 + .../rule-TemplateInjection.java | 138 + .../rule-TemplateInjection.yml | 77 + .../unsafe/rule-ExternalConfigControl.java | 35 + .../unsafe/rule-ExternalConfigControl.yml | 35 + .../java/xml/rule-SAMLIgnoreComments.java | 24 + .../java/xml/rule-SAMLIgnoreComments.yml | 38 + .../upstream/java/xml/rule-XmlDecoder.java | 292 + .../upstream/java/xml/rule-XmlDecoder.yml | 125 + .../upstream/java/xml/rule-XsltTransform.java | 84 + .../upstream/java/xml/rule-XsltTransform.yml | 87 + .../upstream/java/xss/rule-WicketXSS.java | 151 + .../upstream/java/xss/rule-WicketXSS.yml | 66 + .../xss/rule-XSSReqParamToServletWriter.java | 59 + .../xss/rule-XSSReqParamToServletWriter.yml | 165 + .../gitlab/upstream/java/xxe/rule-XMLRdr.java | 36 + .../gitlab/upstream/java/xxe/rule-XMLRdr.yml | 56 + .../buf/rule-buffer-noassert-read.js | 42 + .../buf/rule-buffer-noassert-read.yml | 69 + .../buf/rule-buffer-noassert-write.js | 42 + .../buf/rule-buffer-noassert-write.yml | 70 + .../javascript/buf/rule-detect-new-buffer.js | 23 + .../javascript/buf/rule-detect-new-buffer.yml | 57 + .../javascript/dos/rule-non-literal-regexp.js | 140 + .../dos/rule-non-literal-regexp.yml | 73 + .../eval/rule-eval-with-expression.js | 163 + .../eval/rule-eval-with-expression.yml | 143 + .../rule-non-literal-fs-filename.js | 267 + .../rule-non-literal-fs-filename.yml | 163 + .../random/rule-pseudo-random-bytes.js | 22 + .../random/rule-pseudo-random-bytes.yml | 38 + .../react/rule-dangerouslysetinnerhtml.js | 25 + .../react/rule-dangerouslysetinnerhtml.yml | 64 + .../require/rule-non-literal-require.js | 22 + .../require/rule-non-literal-require.yml | 34 + .../timing/rule-possible-timing-attacks.js | 39 + .../timing/rule-possible-timing-attacks.yml | 527 + .../python/assert/rule-assert-used.py | 13 + .../python/assert/rule-assert-used.yml | 52 + .../rule-general-bindall-interfaces.py | 10 + .../rule-general-bindall-interfaces.yml | 57 + .../python/crypto/rule-cipher-modes.py | 18 + .../python/crypto/rule-cipher-modes.yml | 79 + .../crypto/rule-crypto-cipher-blowfish.py | 25 + .../crypto/rule-crypto-cipher-blowfish.yml | 82 + .../python/crypto/rule-crypto-cipher-des.py | 23 + .../python/crypto/rule-crypto-cipher-des.yml | 80 + .../python/crypto/rule-crypto-cipher-rc2.py | 18 + .../python/crypto/rule-crypto-cipher-rc2.yml | 80 + .../python/crypto/rule-crypto-cipher-rc4.py | 19 + .../python/crypto/rule-crypto-cipher-rc4.yml | 80 + .../python/crypto/rule-crypto-cipher-xor.py | 17 + .../python/crypto/rule-crypto-cipher-xor.yml | 80 + .../crypto/rule-crypto-encrypt-dsa-rsa.py | 75 + .../crypto/rule-crypto-encrypt-dsa-rsa.yml | 80 + .../python/crypto/rule-crypto-hash-md5.py | 13 + .../python/crypto/rule-crypto-hash-md5.yml | 56 + .../python/crypto/rule-crypto-hash-sha1.py | 13 + .../python/crypto/rule-crypto-hash-sha1.yml | 56 + .../crypto/rule-crypto-hazmat-cipher-arc4.py | 13 + .../crypto/rule-crypto-hazmat-cipher-arc4.yml | 74 + .../rule-crypto-hazmat-cipher-blowfish.py | 13 + .../rule-crypto-hazmat-cipher-blowfish.yml | 76 + .../crypto/rule-crypto-hazmat-cipher-idea.py | 13 + .../crypto/rule-crypto-hazmat-cipher-idea.yml | 76 + .../crypto/rule-crypto-hazmat-hash-md5.py | 9 + .../crypto/rule-crypto-hazmat-hash-md5.yml | 50 + .../crypto/rule-crypto-hazmat-hash-sha1.py | 9 + .../crypto/rule-crypto-hazmat-hash-sha1.yml | 50 + .../upstream/python/crypto/rule-hash-md2.py | 13 + .../upstream/python/crypto/rule-hash-md2.yml | 54 + .../upstream/python/crypto/rule-hash-md4.py | 13 + .../upstream/python/crypto/rule-hash-md4.yml | 54 + .../upstream/python/crypto/rule-hash-md5.py | 18 + .../upstream/python/crypto/rule-hash-md5.yml | 51 + .../upstream/python/crypto/rule-hash-sha1.py | 10 + .../upstream/python/crypto/rule-hash-sha1.yml | 51 + .../rule-hashlib-new-insecure-functions.py | 30 + .../rule-hashlib-new-insecure-functions.yml | 51 + .../python/crypto/rule-import-pycrypto.py | 36 + .../python/crypto/rule-import-pycrypto.yml | 35 + .../python/deserialization/rule-cpickle.py | 25 + .../python/deserialization/rule-cpickle.yml | 77 + .../python/deserialization/rule-pickle.py | 49 + .../python/deserialization/rule-pickle.yml | 85 + .../python/deserialization/rule-shelve.py | 7 + .../python/deserialization/rule-shelve.yml | 79 + .../python/deserialization/rule-yaml-load.py | 35 + .../python/deserialization/rule-yaml-load.yml | 73 + .../python/django/rule-django-extra-used.py | 36 + .../python/django/rule-django-extra-used.yml | 91 + .../escaping/rule-jinja2-autoescape-false.py | 41 + .../escaping/rule-jinja2-autoescape-false.yml | 168 + .../escaping/rule-use-of-mako-templates.py | 34 + .../escaping/rule-use-of-mako-templates.yml | 147 + .../gitlab/upstream/python/eval/rule-eval.py | 157 + .../gitlab/upstream/python/eval/rule-eval.yml | 53 + .../upstream/python/exec/rule-exec-used.py | 49 + .../upstream/python/exec/rule-exec-used.yml | 46 + .../rule-linux-command-wildcard-injection.py | 89 + .../rule-linux-command-wildcard-injection.yml | 52 + .../upstream/python/exec/rule-os-path.py | 3 + .../upstream/python/exec/rule-os-path.yml | 30 + .../upstream/python/exec/rule-os-popen2.py | 31 + .../upstream/python/exec/rule-os-popen2.yml | 36 + .../python/exec/rule-subprocess-call.py | 62 + .../python/exec/rule-subprocess-call.yml | 43 + .../python/exec/rule-subprocess-shell-TRUE.py | 60 + .../exec/rule-subprocess-shell-TRUE.yml | 24 + .../rule-general-bad-permission.py | 13 + .../rule-general-bad-permission.yml | 41 + .../files/rule-tarfile-unsafe-members.py | 52 + .../files/rule-tarfile-unsafe-members.yml | 109 + .../gitlab/upstream/python/ftp/rule-ftplib.py | 16 + .../upstream/python/ftp/rule-ftplib.yml | 55 + .../rule-logging-config-insecure-listen.py | 10 + .../rule-logging-config-insecure-listen.yml | 35 + .../upstream/python/random/rule-random.py | 27 + .../upstream/python/random/rule-random.yml | 48 + .../requests/rule-request-without-timeout.py | 67 + .../requests/rule-request-without-timeout.yml | 55 + .../python/snmp/rule-insecure-snmp-version.py | 10 + .../snmp/rule-insecure-snmp-version.yml | 45 + .../snmp/rule-snmp-weak-cryptography.py | 125 + .../snmp/rule-snmp-weak-cryptography.yml | 67 + .../sql/rule-hardcoded-sql-expression.py | 131 + .../sql/rule-hardcoded-sql-expression.yml | 86 + .../python/ssl/rule-req-no-certvalid.py | 27 + .../python/ssl/rule-req-no-certvalid.yml | 51 + .../python/ssl/rule-ssl-no-version.py | 41 + .../python/ssl/rule-ssl-no-version.yml | 64 + .../python/ssl/rule-ssl-with-bad-version.py | 58 + .../python/ssl/rule-ssl-with-bad-version.yml | 81 + .../python/ssl/rule-unverified-context.py | 15 + .../python/ssl/rule-unverified-context.yml | 62 + .../python/telnet/rule-import-telnib.py | 25 + .../python/telnet/rule-import-telnib.yml | 48 + .../python/tmpdir/rule-hardcodedtmp.py | 15 + .../python/tmpdir/rule-hardcodedtmp.yml | 43 + .../upstream/python/tmpdir/rule-mktemp-q.py | 19 + .../upstream/python/tmpdir/rule-mktemp-q.yml | 44 + .../python/urlopen/rule-urllib-urlopen.py | 127 + .../python/urlopen/rule-urllib-urlopen.yml | 66 + .../upstream/python/xml/rule-celement.py | 30 + .../upstream/python/xml/rule-celement.yml | 59 + .../upstream/python/xml/rule-element.py | 29 + .../upstream/python/xml/rule-element.yml | 59 + .../gitlab/upstream/python/xml/rule-etree.py | 22 + .../gitlab/upstream/python/xml/rule-etree.yml | 61 + .../upstream/python/xml/rule-expatbuilder.py | 3 + .../upstream/python/xml/rule-expatbuilder.yml | 58 + .../upstream/python/xml/rule-expatreader.py | 3 + .../upstream/python/xml/rule-expatreader.yml | 59 + .../upstream/python/xml/rule-minidom.py | 25 + .../upstream/python/xml/rule-minidom.yml | 57 + .../upstream/python/xml/rule-pulldom.py | 24 + .../upstream/python/xml/rule-pulldom.yml | 57 + .../gitlab/upstream/python/xml/rule-sax.py | 3 + .../gitlab/upstream/python/xml/rule-sax.yml | 58 + .../src/pipeline/dotnet/fixture_tests.rs | 2 + .../src/pipeline/finding_store.rs | 15 +- compliance-agent/src/pipeline/orchestrator.rs | 43 +- compliance-agent/src/pipeline/plc/mod.rs | 48 +- compliance-agent/src/pipeline/semgrep.rs | 360 +- compliance-agent/tests/nightly.rs | 6 +- control-map/data/cra_control_map.json | 214 + docs/features/control-mapping.md | 3 +- docs/reference/tools.md | 30 +- .../release/staging-test-plan-after-v0.4.5.md | 24 + scripts/vendor-semgrep-rules.py | 351 + 473 files changed, 50690 insertions(+), 116 deletions(-) create mode 100644 compliance-agent/rules/vendor/0xdea/LICENSE create mode 100644 compliance-agent/rules/vendor/0xdea/NOTICE create mode 100644 compliance-agent/rules/vendor/0xdea/UPSTREAM create mode 100644 compliance-agent/rules/vendor/0xdea/pack.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/rules.json create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/argv-envp-access.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/argv-envp-access.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/command-injection.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/command-injection.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/double-free.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/double-free.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/format-string-bugs.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/format-string-bugs.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/high-entropy-assignment.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/high-entropy-assignment.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-order-setuid-setgid.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-order-setuid-setgid.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-unsigned-comparison.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-unsigned-comparison.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-free.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-free.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-memset.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-memset.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.cpp create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-strncat.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-strncat.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-access-stat.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-access-stat.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-alloca.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-alloca.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-ato.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-ato.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-gets.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-gets.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-mktemp-tmpnam-tempnam.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-mktemp-tmpnam-tempnam.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-rand-srand.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-rand-srand.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-scanf.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-scanf.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-signal.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-signal.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-sprintf-vsprintf.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-sprintf-vsprintf.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-strcpy-strcat.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-strcpy-strcat.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-truncation.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-truncation.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-wraparound.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-wraparound.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/interesting-api-calls.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/interesting-api-calls.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/memory-address-exposure.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/memory-address-exposure.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management-cpp.cpp create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management-cpp.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-break-in-switch.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-break-in-switch.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-default-in-switch.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-default-in-switch.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-return.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-return.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/off-by-one.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/off-by-one.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/overlapping-source-destination.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/overlapping-source-destination.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/pointer-subtraction.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/pointer-subtraction.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/putenv-stack-var.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/putenv-stack-var.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/regex-dos.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/regex-dos.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/ret-stack-address.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/ret-stack-address.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.cpp create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/suspicious-assert.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/suspicious-assert.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/typos.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/typos.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-malloc.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-malloc.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-scanf.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-scanf.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-setuid-seteuid.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-setuid-seteuid.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-snprintf-vsnprintf.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-snprintf-vsnprintf.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-strlcpy-strlcat.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-strlcpy-strlcat.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-strlen.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-strlen.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unterminated-string-strncpy.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/unterminated-string-strncpy.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-after-free.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-after-free.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-of-source-size-in-copy.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-of-source-size-in-copy.yaml create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/write-into-stack-buffer.c create mode 100644 compliance-agent/rules/vendor/0xdea/upstream/rules/c/write-into-stack-buffer.yaml create mode 100644 compliance-agent/rules/vendor/elttam/LICENSE create mode 100644 compliance-agent/rules/vendor/elttam/NOTICE create mode 100644 compliance-agent/rules/vendor/elttam/UPSTREAM create mode 100644 compliance-agent/rules/vendor/elttam/pack.yaml create mode 100644 compliance-agent/rules/vendor/elttam/rules.json create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/gorilla/security/audit/gorilla-cookiestore-default-samesite-none.go create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/gorilla/security/audit/gorilla-cookiestore-default-samesite-none.yaml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-decode-without-content-type-check.go create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-decode-without-content-type-check.yaml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-marshaler-pointer-receiver.go create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-marshaler-pointer-receiver.yaml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/len-cast-to-narrow-int-overflow.go create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/len-cast-to-narrow-int-overflow.yaml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/missing-null-byte-check-at-trust-boundary.go create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/missing-null-byte-check-at-trust-boundary.yaml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/net-url-pointer-alias-mutation.go create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/net-url-pointer-alias-mutation.yaml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/polymorphic-typing.java create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/polymorphic-typing.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/type-resolver-override.java create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/type-resolver-override.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/default-properties-devmode.properties create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/default-properties-devmode.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/struts-xml-devmode.xml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/struts-xml-devmode.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/web-xml-devmode.xml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/web-xml-devmode.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-action-dmi.xml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-action-dmi.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-dmi.xml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-dmi.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/taglib-action-dmi.jsp create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/taglib-action-dmi.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/struts-xml-always-select-full-namespace.xml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/struts-xml-always-select-full-namespace.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/xstream/security/audit/fromxml.java create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/xstream/security/audit/fromxml.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/javascript/express/security/audit/mongodb-nosqli.js create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules-audit/javascript/express/security/audit/mongodb-nosqli.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/executable-symlink.go create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/executable-symlink.yaml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/sprintf-plain-string.go create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/sprintf-plain-string.yaml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/uintptr-nonatomic.go create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/uintptr-nonatomic.yaml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/java/audit/email-validation/jakarta-mail-email-primitives.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/java/audit/email-validation/jakarta-mail-email-primitives/jakarta-mail-email-primitives.java create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/gcm-static-iv.java create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/gcm-static-iv.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/randomstringutils.java create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/randomstringutils.yml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporterXml.xml create mode 100644 compliance-agent/rules/vendor/elttam/upstream/rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporterXml.yml create mode 100644 compliance-agent/rules/vendor/gitlab/LICENSE create mode 100644 compliance-agent/rules/vendor/gitlab/NOTICE create mode 100644 compliance-agent/rules/vendor/gitlab/UPSTREAM create mode 100644 compliance-agent/rules/vendor/gitlab/pack.yaml create mode 100644 compliance-agent/rules/vendor/gitlab/rules.json create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutHttpOnlyFlag.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutHttpOnlyFlag.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutSSLFlag.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutSSLFlag.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-CertificateValidationDisabled.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-CertificateValidationDisabled.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherAlgorithm.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherAlgorithm.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherMode.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherMode.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakHashingFunction.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakHashingFunction.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakRNG.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakRNG.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/csrf/rule-Csrf.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/csrf/rule-Csrf.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/deserialization/rule-InsecureDeserialization.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/deserialization/rule-InsecureDeserialization.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/endpoint/rule-UnvalidatedRedirect.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/endpoint/rule-UnvalidatedRedirect.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-CommandInjection.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-CommandInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-LdapInjection.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-LdapInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-SQLInjection.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-SQLInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XPathInjection.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XPathInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlDocumentXXEInjection.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlDocumentXXEInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlReaderXXEInjection.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlReaderXXEInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/other/rule-UnsafeXSLTSettingUsed.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/other/rule-UnsafeXSLTSettingUsed.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/password/rule-PasswordComplexity.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/password/rule-PasswordComplexity.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/path/rule-PathTraversal.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/path/rule-PathTraversal.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/validation/rule-InputValidation.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/validation/rule-InputValidation.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-HtmlElementXss.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-HtmlElementXss.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-ScriptXss.cs create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-ScriptXss.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/go/crypto/rule-tlsversion.go create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/go/crypto/rule-tlsversion.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/cookie/rule-CookieInsecure.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/cookie/rule-CookieInsecure.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/cookie/rule-HttpResponseSplitting.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/cookie/rule-HttpResponseSplitting.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/cookie/rule-RequestParamToHeader.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/cookie/rule-RequestParamToHeader.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/cors/rule-PermissiveCORSInjection.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/cors/rule-PermissiveCORSInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-BlowfishKeySize.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-BlowfishKeySize.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherDESInsecure.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherDESInsecure.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherDESedeInsecure.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherDESedeInsecure.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherECBMode.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherECBMode.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherIntegrity.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherIntegrity.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherPaddingOracle.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CipherPaddingOracle.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CustomMessageDigest.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-CustomMessageDigest.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-HazelcastSymmetricEncryption.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-HazelcastSymmetricEncryption.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-InsufficientKeySizeRsa.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-InsufficientKeySizeRsa.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-NullCipher.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-NullCipher.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-RsaNoPadding.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-RsaNoPadding.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-WeakMessageDigest.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-WeakMessageDigest.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-WeakTLSProtocolDefaultHttpClient.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-WeakTLSProtocolDefaultHttpClient.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-WeakTLSProtocolSSLContext.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-WeakTLSProtocolSSLContext.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-WeakTLSProtocolVersion.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/crypto/rule-WeakTLSProtocolVersion.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/endpoint/rule-HostnameVerifier.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/endpoint/rule-HostnameVerifier.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/endpoint/rule-UnvalidatedRedirect.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/endpoint/rule-UnvalidatedRedirect.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/endpoint/rule-X509TrustManager.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/endpoint/rule-X509TrustManager.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/file/rule-FileUploadFileName.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/file/rule-FileUploadFileName.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/file/rule-FilenameUtils.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/file/rule-FilenameUtils.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-CommandInjection.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-CommandInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-ELInjection.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-ELInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-FileDisclosureRequestDispatcher.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-FileDisclosureRequestDispatcher.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-FileDisclosureSpringFramework.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-FileDisclosureSpringFramework.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-HttpParameterPollution.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-HttpParameterPollution.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-LDAPInjection.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-LDAPInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-OgnlInjection.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-OgnlInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-SpotbugsPathTraversalAbsolute.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/inject/rule-SpotbugsPathTraversalAbsolute.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/ldap/rule-AnonymousLDAP.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/ldap/rule-AnonymousLDAP.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/password/rule-ConstantDBPassword.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/password/rule-ConstantDBPassword.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/password/rule-EmptyDBPassword.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/password/rule-EmptyDBPassword.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/password/rule-HardcodePassword.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/password/rule-HardcodePassword.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/perm/rule-DangerousPermissions.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/perm/rule-DangerousPermissions.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/perm/rule-OverlyPermissiveFilePermissionInline.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/perm/rule-OverlyPermissiveFilePermissionInline.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/pom.xml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/script/rule-ScriptInjection.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/script/rule-ScriptInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/script/rule-SpringSpelExpressionParser.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/script/rule-SpringSpelExpressionParser.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/smtp/rule-InsecureSmtp.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/smtp/rule-InsecureSmtp.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/smtp/rule-SmtpClient.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/smtp/rule-SmtpClient.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/ssrf/rule-SSRF.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/ssrf/rule-SSRF.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/strings/rule-BadHexConversion.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/strings/rule-BadHexConversion.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/strings/rule-FormatStringManipulation.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/strings/rule-FormatStringManipulation.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/strings/rule-ModifyAfterValidation.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/strings/rule-ModifyAfterValidation.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/strings/rule-NormalizeAfterValidation.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/strings/rule-NormalizeAfterValidation.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/templateinjection/rule-TemplateInjection.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/templateinjection/rule-TemplateInjection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/unsafe/rule-ExternalConfigControl.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/unsafe/rule-ExternalConfigControl.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xml/rule-SAMLIgnoreComments.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xml/rule-SAMLIgnoreComments.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xml/rule-XmlDecoder.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xml/rule-XmlDecoder.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xml/rule-XsltTransform.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xml/rule-XsltTransform.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-WicketXSS.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-WicketXSS.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-XSSReqParamToServletWriter.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-XSSReqParamToServletWriter.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xxe/rule-XMLRdr.java create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/java/xxe/rule-XMLRdr.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/buf/rule-buffer-noassert-read.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/buf/rule-buffer-noassert-read.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/buf/rule-buffer-noassert-write.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/buf/rule-buffer-noassert-write.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/buf/rule-detect-new-buffer.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/buf/rule-detect-new-buffer.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/dos/rule-non-literal-regexp.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/dos/rule-non-literal-regexp.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/eval/rule-eval-with-expression.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/eval/rule-eval-with-expression.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/pathtraversal/rule-non-literal-fs-filename.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/pathtraversal/rule-non-literal-fs-filename.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/random/rule-pseudo-random-bytes.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/random/rule-pseudo-random-bytes.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/react/rule-dangerouslysetinnerhtml.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/react/rule-dangerouslysetinnerhtml.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/require/rule-non-literal-require.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/require/rule-non-literal-require.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/timing/rule-possible-timing-attacks.js create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/javascript/timing/rule-possible-timing-attacks.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/assert/rule-assert-used.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/assert/rule-assert-used.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/bind_all_interfaces/rule-general-bindall-interfaces.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/bind_all_interfaces/rule-general-bindall-interfaces.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-cipher-modes.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-cipher-modes.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-blowfish.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-blowfish.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-des.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-des.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc2.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc2.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc4.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc4.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-xor.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-xor.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-encrypt-dsa-rsa.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-encrypt-dsa-rsa.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-md5.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-md5.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-sha1.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-sha1.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-arc4.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-arc4.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-blowfish.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-blowfish.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-idea.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-idea.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-md5.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-md5.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-sha1.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-sha1.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md2.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md2.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md4.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md4.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md5.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md5.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-sha1.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-sha1.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hashlib-new-insecure-functions.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hashlib-new-insecure-functions.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-import-pycrypto.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-import-pycrypto.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-cpickle.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-cpickle.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-pickle.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-pickle.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-shelve.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-shelve.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-yaml-load.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-yaml-load.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/django/rule-django-extra-used.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/django/rule-django-extra-used.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-jinja2-autoescape-false.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-jinja2-autoescape-false.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-use-of-mako-templates.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-use-of-mako-templates.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/eval/rule-eval.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/eval/rule-eval.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-exec-used.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-exec-used.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-linux-command-wildcard-injection.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-linux-command-wildcard-injection.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-path.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-path.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-popen2.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-popen2.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-call.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-call.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-shell-TRUE.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-shell-TRUE.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/file_permissions/rule-general-bad-permission.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/file_permissions/rule-general-bad-permission.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/files/rule-tarfile-unsafe-members.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/files/rule-tarfile-unsafe-members.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ftp/rule-ftplib.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ftp/rule-ftplib.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/log/rule-logging-config-insecure-listen.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/log/rule-logging-config-insecure-listen.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/random/rule-random.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/random/rule-random.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/requests/rule-request-without-timeout.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/requests/rule-request-without-timeout.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-insecure-snmp-version.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-insecure-snmp-version.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-snmp-weak-cryptography.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-snmp-weak-cryptography.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/sql/rule-hardcoded-sql-expression.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/sql/rule-hardcoded-sql-expression.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-req-no-certvalid.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-req-no-certvalid.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-no-version.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-no-version.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-with-bad-version.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-with-bad-version.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-unverified-context.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-unverified-context.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/telnet/rule-import-telnib.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/telnet/rule-import-telnib.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-hardcodedtmp.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-hardcodedtmp.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-mktemp-q.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-mktemp-q.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/urlopen/rule-urllib-urlopen.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/urlopen/rule-urllib-urlopen.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-celement.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-celement.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-element.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-element.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-etree.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-etree.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatbuilder.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatbuilder.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatreader.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatreader.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-minidom.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-minidom.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-pulldom.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-pulldom.yml create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-sax.py create mode 100644 compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-sax.yml create mode 100755 scripts/vendor-semgrep-rules.py diff --git a/compliance-agent/rules/vendor/0xdea/LICENSE b/compliance-agent/rules/vendor/0xdea/LICENSE new file mode 100644 index 0000000..3eddae7 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 raptor + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/compliance-agent/rules/vendor/0xdea/NOTICE b/compliance-agent/rules/vendor/0xdea/NOTICE new file mode 100644 index 0000000..20a63d1 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/NOTICE @@ -0,0 +1,38 @@ +0xdea semgrep-rules (C/C++) +=========================== + +Upstream: https://github.com/0xdea/semgrep-rules +Commit: dae50da6e6e629750f1daec73a01ef9206a372ab +Version: v2.0.0 + 20 commits (2026-09-25) +Licence: MIT +Copyright: Copyright (c) 2022 raptor (Marco Ivaldi) + +Prüfwerk runs these rules with its own semgrep invocation (--metrics=off, +local files only). upstream/ holds the selected files unchanged, with +their semgrep tests. pack.yaml is what the agent runs: the same rules with +ids prefixed by '0xdea-', re-serialised into one file, without +the rules listed below. Both are produced by scripts/vendor-semgrep-rules.py. + +Selected from upstream: rules/c/** +Rules in the pack: 35 (from 49 files) + +Not selected: +- rules/noisy/: upstream marks these unsuitable for general use + +Left out +-------- + +- 0xdea-raptor-argv-envp-access (rules/c/argv-envp-access.yaml): 43 hits on every argv/getenv read; an audit aid, not a weakness +- 0xdea-raptor-format-string-bugs (rules/c/format-string-bugs.yaml): FP storm: 61 hits in lwIP, all literal formats joined with a macro ("%s"NEWLINE); our cra-ai-20-c-non-literal-format-string covers the real case +- 0xdea-raptor-high-entropy-assignment (rules/c/high-entropy-assignment.yaml): 14 hits, sampled hits are base64 tables and exception-name strings; gitleaks covers committed secrets +- 0xdea-raptor-integer-truncation (rules/c/integer-truncation.yaml): 23 hits in lwIP, sampled hits assign small constants (`x = 1`) +- 0xdea-raptor-interesting-api-calls (rules/c/interesting-api-calls.yaml): FP storm: 718 hits in lwIP; lists every call of an "interesting" API for a manual audit +- 0xdea-raptor-mismatched-memory-management (rules/c/mismatched-memory-management.yaml): 36 hits in lwIP, sampled hits are plain matching malloc/free pairs +- 0xdea-raptor-missing-break-in-switch (rules/c/missing-break-in-switch.yaml): intended fallthrough in FreeRTOS-Kernel and lwIP; a review hint by upstream's own description (code quality / audit aid), not a weakness +- 0xdea-raptor-missing-default-in-switch (rules/c/missing-default-in-switch.yaml): 22 hits; a review hint by upstream's own description (code quality / audit aid), not a weakness +- 0xdea-raptor-missing-return (rules/c/missing-return.yaml): FP storm: 1514 hits in FreeRTOS-Kernel (port macros); a review hint by upstream's own description (code quality / audit aid), not a weakness +- 0xdea-raptor-pointer-subtraction (rules/c/pointer-subtraction.yaml): 16 hits in lwIP, all `len = end - start` length arithmetic +- 0xdea-raptor-signed-unsigned-conversion (rules/c/signed-unsigned-conversion.yaml): FP storm: 221 hits in FreeRTOS-Kernel and lwIP, nearly all benign casts +- 0xdea-raptor-suspicious-assert (rules/c/suspicious-assert.yaml): FP storm: 176 hits in FreeRTOS-Kernel and lwIP (configASSERT/LWIP_ASSERT on sizes) +- 0xdea-raptor-typos (rules/c/typos.yaml): FP storm: 989 hits in FreeRTOS-Kernel and lwIP; a review hint by upstream's own description (code quality / audit aid), not a weakness +- 0xdea-raptor-write-into-stack-buffer (rules/c/write-into-stack-buffer.yaml): 27 hits on every write into a stack array; an audit aid, not a weakness diff --git a/compliance-agent/rules/vendor/0xdea/UPSTREAM b/compliance-agent/rules/vendor/0xdea/UPSTREAM new file mode 100644 index 0000000..8344fbc --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/UPSTREAM @@ -0,0 +1 @@ +https://github.com/0xdea/semgrep-rules dae50da6e6e629750f1daec73a01ef9206a372ab diff --git a/compliance-agent/rules/vendor/0xdea/pack.yaml b/compliance-agent/rules/vendor/0xdea/pack.yaml new file mode 100644 index 0000000..edd772d --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/pack.yaml @@ -0,0 +1,2187 @@ +# 0xdea semgrep-rules (C/C++), vendored by scripts/vendor-semgrep-rules.py; do not edit. +# Upstream: https://github.com/0xdea/semgrep-rules at dae50da6e6e629750f1daec73a01ef9206a372ab +# Licence: MIT; see LICENSE and NOTICE next to this file. +# Changed from upstream: ids prefixed with '0xdea-', rules +# left out as listed in NOTICE, rules re-serialised into one file. +rules: + - id: 0xdea-raptor-command-injection + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Command Injection + likelihood: MEDIUM + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-78: Improper Neutralization of Special Elements used in an OS Command (''OS Command Injection'')' + - 'CWE-88: Improper Neutralization of Argument Delimiters in a Command (''Argument Injection'')' + - 'CWE-676: Use of Potentially Dangerous Function' + owasp: + - A05:2025 - Injection + references: + - https://g.co/kgs/PCHQjJ + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: The software constructs an OS command using externally-influenced input, but it does not neutralize + or incorrectly neutralizes special elements that could modify the intended OS command. + severity: ERROR + patterns: + - pattern-either: + - pattern: system(...) + - pattern: popen(...) + - pattern: p2open(...) + - pattern: wordexp(...) + - pattern-not: $_("...", ...) + - id: 0xdea-raptor-double-free + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-415: Double Free' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://github.com/struct/mms + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + - https://dustri.org/b/playing-with-weggli.html + message: The software calls free() twice on the same memory address, potentially leading to memory corruption. + This corruption can cause the program to crash or cause two later calls to malloc() to return the same + pointer. + severity: ERROR + patterns: + - pattern: '$FREE1($PTR); + + ... + + $FREE2($PTR); + + ' + - pattern-not: '$FREE1($PTR); + + ... + + $PTR = ...; + + ... + + $FREE2($PTR); + + ' + - metavariable-pattern: + metavariable: $FREE1 + pattern: free + - metavariable-pattern: + metavariable: $FREE2 + pattern: free + - focus-metavariable: $FREE2 + - id: 0xdea-raptor-incorrect-order-setuid-setgid + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Improper Authorization + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-696: Incorrect Behavior Order' + owasp: + - A01:2025 - Broken Access Control + references: + - https://www.usenix.org/legacy/events/sec02/full_papers/chen/chen.pdf + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + message: A compromised process might be able to regain elevated group privileges if set(e)gid() is called + after set(e)uid(). A similar case is when privileges are temporarily dropped with seteuid() and then + setuid() or seteuid() are called from while under unprivileged user. + severity: ERROR + pattern-either: + - patterns: + - pattern: '<... setuid(...) ...>; + + ... + + <... setgid(...) ...>; + + ' + - pattern-not: '<... setuid(0) ...>; + + ... + + <... setgid(...) ...>; + + ' + - patterns: + - pattern: '<... seteuid(...) ...>; + + ... + + <... setegid(...) ...>; + + ' + - pattern-not: '<... seteuid(0) ...>; + + ... + + <... setegid(...) ...>; + + ' + - pattern-not-inside: '<... seteuid(...) ...>; + + ... + + <... seteuid(0) ...>; + + ... + + <... setegid(...) ...>; + + ' + - patterns: + - pattern: '<... seteuid(...) ...>; + + ... + + <... setuid(...) ...>; + + ' + - pattern-not: '<... seteuid(0) ...>; + + ... + + <... setuid(...) ...>; + + ' + - pattern-not-inside: '<... seteuid(...) ...>; + + ... + + <... seteuid(0) ...>; + + ... + + <... setuid(...) ...>; + + ' + - patterns: + - pattern: '<... seteuid(...) ...>; + + ... + + <... seteuid(...) ...>; + + ' + - pattern-not: '<... seteuid(0) ...>; + + ... + + <... seteuid(...) ...>; + + ' + - pattern-not: '<... seteuid(...) ...>; + + ... + + <... seteuid(0) ...>; + + ' + - pattern-not-inside: '<... seteuid(...) ...>; + + ... + + <... seteuid(0) ...>; + + ... + + <... seteuid(...) ...>; + + ' + - id: 0xdea-raptor-incorrect-unsigned-comparison + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Improper Validation + likelihood: LOW + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-697: Incorrect Comparison' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: Checking if an unsigned variable is negative makes no sense and is usually a good indication + that something is probably wrong with the code. + severity: WARNING + pattern-either: + - pattern: (unsigned short $_) < 0 + - pattern: (unsigned short int $_) < 0 + - pattern: (unsigned int $_) < 0 + - pattern: (unsigned long $_) < 0 + - pattern: (unsigned long int $_) < 0 + - pattern: (size_t $_) < 0 + - pattern: (unsigned short $_) <= 0 + - pattern: (unsigned short int $_) <= 0 + - pattern: (unsigned int $_) <= 0 + - pattern: (unsigned long $_) <= 0 + - pattern: (unsigned long int $_) <= 0 + - pattern: (size_t $_) <= 0 + - pattern: (unsigned short $_) >= 0 + - pattern: (unsigned short int $_) >= 0 + - pattern: (unsigned int $_) >= 0 + - pattern: (unsigned long $_) >= 0 + - pattern: (unsigned long int $_) >= 0 + - pattern: (size_t $_) >= 0 + - id: 0xdea-raptor-incorrect-use-of-free + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-590: Free of Memory not on the Heap' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_spirit.c + message: The software calls free() on a pointer to memory that has a short lifetime and was not allocated + using associated heap allocation functions such as malloc(), calloc(), or realloc(). + severity: ERROR + pattern-either: + - patterns: + - pattern: free($PTR) + - pattern-either: + - pattern-inside: '$_ $PTR[$_]; + + ... + + ' + - pattern-inside: '$_ $PTR[$_] = ...; + + ... + + ' + - pattern-inside: '$_ $PTR[] = ...; + + ... + + ' + - pattern-inside: '$_ $ARR[$_]; + + ... + + $PTR = $ARR; + + ... + + ' + - pattern-inside: '$_ $ARR[$_] = ...; + + ... + + $PTR = $ARR; + + ... + + ' + - pattern-inside: '$_ $ARR[] = ...; + + ... + + $PTR = $ARR; + + ... + + ' + - patterns: + - pattern: free(&$VAR) + - pattern-either: + - pattern-inside: '$_ $VAR; + + ... + + ' + - pattern-inside: '$_ $VAR = ...; + + ... + + ' + - pattern-inside: '$_ $VAR[$_]; + + ... + + ' + - pattern-inside: '$_ $VAR[$_] = ...; + + ... + + ' + - pattern-inside: '$_ $VAR[] = ...; + + ... + + ' + - pattern-inside: '$_ * $VAR; + + ... + + ' + - pattern-inside: '$_ * $VAR = ...; + + ... + + ' + - id: 0xdea-raptor-incorrect-use-of-memset + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Mishandled Sensitive Information + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-683: Function Call With Incorrect Order of Arguments' + owasp: + - A04:2025 - Cryptographic Failures + references: + - https://lkml.org/lkml/2009/11/11/336 + - https://bugs.mysql.com/bug.php?id=23181 + message: The invocation of memset() is easy to get wrong. The second argument is the character and the + third argument is the size, but sometimes these arguments are in the wrong order. This results in a + no-op. + severity: ERROR + pattern-either: + - pattern: memset($_, $_, 0) + - pattern: memset($_, $_, '\0') + - pattern: memset($_, sizeof(...), $_) + - pattern: memset_explicit($_, $_, 0) + - pattern: memset_explicit($_, $_, '\0') + - pattern: memset_explicit($_, sizeof(...), $_) + - id: 0xdea-raptor-incorrect-use-of-sizeof + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-467: Use of sizeof() on a Pointer Type' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + - https://dustri.org/b/playing-with-weggli.html + - https://mastodon.gamedev.place/@amonakov/111577826195014479 + - https://github.com/semgrep/semgrep/issues/11327 + message: The code calls sizeof() on a pointer type, which always returns the wordsize (8 on 64-bit architectures). + This can produce an unexpected result if the programmer intended to determine how much memory has + been allocated. + severity: WARNING + pattern-either: + - patterns: + - pattern: sizeof((char * $_)) + - pattern-not: sizeof("...") + - pattern: sizeof((int * $_)) + - pattern: sizeof((float * $_)) + - pattern: sizeof((double * $_)) + - patterns: + - pattern-either: + - pattern: sizeof($PTR) + - pattern: sizeof($PTR + $_) + - pattern: sizeof($_ + $PTR) + - pattern-either: + - pattern-inside: '$_ * $PTR; + + ... + + ' + - pattern-inside: '$_ * $PTR = ...; + + ... + + ' + - patterns: + - pattern-either: + - pattern: sizeof($PTR) + - pattern: sizeof($PTR + $_) + - pattern: sizeof($_ + $PTR) + - pattern-either: + - pattern-inside: "$_ $_(..., $_ * $PTR, ...) {\n ...\n}\n" + - pattern-inside: "$_ $_(..., $_ $PTR[$_], ...) {\n ...\n}\n" + - pattern-inside: "$_ $_(..., $_ $PTR[], ...) {\n ...\n}\n" + - pattern: sizeof(this) + - id: 0xdea-raptor-incorrect-use-of-strncat + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-787: Out-of-bounds Write' + - 'CWE-193: Off-by-one Error' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: 'The strncat() function is nearly as dangerous as strcat(), in that it''s quite easy to misuse. + The first common mistake is supplying the size of the entire buffer instead of the size remaining in + the buffer. A more subtle mistake can be made: the size parameter needs to be the amount of space left + in the buffer less one; otherwise, the NUL byte is written one byte past the end of the buffer.' + severity: ERROR + pattern-either: + - patterns: + - pattern: strncat($DST, $_, $LEN) + - pattern-either: + - pattern-inside: '$_ $DST[$LEN]; + + ... + + ' + - pattern-inside: '$_ $DST[$LEN] = ...; + + ... + + ' + - pattern: strncat($DST, $_, sizeof($DST)) + - pattern: strncat($DST, $_, strlen($DST)) + - pattern: strncat($DST, $_, sizeof($DST) - strlen($DST)) + - id: 0xdea-raptor-insecure-api-access-stat + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Dangerous Method or Function + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://labs.snyk.io/resources/leaky-vessels-container-vuln-deep-dive/ + message: The software checks the state of a resource before using it, but the resource's state can change + between the check and the use in a way that invalidates the results of the check. This can cause the + software to perform invalid actions when the resource is in an unexpected state. + severity: WARNING + pattern-either: + - pattern: access(...) + - pattern: faccessat(...) + - pattern: faccessat2(...) + - pattern: stat(...) + - pattern: lstat(...) + - pattern: fstatat(...) + - id: 0xdea-raptor-insecure-api-alloca + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: MEDIUM + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-676: Use of Potentially Dangerous Function' + - 'CWE-1325: Improperly Controlled Sequential Memory Allocation' + owasp: + - A06:2025 - Insecure Design + references: + - https://nullprogram.com/blog/2019/10/28/ + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + message: Use of alloca() is unsafe because it cannot ensure that the pointer returned points to a valid + and usable block of memory. The allocation made may exceed the bounds of the stack, or even go further + into other objects in memory, and alloca() cannot determine such an error. + severity: ERROR + pattern: alloca(...) + - id: 0xdea-raptor-insecure-api-ato + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Dangerous Method or Function + likelihood: LOW + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-839: Numeric Range Comparison Without Minimum Check' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://rules.sonarsource.com/c/type/Bug/RSPEC-989 + - https://wiki.sei.cmu.edu/confluence/display/c/ERR34-C.+Detect+errors+when+converting+a+string+to+a+number + - https://github.com/vixie/cron/commit/9cc8ab1087bb9ab861dd5595c41200683c9f6712 + message: The atoi(), atol(), atof(), and similar functions don't handle errors. They don't check for integer + overflow and can return a negative value. They have undefined behavior if the value of the result cannot + be represented. They return 0 (or 0.0) if the string does not represent an integer (or decimal), which + is indistinguishable from a correctly formatted, zero-denoting input string. + severity: INFO + pattern-either: + - pattern: atoi(...) + - pattern: atol(...) + - pattern: atof(...) + - pattern: atoll(...) + - id: 0xdea-raptor-insecure-api-gets + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: HIGH + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-242: Use of Inherently Dangerous Function' + - 'CWE-120: Buffer Copy without Checking Size of Input (''Classic Buffer Overflow'')' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: The gets() function is always unsafe because it does not perform bounds checking on the size + of its input. An attacker can easily send arbitrarily-sized input to gets() and overflow the destination + buffer. + severity: ERROR + pattern: gets(...) + - id: 0xdea-raptor-insecure-api-mktemp-tmpnam-tempnam + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Dangerous Method or Function + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-377: Insecure Temporary File' + - 'CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: Creating and using insecure temporary files can leave application and system data vulnerable + to attack. + severity: WARNING + pattern-either: + - pattern: mktemp(...) + - pattern: tmpnam(...) + - pattern: tempnam(...) + - pattern: tmpnam_r(...) + - id: 0xdea-raptor-insecure-api-rand-srand + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Cryptographic Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)' + - 'CWE-330: Use of Insufficiently Random Values' + owasp: + - A04:2025 - Cryptographic Failures + references: + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: The rand() PRNG should not be used in applications intended to be portable when good randomness + is needed. Instead, the use of random() is recommended. + severity: WARNING + pattern-either: + - pattern: rand(...) + - pattern: srand(...) + - pattern: drand48(...) + - pattern: erand48(...) + - pattern: lrand48(...) + - pattern: nrand48(...) + - pattern: mrand48(...) + - pattern: jrand48(...) + - pattern: lcong48(...) + - pattern: srand48(...) + - pattern: seed48(...) + - id: 0xdea-raptor-insecure-api-scanf + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: HIGH + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-676: Use of Potentially Dangerous Function' + - 'CWE-120: Buffer Copy without Checking Size of Input (''Classic Buffer Overflow'')' + - 'CWE-787: Out-of-bounds Write' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: A buffer overflow condition exists when a program attempts to put more data in a buffer than + it can hold, or when a program attempts to put data in a memory area outside of the boundaries of a + buffer. + severity: ERROR + patterns: + - pattern-either: + - pattern: scanf($FMT, ...) + - pattern: __isoc99_scanf($FMT, ...) + - pattern: vscanf($FMT, ...) + - pattern: __isoc99_vscanf($FMT, ...) + - pattern: fscanf($_, $FMT, ...) + - pattern: __isoc99_fscanf($_, $FMT, ...) + - pattern: vfscanf($_, $FMT, ...) + - pattern: __isoc99_vfscanf($_, $FMT, ...) + - pattern: sscanf($_, $FMT, ...) + - pattern: __isoc99_sscanf($_, $FMT, ...) + - pattern: vsscanf($_, $FMT, ...) + - pattern: __isoc99_vsscanf($_, $FMT, ...) + - pattern: wscanf($FMT, ...) + - pattern: vwscanf($FMT, ...) + - pattern: fwscanf($_, $FMT, ...) + - pattern: vfwscanf($_, $FMT, ...) + - pattern: swscanf($_, $FMT, ...) + - pattern: vswscanf($_, $FMT, ...) + - pattern-not: sscanf("...", $FMT, ...) + - pattern-not: __isoc99_sscanf("...", $FMT, ...) + - pattern-not: vsscanf("...", $FMT, ...) + - pattern-not: __isoc99_vsscanf("...", $FMT, ...) + - pattern-not: swscanf("...", $FMT, ...) + - pattern-not: vswscanf("...", $FMT, ...) + - metavariable-regex: + metavariable: $FMT + regex: (".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*) + - id: 0xdea-raptor-insecure-api-signal + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Dangerous Method or Function + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-364: Signal Handler Race Condition' + - 'CWE-479: Signal Handler Use of a Non-reentrant Function' + - 'CWE-828: Signal Handler with Functionality that is not Asynchronous-Safe' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://lcamtuf.coredump.cx/signals.txt + message: The signal() API should be regarded as deprecated. When possible, sigaction() should be used + instead, because it allows to precisely specify the desired behavior in case two signals arrive shortly + after each other thus preventing many race conditions. + severity: WARNING + pattern-either: + - pattern: signal(...) + - pattern: gsignal(...) + - pattern: ssignal(...) + - id: 0xdea-raptor-insecure-api-sprintf-vsprintf + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: HIGH + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-676: Use of Potentially Dangerous Function' + - 'CWE-120: Buffer Copy without Checking Size of Input (''Classic Buffer Overflow'')' + - 'CWE-787: Out-of-bounds Write' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: A buffer overflow condition exists when a program attempts to put more data in a buffer than + it can hold, or when a program attempts to put data in a memory area outside of the boundaries of a + buffer. + severity: ERROR + patterns: + - pattern-either: + - pattern: sprintf($_, $FMT, ...) + - pattern: vsprintf($_, $FMT, ...) + - metavariable-regex: + metavariable: $FMT + regex: (".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*) + - id: 0xdea-raptor-insecure-api-strcpy-strcat + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: HIGH + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - 'CWE-676: Use of Potentially Dangerous Function' + - 'CWE-120: Buffer Copy without Checking Size of Input (''Classic Buffer Overflow'')' + - 'CWE-787: Out-of-bounds Write' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: A buffer overflow condition exists when a program attempts to put more data in a buffer than + it can hold, or when a program attempts to put data in a memory area outside of the boundaries of a + buffer. + severity: ERROR + patterns: + - pattern-either: + - pattern: strcpy(...) + - pattern: stpcpy(...) + - pattern: strcat(...) + - pattern: wcscpy(...) + - pattern: wcpcpy(...) + - pattern: wcscat(...) + - pattern: _mbscpy(...) + - pattern: _mbscat(...) + - pattern: strccpy(...) + - pattern: strcadd(...) + - pattern: streadd(...) + - pattern: strecpy(...) + - pattern: strtrns(...) + - pattern-not: $_($_, "...", ...) + - id: 0xdea-raptor-integer-wraparound + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-190: Integer Overflow or Wraparound' + - 'CWE-128: Wrap-around Error' + - 'CWE-131: Incorrect Calculation of Buffer Size' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - http://www.phrack.org/issues/60/10.html#article + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + - https://dustri.org/b/playing-with-weggli.html + message: The software performs a calculation that can produce an integer overflow or wraparound, when + the logic assumes that the resulting value will always be larger than the original value. This can introduce + other weaknesses when the calculation is used for resource management or execution control. + severity: WARNING + pattern-either: + - patterns: + - pattern-either: + - pattern: $FUN($_ * $_) + - pattern: $FUN($_ *= $_) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: valloc + - patterns: + - pattern: $FUN($N) + - pattern-either: + - pattern-inside: '$N = $_ * $_; + + ... + + ' + - pattern-inside: '$N *= $_; + + ... + + ' + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: valloc + - patterns: + - pattern-either: + - pattern: $FUN($_ + $_) + - pattern: $FUN($_ += $_) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: valloc + - patterns: + - pattern: $FUN($N) + - pattern-either: + - pattern-inside: '$N = $_ + $_; + + ... + + ' + - pattern-inside: '$N += $_; + + ... + + ' + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: valloc + - patterns: + - pattern-either: + - pattern: $FUN($_, $_ * $_, ...) + - pattern: $FUN($_, $_ *= $_, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: aligned_alloc + - pattern: VirtualAlloc + - patterns: + - pattern: $FUN($_, $N, ...) + - pattern-either: + - pattern-inside: '$N = $_ * $_; + + ... + + ' + - pattern-inside: '$N *= $_; + + ... + + ' + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: aligned_alloc + - pattern: VirtualAlloc + - patterns: + - pattern-either: + - pattern: $FUN($_, $_ + $_, ...) + - pattern: $FUN($_, $_ += $_, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: aligned_alloc + - pattern: VirtualAlloc + - patterns: + - pattern: $FUN($_, $N, ...) + - pattern-either: + - pattern-inside: '$N = $_ + $_; + + ... + + ' + - pattern-inside: '$N += $_; + + ... + + ' + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: aligned_alloc + - pattern: VirtualAlloc + - patterns: + - pattern-either: + - pattern: $FUN($_ * $_, $_) + - pattern: $FUN($_ *= $_, $_) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - patterns: + - pattern: $FUN($N, $_) + - pattern-either: + - pattern-inside: '$N = $_ * $_; + + ... + + ' + - pattern-inside: '$N *= $_; + + ... + + ' + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - patterns: + - pattern-either: + - pattern: $FUN($_ + $_, $_) + - pattern: $FUN($_ += $_, $_) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - patterns: + - pattern: $FUN($N, $_) + - pattern-either: + - pattern-inside: '$N = $_ + $_; + + ... + + ' + - pattern-inside: '$N += $_; + + ... + + ' + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - pattern: $X > $MAX || ($X + $_) > $MAX + - pattern: $X >= $MAX || ($X + $_) > $MAX + - pattern: $X > $MAX || ($X + $_) >= $MAX + - pattern: $X >= $MAX || ($X + $_) >= $MAX + - pattern: $X < $MAX && ($X + $_) < $MAX + - pattern: $X <= $MAX && ($X + $_) < $MAX + - pattern: $X < $MAX && ($X + $_) <= $MAX + - pattern: $X <= $MAX && ($X + $_) <= $MAX + - pattern: $X > $MAX || ($X * $_) > $MAX + - pattern: $X >= $MAX || ($X * $_) > $MAX + - pattern: $X > $MAX || ($X * $_) >= $MAX + - pattern: $X >= $MAX || ($X * $_) >= $MAX + - pattern: $X < $MAX && ($X * $_) < $MAX + - pattern: $X <= $MAX && ($X * $_) < $MAX + - pattern: $X < $MAX && ($X * $_) <= $MAX + - pattern: $X <= $MAX && ($X * $_) <= $MAX + - id: 0xdea-raptor-memory-address-exposure + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Mishandled Sensitive Information + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - c + - cpp + cwe: + - 'CWE-209: Generation of Error Message Containing Sensitive Information' + - 'CWE-497: Exposure of Sensitive System Information to an Unauthorized Control Sphere' + owasp: + - A04:2025 - Cryptographic Failures + references: + - https://github.com/struct/mms + message: The software generates an error message that includes sensitive information about its environment, + users, or associated data. In particular, exposure of memory addresses might defeat ASLR. + severity: INFO + patterns: + - pattern-either: + - pattern: printf($FMT, ...) + - pattern: vprintf($FMT, ...) + - pattern: wprintf($FMT, ...) + - pattern: vwprintf($FMT, ...) + - pattern: vcprintf($FMT, ...) + - pattern: vcwprintf($FMT, ...) + - pattern: vscprintf($FMT, ...) + - pattern: vscwprintf($FMT, ...) + - pattern: printk($FMT, ...) + - pattern: warn($FMT, ...) + - pattern: vwarn($FMT, ...) + - pattern: warnx($FMT, ...) + - pattern: vwarnx($FMT, ...) + - pattern: fprintf($_, $FMT, ...) + - pattern: vfprintf($_, $FMT, ...) + - pattern: fwprintf($_, $FMT, ...) + - pattern: vfwprintf($_, $FMT, ...) + - pattern: sprintf($_, $FMT, ...) + - pattern: vsprintf($_, $FMT, ...) + - pattern: asprintf($_, $FMT, ...) + - pattern: vasprintf($_, $FMT, ...) + - pattern: dprintf($_, $FMT, ...) + - pattern: vdprintf($_, $FMT, ...) + - pattern: wsprintf($_, $FMT, ...) + - pattern: syslog($_, $FMT, ...) + - pattern: vsyslog($_, $FMT, ...) + - pattern: err($_, $FMT, ...) + - pattern: verr($_, $FMT, ...) + - pattern: errx($_, $FMT, ...) + - pattern: verrx($_, $FMT, ...) + - pattern: warnc($_, $FMT, ...) + - pattern: vwarnc($_, $FMT, ...) + - pattern: snprintf($_, $_, $FMT, ...) + - pattern: vsnprintf($_, $_, $FMT, ...) + - pattern: swprintf($_, $_, $FMT, ...) + - pattern: vswprintf($_, $_, $FMT, ...) + - pattern: errc($_, $_, $FMT, ...) + - pattern: verrc($_, $_, $FMT, ...) + - metavariable-regex: + metavariable: $FMT + regex: (".*%\w*x.*"|".*%\w*X.*"|".*%\w*p.*") + - id: 0xdea-raptor-mismatched-memory-management-cpp + languages: [cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - cpp + cwe: + - 'CWE-762: Mismatched Memory Management Routines' + owasp: + - A06:2025 - Insecure Design + references: + - https://github.com/struct/mms + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + message: The software attempts to return a memory resource to the system, but it calls a release function + that is not compatible with the function that was originally used to allocate that resource. Due to + inherent limitations of Semgrep, this rule might generate many false positives and should therefore + be customized for your codebase. + severity: INFO + pattern-either: + - patterns: + - pattern: free($PTR) + - pattern-not-inside: '$PTR = malloc(...); + + ... + + ' + - pattern-not-inside: '$PTR = calloc(...); + + ... + + ' + - pattern-not-inside: '$PTR = realloc(...); + + ... + + ' + - pattern-not-inside: '$PTR = strdup(...); + + ... + + ' + - pattern-not-inside: '$PTR = strndup(...); + + ... + + ' + - patterns: + - pattern: delete[]($PTR) + - pattern-not-inside: '$PTR = new $_[$_]; + + ... + + ' + - patterns: + - pattern: delete($PTR) + - pattern-not-inside: '$PTR = new $_; + + ... + + ' + - patterns: + - pattern: delete($PTR) + - pattern-inside: '$PTR = new $_[$_]; + + ... + + ' + - id: 0xdea-raptor-off-by-one + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-193: Off-by-one Error' + - 'CWE-787: Out-of-bounds Write' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + message: The software calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, + than the correct value. + severity: WARNING + pattern-either: + - pattern: $BUF[sizeof($BUF)] = ... + - patterns: + - pattern: $BUF[$LEN] = ... + - pattern-either: + - pattern-inside: '$_ $BUF[$LEN]; + + ... + + ' + - pattern-inside: '$_ $BUF[$LEN] = ...; + + ... + + ' + - patterns: + - pattern: '*($BUF + $LEN) = ... + + ' + - pattern-either: + - pattern-inside: '$_ $BUF[$LEN]; + + ... + + ' + - pattern-inside: '$_ $BUF[$LEN] = ...; + + ... + + ' + - patterns: + - pattern: $BUF[$X][$Y] = ... + - pattern-either: + - pattern-inside: '$_ $BUF[$_][$Y]; + + ... + + ' + - pattern-inside: '$_ $BUF[$X][$_]; + + ... + + ' + - pattern: strlen($SRC) > sizeof($DST) + - pattern: strlen($SRC) <= sizeof($DST) + - pattern: sizeof($DST) < strlen($SRC) + - pattern: sizeof($DST) >= strlen($SRC) + - patterns: + - pattern: strncat($_, $_, $LEN) + - metavariable-pattern: + metavariable: $LEN + patterns: + - pattern-not: $_ - 1 + - pattern: $STR[strlen($STR) - 1] + - patterns: + - pattern-inside: '$LEN = strlen($STR) - 1; + + ... + + ' + - pattern: $STR[$LEN] + - patterns: + - pattern-inside: '$LEN = strlen($STR); + + ... + + ' + - pattern: $STR[$LEN - 1] + - pattern: malloc(strlen($STR)) + - patterns: + - pattern-inside: '$LEN = strlen($STR); + + ... + + ' + - pattern: malloc($LEN) + - id: 0xdea-raptor-overlapping-source-destination + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: LOW + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-1260: Improper Handling of Overlap Between Protected Memory Ranges' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://linux.die.net/man/3/sprintf + message: C standards specify that the results are undefined if a call to copy functions, with the exception + of memmove(), would cause copying to take place between objects that overlap (e.g., if the target string + array and one of the supplied input arguments refer to the same buffer). + severity: WARNING + pattern-either: + - patterns: + - pattern: $FUN($DST, $DST, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strcpy + - pattern: strncpy + - pattern: stpcpy + - pattern: stpncpy + - pattern: strlcpy + - pattern: strscpy + - pattern: wcscpy + - pattern: wcsncpy + - pattern: wcpcpy + - pattern: wcpncpy + - pattern: wcslcpy + - pattern: _mbscpy + - pattern: _mbsncpy + - pattern: _mbpcpy + - pattern: _mbpncpy + - pattern: _mbslcpy + - pattern: strccpy + - pattern: strcadd + - pattern: streadd + - pattern: strecpy + - pattern: strcat + - pattern: strncat + - pattern: strlcat + - pattern: wcscat + - pattern: wcsncat + - pattern: wcslcat + - pattern: _mbscat + - pattern: _mbsncat + - pattern: _mbslcat + - pattern: memcpy + - pattern: memccpy + - pattern: wmemcpy + - pattern: mempcpy + - pattern: wmempcpy + - pattern: bcopy + - pattern: sprintf($DST, ..., $DST, ...) + - pattern: snprintf($DST, $_, ..., $DST, ...) + - id: 0xdea-raptor-putenv-stack-var + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-686: Function Call With Incorrect Argument Type' + - 'CWE-562: Return of Stack Variable Address' + owasp: + - A06:2025 - Insecure Design + references: + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: The software calls putenv() with a variable that has a short lifetime, such as a pointer to an + automatic variable allocated on the stack. The correct behavior is to call putenv() with a static/global + string. + severity: INFO + patterns: + - pattern: putenv($PTR) + - pattern-either: + - patterns: + - pattern-inside: '$_ $PTR[$_]; + + ... + + ' + - pattern-not-inside: 'static $_ $PTR[$_]; + + ... + + ' + - patterns: + - pattern-inside: '$_ $PTR[$_] = ...; + + ... + + ' + - pattern-not-inside: 'static $_ $PTR[$_] = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ $PTR[] = ...; + + ... + + ' + - pattern-not-inside: 'static $_ $PTR[] = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ $ARR[$_]; + + ... + + $PTR = $ARR; + + ... + + ' + - pattern-not-inside: 'static $_ $ARR[$_]; + + ... + + ' + - patterns: + - pattern-inside: '$_ $ARR[$_] = ...; + + ... + + $PTR = $ARR; + + ... + + ' + - pattern-not-inside: 'static $_ $ARR[$_] = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ $ARR[] = ...; + + ... + + $PTR = $ARR; + + ... + + ' + - pattern-not-inside: 'static $_ $ARR[] = ...; + + ... + + ' + - id: 0xdea-raptor-regex-dos + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Denial-of-Service (DoS) + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-1333: Inefficient Regular Expression Complexity' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://semgrep.dev/docs/writing-rules/metavariable-analysis + - https://github.com/semgrep/semgrep/pull/4672 + message: The software uses a regular expression with an inefficient, possibly exponential worst-case computational + complexity that consumes excessive CPU cycles. Poorly constructed regular expressions that exhibit exponential + runtime when fed specifically crafted inputs can cause RegEx denial of service (ReDoS). + severity: WARNING + patterns: + - pattern-either: + - pattern: $FUN($_, $REGEX, $_) + - pattern: '$STRING = $REGEX; + + ... + + <... $FUN($_, $STRING, $_) ...>; + + ' + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: regcomp + - pattern: regncomp + - pattern: regwcomp + - pattern: regwncomp + - pattern: regcomp_l + - pattern: regncomp_l + - pattern: regwcomp_l + - pattern: regwncomp_l + - metavariable-analysis: + analyzer: redos + metavariable: $REGEX + - focus-metavariable: $REGEX + - id: 0xdea-raptor-ret-stack-address + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: LOW + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-562: Return of Stack Variable Address' + owasp: + - A06:2025 - Insecure Design + references: + - https://github.com/struct/mms + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + - https://rules.sonarsource.com/c/type/Bug/RSPEC-946 + message: A function returns the address of a stack variable, which will cause unintended program behavior, + typically in the form of a crash. + severity: INFO + pattern-either: + - patterns: + - pattern: return $PTR; + - pattern-either: + - patterns: + - pattern-inside: '$_ $PTR[$_]; + + ... + + ' + - pattern-not-inside: 'static $_ $PTR[$_]; + + ... + + ' + - patterns: + - pattern-inside: '$_ $PTR[$_] = ...; + + ... + + ' + - pattern-not-inside: 'static $_ $PTR[$_] = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ $PTR[] = ...; + + ... + + ' + - pattern-not-inside: 'static $_ $PTR[] = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ $ARR[$_]; + + ... + + $PTR = $ARR; + + ... + + ' + - pattern-not-inside: 'static $_ $ARR[$_]; + + ... + + ' + - patterns: + - pattern-inside: '$_ $ARR[$_] = ...; + + ... + + $PTR = $ARR; + + ... + + ' + - pattern-not-inside: 'static $_ $ARR[$_] = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ $ARR[] = ...; + + ... + + $PTR = $ARR; + + ... + + ' + - pattern-not-inside: 'static $_ $ARR[] = ...; + + ... + + ' + - patterns: + - pattern: return &$VAR; + - pattern-either: + - patterns: + - pattern-inside: '$_ $VAR; + + ... + + ' + - pattern-not-inside: 'static $_ $VAR; + + ... + + ' + - patterns: + - pattern-inside: '$_ $VAR = ...; + + ... + + ' + - pattern-not-inside: 'static $_ $VAR = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ $VAR[$_]; + + ... + + ' + - pattern-not-inside: 'static $_ $VAR[$_]; + + ... + + ' + - patterns: + - pattern-inside: '$_ $VAR[$_] = ...; + + ... + + ' + - pattern-not-inside: 'static $_ $VAR[$_] = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ $VAR[] = ...; + + ... + + ' + - pattern-not-inside: 'static $_ $VAR[] = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ * $VAR; + + ... + + ' + - pattern-not-inside: 'static $_ * $VAR; + + ... + + ' + - patterns: + - pattern-inside: '$_ * $VAR = ...; + + ... + + ' + - pattern-not-inside: 'static $_ * $VAR = ...; + + ... + + ' + - id: 0xdea-raptor-unchecked-ret-malloc + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-252: Unchecked Return Value' + - 'CWE-690: Unchecked Return Value to NULL Pointer Dereference' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: The software does not check the return value from a method or function, which can prevent it + from detecting unexpected states and conditions. + severity: WARNING + patterns: + - pattern-either: + - pattern: $RET = $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: valloc + - pattern: aligned_alloc + - pattern: strdup + - pattern: strndup + - pattern-not-inside: '$FUN(...); + + ... + + if (<... $RET ...>) ... + + ' + - pattern-not-inside: <... $_ == NULL ...> + - pattern-not-inside: <... NULL == $_ ...> + - pattern-not-inside: <... $_ != NULL ...> + - pattern-not-inside: <... NULL != $_ ...> + - pattern-not-inside: <... !$_ ...> + - id: 0xdea-raptor-unchecked-ret-scanf + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Other Security + likelihood: MEDIUM + impact: LOW + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-252: Unchecked Return Value' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://codeql.github.com/codeql-query-help/cpp/cpp-missing-check-scanf/ + message: The software does not check the return value from a method or function, which can prevent it + from detecting unexpected states and conditions. + severity: WARNING + patterns: + - pattern: $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: scanf + - pattern: __isoc99_scanf + - pattern: vscanf + - pattern: __isoc99_vscanf + - pattern: fscanf + - pattern: __isoc99_fscanf + - pattern: vfscanf + - pattern: __isoc99_vfscanf + - pattern: sscanf + - pattern: __isoc99_sscanf + - pattern: vsscanf + - pattern: __isoc99_vsscanf + - pattern: wscanf + - pattern: vwscanf + - pattern: fwscanf + - pattern: vfwscanf + - pattern: swscanf + - pattern: vswscanf + - pattern-not-inside: $_ = $FUN(...) + - pattern-not-inside: <... $FUN(...) == $_ ...> + - pattern-not-inside: <... $_ == $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) != $_ ...> + - pattern-not-inside: <... $_ != $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) < $_ ...> + - pattern-not-inside: <... $_ > $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) <= $_ ...> + - pattern-not-inside: <... $_ >= $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) > $_ ...> + - pattern-not-inside: <... $_ < $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) >= $_ ...> + - pattern-not-inside: <... $_ <= $FUN(...) ...> + - pattern-not-inside: return $FUN(...); + - id: 0xdea-raptor-unchecked-ret-setuid-seteuid + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Improper Authorization + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-252: Unchecked Return Value' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://lwn.net/Articles/451985/ + - https://www.usenix.org/legacy/events/sec02/full_papers/chen/chen.pdf + - https://www.openwall.com/lists/oss-security/2023/12/30/4 + message: The software does not check the return value from a method or function, which can prevent it + from detecting unexpected states and conditions. If the program calls a function to drop privileges + but does not check the return code to ensure that privileges were successfully dropped, then the program + will continue to operate with the higher privileges. + severity: WARNING + patterns: + - pattern: $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: setuid + - pattern: seteuid + - pattern-not-inside: $_ = $FUN(...) + - pattern-not-inside: <... $FUN(...) == $_ ...> + - pattern-not-inside: <... $_ == $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) != $_ ...> + - pattern-not-inside: <... $_ != $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) < $_ ...> + - pattern-not-inside: <... $_ > $FUN(...) ...> + - pattern-not-inside: <... !$FUN(...) ...> + - pattern-not-inside: return $FUN(...); + - id: 0xdea-raptor-unsafe-ret-snprintf-vsnprintf + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-131: Incorrect Calculation of Buffer Size' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://lwn.net/Articles/507319/ + - https://g.co/kgs/PCHQjJ + - https://dustri.org/b/playing-with-weggli.html + message: The snprintf() and vsnprintf() functions return the total length of the string they tried to + create. Therefore, this return value can be larger than the size of the destination buffer. If it is + used unsafely, e.g. as an index to write to the destination buffer, memory corruption might occur. + severity: WARNING + patterns: + - pattern-either: + - pattern: $_ = $FUN($_, $_, $FMT, ...) + - pattern: $_ += $FUN($_, $_, $FMT, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: snprintf + - pattern: vsnprintf + - metavariable-regex: + metavariable: $FMT + regex: (".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*) + - id: 0xdea-raptor-unsafe-ret-strlcpy-strlcat + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-131: Incorrect Calculation of Buffer Size' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://lwn.net/Articles/507319/ + - https://g.co/kgs/PCHQjJ + message: The strlcpy() and strlcat() functions return the total length of the string they tried to create. + For strlcpy() that means the length of the source string. For strlcat() that means the initial length + of the destination string plus the length of of the source string. Therefore, this return value can + be larger than the size of the destination buffer. If it is used unsafely, e.g. as an index to write + to the destination buffer, memory corruption might occur. + severity: WARNING + patterns: + - pattern-either: + - pattern: $_ = $FUN(...) + - pattern: $_ += $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strlcpy + - pattern: strlcat + - pattern: wcslcpy + - pattern: wcslcat + - pattern: _mbslcpy + - pattern: _mbslcat + - id: 0xdea-raptor-unsafe-strlen + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Other Security + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-190: Integer Overflow or Wraparound' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://github.com/struct/mms + message: The software performs a calculation that can produce an integer overflow or wraparound, when + the logic assumes that the resulting value will always be larger than the original value. This can introduce + other weaknesses when the calculation is used for resource management or execution control. When influenced + by the size of an input it is often easier to overflow a short than an int. + severity: WARNING + patterns: + - pattern-either: + - pattern: (short $_) = $FUN(...) + - pattern: (short int $_) = $FUN(...) + - pattern: (unsigned short $_) = $FUN(...) + - pattern: (unsigned short int $_) = $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strlen + - pattern: lstrlen + - pattern: strnlen + - pattern: wcslen + - pattern: wcsnlen + - id: 0xdea-raptor-unterminated-string-strncpy + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-170: Improper Null Termination' + - 'CWE-126: Buffer Over-read' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: If there is no NUL character byte in the first n bytes of the source string, strncpy() and stpncpy() + do not NUL-terminate the destination buffer. If the program does not explicitly terminate the destination + buffer, this will almost certainly result in information disclosure, and possibly a buffer overflow + condition. + severity: WARNING + patterns: + - pattern: $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strncpy + - pattern: stpncpy + - pattern: wcsncpy + - pattern: wcpncpy + - pattern: _mbsncpy + - pattern-not-inside: '$FUN($DST, $_, $_); + + ... + + $DST[$_] = NULL; + + ' + - pattern-not-inside: '$FUN($DST, $_, $_); + + ... + + $DST[$_] = ''\0''; + + ' + - pattern-not-inside: '$FUN($DST, $_, $_); + + ... + + $DST[$_] = 0; + + ' + - id: 0xdea-raptor-use-after-free + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-416: Use After Free' + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://github.com/struct/mms + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + message: The use of previously-freed memory can have any number of adverse consequences, ranging from + the corruption of valid data to the execution of arbitrary code, depending on the instantiation and + timing of the flaw. The simplest way data corruption may occur involves the system's reuse of the freed + memory. + severity: ERROR + patterns: + - pattern-either: + - pattern: $PTR->$_ + - pattern: $PTR[$_] + - pattern: (*$PTR) + - pattern: return $PTR; + - patterns: + - pattern-either: + - pattern: $FUN(..., <... $PTR ...>, ...) + - pattern: $PTR->$FUN(...) + - metavariable-pattern: + metavariable: $FUN + patterns: + - pattern-not: free + - pattern-inside: free($PTR); ... + - pattern-not-inside: "free($PTR);\n...\n$PTR = ...; \n...\n" + - id: 0xdea-raptor-use-of-source-size-in-copy + languages: [c, cpp] + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - 'CWE-806: Buffer Access Using Size of Source Buffer' + owasp: + - A06:2025 - Insecure Design + references: + - https://github.com/0xdea/advisories/blob/master/2020-07-solaris-whodo-w.txt + - https://dustri.org/b/playing-with-weggli.html + message: The software uses the size of a source buffer when reading from or writing to a destination buffer, + which may cause it to access memory that is outside of the bounds of the buffer. + severity: ERROR + pattern-either: + - patterns: + - pattern: $FUN($DST, $SRC, $LEN) + - pattern-not: $FUN($DST, "...", $LEN) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strncpy + - pattern: stpncpy + - pattern: strlcpy + - pattern: strscpy + - pattern: memcpy + - pattern: memmove + - pattern: wmemcpy + - pattern: wmemmove + - pattern: mempcpy + - pattern: wmempcpy + - pattern-either: + - patterns: + - pattern-inside: '$_ $SRC[$LEN]; + + ... + + ' + - pattern-not-inside: '$_ $DST[$LEN]; + + ... + + ' + - pattern-not-inside: '$_ $DST[$LEN] = ...; + + ... + + ' + - patterns: + - pattern-inside: '$_ $SRC[$LEN] = ...; + + ... + + ' + - pattern-not-inside: '$_ $DST[$LEN]; + + ... + + ' + - pattern-not-inside: '$_ $DST[$LEN] = ...; + + ... + + ' + - patterns: + - pattern: $FUN($DST, $SRC, <... $SRC ...>) + - pattern-not: $FUN($DST, "...", <... $SRC ...>) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strncpy + - pattern: stpncpy + - pattern: strlcpy + - pattern: strscpy + - pattern: memcpy + - pattern: memmove + - pattern: wmemcpy + - pattern: wmemmove + - pattern: mempcpy + - pattern: wmempcpy + - patterns: + - pattern: $FUN($DST, <... $SRC ...>, ..., $SRC, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: snprintf + - pattern: vsnprintf + - pattern: swprintf + - pattern: vswprintf diff --git a/compliance-agent/rules/vendor/0xdea/rules.json b/compliance-agent/rules/vendor/0xdea/rules.json new file mode 100644 index 0000000..5d2271a --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/rules.json @@ -0,0 +1,281 @@ +[ + { + "id": "0xdea-raptor-command-injection", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-78" + }, + { + "id": "0xdea-raptor-double-free", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-415" + }, + { + "id": "0xdea-raptor-incorrect-order-setuid-setgid", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-696" + }, + { + "id": "0xdea-raptor-incorrect-unsigned-comparison", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-697" + }, + { + "id": "0xdea-raptor-incorrect-use-of-free", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-590" + }, + { + "id": "0xdea-raptor-incorrect-use-of-memset", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-683" + }, + { + "id": "0xdea-raptor-incorrect-use-of-sizeof", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-467" + }, + { + "id": "0xdea-raptor-incorrect-use-of-strncat", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-787" + }, + { + "id": "0xdea-raptor-insecure-api-access-stat", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-367" + }, + { + "id": "0xdea-raptor-insecure-api-alloca", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-676" + }, + { + "id": "0xdea-raptor-insecure-api-ato", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-839" + }, + { + "id": "0xdea-raptor-insecure-api-gets", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-242" + }, + { + "id": "0xdea-raptor-insecure-api-mktemp-tmpnam-tempnam", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-377" + }, + { + "id": "0xdea-raptor-insecure-api-rand-srand", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-338" + }, + { + "id": "0xdea-raptor-insecure-api-scanf", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-676" + }, + { + "id": "0xdea-raptor-insecure-api-signal", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-364" + }, + { + "id": "0xdea-raptor-insecure-api-sprintf-vsprintf", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-676" + }, + { + "id": "0xdea-raptor-insecure-api-strcpy-strcat", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-676" + }, + { + "id": "0xdea-raptor-integer-wraparound", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-190" + }, + { + "id": "0xdea-raptor-memory-address-exposure", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-209" + }, + { + "id": "0xdea-raptor-mismatched-memory-management-cpp", + "languages": [ + "cpp" + ], + "cwe": "CWE-762" + }, + { + "id": "0xdea-raptor-off-by-one", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-193" + }, + { + "id": "0xdea-raptor-overlapping-source-destination", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-1260" + }, + { + "id": "0xdea-raptor-putenv-stack-var", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-686" + }, + { + "id": "0xdea-raptor-regex-dos", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-1333" + }, + { + "id": "0xdea-raptor-ret-stack-address", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-562" + }, + { + "id": "0xdea-raptor-unchecked-ret-malloc", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-252" + }, + { + "id": "0xdea-raptor-unchecked-ret-scanf", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-252" + }, + { + "id": "0xdea-raptor-unchecked-ret-setuid-seteuid", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-252" + }, + { + "id": "0xdea-raptor-unsafe-ret-snprintf-vsnprintf", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-131" + }, + { + "id": "0xdea-raptor-unsafe-ret-strlcpy-strlcat", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-131" + }, + { + "id": "0xdea-raptor-unsafe-strlen", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-190" + }, + { + "id": "0xdea-raptor-unterminated-string-strncpy", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-170" + }, + { + "id": "0xdea-raptor-use-after-free", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-416" + }, + { + "id": "0xdea-raptor-use-of-source-size-in-copy", + "languages": [ + "c", + "cpp" + ], + "cwe": "CWE-806" + } +] diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/argv-envp-access.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/argv-envp-access.c new file mode 100644 index 0000000..ba17054 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/argv-envp-access.c @@ -0,0 +1,28 @@ +// Marco Ivaldi + +#include +#include + +#define CMD_MAX 512 + +int main(int argc, char **argv) +{ + char cmd[CMD_MAX] = "/usr/bin/cat "; + // ruleid: raptor-argv-envp-access + strcat(cmd, argv[1]); + system(cmd); + + return 0; +} + +int main(int c, char **v) +{ + char cmd[CMD_MAX] = "/usr/bin/cat "; + // this should arguably trigger the detection, but it doesn't because the rule is currently extremely + // simple and only looks for "argv" and "envp" as variable names, not for the actual parameters of main() + // todoruleid: raptor-argv-envp-access + strcat(cmd, v[1]); + system(cmd); + + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/argv-envp-access.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/argv-envp-access.yaml new file mode 100644 index 0000000..a2111de --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/argv-envp-access.yaml @@ -0,0 +1,31 @@ +rules: + - id: raptor-argv-envp-access + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Other Security + likelihood: LOW + impact: LOW + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-15: External Control of System or Configuration Setting" + owasp: + - A05:2025 - Injection + references: + - https://www.gnu.org/software/libc/manual/html_node/Program-Arguments.html + message: >- + The program accesses command-line arguments or environment variables, + which are controlled by potential attackers. + severity: INFO + languages: + - c + - cpp + patterns: + - pattern-either: + - pattern: argv + - pattern: envp diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/command-injection.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/command-injection.c new file mode 100644 index 0000000..6292976 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/command-injection.c @@ -0,0 +1,103 @@ +// Marco Ivaldi + +#include +#include +#include + +void invoke1(char *string) +{ + char buf[] = "uname -a; id"; + + // ok: raptor-command-injection + system(buf); + + // ok: raptor-command-injection + system("whoami"); + + // ruleid: raptor-command-injection + system(string); +} + +void invoke2(char *string) +{ + char buf[] = "uname -a; id"; + + // ok: raptor-command-injection + popen(buf, "r"); + + // ok: raptor-command-injection + popen("whoami", "r"); + + // ruleid: raptor-command-injection + popen(string, "r"); +} + +int send_mail(char *user) +{ + char buf[1024]; + FILE *fp; + + snprintf(buf, sizeof(buf), "/usr/bin/sendmail -s \"hi\" %s", user); + + // ruleid: raptor-command-injection + fp = popen(buf, "w"); + + if (fp == NULL) + return 1; + // ... +} + +enum +{ + BUFFERSIZE = 512 +}; + +void test_001(const char *input) +{ + char cmdbuf[BUFFERSIZE]; + int len_wanted = snprintf(cmdbuf, BUFFERSIZE, + "any_cmd '%s'", input); + if (len_wanted >= BUFFERSIZE) + { + /* Handle error */ + } + else if (len_wanted < 0) + { + /* Handle error */ + } + // ruleid: raptor-command-injection + else if (system(cmdbuf) == -1) + { + /* Handle error */ + } +} + +void test_002(const char *input) +{ + char cmdbuf[BUFFERSIZE]; + int len_wanted = snprintf(cmdbuf, BUFFERSIZE, + "any_cmd '%s'", input); + // ruleid: raptor-command-injection + system(cmdbuf); +} + +void test_003(const char *input) +{ + // ok: raptor-command-injection + storer->store_binary(Clocks->system()); +} + +void test_004(const char *input) +{ + // ok: raptor-command-injection + storer->store_binary(Clocks::system()); + + // ok: raptor-command-injection + double passed_server_time = max(Clocks::system() - old_server_time, 0.0); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/command-injection.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/command-injection.yaml new file mode 100644 index 0000000..92183f2 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/command-injection.yaml @@ -0,0 +1,40 @@ +rules: + - id: raptor-command-injection + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Command Injection + likelihood: MEDIUM + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')" + - "CWE-88: Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')" + - "CWE-676: Use of Potentially Dangerous Function" + owasp: + - A05:2025 - Injection + references: + - https://g.co/kgs/PCHQjJ + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: >- + The software constructs an OS command using externally-influenced input, + but it does not neutralize or incorrectly neutralizes special elements + that could modify the intended OS command. + severity: ERROR + languages: + - c + - cpp + # NOTE: add path injection rule for `execlp`, `execvp`, and `execvP`. + # NOTE: add argument injection (e.g., in the `exec` functions family). + patterns: + - pattern-either: + - pattern: system(...) + - pattern: popen(...) + - pattern: p2open(...) + - pattern: wordexp(...) + - pattern-not: $_("...", ...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/double-free.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/double-free.c new file mode 100644 index 0000000..7418f2f --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/double-free.c @@ -0,0 +1,96 @@ +// Marco Ivaldi + +#include +#include + +#define MEMSIZE 256 +#define BUFSIZE1 128 +#define BUFSIZE2 256 + +void alloc_and_free1() +{ + int bailout = 1; + char *ptr = (char *)malloc(MEMSIZE); + + // this should be caught but it isn't, due to a documented limitation in semgrep + // https://semgrep.dev/docs/writing-rules/pattern-syntax/#ellipses-and-statement-blocks + // todoruleid: raptor-double-free + if (bailout) + free(ptr); + + free(ptr); + // ruleid: raptor-double-free + free(ptr); +} + +void alloc_and_free2() +{ + char *ptr = (char *)malloc(MEMSIZE); + + free(ptr); + ptr = NULL; + // ok: raptor-double-free + free(ptr); +} + +void alloc_and_free3() +{ + char *ptr = (char *)malloc(MEMSIZE); + + free(ptr); + ptr = (char *)malloc(MEMSIZE); + // ok: raptor-double-free + free(ptr); +} + +void double_free(int argc, char **argv) +{ + char *buf1R1; + char *buf2R1; + char *buf1R2; + buf1R1 = (char *)malloc(BUFSIZE2); + buf2R1 = (char *)malloc(BUFSIZE2); + free(buf1R1); + free(buf2R1); + buf1R2 = (char *)malloc(BUFSIZE1); + strncpy(buf1R2, argv[1], BUFSIZE1 - 1); + // ruleid: raptor-double-free + free(buf2R1); + free(buf1R2); +} + +Packet *getNextPacket() +{ + // ... + Packet *y = (Packet *)malloc(1024); + retval = waitForPacket(y); + if (retval == OK) + { + return y; + } + else + { + return NULL; + } +} + +int bad() +{ + // ... + free(logData); + pkt = getNextPacket(); + if (!pkt) + { + return NULL; + } + logPktData(pkt); + // ruleid: raptor-double-free + free(logData); + processPacket(pkt); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/double-free.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/double-free.yaml new file mode 100644 index 0000000..6cefafd --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/double-free.yaml @@ -0,0 +1,55 @@ +rules: + - id: raptor-double-free + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-415: Double Free" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://github.com/struct/mms + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + - https://dustri.org/b/playing-with-weggli.html + message: >- + The software calls free() twice on the same memory address, potentially + leading to memory corruption. This corruption can cause the program to + crash or cause two later calls to malloc() to return the same pointer. + severity: ERROR + languages: + - c + - cpp + # NOTE: C++ `delete` and `delete[]` operators and custom wrappers to `free` are not covered. + # NOTE: `realloc` is not covered. + # NOTE: variations on the `free` argument are not covered. + patterns: + - pattern: | + $FREE1($PTR); + ... + $FREE2($PTR); + - pattern-not: | + $FREE1($PTR); + ... + $PTR = ...; + ... + $FREE2($PTR); + - metavariable-pattern: + metavariable: $FREE1 + pattern: free + # more patterns could be added here to cover other ways to free memory + - metavariable-pattern: + metavariable: $FREE2 + pattern: free + # more patterns could be added here to cover other ways to free memory + # improve output readability + - focus-metavariable: $FREE2 diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/format-string-bugs.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/format-string-bugs.c new file mode 100644 index 0000000..c70897d --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/format-string-bugs.c @@ -0,0 +1,108 @@ +// Marco Ivaldi + +#include +#include + +#define BUFSIZE 256 + +void build_string(char *string) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-format-string-bugs + snprintf(buf, BUFSIZE, string); + + // ok: raptor-format-string-bugs + snprintf(buf, BUFSIZE, "%s", string); +} + +void print_stuff(char *string) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-format-string-bugs + printf(string); + + // ok: raptor-format-string-bugs + printf("%s\n", string); +} + +void log_stuff(char *string) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-format-string-bugs + syslog(LOG_ERR, string); + + // ok: raptor-format-string-bugs + syslog(LOG_ERR, "%s", string); +} + +void log_error(char *fmt, ...) +{ + char buf[BUFSIZE]; + va_list ap; + + va_start(ap, fmt); + // ruleid: raptor-format-string-bugs + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + // ruleid: raptor-format-string-bugs + syslog(LOG_NOTICE, buf); +} + +void printWrapper(char *string) +{ + // ruleid: raptor-format-string-bugs + printf(string); +} + +namespace basic_tests +{ + + void test_001() + { + const char *env_001 = getenv("PATH"); + + // ruleid: raptor-format-string-bugs + printf(env_001, 1); + + // ok: raptor-format-string-bugs + printf("%s", env_001); + + // ruleid: raptor-format-string-bugs + scanf(env_001, &d); + } +} + +int test_002(int argc, char **argv) +{ + int d = 0; + // ruleid: raptor-format-string-bugs + scanf(argv[1], &d); +} + +int test_003(int argc, char **argv) +{ + static const size_t n_quads = 300; + + sord_free(NULL); // Shouldn't crash + + SordWorld *world = sord_world_new(); + + // ok: raptor-format-string-bugs + fprintf(stderr, "expected "); + + // ruleid: raptor-format-string-bugs + fprintf(stderr, argv[1]); + + return finished(world, sord, EXIT_SUCCESS); +} + +int main(int argc, char **argv) +{ + char buf[5012]; + memcpy(buf, argv[1], 5012); + printWrapper(argv[1]); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/format-string-bugs.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/format-string-bugs.yaml new file mode 100644 index 0000000..350270e --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/format-string-bugs.yaml @@ -0,0 +1,122 @@ +rules: + - id: raptor-format-string-bugs + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-134: Use of Externally-Controlled Format String" + owasp: + - A05:2025 - Injection + references: + - https://julianor.tripod.com/bc/formatstring-1.2.pdf + - http://phrack.org/issues/70/13.html#article + - https://g.co/kgs/PCHQjJ + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: >- + The software uses a function that accepts a format string as an argument, + but the format string originates from an external source. This can lead + to buffer overflows, denial of service, or data representation problems. + severity: ERROR + languages: + - c + - cpp + # NOTE: generic `va_list` matching for custom wrappers is not covered. + # NOTE: `dprintf` in C++ has a different signature; this rule may cause false positives with it. + # NOTE: `#define` format specifiers are not excluded due to Semgrep limitations; perhaps we could implement this with symbolic propagation (Semgrep Pro experimental feature)? + # NOTE: some obsolete Microsoft-specific functions, such as `_ftprintf`, `_sntprintf`, `_snwprintf`, `_sntscanf`, etc., are not covered. + pattern-either: + # format string in 1st arg + - patterns: + - pattern-either: + # printf family + - pattern: printf(...) + - pattern: vprintf(...) + - pattern: wprintf(...) + - pattern: vwprintf(...) + - pattern: vcprintf(...) + - pattern: vcwprintf(...) + - pattern: vscprintf(...) + - pattern: vscwprintf(...) + - pattern: printk(...) + # scanf family + - pattern: scanf(...) + - pattern: __isoc99_scanf(...) + - pattern: vscanf(...) + - pattern: __isoc99_vscanf(...) + - pattern: wscanf(...) + - pattern: vwscanf(...) + # err/warn family + - pattern: warn(...) + - pattern: vwarn(...) + - pattern: warnx(...) + - pattern: vwarnx(...) + - pattern-not: $_("...", ...) + - pattern-not: $_(gettext(...), ...) + - pattern-not: $_(dgettext(...), ...) + - pattern-not: $_(dcgettext(...), ...) + # format string in 2nd arg + - patterns: + - pattern-either: + # printf family + - pattern: fprintf(...) + - pattern: vfprintf(...) + - pattern: fwprintf(...) + - pattern: vfwprintf(...) + - pattern: sprintf(...) + - pattern: vsprintf(...) + - pattern: asprintf(...) + - pattern: vasprintf(...) + - pattern: dprintf(...) + - pattern: vdprintf(...) + - pattern: wsprintf(...) + # scanf family + - pattern: fscanf(...) + - pattern: __isoc99_fscanf(...) + - pattern: vfscanf(...) + - pattern: __isoc99_vfscanf(...) + - pattern: fwscanf(...) + - pattern: vfwscanf(...) + - pattern: sscanf(...) + - pattern: __isoc99_sscanf(...) + - pattern: vsscanf(...) + - pattern: __isoc99_vsscanf(...) + - pattern: swscanf(...) + - pattern: vswscanf(...) + # syslog family + - pattern: syslog(...) + - pattern: vsyslog(...) + # err/warn family + - pattern: err(...) + - pattern: verr(...) + - pattern: errx(...) + - pattern: verrx(...) + - pattern: warnc(...) + - pattern: vwarnc(...) + - pattern-not: $_($_, "...", ...) + - pattern-not: $_($_, gettext(...), ...) + - pattern-not: $_($_, dgettext(...), ...) + - pattern-not: $_($_, dcgettext(...), ...) + # format string in 3rd arg + - patterns: + - pattern-either: + # printf family + - pattern: snprintf(...) + - pattern: vsnprintf(...) + - pattern: swprintf(...) + - pattern: vswprintf(...) + # err/warn family + - pattern: errc(...) + - pattern: verrc(...) + - pattern-not: $_($_, $_, "...", ...) + - pattern-not: $_($_, $_, gettext(...), ...) + - pattern-not: $_($_, $_, dgettext(...), ...) + - pattern-not: $_($_, $_, dcgettext(...), ...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/high-entropy-assignment.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/high-entropy-assignment.c new file mode 100644 index 0000000..dc386bd --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/high-entropy-assignment.c @@ -0,0 +1,20 @@ +// Marco Ivaldi + +int hush_hush() +{ + // ruleid: raptor-high-entropy-assignment + char *secret = "d3a447630194bd4b"; + + // ok: raptor-high-entropy-assignment + char *public = "Hello, world!"; + + // ... + + return 0; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/high-entropy-assignment.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/high-entropy-assignment.yaml new file mode 100644 index 0000000..c04242f --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/high-entropy-assignment.yaml @@ -0,0 +1,34 @@ +rules: + - id: raptor-high-entropy-assignment + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Hard-coded Secrets + likelihood: LOW + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-540: Inclusion of Sensitive Information in Source Code" + owasp: + - A06:2025 - Insecure Design + references: + - https://semgrep.dev/docs/writing-rules/metavariable-analysis + - https://github.com/semgrep/semgrep/pull/4672 + message: >- + Entropy, or randomness, is a common approach for detecting secret + strings. If an assignment has high entropy, it might involve a + secret that should not be accessible to users. + severity: INFO + languages: + - c + - cpp + patterns: + - pattern: $_ = "$X" + - metavariable-analysis: + analyzer: entropy + metavariable: $X diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-order-setuid-setgid.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-order-setuid-setgid.c new file mode 100644 index 0000000..659be0d --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-order-setuid-setgid.c @@ -0,0 +1,101 @@ +// Marco Ivaldi + +#include +#include + +void drop_priv_bad() +{ + // ruleid: raptor-incorrect-order-setuid-setgid + setuid(getuid()); + setgid(getgid()); +} + +void drop_priv_ok() +{ + // ok: raptor-incorrect-order-setuid-setgid + setgid(getgid()); + setuid(getuid()); +} + +void bad1() +{ + // ruleid: raptor-incorrect-order-setuid-setgid + seteuid(getuid()); + // ... + setuid(getuid()); +} + +void good1() +{ + // ok: raptor-incorrect-order-setuid-setgid + seteuid(getuid()); + // ... + seteuid(0); + // ... + setuid(getuid()); +} + +void bad2() +{ + int user1 = 500, user2 = 501; + + /* become user1 */ + // ruleid: raptor-incorrect-order-setuid-setgid + seteuid(user1); + process_log1(); + /* become user2 */ + seteuid(user2); + process_log2(); + /* become root again */ + seteuid(0); +} + +void good2() +{ + int user1 = 500, user2 = 501; + + /* become user1 */ + // ok: raptor-incorrect-order-setuid-setgid + seteuid(user1); + process_log1(); + /* become user2 */ + seteuid(0); + seteuid(user2); + process_log2(); + /* become root again */ + seteuid(0); +} + +void drop_priv_conditional_bad(int uid, int gid) +{ + // ruleid: raptor-incorrect-order-setuid-setgid + if (uid != -1 && setuid(uid)) + { + fprintf(stderr, "Failed to set uid\n"); + } + + if (gid != -1) + { + setgid(gid); + } +} + +void drop_priv_conditional_ok(int uid, int gid) +{ + // ok: raptor-incorrect-order-setuid-setgid + if (gid != -1 && setgid(gid)) + { + fprintf(stderr, "Failed to set gid\n"); + } + + if (uid != -1) + { + setuid(uid); + } +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-order-setuid-setgid.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-order-setuid-setgid.yaml new file mode 100644 index 0000000..28a1f8d --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-order-setuid-setgid.yaml @@ -0,0 +1,94 @@ +rules: + - id: raptor-incorrect-order-setuid-setgid + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Improper Authorization + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-696: Incorrect Behavior Order" + owasp: + - A01:2025 - Broken Access Control + references: + - https://www.usenix.org/legacy/events/sec02/full_papers/chen/chen.pdf + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + message: >- + A compromised process might be able to regain elevated group privileges + if set(e)gid() is called after set(e)uid(). A similar case is when + privileges are temporarily dropped with seteuid() and then setuid() or + seteuid() are called from while under unprivileged user. + severity: ERROR + languages: + - c + - cpp + pattern-either: + # setuid/setgid + - patterns: + - pattern: | + <... setuid(...) ...>; + ... + <... setgid(...) ...>; + - pattern-not: | + <... setuid(0) ...>; + ... + <... setgid(...) ...>; + # seteuid/setegid + - patterns: + - pattern: | + <... seteuid(...) ...>; + ... + <... setegid(...) ...>; + - pattern-not: | + <... seteuid(0) ...>; + ... + <... setegid(...) ...>; + - pattern-not-inside: | + <... seteuid(...) ...>; + ... + <... seteuid(0) ...>; + ... + <... setegid(...) ...>; + # seteuid/setuid + - patterns: + - pattern: | + <... seteuid(...) ...>; + ... + <... setuid(...) ...>; + - pattern-not: | + <... seteuid(0) ...>; + ... + <... setuid(...) ...>; + - pattern-not-inside: | + <... seteuid(...) ...>; + ... + <... seteuid(0) ...>; + ... + <... setuid(...) ...>; + # seteuid/seteuid + - patterns: + - pattern: | + <... seteuid(...) ...>; + ... + <... seteuid(...) ...>; + - pattern-not: | + <... seteuid(0) ...>; + ... + <... seteuid(...) ...>; + - pattern-not: | + <... seteuid(...) ...>; + ... + <... seteuid(0) ...>; + - pattern-not-inside: | + <... seteuid(...) ...>; + ... + <... seteuid(0) ...>; + ... + <... seteuid(...) ...>; diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-unsigned-comparison.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-unsigned-comparison.c new file mode 100644 index 0000000..9666e37 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-unsigned-comparison.c @@ -0,0 +1,42 @@ +// Marco Ivaldi + +#include + +int bad1() +{ + size_t uvar; + + // ruleid: raptor-incorrect-unsigned-comparison + if (uvar < 0) + return 1; + + return 0; +} + +int bad2() +{ + size_t uvar; + + // ruleid: raptor-incorrect-unsigned-comparison + if (uvar <= 0) + return 1; + + return 0; +} + +int good1() +{ + size_t uvar; + + // ok: raptor-incorrect-unsigned-comparison + if (uvar > 0) + return 1; + + return 0; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-unsigned-comparison.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-unsigned-comparison.yaml new file mode 100644 index 0000000..549c7e8 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-unsigned-comparison.yaml @@ -0,0 +1,52 @@ +rules: + - id: raptor-incorrect-unsigned-comparison + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Improper Validation + likelihood: LOW + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-697: Incorrect Comparison" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: >- + Checking if an unsigned variable is negative makes no sense and is + usually a good indication that something is probably wrong with the + code. + severity: WARNING + languages: + - c + - cpp + # NOTE: some types are not covered. + # NOTE: incorrect unsigned assigments are not covered. + pattern-either: + # < (always false) + - pattern: (unsigned short $_) < 0 + - pattern: (unsigned short int $_) < 0 + - pattern: (unsigned int $_) < 0 + - pattern: (unsigned long $_) < 0 + - pattern: (unsigned long int $_) < 0 + - pattern: (size_t $_) < 0 + # <= + - pattern: (unsigned short $_) <= 0 + - pattern: (unsigned short int $_) <= 0 + - pattern: (unsigned int $_) <= 0 + - pattern: (unsigned long $_) <= 0 + - pattern: (unsigned long int $_) <= 0 + - pattern: (size_t $_) <= 0 + # >= (always true) + - pattern: (unsigned short $_) >= 0 + - pattern: (unsigned short int $_) >= 0 + - pattern: (unsigned int $_) >= 0 + - pattern: (unsigned long $_) >= 0 + - pattern: (unsigned long int $_) >= 0 + - pattern: (size_t $_) >= 0 diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-free.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-free.c new file mode 100644 index 0000000..55ccd31 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-free.c @@ -0,0 +1,55 @@ +// Marco Ivaldi + +#include +#include + +#define SIZE 256 + +void wrong() +{ + record_t bar[MAX_SIZE]; + + /* do something interesting with bar */ + + // ruleid: raptor-incorrect-use-of-free + free(bar); +} + +void right() +{ + record_t *bar = (record_t *)malloc(MAX_SIZE * sizeof(record_t)); + + /* do something interesting with bar */ + + // ok: raptor-incorrect-use-of-free + free(bar); +} + +int check_auth(char *login, char *passwd) +{ + char *cpass; + char *message; + int i = 0; + int stat = STATUS_INVALID; + struct passwd *pwd; + + if ((pwd = getpwnam(login)) == NULL) + return (STATUS_UNKNOWN); + hisuid = pwd->pw_uid; + haveuid = 1; + if (hisuid < MIN_UNIX_UID) + return (STATUS_BLOCKED); + if (authenticate(login, passwd, &i, &message) == 0) + { + stat = STATUS_OK; + } + // ruleid: raptor-incorrect-use-of-free + free(&message); + return (stat); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-free.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-free.yaml new file mode 100644 index 0000000..a87f0a4 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-free.yaml @@ -0,0 +1,86 @@ +rules: + - id: raptor-incorrect-use-of-free + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-590: Free of Memory not on the Heap" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_spirit.c + message: >- + The software calls free() on a pointer to memory that has a short + lifetime and was not allocated using associated heap allocation + functions such as malloc(), calloc(), or realloc(). + severity: ERROR + languages: + - c + - cpp + # NOTE: this rule only covers `free` called on stack-allocated buffers (and possibly static variables); it does not cover other instances of `free` called on non-heap-allocated buffers; it also does not cover `alloca` and custom wrappers to `free`. + # NOTE: multi-dimensional arrays and other ways to create an array are not covered. + # NOTE: refer also to `raptor-mismatched-memory-management.yaml`. + pattern-either: + - patterns: + - pattern: free($PTR) + - pattern-either: + # array + - pattern-inside: | + $_ $PTR[$_]; + ... + - pattern-inside: | + $_ $PTR[$_] = ...; + ... + - pattern-inside: | + $_ $PTR[] = ...; + ... + # pointer to array + - pattern-inside: | + $_ $ARR[$_]; + ... + $PTR = $ARR; + ... + - pattern-inside: | + $_ $ARR[$_] = ...; + ... + $PTR = $ARR; + ... + - pattern-inside: | + $_ $ARR[] = ...; + ... + $PTR = $ARR; + ... + - patterns: + # address of local variable + - pattern: free(&$VAR) + - pattern-either: + - pattern-inside: | + $_ $VAR; + ... + - pattern-inside: | + $_ $VAR = ...; + ... + - pattern-inside: | + $_ $VAR[$_]; + ... + - pattern-inside: | + $_ $VAR[$_] = ...; + ... + - pattern-inside: | + $_ $VAR[] = ...; + ... + - pattern-inside: | + $_ * $VAR; + ... + - pattern-inside: | + $_ * $VAR = ...; + ... diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-memset.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-memset.c new file mode 100644 index 0000000..e37623d --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-memset.c @@ -0,0 +1,55 @@ +// Marco Ivaldi + +#include +#include + +#define SIZE 256 + +int test1() +{ + char buf[1024]; + + // ruleid: raptor-incorrect-use-of-memset + memset(buf, sizeof(buf), 0); + + // ruleid: raptor-incorrect-use-of-memset + memset(buf, sizeof(buf), 'A'); + + // ok: raptor-incorrect-use-of-memset + memset(buf, 0, sizeof(buf)); + + return 0; +} + +int test2() +{ + char buf[SIZE]; + + // ruleid: raptor-incorrect-use-of-memset + memset(buf, SIZE, 0); + + // ok: raptor-incorrect-use-of-memset + memset(buf, 0, SIZE); + + return 0; +} + +void test3() +{ + // ... + if (!StartServiceCtrlDispatcher(steDispatchTable)) + { + char szString[1024]; + + // ruleid: raptor-incorrect-use-of-memset + memset(szString, sizeof(szString), '\0'); + SvcFormatMessage(szString, sizeof(szString)); + SvcDebugOut(szString, 0); + } +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-memset.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-memset.yaml new file mode 100644 index 0000000..5467115 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-memset.yaml @@ -0,0 +1,37 @@ +rules: + - id: raptor-incorrect-use-of-memset + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Mishandled Sensitive Information + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-683: Function Call With Incorrect Order of Arguments" + owasp: + - A04:2025 - Cryptographic Failures + references: + - https://lkml.org/lkml/2009/11/11/336 + - https://bugs.mysql.com/bug.php?id=23181 + message: >- + The invocation of memset() is easy to get wrong. The second argument + is the character and the third argument is the size, but sometimes + these arguments are in the wrong order. This results in a no-op. + severity: ERROR + languages: + - c + - cpp + # NOTE: refer also to `c.lang.security.insecure-use-memset.insecure-use-memset` and `cpp.lang.correctness.memset-removal.memset-removal` for a different potential flaw involving `memset` optimization. + pattern-either: + - pattern: memset($_, $_, 0) + - pattern: memset($_, $_, '\0') + - pattern: memset($_, sizeof(...), $_) + - pattern: memset_explicit($_, $_, 0) + - pattern: memset_explicit($_, $_, '\0') + - pattern: memset_explicit($_, sizeof(...), $_) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.c new file mode 100644 index 0000000..7711ea7 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.c @@ -0,0 +1,184 @@ +// Marco Ivaldi + +#include +#include +#include +#include + +void bad1() +{ + double *foo; + + // ruleid: raptor-incorrect-use-of-sizeof + foo = (double *)malloc(sizeof(foo)); +} + +void good1() +{ + double *foo; + + // ok: raptor-incorrect-use-of-sizeof + foo = (double *)malloc(sizeof(*foo)); +} + +void bad2(char *buf) +{ + size_t size; + + // ruleid: raptor-incorrect-use-of-sizeof + size = sizeof(buf); +} + +void good2() +{ + char buf[256]; + size_t size; + + // ok: raptor-incorrect-use-of-sizeof + size = sizeof(buf); +} + +void bad3() +{ + AnObj *o = (AnObj *)malloc(sizeof(AnObj)); + // ruleid: raptor-incorrect-use-of-sizeof + memset(o, 0x0, sizeof(o)); +} + +char *read_username(int sockfd) +{ + char *buffer, *style, userstring[1024]; + int i; + + buffer = (char *)malloc(1024); + + if (!buffer) + { + error("buffer allocation failed: %m"); + return NULL; + } + + if (read(sockfd, userstring, sizeof(userstring) - 1) <= 0) + { + free(buffer); + error("read failure: %m"); + return NULL; + } + userstring[sizeof(userstring) - 1] = '\0'; + style = strchr(userstring, ':'); + + if (style) + *style++ = '\0'; + sprintf(buffer, "username=%.32s", userstring); + + if (style) + // ruleid: raptor-incorrect-use-of-sizeof + snprintf(buffer, sizeof(buffer) - strlen(buffer) - 1, ", style=%s\n", style); + + return buffer; +} + +char *username = "admin"; +char *pass = "password"; + +int AuthenticateUser(char *inUser, char *inPass) +{ + // ruleid: raptor-incorrect-use-of-sizeof + printf("Sizeof username = %d\n", sizeof(username)); + // ruleid: raptor-incorrect-use-of-sizeof + printf("Sizeof pass = %d\n", sizeof(pass)); + + // ruleid: raptor-incorrect-use-of-sizeof + if (strncmp(username, inUser, sizeof(username))) + { + printf("Auth failure of username using sizeof\n"); + return (AUTH_FAIL); + } + + // ruleid: raptor-incorrect-use-of-sizeof + if (!strncmp(pass, inPass, sizeof(pass))) + { + printf("Auth success of password using sizeof\n"); + return (AUTH_SUCCESS); + } + else + { + printf("Auth fail of password using sizeof\n"); + return (AUTH_FAIL); + } +} + +// https://github.com/openresty/memc-nginx-module/commit/1e5e8655b3783d29dec1a9941bb6571989cf7dbb +ngx_int_t +ngx_http_memc_create_incr_decr_cmd_request(ngx_http_request_t *r) +{ + size_t len; + ngx_buf_t *b; + ngx_http_memc_ctx_t *ctx; + ngx_chain_t *cl; + uintptr_t escape; + ngx_http_variable_value_t *key_vv; + ngx_http_variable_value_t *value_vv; + + ctx = ngx_http_get_module_ctx(r, ngx_http_memc_module); + + /* prepare the "key" argument */ + + key_vv = ctx->memc_key_vv; + + if (key_vv == NULL || key_vv->not_found || key_vv->len == 0) + { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "the \"$memc_key\" variable is not set"); + return NGX_ERROR; + } + + escape = 2 * ngx_escape_uri(NULL, key_vv->data, key_vv->len, + NGX_ESCAPE_MEMCACHED); + + /* prepare the "value" argument */ + + value_vv = ctx->memc_value_vv; + + /* XXX validate if $memc_value_vv is a valid uint64 string */ + // this should be caught but it isn't, due to a known issue in semgrep + // https://github.com/semgrep/semgrep/issues/11327 + // todoruleid: raptor-incorrect-use-of-sizeof + len = ctx->cmd_str.len + sizeof(' ') + key_vv->len + escape + sizeof(' ') + value_vv->len + sizeof(CRLF) - 1; + + b = ngx_create_temp_buf(r->pool, len); + if (b == NULL) + { + return NGX_ERROR; + } + + cl = ngx_alloc_chain_link(r->pool); + if (cl == NULL) + { + return NGX_ERROR; + } + + // ... + + return NGX_OK; +} + +int main(int argc, char **argv) +{ + int authResult; + + if (argc < 3) + { + ExitError("Usage: Provide a username and password"); + } + authResult = AuthenticateUser(argv[1], argv[2]); + if (authResult != AUTH_SUCCESS) + { + ExitError("Authentication failed"); + } + else + { + DoAuthenticatedTask(argv[1]); + } + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.cpp b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.cpp new file mode 100644 index 0000000..0e04e13 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.cpp @@ -0,0 +1,121 @@ +// Marco Ivaldi + +#include +#include +#include + +struct Foo +{ + uint64_t a; + uint8_t b; + + size_t get_size() const + { + // ruleid: raptor-incorrect-use-of-sizeof + return sizeof(this); + } + + size_t get_size() const + { + // ok: raptor-incorrect-use-of-sizeof + return sizeof(*this); + } +}; + +void test_001_fn(int arr[]) +{ + // ruleid: raptor-incorrect-use-of-sizeof + for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) + { + arr[i] = 0; + } + + // ruleid: raptor-incorrect-use-of-sizeof + for (size_t i = 0; i < sizeof(arr) / 2; ++i) + { + arr[i] = 0; + } + + // ruleid: raptor-incorrect-use-of-sizeof + for (size_t i = 0; i < 3 * sizeof(arr); ++i) + { + arr[i] = 0; + } +} + +void test_001(int arr[]) +{ + // ruleid: raptor-incorrect-use-of-sizeof + for (size_t i = 0; i < sizeof(arr); ++i) + { + arr[i] = 0; + } +} + +void test_002() +{ + const FooType *foo_ptr = get_foo(); + + // ruleid: raptor-incorrect-use-of-sizeof + std::cout << sizeof(foo_ptr); + + // ruleid: raptor-incorrect-use-of-sizeof + std::cout << sizeof(foo_ptr + 0); + + // ruleid: raptor-incorrect-use-of-sizeof + std::cout << sizeof(0 + foo_ptr); + + // ruleid: raptor-incorrect-use-of-sizeof + std::cout << (sizeof(foo_ptr) / sizeof(foo_ptr[0])); + + // ok: raptor-incorrect-use-of-sizeof + std::cout << sizeof(*foo_ptr); +} + +void test_002_pad() +{ + int a = 1; + const FooType *foo_ptr = get_foo(); + + // ruleid: raptor-incorrect-use-of-sizeof + std::cout << sizeof(foo_ptr); + + // ruleid: raptor-incorrect-use-of-sizeof + std::cout << (sizeof(foo_ptr) / sizeof(foo_ptr[0])); + + // ok: raptor-incorrect-use-of-sizeof + std::cout << sizeof(*foo_ptr); +} + +void test_002_atofat() +{ + int a = 1; + const FooType **foo_ptr = get_foo(); + + // ok: raptor-incorrect-use-of-sizeof + std::cout << sizeof(*foo_ptr); + + // ok: raptor-incorrect-use-of-sizeof + std::cout << (sizeof(*foo_ptr) / sizeof(foo_ptr[0])); + + // ok: raptor-incorrect-use-of-sizeof + std::cout << sizeof(**foo_ptr); +} + +void test_003(void *foo, int *int_ptr) +{ + // ruleid: raptor-incorrect-use-of-sizeof + std::cout << sizeof(int_ptr); + + // ruleid: raptor-incorrect-use-of-sizeof + std::cout << (sizeof(int_ptr) / sizeof(int_ptr[0])); + + // ok: raptor-incorrect-use-of-sizeof + std::cout << sizeof(*int_ptr); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.yaml new file mode 100644 index 0000000..1e7b26f --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-sizeof.yaml @@ -0,0 +1,78 @@ +rules: + - id: raptor-incorrect-use-of-sizeof + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-467: Use of sizeof() on a Pointer Type" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + - https://dustri.org/b/playing-with-weggli.html + - https://mastodon.gamedev.place/@amonakov/111577826195014479 + - https://github.com/semgrep/semgrep/issues/11327 + message: >- + The code calls sizeof() on a pointer type, which always returns + the wordsize (8 on 64-bit architectures). This can produce an + unexpected result if the programmer intended to determine how + much memory has been allocated. + severity: WARNING + languages: + - c + - cpp + # NOTE: another relevant pattern would be `sizeof('...')`, but unfortunately that's currently not supported by Semgrep. + pattern-either: + # type-based patterns (some types are missing) + - patterns: + - pattern: sizeof((char * $_)) + - pattern-not: sizeof("...") + # NOTE: sizeof of character literals is still not supported by Semgrep as of 2025-11-22 + # - pattern: sizeof('...') + - pattern: sizeof((int * $_)) + - pattern: sizeof((float * $_)) + - pattern: sizeof((double * $_)) + # other patterns + - patterns: + - pattern-either: + - pattern: sizeof($PTR) + - pattern: sizeof($PTR + $_) + - pattern: sizeof($_ + $PTR) + - pattern-either: + - pattern-inside: | + $_ * $PTR; + ... + - pattern-inside: | + $_ * $PTR = ...; + ... + # function calls + - patterns: + - pattern-either: + - pattern: sizeof($PTR) + - pattern: sizeof($PTR + $_) + - pattern: sizeof($_ + $PTR) + - pattern-either: + - pattern-inside: | + $_ $_(..., $_ * $PTR, ...) { + ... + } + - pattern-inside: | + $_ $_(..., $_ $PTR[$_], ...) { + ... + } + - pattern-inside: | + $_ $_(..., $_ $PTR[], ...) { + ... + } + # c++ `this` pattern + - pattern: sizeof(this) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-strncat.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-strncat.c new file mode 100644 index 0000000..6ea4656 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-strncat.c @@ -0,0 +1,62 @@ +// Marco Ivaldi + +#include +#include + +int copy_data(char *username) +{ + char buf[1024]; + + strcpy(buf, "username is: "); + // ruleid: raptor-incorrect-use-of-strncat + strncat(buf, username, sizeof(buf)); + + log("%s\n", buf); + + return 0; +} + +int copy_data2(char *username) +{ + char buf[1024]; + + strcpy(buf, "username is: "); + // ruleid: raptor-incorrect-use-of-strncat + strncat(buf, username, 1024); + + log("%s\n", buf); + + return 0; +} + +int copy_data3(char *username) +{ + char buf[1024]; + + strcpy(buf, "username is: "); + // ruleid: raptor-incorrect-use-of-strncat + strncat(buf, username, sizeof(buf) - strlen(buf)); + + log("%s\n", buf); + + return 0; +} + +int good(char *username) +{ + char buf[1024]; + + strcpy(buf, "username is: "); + // ok: raptor-incorrect-use-of-strncat + strncat(buf, username, sizeof(buf) - strlen(buf) - 1); + + log("%s\n", buf); + + return 0; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-strncat.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-strncat.yaml new file mode 100644 index 0000000..478ddf0 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/incorrect-use-of-strncat.yaml @@ -0,0 +1,50 @@ +rules: + - id: raptor-incorrect-use-of-strncat + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-787: Out-of-bounds Write" + - "CWE-193: Off-by-one Error" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: >- + The strncat() function is nearly as dangerous as strcat(), in that it's + quite easy to misuse. The first common mistake is supplying the size of + the entire buffer instead of the size remaining in the buffer. A more + subtle mistake can be made: the size parameter needs to be the amount of + space left in the buffer less one; otherwise, the NUL byte is written + one byte past the end of the buffer. + severity: ERROR + languages: + - c + - cpp + pattern-either: + # size of array + - patterns: + - pattern: strncat($DST, $_, $LEN) + - pattern-either: + - pattern-inside: | + $_ $DST[$LEN]; + ... + - pattern-inside: | + $_ $DST[$LEN] = ...; + ... + # sizeof operator + - pattern: strncat($DST, $_, sizeof($DST)) + # strlen function + - pattern: strncat($DST, $_, strlen($DST)) + # off-by-one + # see also off-by-one.yaml for a slightly different pattern + - pattern: strncat($DST, $_, sizeof($DST) - strlen($DST)) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-access-stat.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-access-stat.c new file mode 100644 index 0000000..836b1dd --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-access-stat.c @@ -0,0 +1,150 @@ +// Marco Ivaldi + +#include +#include +#include +#include +#include + +#define MEMSIZE 256 + +void bad1() +{ + // ruleid: raptor-insecure-api-access-stat + int res = access("/tmp/userfile", R_OK); + if (res != 0) + die("access"); + + int fd = open("/tmp/userfile", O_RDONLY); + // ... +} + +void bad2(char *file) +{ + struct stat statb; + int fd; + + errno = 0; + + // ruleid: raptor-insecure-api-access-stat + if (lstat(file, &statb) < 0) + goto out; + + if (!(statb.st_mode & S_IFREG) || statb.st_mode & 077) + goto out; + if ((fd = open(file, O_RDWR | O_SYNC, 0)) < 0) + goto out; +} + +void bad3(char *fname) +{ + struct stat stbl; + int fd = open(fname, O_RDONLY); + + if (fd == -1) + perror("open"); + // ruleid: raptor-insecure-api-access-stat + if (lstat(fname, &stbl) != 0) + die("file not there"); + if (!S_ISREG(stbl.st_mode)) + die("its a symlink"); + // ... +} + +void test_001() +{ + const char *original_key = "path/to/file/filename"; + const char *mirror_key = "path/to/another/file/filename"; + + // ruleid: raptor-insecure-api-access-stat + if ((access(original_key, F_OK) == 0) && (access(mirror_key, F_OK) == 0)) + { + copy_file("/bin/cp %s %s", original_key, mirror_key); + + unlink(original_key); + } +} + +void test_002() +{ + const char *original_key = "path/to/file/filename"; + + // ruleid: raptor-insecure-api-access-stat + if (access(original_key, W_OK) == 0) + { + FILE *fp = fopen(original_key, "wb"); + } +} + +void test_001_stack_overflow() +{ + struct stat buf; + FILE *fp; + char data[2560]; + + // ruleid: raptor-insecure-api-access-stat + if (stat(file.c_str(), &buf) == 0) + { + + // Open the file for reading + fp = fopen(file.c_str(), "r"); + if (fp == NULL) + { + char message[2560]; + sprintf(message, "File '%s' Cound Not be Opened", file.c_str()); + // DISPLAY_MSG_ERROR( this, message, "GetFileContents", "System" ); + throw message; + } + + // Read the file + MvString s, ss; + while (fgets(data, sizeof(data), fp) != (char *)0) + { + s = data; + s.trimBoth(); + if (s.compare(0, 5, "GROUP") == 0) + { + // size_t t = s.find_last_of( ":" ); + size_t t = s.find(":"); + if (t != string::npos) + { + ss = s.substr(t + 1).c_str(); + ss.trimBoth(); + ss = ss.substr(1, ss.length() - 3).c_str(); + group_list.push_back(ss); + } + } + } + + // Close the file + fclose(fp); + } +} + +void ok() +{ + int fd = open("file.txt", O_RDONLY); + if (fd == -1) + { + perror("open"); + return -1; + } + + struct stat st; + // ok: raptor-insecure-api-access-stat + if (fstat(fd, &st) == -1) + { + perror("fstat"); + close(fd); + return -1; + } + + // Now safely use st.st_mode, st.st_size, etc. on the already-open fd + // ... +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-access-stat.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-access-stat.yaml new file mode 100644 index 0000000..092204a --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-access-stat.yaml @@ -0,0 +1,39 @@ +rules: + - id: raptor-insecure-api-access-stat + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Dangerous Method or Function + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://labs.snyk.io/resources/leaky-vessels-container-vuln-deep-dive/ + message: >- + The software checks the state of a resource before using it, but the + resource's state can change between the check and the use in a way that + invalidates the results of the check. This can cause the software to + perform invalid actions when the resource is in an unexpected state. + severity: WARNING + languages: + - c + - cpp + # NOTE: `_stat` and `_lstat` are not covered. + # NOTE: refer also to `cpp.lang.security.filesystem.*` for stricter check/action patterns. + pattern-either: + - pattern: access(...) + - pattern: faccessat(...) + - pattern: faccessat2(...) + - pattern: stat(...) + - pattern: lstat(...) + - pattern: fstatat(...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-alloca.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-alloca.c new file mode 100644 index 0000000..924fa56 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-alloca.c @@ -0,0 +1,42 @@ +// Marco Ivaldi + +#include +#include + +#define MEMSIZE 256 + +void allocate_memory1() +{ + // ruleid: raptor-insecure-api-alloca + char *buf = alloca(MEMSIZE); + + // ... +} + +void allocate_memory2() +{ + // ok: raptor-insecure-api-alloca + char *buf = malloc(MEMSIZE); + + // ... +} + +void allocate_memory2() +{ + int end_limit = get_nmbr_obj_from_db(); + int i; + int *base = NULL; + int *p = base; + for (i = 0; i < end_limit; i++) + { + // ruleid: raptor-insecure-api-alloca + *p = alloca(sizeof(int *)); + p = *p; + } +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-alloca.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-alloca.yaml new file mode 100644 index 0000000..c994acb --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-alloca.yaml @@ -0,0 +1,32 @@ +rules: + - id: raptor-insecure-api-alloca + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: MEDIUM + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-676: Use of Potentially Dangerous Function" + - "CWE-1325: Improperly Controlled Sequential Memory Allocation" + owasp: + - A06:2025 - Insecure Design + references: + - https://nullprogram.com/blog/2019/10/28/ + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + message: >- + Use of alloca() is unsafe because it cannot ensure that the pointer + returned points to a valid and usable block of memory. The allocation + made may exceed the bounds of the stack, or even go further into other + objects in memory, and alloca() cannot determine such an error. + severity: ERROR + languages: + - c + - cpp + pattern: alloca(...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-ato.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-ato.c new file mode 100644 index 0000000..0c4e25f --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-ato.c @@ -0,0 +1,22 @@ +// Marco Ivaldi + +#include +#include + +int converter_bad(const char *numstr) +{ + // ruleid: raptor-insecure-api-ato + return atoi(numstr); +} + +int converter_good(const char *numstr) +{ + // ok: raptor-insecure-api-ato + return strtol(numstr, NULL, 10); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-ato.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-ato.yaml new file mode 100644 index 0000000..a7f9e64 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-ato.yaml @@ -0,0 +1,39 @@ +rules: + - id: raptor-insecure-api-ato + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Dangerous Method or Function + likelihood: LOW + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-839: Numeric Range Comparison Without Minimum Check" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://rules.sonarsource.com/c/type/Bug/RSPEC-989 + - https://wiki.sei.cmu.edu/confluence/display/c/ERR34-C.+Detect+errors+when+converting+a+string+to+a+number + - https://github.com/vixie/cron/commit/9cc8ab1087bb9ab861dd5595c41200683c9f6712 + message: >- + The atoi(), atol(), atof(), and similar functions don't handle errors. + They don't check for integer overflow and can return a negative value. + They have undefined behavior if the value of the result cannot be + represented. They return 0 (or 0.0) if the string does not represent + an integer (or decimal), which is indistinguishable from a correctly + formatted, zero-denoting input string. + severity: INFO + languages: + - c + - cpp + # NOTE: some function variants are missing. + pattern-either: + - pattern: atoi(...) + - pattern: atol(...) + - pattern: atof(...) + - pattern: atoll(...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-gets.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-gets.c new file mode 100644 index 0000000..2de55a2 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-gets.c @@ -0,0 +1,43 @@ +// Marco Ivaldi + +#include + +#define BUFSIZE 256 + +void get_string() +{ + char buf[BUFSIZE]; + + // ruleid: raptor-insecure-api-gets + gets(buf); +} + +void test_001() +{ + char buf[BUFFER_SIZE]; + // ruleid: raptor-insecure-api-gets + if (gets(buf) == NULL) + { + // ... + } +} + +void foo() +{ + char buf[64]; + // ruleid: raptor-insecure-api-gets + gets(buf); +} + +void foo() +{ + char buf[64]; + // ok: raptor-insecure-api-gets + fgets(buf, 63, stdin); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-gets.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-gets.yaml new file mode 100644 index 0000000..4f67b55 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-gets.yaml @@ -0,0 +1,30 @@ +rules: + - id: raptor-insecure-api-gets + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: HIGH + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-242: Use of Inherently Dangerous Function" + - "CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: >- + The gets() function is always unsafe because it does not perform bounds + checking on the size of its input. An attacker can easily send + arbitrarily-sized input to gets() and overflow the destination buffer. + severity: ERROR + languages: + - c + - cpp + pattern: gets(...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-mktemp-tmpnam-tempnam.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-mktemp-tmpnam-tempnam.c new file mode 100644 index 0000000..1908748 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-mktemp-tmpnam-tempnam.c @@ -0,0 +1,28 @@ +// Marco Ivaldi + +#include +#include + +void open_tmpfile1(char *path) +{ + // ruleid: raptor-insecure-api-mktemp-tmpnam-tempnam + char *filename = mktemp(path); + + FILE *tmp = fopen(filename, "wb+"); + // do something +} + +void open_tmpfile2(char *path, char *data, size_t len) +{ + // ok: raptor-insecure-api-mktemp-tmpnam-tempnam + int fd = mkstemp(path); + + write(fd, data, len); + // do something +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-mktemp-tmpnam-tempnam.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-mktemp-tmpnam-tempnam.yaml new file mode 100644 index 0000000..682f26f --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-mktemp-tmpnam-tempnam.yaml @@ -0,0 +1,37 @@ +rules: + - id: raptor-insecure-api-mktemp-tmpnam-tempnam + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Dangerous Method or Function + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-377: Insecure Temporary File" + - "CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: >- + Creating and using insecure temporary files can leave application and + system data vulnerable to attack. + severity: WARNING + languages: + - c + - cpp + pattern-either: + - pattern: mktemp(...) + - pattern: tmpnam(...) + - pattern: tempnam(...) + - pattern: tmpnam_r(...) + # - pattern: _mktemp(...) + # - pattern: _tmpnam(...) + # - pattern: _tempnam(...) + # - pattern: GetTempFileName(...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-rand-srand.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-rand-srand.c new file mode 100644 index 0000000..8130626 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-rand-srand.c @@ -0,0 +1,56 @@ +// Marco Ivaldi + +#include +#include +#include + +enum +{ + len = 12 +}; + +void func_bad(void) +{ + char id[len]; + int r; + int num; + + // ... + + // ruleid: raptor-insecure-api-rand-srand + r = rand(); + num = snprintf(id, len, "ID%-d", r); + + // ... +} + +void func_good(void) +{ + char id[len]; + int r; + int num; + + // ... + + struct timespec ts; + if (timespec_get(&ts, TIME_UTC) == 0) + { + /* handle error */ + } + // ok: raptor-insecure-api-rand-srand + srandom(ts.tv_nsec ^ ts.tv_sec); + + // ... + + // ok: raptor-insecure-api-rand-srand + r = random(); + num = snprintf(id, len, "ID%-d", r); + + // ... +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-rand-srand.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-rand-srand.yaml new file mode 100644 index 0000000..42c3b9a --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-rand-srand.yaml @@ -0,0 +1,44 @@ +rules: + - id: raptor-insecure-api-rand-srand + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Cryptographic Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)" + - "CWE-330: Use of Insufficiently Random Values" + owasp: + - A04:2025 - Cryptographic Failures + references: + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: >- + The rand() PRNG should not be used in applications intended to be + portable when good randomness is needed. Instead, the use of random() + is recommended. + severity: WARNING + languages: + - c + - cpp + # NOTE: `rand_r` and other non-standard PRNGs are not covered. + # NOTE: improperly seeded strong PRNGs are not covered. + # NOTE: refer also to `cpp.lang.security.rng.*`, `cpp.lang.security.crypto.*`, and `gitlab.flawfinder.*`. + pattern-either: + - pattern: rand(...) + - pattern: srand(...) + - pattern: drand48(...) + - pattern: erand48(...) + - pattern: lrand48(...) + - pattern: nrand48(...) + - pattern: mrand48(...) + - pattern: jrand48(...) + - pattern: lcong48(...) + - pattern: srand48(...) + - pattern: seed48(...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-scanf.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-scanf.c new file mode 100644 index 0000000..8c204f0 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-scanf.c @@ -0,0 +1,236 @@ +// Marco Ivaldi + +#include + +#define BUFSIZE 256 +#define FMT "whatever" + +void read_string(char *string) +{ + char buf[BUFSIZE]; + int number; + char fmt[] = "whatever"; + + // ruleid: raptor-insecure-api-scanf + scanf("%s", buf); + + // ok: raptor-insecure-api-scanf + scanf("%d", &number); + + // ruleid: raptor-insecure-api-scanf + sscanf(string, "string: %s", buf); + + // ruleid: raptor-insecure-api-scanf + scanf(FMT, buf); + + // ruleid: raptor-insecure-api-scanf + scanf(fmt, buf); + + // ruleid: raptor-insecure-api-scanf + scanf(buf); +} + +void test_func() +{ + char last_name[20]; + printf("Enter your last name: "); + // ruleid: raptor-insecure-api-scanf + scanf("%s", last_name); +} + +int read_ident(int sockfd) +{ + int sport, cport; + char user[32], rtype[32], addinfo[32]; + char buffer[1024]; + + if (read(sockfd, buffer, sizeof(buffer)) <= 0) + { + perror("read: %m"); + return 1; + } + + buffer[sizeof(buffer) - 1] = '\0'; + // ruleid: raptor-insecure-api-scanf + sscanf(buffer, "%d:%d:%s:%s:%s", &sport, &cport, rtype, user, addinfo); + // ... +} + +// https://github.com/pedrib/PoC/blob/master/advisories/Pwn2Own/Tokyo_2019/tokyo_drift/tokyo_drift.md +undefined4 sa_setBlockName(char *block_name, int len) +{ + int scanf_res; + char *__src; + char scanf_str[1024]; + undefined4 scanf_int; + + scanf_int = 0; + scanf_str._0_4_ = 0; + memset(scanf_str + 4, 0, 0x3fc); + print_debug(3, "%s(%d);\n", "sa_setBlockName", 0x42d); + if (len != 0) + { + // ruleid: raptor-insecure-api-scanf + scanf_res = sscanf(block_name, "%d%s", &scanf_int, scanf_str); + /* if ((scanf_res == 2) && (__src = strstr(block_name, s), __src != NULL)) { + // ... + } */ + } + return 0; +} + +// https://www.synacktiv.com/en/publications/pwn2own-austin-2021-defeating-the-netgear-r6700v3.html +int updating_database(int a1, const char *update_server) +{ + // ... + char line[1020]; // [sp+894h] [bp-4FCh] BYREF + char db_checksum_val[256]; // [sp+D94h] [bp+4h] BYREF + char db_checksum[256]; // [sp+E94h] [bp+104h] BYREF + // ... + v7 = fopen("/tmp/circleinfo.txt", "r"); + if (v7) + { + line[0] = 0; + while (fgets(line, 1024, v7)) + { + // ruleid: raptor-insecure-api-scanf + if (sscanf(line, "%s %s", db_checksum, db_checksum_val) == 2 && !strcmp(db_checksum, "db_checksum")) + { + // ... + break; + } + } + } + return 0; +} + +void test_003(void) +{ + char buf[BUFFER_SIZE]; + // ruleid: raptor-insecure-api-scanf + if (1 != fscanf(stdin, "%s", buf)) + { + // ... + } +} + +void test_003_valist(void) +{ + char buf[BUFFER_SIZE]; + // ruleid: raptor-insecure-api-scanf + if (1 != fscanf(stdin, "%d%d%s", 1, 2, buf)) + { + // ... + } +} + +void test_003_stmt(void) +{ + char buf[BUFFER_SIZE]; + // ruleid: raptor-insecure-api-scanf + fscanf(stdin, "%d%d%s", 1, 2, buf); +} + +void test_004(void) +{ + char buf[BUFFER_SIZE]; + // ok: raptor-insecure-api-scanf + if (1 != fscanf(stdin, "%d", buf)) + { + // ... + } +} + +void test_007(wchar_t *name) +{ + char filename[128]; + // ruleid: raptor-insecure-api-scanf + fwscanf(stdin, L"foo%sbar", filename); +} + +void foo() +{ + char buf[128]; + int n; + // ruleid: raptor-insecure-api-scanf + fscanf(stdin, "%dfoo%sbar", n, buf); + // ruleid: raptor-insecure-api-scanf + fscanf(stdin, "%sbar", n, buf); + // ruleid: raptor-insecure-api-scanf + fscanf(stdin, "foo%s", n, buf); +} + +void foo() +{ + char buf[128]; + int n; + // ok: raptor-insecure-api-scanf + fscanf(stdin, "%dfoo%10sbar", n, buf); +} + +void foo() +{ + char buf[128]; + int n; + // sized format specifiers aren't parsed yet + // todoruleid: raptor-insecure-api-scanf + fscanf(stdin, "%dfoo%1024sbar", n, buf); +} + +void foo() +{ + char buf[128]; + // ruleid: raptor-insecure-api-scanf + fscanf(stdin, "%sfoo%%s", buf); + + // ruleid: raptor-insecure-api-scanf + fscanf(stdin, "%sfoo%%%s", buf); +} + +void foo() +{ + char buf[64]; + va_list ap; + va_start(ap, buf); + // ruleid: raptor-insecure-api-scanf + vscanf("%s", ap); + va_end(ap); +} + +void foo() +{ + char buf[64]; + va_list ap; + va_start(ap, buf); + // ruleid: raptor-insecure-api-scanf + vfscanf(stdin, "%s", ap); + va_end(ap); +} + +void foo(char *str) +{ + char buf[0]; + // ruleid: raptor-insecure-api-scanf + sscanf(str, "%s", buf); + + // ok: raptor-insecure-api-scanf + sscanf("constant string", "%s", buf); + + va_list ap; + va_start(ap, fmt); + // ruleid: raptor-insecure-api-scanf + vsscanf(str, "%s", buf); + va_end(ap); + + va_list ap; + va_start(ap, fmt); + // ok: raptor-insecure-api-scanf + vsscanf("constant string", "%s", buf); + va_end(ap); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-scanf.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-scanf.yaml new file mode 100644 index 0000000..622777a --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-scanf.yaml @@ -0,0 +1,61 @@ +rules: + - id: raptor-insecure-api-scanf + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: HIGH + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-676: Use of Potentially Dangerous Function" + - "CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')" + - "CWE-787: Out-of-bounds Write" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: >- + A buffer overflow condition exists when a program attempts to put + more data in a buffer than it can hold, or when a program attempts to + put data in a memory area outside of the boundaries of a buffer. + severity: ERROR + languages: + - c + - cpp + patterns: + - pattern-either: + - pattern: scanf($FMT, ...) + - pattern: __isoc99_scanf($FMT, ...) + - pattern: vscanf($FMT, ...) + - pattern: __isoc99_vscanf($FMT, ...) + - pattern: fscanf($_, $FMT, ...) + - pattern: __isoc99_fscanf($_, $FMT, ...) + - pattern: vfscanf($_, $FMT, ...) + - pattern: __isoc99_vfscanf($_, $FMT, ...) + - pattern: sscanf($_, $FMT, ...) + - pattern: __isoc99_sscanf($_, $FMT, ...) + - pattern: vsscanf($_, $FMT, ...) + - pattern: __isoc99_vsscanf($_, $FMT, ...) + - pattern: wscanf($FMT, ...) + - pattern: vwscanf($FMT, ...) + - pattern: fwscanf($_, $FMT, ...) + - pattern: vfwscanf($_, $FMT, ...) + - pattern: swscanf($_, $FMT, ...) + - pattern: vswscanf($_, $FMT, ...) + # exclude string literals as source + - pattern-not: sscanf("...", $FMT, ...) + - pattern-not: __isoc99_sscanf("...", $FMT, ...) + - pattern-not: vsscanf("...", $FMT, ...) + - pattern-not: __isoc99_vsscanf("...", $FMT, ...) + - pattern-not: swscanf("...", $FMT, ...) + - pattern-not: vswscanf("...", $FMT, ...) + - metavariable-regex: + metavariable: $FMT + # NOTE: some format string specifiers are not handled + regex: '(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)' diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-signal.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-signal.c new file mode 100644 index 0000000..b751179 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-signal.c @@ -0,0 +1,47 @@ +// Marco Ivaldi + +#include +#include +#include + +char *logMessage; + +void handler(int sigNum) +{ + syslog(LOG_NOTICE, "%s\n", logMessage); + free(logMessage); + + sleep(10); + exit(0); +} + +int bad_main(int argc, char *argv[]) +{ + logMessage = strdup(argv[1]); + + // ruleid: raptor-insecure-api-signal + signal(SIGHUP, handler); + // ruleid: raptor-insecure-api-signal + signal(SIGTERM, handler); + + sleep(10); + + return 0; +} + +int good_main(int argc, char *argv[]) +{ + logMessage = strdup(argv[1]); + + struct sigaction sa; + sa.sa_handler = handler; + + // ok: raptor-insecure-api-signal + sigaction(SIGHUP, &sa, NULL); + // ok: raptor-insecure-api-signal + sigaction(SIGTERM, &sa, NULL); + + sleep(10); + + return 0; +} \ No newline at end of file diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-signal.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-signal.yaml new file mode 100644 index 0000000..7029f95 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-signal.yaml @@ -0,0 +1,35 @@ +rules: + - id: raptor-insecure-api-signal + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Dangerous Method or Function + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-364: Signal Handler Race Condition" + - "CWE-479: Signal Handler Use of a Non-reentrant Function" + - "CWE-828: Signal Handler with Functionality that is not Asynchronous-Safe" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://lcamtuf.coredump.cx/signals.txt + message: >- + The signal() API should be regarded as deprecated. When possible, + sigaction() should be used instead, because it allows to precisely + specify the desired behavior in case two signals arrive shortly after + each other thus preventing many race conditions. + severity: WARNING + languages: + - c + - cpp + pattern-either: + - pattern: signal(...) + - pattern: gsignal(...) + - pattern: ssignal(...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-sprintf-vsprintf.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-sprintf-vsprintf.c new file mode 100644 index 0000000..2547667 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-sprintf-vsprintf.c @@ -0,0 +1,72 @@ +// Marco Ivaldi + +#include + +#define BUFSIZE 256 +#define FMT "whatever" + +void copy_string(char *string, int number) +{ + char buf[BUFSIZE]; + char fmt[] = "whatever"; + + // ruleid: raptor-insecure-api-sprintf-vsprintf + sprintf(buf, "string: %s\n", string); + + // ok: raptor-insecure-api-sprintf-vsprintf + sprintf(buf, "number: %d\n", number); + + // ruleid: raptor-insecure-api-sprintf-vsprintf + sprintf(buf, FMT, string); + + // ruleid: raptor-insecure-api-sprintf-vsprintf + sprintf(buf, fmt, string); + + // ruleid: raptor-insecure-api-sprintf-vsprintf + sprintf(buf, string); +} + +static void +WriteToLog(jrun_request *r, const char *szFormat, ...) +{ + server_rec *s = (server_rec *)r->context; + va_list list; + char szBuf[2048]; + + strcpy(szBuf, r->stringRep); + va_start(list, szFormat); + // ruleid: raptor-insecure-api-sprintf-vsprintf + vsprintf(strchr(szBuf, '\0'), szFormat, list); + va_end(list); + +#if MODULE_MAGIC_NUMBER > 19980401 + ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_NOTICE, s, "%s", szBuf); +#else + log_error(szBuf, s); +#endif + +#ifdef WIN32 + strcat(szBuf, "\r\n"); + OutputDebugString(szBuf); +#endif +} + +void test_005(const char *name) +{ + char filename[128]; + // ruleid: raptor-insecure-api-sprintf-vsprintf + sprintf(filename, "%s", name); +} + +void test_006(const char *name) +{ + char filename[128]; + // ok: raptor-insecure-api-sprintf-vsprintf + sprintf(filename, "%d", name); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-sprintf-vsprintf.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-sprintf-vsprintf.yaml new file mode 100644 index 0000000..a250134 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-sprintf-vsprintf.yaml @@ -0,0 +1,38 @@ +rules: + - id: raptor-insecure-api-sprintf-vsprintf + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: HIGH + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-676: Use of Potentially Dangerous Function" + - "CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')" + - "CWE-787: Out-of-bounds Write" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: >- + A buffer overflow condition exists when a program attempts to put + more data in a buffer than it can hold, or when a program attempts to + put data in a memory area outside of the boundaries of a buffer. + severity: ERROR + languages: + - c + - cpp + patterns: + - pattern-either: + - pattern: sprintf($_, $FMT, ...) + - pattern: vsprintf($_, $FMT, ...) + - metavariable-regex: + metavariable: $FMT + # NOTE: some format string specifiers are not handled + regex: '(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)' diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-strcpy-strcat.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-strcpy-strcat.c new file mode 100644 index 0000000..225121e --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-strcpy-strcat.c @@ -0,0 +1,150 @@ +// Marco Ivaldi + +#include +#include + +#define BUFSIZE 256 + +void copy_append_string1(char *string1, char *string2) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-insecure-api-strcpy-strcat + strcpy(buf, string1); + + // ruleid: raptor-insecure-api-strcpy-strcat + strcat(buf, string2); +} + +int copy_append_string2(const char *string1, const char *string2, + char *buf, size_t bufsz) +{ + if (!string1 || !string2 || !buf || bufsz == 0) + return -1; + + // ok: raptor-insecure-api-strcpy-strcat + if (strlcpy(buf, string1, bufsz) >= bufsz) + return -1; // truncation + + // ok: raptor-insecure-api-strcpy-strcat + if (strlcat(buf, string2, bufsz) >= bufsz) + return -1; // truncation + + return 0; +} + +void copy_string(char *string) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-insecure-api-strcpy-strcat + stpcpy(buf, string); +} + +void test_func() +{ + struct hostent *clienthp; + char hostname[MAX_LEN]; + + // ... + + int count = 0; + for (count = 0; count < MAX_CONNECTIONS; count++) + { + + int clientlen = sizeof(struct sockaddr_in); + int clientsocket = accept(serversocket, (struct sockaddr *)&clientaddr, &clientlen); + + if (clientsocket >= 0) + { + clienthp = gethostbyaddr((char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET); + // ruleid: raptor-insecure-api-strcpy-strcat + strcpy(hostname, clienthp->h_name); + logOutput("Accepted client connection from host ", hostname); + + // ... + + close(clientsocket); + } + } + close(serversocket); + + // ... +} + +char *read_command(int sockfd) +{ + char username[32], buffer[1024]; + int n; + + if ((n = read(sockfd, buffer, sizeof(buffer) - 1) <= 0)) + return NULL; + buffer[n] = '\0'; + + switch (buffer[0]) + { + case 'U': + // ruleid: raptor-insecure-api-strcpy-strcat + strcpy(username, &buffer[1]); + break; + // ... + } +} + +int process_email(char *email) +{ + char username[32], domain[128], *delim; + int c; + + delim = strchr(email, '@'); + + if (!delim) + return -1; + + *delim++ = '\0'; + + if (strlen(email) >= sizeof(username)) + return -1; + + // ruleid: raptor-insecure-api-strcpy-strcat + strcpy(username, email); + + if (strlen(delim) >= sizeof(domain)) + return -1; + + // ruleid: raptor-insecure-api-strcpy-strcat + strcpy(domain, delim); + + if (!strchr(delim, '.')) + // ruleid: raptor-insecure-api-strcpy-strcat + strcat(domain, default_domain); + + // ... +} + +void process_address(int sockfd) +{ + char username[256], domain[256], netbuf[256], *ptr; + + read_data(sockfd, netbuf, sizeof(netbuf)); + + ptr = strchr(netbuf, ':'); + + if (ptr) + *ptr++ = '\0'; + + // ruleid: raptor-insecure-api-strcpy-strcat + strcpy(username, netbuf); + + if (ptr) + // ruleid: raptor-insecure-api-strcpy-strcat + strcpy(domain, ptr); + + // ... +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-strcpy-strcat.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-strcpy-strcat.yaml new file mode 100644 index 0000000..bbe2119 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/insecure-api-strcpy-strcat.yaml @@ -0,0 +1,47 @@ +rules: + - id: raptor-insecure-api-strcpy-strcat + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Dangerous Method or Function + likelihood: HIGH + impact: HIGH + confidence: HIGH + technology: + - c + - cpp + cwe: + - "CWE-676: Use of Potentially Dangerous Function" + - "CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')" + - "CWE-787: Out-of-bounds Write" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + message: >- + A buffer overflow condition exists when a program attempts to put + more data in a buffer than it can hold, or when a program attempts to + put data in a memory area outside of the boundaries of a buffer. + severity: ERROR + languages: + - c + - cpp + # NOTE: some functions, such as `_fstrcpy` and `_fstrcat`, are not covered. + patterns: + - pattern-either: + - pattern: strcpy(...) + - pattern: stpcpy(...) + - pattern: strcat(...) + - pattern: wcscpy(...) + - pattern: wcpcpy(...) + - pattern: wcscat(...) + - pattern: _mbscpy(...) + - pattern: _mbscat(...) + - pattern: strccpy(...) + - pattern: strcadd(...) + - pattern: streadd(...) + - pattern: strecpy(...) + - pattern: strtrns(...) + - pattern-not: $_($_, "...", ...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-truncation.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-truncation.c new file mode 100644 index 0000000..7baf37c --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-truncation.c @@ -0,0 +1,53 @@ +// Marco Ivaldi + +#include + +void assign_int(int int_var) +{ + // ruleid: raptor-integer-truncation + char char_var = int_var; + short short_var; + int int_var2; + + // ruleid: raptor-integer-truncation + short_var = int_var; + + // ok: raptor-integer-truncation + int_var2 = int_var + 1; +} + +void assign_long(long long_var) +{ + short short_var; + // ruleid: raptor-integer-truncation + int int_var = long_var + 1; + + // ruleid: raptor-integer-truncation + short_var = long_var; + + // ok: raptor-integer-truncation + long long_var2 = long_var + 1; +} + +void test_func() +{ + int intPrimitive; + short shortPrimitive; + intPrimitive = (int)(~((int)0) ^ (1 << (sizeof(int) * 8 - 1))); + // ruleid: raptor-integer-truncation + shortPrimitive = intPrimitive; + printf("Int MAXINT: %d\nShort MAXINT: %d\n", intPrimitive, shortPrimitive); +} + +// ruleid: raptor-integer-truncation +char func(void) +{ + int a = 42; + return a; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-truncation.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-truncation.yaml new file mode 100644 index 0000000..4987332 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-truncation.yaml @@ -0,0 +1,133 @@ +rules: + - id: raptor-integer-truncation + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Other Security + likelihood: MEDIUM + impact: MEDIUM + confidence: LOW + technology: + - c + - cpp + cwe: + - "CWE-197: Numeric Truncation Error" + - "CWE-681: Incorrect Conversion between Numeric Types" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + message: >- + Truncation errors occur when a primitive is cast to a primitive of a + smaller size and data is lost in the conversion. The value cannot be + trusted and the application will be in an undefined state. + severity: WARNING + languages: + - c + - cpp + # NOTE: the deep expression operator is necessary to catch some matches because C/C++ integer promotions do not seem entirely supported by Semgrep; this may generate lots of false positives. + # NOTE: some types (e.g., pointers) and use cases (e.g., comparisons) are not covered. + pattern-either: + # char: assignments + - patterns: + - pattern-either: + - pattern: (char $_) = <... (short $_) ...> + - pattern: (char $_) = <... (short int $_) ...> + - pattern: (char $_) = <... (unsigned short $_) ...> + - pattern: (char $_) = <... (unsigned short int $_) ...> + - pattern: (char $_) = <... (int $_) ...> + - pattern: (char $_) = <... (unsigned $_) ...> + - pattern: (char $_) = <... (unsigned int $_) ...> + - pattern: (char $_) = <... (long $_) ...> + - pattern: (char $_) = <... (long int $_) ...> + - pattern: (char $_) = <... (unsigned long $_) ...> + - pattern: (char $_) = <... (unsigned long int $_) ...> + - pattern-not: $_ = 0 + # char: function return + - patterns: + - pattern-either: + - pattern: | + char $FUN(...) + { + ... + return (short $_); + } + - pattern: | + char $FUN(...) + { + ... + return (int $_); + } + - pattern: | + char $FUN(...) + { + ... + return (long $_); + } + # improve output readability + - focus-metavariable: $FUN + # short: assignments + - patterns: + - pattern-either: + - pattern: (short $_) = <... (unsigned short $_) ...> + - pattern: (short int $_) = <... (unsigned short int $_) ...> + - pattern: (short $_) = <... (int $_) ...> + - pattern: (short $_) = <... (unsigned $_) ...> + - pattern: (short int $_) = <... (unsigned int $_) ...> + - pattern: (short $_) = <... (long $_) ...> + - pattern: (short int $_) = <... (long int $_) ...> + - pattern: (short $_) = <... (unsigned long $_) ...> + - pattern: (short int $_) = <... (unsigned long int $_) ...> + - pattern: (unsigned short $_) = <... (int $_) ...> + - pattern: (unsigned short int $_) = <... (unsigned int $_) ...> + - pattern: (unsigned short $_) = <... (long $_) ...> + - pattern: (unsigned short int $_) = <... (long int $_) ...> + - pattern: (unsigned short $_) = <... (unsigned long $_) ...> + - pattern: (unsigned short int $_) = <... (unsigned long int $_) ...> + - pattern-not: $_ = 0 + # short: function return + - patterns: + - pattern-either: + - pattern: | + short $FUN(...) + { + ... + return (int $_); + } + - pattern: | + short $FUN(...) + { + ... + return (long $_); + } + # improve output readability + - focus-metavariable: $FUN + # int: assignments + - patterns: + - pattern-either: + - pattern: (int $_) = <... (unsigned $_) ...> + - pattern: (int $_) = <... (unsigned int $_) ...> + - pattern: (int $_) = <... (long $_) ...> + - pattern: (int $_) = <... (long int $_) ...> + - pattern: (int $_) = <... (unsigned long $_) ...> + - pattern: (int $_) = <... (unsigned long int $_) ...> + - pattern-not: $_ = 0 + # int: function return + - patterns: + - pattern: | + int $FUN(...) + { + ... + return (long $_); + } + # improve output readability + - focus-metavariable: $FUN + # long: assignments + - patterns: + - pattern-either: + - pattern: (long $_) = <... (unsigned long $_) ...> + - pattern: (long int $_) = <... (unsigned long int $_) ...> + - pattern-not: $_ = 0 diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-wraparound.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-wraparound.c new file mode 100644 index 0000000..21fa3b0 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-wraparound.c @@ -0,0 +1,310 @@ +// Marco Ivaldi + +#include +#include +#include // C23 + +void bad1() +{ + img_t table_ptr; + int num_imgs; + + // ... + + num_imgs = get_num_imgs(); + // ruleid: raptor-integer-wraparound + table_ptr = (img_t *)malloc(sizeof(img_t) * num_imgs); + + // ... +} + +int good1(void) +{ + int num_imgs = get_num_imgs(); + size_t alloc_size; + + if (num_imgs <= 0) + return -1; + + if (ckd_mul(&alloc_size, (size_t)num_imgs, sizeof(img_t))) + return -1; // overflow + + // ok: raptor-integer-wraparound + img_t *table_ptr = malloc(alloc_size); + if (!table_ptr) + return -1; + + // ... + + free(table_ptr); + return 0; +} + +int good2(void) +{ + int num_imgs = get_num_imgs(); + + if (num_imgs <= 0) + return -1; + + if ((size_t)num_imgs > SIZE_MAX / sizeof(img_t)) + return -1; // overflow + + // the rule doesn't currently check for this pattern of overflow prevention, but it arguably should + // todook: raptor-integer-wraparound + img_t *table_ptr = malloc((size_t)num_imgs * sizeof(img_t)); + if (!table_ptr) + return -1; + + // ... + + free(table_ptr); + return 0; +} + +// https://vulncat.fortify.com/ +void bad2() +{ + int nresp = packet_get_int(); + + if (nresp > 0) + { + // ruleid: raptor-integer-wraparound + response = malloc(nresp * sizeof(char *)); + for (int i = 0; i < nresp; i++) + response[i] = packet_get_string(NULL); + } +} + +// https://fromdayzerotozeroday.com/ +void bad3(n) +{ + // ruleid: raptor-integer-wraparound + char *const new_connector = (char *)realloc(parser->m_groupConnector, parser->m_groupSize *= 2); + // ruleid: raptor-integer-wraparound + int *const new_scaff_index = (int *)realloc(dtd->scaffIndex, parser->m_groupSize * sizeof(int)); + + n *= 2; + // ruleid: raptor-integer-wraparound + char *buf = (char *)malloc(n) +} + +u_char *make_table(unsigned int width, unsigned int height, u_char *init_row) +{ + unsigned int n; + int i; + u_char *buf; + + n = width * height; + + // ruleid: raptor-integer-wraparound + buf = (char *)malloc(n); + if (!buf) + return NULL; + for (i = 0; i < height; i++) + memcpy(&buf[i * width], init_row, width); + + return buf; +} + +// http://www.phrack.org/issues/60/10.html#article +int myfunction(int *array, int len) +{ + int *myarray, i; + + // ruleid: raptor-integer-wraparound + myarray = malloc(len * sizeof(int)); + if (myarray == NULL) + { + return -1; + } + + for (i = 0; i < len; i++) + { + myarray[i] = array[i]; + } + + return myarray; +} + +static int +set_cursor(struct tfb_softc *sc, struct wsdisplay_cursor *p) +{ + u_int v, index = 0, count = 0, icount = 0; + uint8_t r[2], g[2], b[2], image[512], mask[512]; + int error, s; + + v = p->which; + if (v & WSDISPLAY_CURSOR_DOCMAP) + { + index = p->cmap.index; // p->cmap.index is u_int + count = p->cmap.count; // p->cmap.count is u_int + // ruleid: raptor-integer-wraparound + if (index >= 2 || (index + count) > 2) + return (EINVAL); + error = copyin(p->cmap.red, &r[index], count); + } +} + +void **ht_get_all(ht_t self, int want_key) +{ + // ruleid: raptor-integer-wraparound + void **ret = (void **)calloc(self->num_keys + 1, sizeof(void *)); + if (ret) + { + void **tail = ret; + size_t i; + for (i = 0; i < self->num_buckets; i++) + { + ht_entry_t curr; + for (curr = self->buckets[i]; curr; curr = curr->next) + { + *tail++ = (want_key ? curr->key : curr->value); + } + } + } + return ret; +} + +dl_status dl_start(dl_t self) +{ + // ... + plist_t dict = plist_new_dict(); + // ... + char *xml = NULL; + uint32_t xml_length = 0; + plist_to_xml(dict, &xml, &xml_length); + plist_free(dict); + + size_t length = 16 + xml_length; + // ruleid: raptor-integer-wraparound + char *packet = (char *)calloc(length, sizeof(char)); + if (!packet) + { + return DL_ERROR; + } + + // ... +} + +// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/ +CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data, + const char *password, + unsigned char *ntbuffer /* 21 bytes */) +{ + size_t len = strlen(password); + // ruleid: raptor-integer-wraparound + unsigned char *pw = len ? malloc(len * 2) : strdup(""); + CURLcode result; + + if (!pw) + return CURLE_OUT_OF_MEMORY; +} + +// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/ +static int +defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata, + XML_Bool isId, const XML_Char *value, XML_Parser parser) +{ + DEFAULT_ATTRIBUTE *temp; + int count = type->allocDefaultAtts * 2; + // ruleid: raptor-integer-wraparound + temp = (DEFAULT_ATTRIBUTE *)realloc(type->defaultAtts, + (count * sizeof(DEFAULT_ATTRIBUTE))); + if (temp == NULL) + return 0; + type->allocDefaultAtts = count; + type->defaultAtts = temp; +} + +// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/ +static enum XML_Error +doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, + int tok, const char *next, const char **nextPtr, XML_Bool haveMore, + XML_Bool allowClosingDoctype, enum XML_Account account) +{ +case XML_ROLE_GROUP_OPEN: + if (parser->m_prologState.level >= parser->m_groupSize) + { + if (parser->m_groupSize) + { + // ruleid: raptor-integer-wraparound + char *const new_connector = (char *)realloc( + parser->m_groupConnector, parser->m_groupSize *= 2); + } + } + + // ... + return XML_ERROR_NONE; +} + +// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/ +int test_propagation() +{ + lVar2 = sVar1 * 2; + // ruleid: raptor-integer-wraparound + data = (void *)(*(code *)malloc)(lVar2); + + // ... + return 0; +} + +// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/ +int more_operands() +{ + // ruleid: raptor-integer-wraparound + __s = (char *)(*(code *)malloc)(sVar7 * 3 + 1); + + // ... + return 0; +} + +// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/ +int printbuf_memappend(printbuf *p, char *buf, int size) +{ + if (p->size <= iVar2) + { + iVar3 = p->size * 2; // Integer overflow + if (iVar3 <= iVar2 + 8) + { + iVar3 = iVar2 + 9; + } + // ruleid: raptor-integer-wraparound + __ptr = (char *)realloc(__ptr, (long)iVar3); // Alloc call + } +} + +#include +#include + +int windows_example() +{ + int nresp = 1073741824; // 2^30, close to INT_MAX + size_t size = nresp * sizeof(char *); // Overflow occurs here! + + // If sizeof(char*) == 4, then nresp * 4 = 4,294,967,296 + // But this exceeds UINT32_MAX (4,294,967,295), so it wraps to 0 + if (size == 0) + { + std::cerr << "Integer overflow detected! Size is 0." << std::endl; + return 1; + } + + // ruleid: raptor-integer-wraparound + LPVOID ptr = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (ptr == NULL) + { + std::cerr << "VirtualAlloc failed. Size may be invalid due to overflow." << std::endl; + return 1; + } + + std::cout << "Memory allocated successfully at: " << ptr << std::endl; + VirtualFree(ptr, 0, MEM_RELEASE); + return 0; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-wraparound.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-wraparound.yaml new file mode 100644 index 0000000..c2f477b --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/integer-wraparound.yaml @@ -0,0 +1,214 @@ +rules: + - id: raptor-integer-wraparound + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-190: Integer Overflow or Wraparound" + - "CWE-128: Wrap-around Error" + - "CWE-131: Incorrect Calculation of Buffer Size" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - http://www.phrack.org/issues/60/10.html#article + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + - https://dustri.org/b/playing-with-weggli.html + message: >- + The software performs a calculation that can produce an integer + overflow or wraparound, when the logic assumes that the resulting + value will always be larger than the original value. This can + introduce other weaknesses when the calculation is used for resource + management or execution control. + severity: WARNING + languages: + - c + - cpp + # NOTE: only multiplication and sum with two operands are covered; other arithmetic operations should also be considered (e.g., left shift, even subtraction), as well as any operation with more than two operands. + # NOTE: some allocation functions such as `kmalloc`, `HeapAlloc`, and custom wrappers are not covered. + # NOTE: there might exist other buggy input validation patterns not covered here, including the same patterns with a different order of operands. + # NOTE: consider excluding `strlen` patterns to avoid false positives (at the cost of some false negatives). + # NOTE: we should do some tests with the deep expression operator, refer also to `cpp.lang.security.memory.integer-overflow-allocation.integer-overflow-allocation`. + # NOTE: a dedicated rule for C++ operators such as `new` should be implemented. + pattern-either: + # malloc, valloc (multiplication) + - patterns: + - pattern-either: + - pattern: $FUN($_ * $_) + - pattern: $FUN($_ *= $_) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: valloc + - patterns: + - pattern: $FUN($N) + - pattern-either: + - pattern-inside: | + $N = $_ * $_; + ... + - pattern-inside: | + $N *= $_; + ... + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: valloc + # malloc, valloc (sum) + - patterns: + - pattern-either: + - pattern: $FUN($_ + $_) + - pattern: $FUN($_ += $_) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: valloc + - patterns: + - pattern: $FUN($N) + - pattern-either: + - pattern-inside: | + $N = $_ + $_; + ... + - pattern-inside: | + $N += $_; + ... + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: valloc + # calloc, realloc, reallocf, aligned_alloc, VirtualAlloc (multiplication) + - patterns: + - pattern-either: + - pattern: $FUN($_, $_ * $_, ...) + - pattern: $FUN($_, $_ *= $_, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: aligned_alloc + - pattern: VirtualAlloc + - patterns: + - pattern: $FUN($_, $N, ...) + - pattern-either: + - pattern-inside: | + $N = $_ * $_; + ... + - pattern-inside: | + $N *= $_; + ... + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: aligned_alloc + - pattern: VirtualAlloc + # calloc, realloc, reallocf, aligned_alloc, VirtualAlloc (sum) + - patterns: + - pattern-either: + - pattern: $FUN($_, $_ + $_, ...) + - pattern: $FUN($_, $_ += $_, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: aligned_alloc + - pattern: VirtualAlloc + - patterns: + - pattern: $FUN($_, $N, ...) + - pattern-either: + - pattern-inside: | + $N = $_ + $_; + ... + - pattern-inside: | + $N += $_; + ... + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: aligned_alloc + - pattern: VirtualAlloc + # calloc (multiplication in 1st arg) + - patterns: + - pattern-either: + - pattern: $FUN($_ * $_, $_) + - pattern: $FUN($_ *= $_, $_) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - patterns: + - pattern: $FUN($N, $_) + - pattern-either: + - pattern-inside: | + $N = $_ * $_; + ... + - pattern-inside: | + $N *= $_; + ... + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + # calloc (sum in 1st arg) + - patterns: + - pattern-either: + - pattern: $FUN($_ + $_, $_) + - pattern: $FUN($_ += $_, $_) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + - patterns: + - pattern: $FUN($N, $_) + - pattern-either: + - pattern-inside: | + $N = $_ + $_; + ... + - pattern-inside: | + $N += $_; + ... + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: calloc + # buggy input validation (sum) + # consider integer promotion (i.e., uint16_t are not vulnerable on 32-bit systems) + - pattern: $X > $MAX || ($X + $_) > $MAX + - pattern: $X >= $MAX || ($X + $_) > $MAX + - pattern: $X > $MAX || ($X + $_) >= $MAX + - pattern: $X >= $MAX || ($X + $_) >= $MAX + - pattern: $X < $MAX && ($X + $_) < $MAX + - pattern: $X <= $MAX && ($X + $_) < $MAX + - pattern: $X < $MAX && ($X + $_) <= $MAX + - pattern: $X <= $MAX && ($X + $_) <= $MAX + # buggy input validation (multiplication) + # consider integer promotion (i.e., uint16_t are not vulnerable on 32-bit systems) + - pattern: $X > $MAX || ($X * $_) > $MAX + - pattern: $X >= $MAX || ($X * $_) > $MAX + - pattern: $X > $MAX || ($X * $_) >= $MAX + - pattern: $X >= $MAX || ($X * $_) >= $MAX + - pattern: $X < $MAX && ($X * $_) < $MAX + - pattern: $X <= $MAX && ($X * $_) < $MAX + - pattern: $X < $MAX && ($X * $_) <= $MAX + - pattern: $X <= $MAX && ($X * $_) <= $MAX diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/interesting-api-calls.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/interesting-api-calls.c new file mode 100644 index 0000000..5ad7fdb --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/interesting-api-calls.c @@ -0,0 +1,340 @@ +// Marco Ivaldi + +#include +#include +#include + +#define BUFSIZE 256 + +void drop_priv_perm() +{ + // ruleid: raptor-interesting-api-calls + setuid(getuid()); +} + +void drop_priv_temp() +{ + // ruleid: raptor-interesting-api-calls + seteuid(getuid()); +} + +void copy_append_string(char *string1, char *string2) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-interesting-api-calls + strcpy(buf, string1); + + // ruleid: raptor-interesting-api-calls + strcat(buf, string2); +} + +void copy_string(char *string) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-interesting-api-calls + stpcpy(buf, string); +} + +void copy_string1(char *string) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-interesting-api-calls + strncpy(buf, string, BUFSIZE); +} + +void copy_string2(char *string) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-interesting-api-calls + stpncpy(buf, string, BUFSIZE); +} + +void get_string() +{ + char buf[BUFSIZE]; + + // ruleid: raptor-interesting-api-calls + gets(buf); +} + +void memory_copy() +{ + + // ... + + // ruleid: raptor-interesting-api-calls + memcpy(&(((char *)p_buf)[serialization_buffer_offset]), + serialized_context_buffer, + serialized_context_size); + + // ... + + // ruleid: raptor-interesting-api-calls + memcpy(&(((char *)p_buf)[serialization_buffer_offset]), + serialized_profiles_context_buffer, + cfl_sds_len(serialized_profiles_context_buffer)); + + // ... + + // ruleid: raptor-interesting-api-calls + memcpy((void *)str->wrapped.buf, src, 3 * length + 1); + + // ... + + if (net_setup == NULL) + { + flb_net_setup_init(&stream->net); + } + else + { + // ok: raptor-interesting-api-calls + memcpy(&stream->net, net_setup, sizeof(struct flb_net_setup)); + } + + // ... + + crc = __bswap_32(crc32(0, (const Bytef *)data, len)); + // ok: raptor-interesting-api-calls + memcpy((char *)c->block_data + outlen, &crc, 4); + c->used_size = outlen + 4; + + // ... + + // ok: raptor-interesting-api-calls + memcpy(&load_command, pcmd, sizeof load_command); + + // ... + + // chose not to use pattern-not: $FUN($_, $_, <... sizeof(...) ...>, ...) + // ruleid: raptor-interesting-api-calls + memcpy(temp, sysconfig->sortlist, + sizeof(*channel->sortlist) * sysconfig->nsortlist); +} + +// https://cc-sw.com/semgrep-guide-for-a-security-engineer-part-6-of-6/ +static int service_attr_req(sdp_req_t *req, sdp_buf_t *buf) +{ + sdp_cont_state_t *cstate = NULL; + // ... + if (cstate) + { + sdp_buf_t *pCache = sdp_get_cached_rsp(cstate); + + SDPDBG("Obtained cached rsp : %p", pCache); + + if (pCache) + { + short sent = MIN(max_rsp_size, pCache->data_size - cstate->cStateValue.maxBytesSent); + pResponse = pCache->data; + // ruleid: raptor-interesting-api-calls + memcpy(buf->data, pResponse + cstate->cStateValue.maxBytesSent, sent); // Out-of-bound read here + buf->data_size += sent; + cstate->cStateValue.maxBytesSent += sent; + // ... + } + // ... + } +} + +static int call_clone3(uint64_t flags, size_t size, enum test_mode test_mode) +{ + struct __clone_args args = { + .flags = flags, + .exit_signal = SIGCHLD, + }; + + struct clone_args_extended + { + struct __clone_args args; + __aligned_u64 excess_space[2]; + } args_ext; + + pid_t pid = -1; + int status; + + memset(&args_ext, 0, sizeof(args_ext)); + if (size > sizeof(struct __clone_args)) + args_ext.excess_space[1] = 1; + + if (size == 0) + size = sizeof(struct __clone_args); + + switch (test_mode) + { + case CLONE3_ARGS_NO_TEST: + /* + * Uses default 'flags' and 'SIGCHLD' + * assignment. + */ + break; + case CLONE3_ARGS_ALL_0: + args.flags = 0; + args.exit_signal = 0; + break; + case CLONE3_ARGS_INVAL_EXIT_SIGNAL_BIG: + args.exit_signal = 0xbadc0ded00000000ULL; + break; + case CLONE3_ARGS_INVAL_EXIT_SIGNAL_NEG: + args.exit_signal = 0x0000000080000000ULL; + break; + case CLONE3_ARGS_INVAL_EXIT_SIGNAL_CSIG: + args.exit_signal = 0x0000000000000100ULL; + break; + case CLONE3_ARGS_INVAL_EXIT_SIGNAL_NSIG: + args.exit_signal = 0x00000000000000f0ULL; + break; + } + + memcpy(&args_ext.args, &args, sizeof(struct __clone_args)); + + // currently commented-out in the rule to avoid too much noise + // todoruleid: raptor-interesting-api-calls + pid = sys_clone3((struct __clone_args *)&args_ext, size); + if (pid < 0) + { + ksft_print_msg("%s - Failed to create new process\n", + strerror(errno)); + return -errno; + } + + if (pid == 0) + { + ksft_print_msg("I am the child, my PID is %d\n", getpid()); + _exit(EXIT_SUCCESS); + } + + ksft_print_msg("I am the parent (%d). My child's pid is %d\n", + getpid(), pid); + + if (waitpid(-1, &status, __WALL) < 0) + { + ksft_print_msg("Child returned %s\n", strerror(errno)); + return -errno; + } + if (WEXITSTATUS(status)) + return WEXITSTATUS(status); + + return 0; +} + +static pid_t sys_clone3(struct clone_args *args) +{ + // ruleid: raptor-interesting-api-calls + return syscall(__NR_clone3, args, sizeof(struct clone_args)); +} + +int test_exec(void) +{ + // ok: raptor-interesting-api-calls + void *system_wide = system_path(ETC_GITATTRIBUTES); + printf("Main program started\n"); + char *argv[] = {"jim", "jams", NULL}; + char *envp[] = {"some", "environment", NULL}; + // ruleid: raptor-interesting-api-calls + if (execve("./sub", argv, envp) == -1) + perror("Could not execve"); + // ruleid: raptor-interesting-api-calls + execlp(path, "emacsclient", "-e", man_page.buf, (char *)NULL); + // ruleid: raptor-interesting-api-calls + execl(SHELL_PATH, SHELL_PATH, "-c", shell_cmd.buf, (char *)NULL); + // ruleid: raptor-interesting-api-calls + execv(user_argv[0], (char *const *)user_argv); + // ruleid: raptor-interesting-api-calls + return system("echo 3 | sudo tee /proc/sys/vm/drop_caches"); + return 1; +} + +void test_spawn(int argc, char *argv[]) +{ + pid_t child; + int fd_count, fd_map[10]; + struct inheritance inherit; + const char *c_argv[10], *c_envp[10]; + char buf[256]; + int nbytes; + + int c_stdin[2], c_stdout[2], c_stderr[2]; /* Pipes for child + * communication */ + + /* Create pipes to communicate with child via stdin/stdout/stderr */ + // ruleid: raptor-interesting-api-calls + if (pipe(c_stdin) || pipe(c_stdout) || pipe(c_stderr)) + { + perror("Bad pipe"); + exit(-1); + } + + /* Set up file descriptor map for child process */ + fd_map[0] = dup(c_stdin[0]); /* child stdin is read end of pipe */ + fd_map[1] = dup(c_stdout[1]); /* child stdout is write end of pipe */ + fd_map[2] = dup(c_stderr[1]); /* child stderr is write end of pipe */ + fd_count = 3; + + /* Close unused end of pipes for the parent */ + close(c_stdin[0]); + close(c_stdout[1]); + close(c_stderr[1]); + + /* Build the argument structure for child arguments. + * [0] is the program name */ + c_argv[0] = "spawnc"; + c_argv[1] = "arg1"; + c_argv[2] = "arg2"; + c_argv[3] = NULL; + + /* Build the environment structure which defines the child's + * environment variables */ + c_envp[0] = "TEST_ENV=YES"; + c_envp[1] = "BPX_SHAREAS=NO"; + c_envp[2] = NULL; + + /* Spawn the child process */ + // ruleid: raptor-interesting-api-calls + child = spawnp("spawnc", fd_count, fd_map, &inherit, c_argv, c_envp); + // ruleid: raptor-interesting-api-calls + child = spawn("/usr/bin/spawnc", fd_count, fd_map, &inherit, c_argv, c_envp); + if (child == -1) + { + perror("Error on spawn"); + exit(-1); + } + else + printf("Spawned %i\n", child); + + /* Test interaction with the child process */ + printf("parent: Asking child, \"what are you doing?\\n\"\n"); + // ruleid: raptor-interesting-api-calls + strcpy(buf, "child from parent: what are you doing?\n"); + if (write(c_stdin[1], buf, sizeof(buf)) == -1) + { + perror("write stdout"); + exit(-1); + } + + memset(buf, 0, 255); /* Just zeroing out the buffer */ + printf("parent: reading from child now\n"); + // ruleid: raptor-interesting-api-calls + if ((nbytes = read(c_stdout[0], buf, 255)) == -1) + { + perror("read error:"); + exit(-1); + } + printf("parent: child says, \"%s\"\n", buf); + + /* Cleanup pipes before exiting */ + close(c_stdin[1]); + close(c_stdout[0]); + close(c_stderr[0]); + + exit(0); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/interesting-api-calls.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/interesting-api-calls.yaml new file mode 100644 index 0000000..62a1af7 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/interesting-api-calls.yaml @@ -0,0 +1,263 @@ +rules: + - id: raptor-interesting-api-calls + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Dangerous Method or Function + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-676: Use of Potentially Dangerous Function" + owasp: + - A08:2025 - Software or Data Integrity Failures + references: + - https://github.com/0xdea/rhabdomancer + - https://github.com/0xdea/ghidra-scripts/blob/main/Rhabdomancer.java + - https://github.com/x509cert/banned/blob/master/banned.h + - https://g.co/kgs/PCHQjJ + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/28719-banned-api-usage-use-updated-function-replacement + - https://docs.oracle.com/cd/E37838_01/html/E61050/gnclc.html + message: >- + Locate all calls to interesting and potentially insecure API + functions (candidate points). The auditor can backtrace from these + candidate points to find pathways allowing access from untrusted + input. + severity: WARNING + languages: + - c + - cpp + # NOTE: `goto`, `try/catch`, `sem/mutex`, `new/delete`, and `static_cast/reinterpret_cast` are not covered. + # NOTE: not all Microsoft-specific obsolete functions are covered. + # NOTE: consider excluding some matches for `strncpy`, `snprintf`, and similar functions where the length parameter is known at compile time (see `memcpy` below for an example). See also another possible approach described at https://cc-sw.com/semgrep-guide-for-a-security-engineer-part-6-of-6/. Beware of possible false negatives, though. + # NOTE: consider checking for format string specifiers that match the `(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)` regex. + # NOTE: consider extracting some patterns into separate rules to focus on the most interesting API calls (copy operations, exec functions, etc.). + # NOTE: nonlocking stdio functions (https://linux.die.net/man/3/fgets_unlocked) are not covered. + # NOTE: refer also to https://semgrep.dev/r?lang=C + pattern-either: + # priv + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*set\w*(u|g)id\s*$|^\w*(init|set)groups\s*$|^\w*Impersonate\w*\s*$' + # strcpy + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*str\w?(cpy|add)(_s)?(_l)?\s*$|^\w*stpn?cpy(_s)?(_l)?\s*$|^\w*(wc|mb|ftc|tc)s\w?cpy(_s)?(_l)?\s*$|^\w*wcpn?cpy(_s)?(_l)?\s*$' + # strcat + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*str\w?cat(_s)?(_l)?\s*$|^\w*(wc|mb|ftc|tc)s\w?cat(_s)?(_l)?\s*$' + # strtok + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*strtok(_r)?(_s)?(_l)?\s*$|^\w*(wc|mb)stok(_r)?(_s)?(_l)?\s*$|^\w*str(find|rspn|trns)\s*$' + # more string parsing (too noisy?) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*strr?chr\s*$|^\w*memchr\s*$|^\w*str(str|sep)\s*$|^\w*strc?spn\s*$|^\w*(str|wcs)pbrk\s*$' + # strlen (too noisy) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*(str|wcs|mbs)n?len\s*$' + # printf + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*s\w*printf(_s)?(_l)?\w*\s*$' + # more printf (should be covered by the format-string-bugs rule) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*printf\w*\s*$|^\w*err\w*\s*$|^\w*warn\w*\s*$|^\w*syslog\w*\s*$' + # scanf + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*scanf(_s)?(_l)?\s*$' + # get + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*get(s|ws(_l)?|ts|tws|c|char|pw|pass|wd|cwd|login(_r)?|groups|hostname|domainname|opt|opt_long)\s*$|^\w*cuserid\s*$' + # environment + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*(get|set|put|unset)env\s*$|^\w*g_get_(home|tmp)_dir\s*$' + # memcpy + - patterns: + - pattern: $FUN($_, $_, $LEN, ...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*mem(c|p)?cpy(_s)?\s*$|^\w*memmove(_s)?\s*$|^\w*bcopy\s*$|^\w*CopyMemory\s*$' + # exclude length known at compile time (sizeof macro) - imperfect match with `memccpy`, but that's acceptable + - pattern-not: $FUN($_, $_, sizeof(...), ...) + # - pattern-not: $FUN($_, $_, <... sizeof(...) ...>, ...) + # exclude length known at compile time (numeric literal) + - metavariable-regex: + metavariable: $LEN + regex: '^(?!\s*(?:0[xX][0-9A-Fa-f]+|0[bB][01]+|0[0-7]*|[1-9][0-9]*)[uUlL]*\s*$).+' + # memset (too noisy, mostly irrelevant unless you use it to erase sensitive data) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*memset(_explicit)?\s*$|^\w*(explicit_)?bzero\s*$' + # alloc + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*alloc(a|f)?\s*$|^\w*alloc_?array\s*$' + # free (too noisy) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*free\s*$' + # exec + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*exec(l|v)?(p|e)?e?\s*$|^\w*system\s*$|^\w*spawn\w?\s*$|^\w*wordexp\s*$|^\w*WinExec\s*$|^\w*ShellExecute(A|ExA|W|ExW)?\s*$|^\w*CreateProcess(A|AsUserA|W|AsUserW|WithLogonW|WithTokenW)?\s*$' + # i/o + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*open(at)?(64)?\s*$|^\w*pipe\s*$|^\w*read\s*$|^\w*recv(from)?\s*$|^\w*copylist\s*$|^\w*dbminit\s*$|^\w*LoadLibrary(A|ExA|W|ExW)?\s*$' + # more i/o (too noisy) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*connect\s*$|^\w*write\s*$|^\w*hton(l|s)\s*$|^\w*ntoh(l|s)\s*$|^\w*dup2?\s*$' + # proc + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*fork\s*$' + # more proc (too noisy) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*clone3?\s*$' + # rand + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*rand(_r|48)?\s*$' + # tmp + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*mk\w?temp(64)?\s*$|^\w*te?mpnam(_r)?\s*$|^\w*tmpfile\s*$|^\w*GetTempFileName(A|W)?\s*$' + # file + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*(mk|ch)(dir|nod)(at)?\s*$|^\w*creat\s*$|^\w*link(at)?\s*$|^\w*rename(at)?\s*$|^\w*access(at|at2|_ok)?\s*$|^\w*stat(at)?\s*$|^\w*ch(own|mod|root)(at)?\s*$|^\w*realpath\s*$|^\w*readlink(at)?\s*$|^\w*(tty|pts)name_r\s*$' + # more file + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*locale\s*$|^\w*(make|split)path\s*$|^\w*fattach\s*$|^\w*ftw\s*$|^\w*truncate\s*$|^\w*u(mask|limit)\s*$|^\w*AddAccessAllowedAce\s*$' + # conf + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*confstr\s*$|^\w*utmpx?name\s*$' + # string conversions + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*mbs(nr|r)?towcs(_l)?\s*$|^\w*wcs(nr|r)?tombs(_l)?\s*$|^\w*OemToCharW\s*$|^\w*MultiByteToWideChar\s*$' + # character conversions (mostly irrelevant) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*mbr?towc(_l)?\s*$|^\w*wcr?tomb(_l)?\s*$' + # inet + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*inet_(ntop|pton)\s*$' + # signals (too noisy) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*kill\s*$|^\w*signal\s*$|^\w*sigaction\s*$|^\w*(set|long)jmp\s*$' + # time + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*cftime\s*$' + # syscall + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*syscall\s*$' + # kernel + - patterns: + - pattern: $FUN(...) + - metavariable-regex: + metavariable: $FUN + regex: '(?i)^\w*copy_(from|to)_user\s*$|^\w*(get|put)_user\s*$|^\w*copy(in|out)\s*$|^\w*cdev_init\s*$' + # more kernel (too noisy) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*ioctl\w*\s*$|^\w*m(re|un)?map\s*$' + # more kernel (too noisy) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*cpu_to_(b|l)e(16|32|64)(p|s)?\s*$|^\w*(b|l)e(16|32|64)(p|s)?_to_cpu\s*$|^\w*xb_get_(32|64|bytes|word_array|bitmap)\s*$' + # assert (should be covered by suspicious-assert rule) + # - patterns: + # - pattern: $FUN(...) + # - metavariable-regex: + # metavariable: $FUN + # regex: '(?i)^\w*assert\w*\s*$' + # switch (too noisy) + # - pattern: | + # switch ($VAR) { } diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/memory-address-exposure.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/memory-address-exposure.c new file mode 100644 index 0000000..5bb02e9 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/memory-address-exposure.c @@ -0,0 +1,51 @@ +// Marco Ivaldi + +#include + +#define BUFSIZE 256 +#define FMT "whatever" + +void print_address(char *string) +{ + char buf[BUFSIZE]; + char fmt[] = "whatever"; + + // ruleid: raptor-memory-address-exposure + printf("address: %p\n", buf); + + // ruleid: raptor-memory-address-exposure + sprintf(buf, "address: %x\n", string); + + // ok: raptor-memory-address-exposure + sprintf(buf, FMT, string); + + // ok: raptor-memory-address-exposure + sprintf(buf, fmt, string); + + // ok: raptor-memory-address-exposure + sprintf(buf, string); +} + +char *genUniqueVal(Node *n) +{ + char *buf = (char *)malloc(32); + if (!buf) + return NULL; + + memset(buf, 0x0, 32); + uint32_t uval = &buf; + + if (uval == 0) + { + uval = drand(); + } + // ruleid: raptor-memory-address-exposure + snprintf(buf, 32, "%x", uval); + return buf; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/memory-address-exposure.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/memory-address-exposure.yaml new file mode 100644 index 0000000..37cef34 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/memory-address-exposure.yaml @@ -0,0 +1,77 @@ +rules: + - id: raptor-memory-address-exposure + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Mishandled Sensitive Information + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - c + - cpp + cwe: + - "CWE-209: Generation of Error Message Containing Sensitive Information" + - "CWE-497: Exposure of Sensitive System Information to an Unauthorized Control Sphere" + owasp: + - A04:2025 - Cryptographic Failures + references: + - https://github.com/struct/mms + message: >- + The software generates an error message that includes sensitive + information about its environment, users, or associated data. + In particular, exposure of memory addresses might defeat ASLR. + severity: INFO + languages: + - c + - cpp + # NOTE: `#define` format specifiers are not considered due to Semgrep limitations, perhaps we could implement this with symbolic propagation (Semgrep Pro experimental feature)? + patterns: + - pattern-either: + # format string in 1st arg + - pattern: printf($FMT, ...) + - pattern: vprintf($FMT, ...) + - pattern: wprintf($FMT, ...) + - pattern: vwprintf($FMT, ...) + - pattern: vcprintf($FMT, ...) + - pattern: vcwprintf($FMT, ...) + - pattern: vscprintf($FMT, ...) + - pattern: vscwprintf($FMT, ...) + - pattern: printk($FMT, ...) + - pattern: warn($FMT, ...) + - pattern: vwarn($FMT, ...) + - pattern: warnx($FMT, ...) + - pattern: vwarnx($FMT, ...) + # format string in 2nd arg + - pattern: fprintf($_, $FMT, ...) + - pattern: vfprintf($_, $FMT, ...) + - pattern: fwprintf($_, $FMT, ...) + - pattern: vfwprintf($_, $FMT, ...) + - pattern: sprintf($_, $FMT, ...) + - pattern: vsprintf($_, $FMT, ...) + - pattern: asprintf($_, $FMT, ...) + - pattern: vasprintf($_, $FMT, ...) + - pattern: dprintf($_, $FMT, ...) + - pattern: vdprintf($_, $FMT, ...) + - pattern: wsprintf($_, $FMT, ...) + - pattern: syslog($_, $FMT, ...) + - pattern: vsyslog($_, $FMT, ...) + - pattern: err($_, $FMT, ...) + - pattern: verr($_, $FMT, ...) + - pattern: errx($_, $FMT, ...) + - pattern: verrx($_, $FMT, ...) + - pattern: warnc($_, $FMT, ...) + - pattern: vwarnc($_, $FMT, ...) + # format string in 3rd arg + - pattern: snprintf($_, $_, $FMT, ...) + - pattern: vsnprintf($_, $_, $FMT, ...) + - pattern: swprintf($_, $_, $FMT, ...) + - pattern: vswprintf($_, $_, $FMT, ...) + - pattern: errc($_, $_, $FMT, ...) + - pattern: verrc($_, $_, $FMT, ...) + - metavariable-regex: + metavariable: $FMT + # NOTE: some format string specifiers are not handled + regex: '(".*%\w*x.*"|".*%\w*X.*"|".*%\w*p.*")' diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management-cpp.cpp b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management-cpp.cpp new file mode 100644 index 0000000..170978d --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management-cpp.cpp @@ -0,0 +1,81 @@ +// Marco Ivaldi + +#include +#include + +void bad1() +{ + BarObj *ptr = new BarObj() + + // ruleid: raptor-mismatched-memory-management-cpp + free(ptr); +} + +void good1() +{ + BarObj *ptr = new BarObj() + + // ok: raptor-mismatched-memory-management-cpp + delete ptr; +} + +class A +{ + void bad2(); + void good2(); +}; + +void A::bad2() +{ + int *ptr; + ptr = (int *)malloc(sizeof(int)); + + // ruleid: raptor-mismatched-memory-management-cpp + delete ptr; +} + +void A::good2() +{ + int *ptr; + ptr = (int *)malloc(sizeof(int)); + + // ok: raptor-mismatched-memory-management-cpp + free(ptr); +} + +class B +{ + void bad3(bool); + void good3(); +}; + +void B::bad3(bool heap) +{ + int localArray[2] = {11, 22}; + int *p = localArray; + + if (heap) + { + p = new int[2]; + } + + // ruleid: raptor-mismatched-memory-management-cpp + delete[] p; +} + +void B::good3() +{ + int localArray[2] = {11, 22}; + int *p = localArray; + + p = new (std::nothrow) int[2]; + + // ok: raptor-mismatched-memory-management-cpp + delete[] p; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management-cpp.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management-cpp.yaml new file mode 100644 index 0000000..e9123ed --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management-cpp.yaml @@ -0,0 +1,67 @@ +rules: + - id: raptor-mismatched-memory-management-cpp + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - cpp + cwe: + - "CWE-762: Mismatched Memory Management Routines" + owasp: + - A06:2025 - Insecure Design + references: + - https://github.com/struct/mms + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + message: >- + The software attempts to return a memory resource to the system, but + it calls a release function that is not compatible with the function + that was originally used to allocate that resource. + Due to inherent limitations of Semgrep, this rule might generate many + false positives and should therefore be customized for your codebase. + severity: INFO + languages: + - cpp + # NOTE: `valloc`, `reallocf`, `aligned_alloc`, and custom wrappers are not covered. + # NOTE: overloaded operators, `VirtualAlloc/VirtualFree`, and `mmap/munmap` are not covered. + pattern-either: + # free + - patterns: + - pattern: free($PTR) + - pattern-not-inside: | + $PTR = malloc(...); + ... + - pattern-not-inside: | + $PTR = calloc(...); + ... + - pattern-not-inside: | + $PTR = realloc(...); + ... + - pattern-not-inside: | + $PTR = strdup(...); + ... + - pattern-not-inside: | + $PTR = strndup(...); + ... + # delete[] + - patterns: + - pattern: delete[]($PTR) + - pattern-not-inside: | + $PTR = new $_[$_]; + ... + # delete + - patterns: + - pattern: delete($PTR) + - pattern-not-inside: | + $PTR = new $_; + ... + - patterns: + - pattern: delete($PTR) + - pattern-inside: | + $PTR = new $_[$_]; + ... diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management.c new file mode 100644 index 0000000..1fb6379 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management.c @@ -0,0 +1,28 @@ +// Marco Ivaldi + +#include +#include + +void bad1() +{ + int localArray[2] = {11, 22}; + int *p = localArray; + + // ruleid: raptor-mismatched-memory-management + free(p); +} + +void good1() +{ + int *ptr; + ptr = (int *)malloc(sizeof(int)); + + // ok: raptor-mismatched-memory-management + free(ptr); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management.yaml new file mode 100644 index 0000000..a203052 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/mismatched-memory-management.yaml @@ -0,0 +1,51 @@ +rules: + - id: raptor-mismatched-memory-management + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - c + - cpp + cwe: + - "CWE-762: Mismatched Memory Management Routines" + owasp: + - A06:2025 - Insecure Design + references: + - https://github.com/struct/mms + message: >- + The software attempts to return a memory resource to the system, but + it calls a release function that is not compatible with the function + that was originally used to allocate that resource. + Due to inherent limitations of Semgrep, this rule might generate many + false positives and should therefore be customized for your codebase. + severity: INFO + languages: + - c + - cpp + # NOTE: `valloc`, `reallocf`, `aligned_alloc`, and custom wrappers are not covered. + # NOTE: `VirtualAlloc/VirtualFree` and `mmap/munmap` are not covered. + pattern-either: + # free + - patterns: + - pattern: free($PTR) + - pattern-not-inside: | + $PTR = malloc(...); + ... + - pattern-not-inside: | + $PTR = calloc(...); + ... + - pattern-not-inside: | + $PTR = realloc(...); + ... + - pattern-not-inside: | + $PTR = strdup(...); + ... + - pattern-not-inside: | + $PTR = strndup(...); + ... diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-break-in-switch.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-break-in-switch.c new file mode 100644 index 0000000..78227f9 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-break-in-switch.c @@ -0,0 +1,141 @@ +// Marco Ivaldi + +#include +#include +#include + +#define FAIL 0 +#define PASS 1 + +void bad1(char *data) +{ + int result = security_check(data); + + // ruleid: raptor-missing-break-in-switch + switch (result) + { + case FAIL: + printf("Security check failed!\n"); + case PASS: + printf("Security check passed.\n"); + break; + default: + printf("Unknown error (%d), exiting...\n", result); + exit(1); + } +} + +void good1(char *data) +{ + int result = security_check(data); + + // ok: raptor-missing-break-in-switch + switch (result) + { + case FAIL: + printf("Security check failed!\n"); + exit(1); + case PASS: + printf("Security check passed.\n"); + break; + default: + printf("Unknown error (%d), exiting...\n", result); + exit(1); + } +} + +struct object *init_object(int type) +{ + struct object *obj; + + if (!(obj = (struct object *)malloc(sizeof(struct object)))) + return NULL; + + obj->type = type; + // ruleid: raptor-missing-break-in-switch + switch (type) + { + case OBJ_STR: + obj->un.str = alloc_string(); + case OBJ_INT: + obj->un.num = alloc_int(); + break; + case OBJ_BOOL: + obj->un.bool = alloc_bool(); + break; + } + return obj; +} + +void printMessage(int month) +{ + // ruleid: raptor-missing-break-in-switch + switch (month) + { + case 1: + printf("January"); + case 2: + printf("February"); + case 3: + printf("March"); + case 4: + printf("April"); + case 5: + printff("May"); + case 6: + printf("June"); + case 7: + printf("July"); + case 8: + printf("August"); + case 9: + printf("September"); + case 10: + printf("October"); + case 11: + printf("November"); + case 12: + printf("December"); + } + printf(" is a great month"); +} + +char *escape_string(char *string) +{ + char *output, *dest; + int escape = 0; + + // there's also an incorrect use of sizeof() here + if (!(output = dest = (char *)calloc(strlen(string + 1, sizeof(string))))) + die("calloc: %m"); + + while (*string) + { + // ruleid: raptor-missing-break-in-switch + switch (*cp) + { + case '\\': + if (escape) + { + *dest++ = '\\'; + escape = 0; + } + else + escape = 1; + break; + case '\n': + *dest++ = ' '; + default: + *string = *dest++; + } + string++; + } + + return output; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-break-in-switch.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-break-in-switch.yaml new file mode 100644 index 0000000..e34e6a8 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-break-in-switch.yaml @@ -0,0 +1,66 @@ +rules: + - id: raptor-missing-break-in-switch + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Other Security + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - c + - cpp + cwe: + - "CWE-484: Omitted Break Statement in Switch" + owasp: + - A08:2025 - Software or Data Integrity Failures + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + - https://github.com/returntocorp/semgrep/issues/4939 + message: >- + The software omits a break statement within a switch or similar + construct, causing code associated with multiple conditions to + execute. This can cause problems when the programmer only intended to + execute code associated with one condition. + severity: INFO + languages: + - c + - cpp + # NOTE: we should also check for default blocks that miss the `break/return/exit/goto` or equivalent statement/function call. + patterns: + - pattern: | + switch ($VAR) { case $VAL1: ... case $VAL2: ... } + # break + - pattern-not: | + switch ($VAR) { case $VAL1: ... break; case $VAL2: ... } + - pattern-not: | + switch ($VAR) { case $VAL1: break; case $VAL2: ... } + # exit + - pattern-not: | + switch ($VAR) { case $VAL1: ... exit($_); case $VAL2: ... } + - pattern-not: | + switch ($VAR) { case $VAL1: exit($_); case $VAL2: ... } + # return + - pattern-not: | + switch ($VAR) { case $VAL1: ... return; case $VAL2: ... } + - pattern-not: | + switch ($VAR) { case $VAL1: return; case $VAL2: ... } + - pattern-not: | + switch ($VAR) { case $VAL1: ... return $_; case $VAL2: ... } + - pattern-not: | + switch ($VAR) { case $VAL1: return $_; case $VAL2: ... } + # goto + - pattern-not: | + switch ($VAR) { case $VAL1: ... goto $_; case $VAL2: ... } + - pattern-not: | + switch ($VAR) { case $VAL1: goto $_; case $VAL2: ... } + # throw (C++) + # - pattern-not: | + # switch ($VAR) { case $VAL1: ... throw $_; case $VAL2: ... } + # - pattern-not: | + # switch ($VAR) { case $VAL1: throw $_; case $VAL2: ... } + # improve output readability + - focus-metavariable: $VAR diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-default-in-switch.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-default-in-switch.c new file mode 100644 index 0000000..05745d6 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-default-in-switch.c @@ -0,0 +1,128 @@ +// Marco Ivaldi + +#include +#include +#include + +#define FAIL 0 +#define PASS 1 + +void bad1(char *data) +{ + int result = security_check(data); + + // ruleid: raptor-missing-default-in-switch + switch (result) + { + case FAIL: + printf("Security check failed!\n"); + exit(1); + break; + case PASS: + printf("Security check passed.\n"); + break; + } +} + +void good1(char *data) +{ + int result = security_check(data); + + // ok: raptor-missing-default-in-switch + switch (result) + { + case FAIL: + printf("Security check failed!\n"); + exit(1); + break; + case PASS: + printf("Security check passed.\n"); + break; + default: + printf("Unknown error (%d), exiting...\n", result); + exit(1); + } +} + +void bad2(Pkt packet) +{ + // ruleid: raptor-missing-default-in-switch + switch (packet->id) + { + case 1: + initAuth(packet); + break; + case 2: + initReset(packet); + break; + case 3: + initDisconnect(packet); + break; + } + + processPacket(packet); +} + +struct object *init_object(int type) +{ + struct object *obj; + + if (!(obj = (struct object *)malloc(sizeof(struct object)))) + return NULL; + + obj->type = type; + // ruleid: raptor-missing-default-in-switch + switch (type) + { + case OBJ_STR: + obj->un.str = alloc_string(); + break; + case OBJ_INT: + obj->un.num = alloc_int(); + break; + case OBJ_BOOL: + obj->un.bool = alloc_bool(); + break; + } + return obj; +} + +void test() +{ + // ruleid: raptor-missing-default-in-switch + switch (foo() + x + y) + { + case 1: + break; + case 2: + break; + } + + // ok: raptor-missing-default-in-switch + switch (foo() + x + y) + { + case 1: + break; + default: + break; + case 2: + break; + } + + // ok: raptor-missing-default-in-switch + switch (foo() + x + y) + { + case 1: + break; + case 2: + break; + default: + break; + } +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-default-in-switch.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-default-in-switch.yaml new file mode 100644 index 0000000..ab392de --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-default-in-switch.yaml @@ -0,0 +1,36 @@ +rules: + - id: raptor-missing-default-in-switch + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Other Security + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - c + - cpp + cwe: + - "CWE-478: Missing Default Case in Multiple Condition Expression" + owasp: + - A08:2025 - Software or Data Integrity Failures + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + - https://github.com/returntocorp/semgrep/issues/4939 + message: >- + The code does not have a default case in an expression with multiple + conditions, such as a switch statement. + severity: INFO + languages: + - c + - cpp + patterns: + - pattern: | + switch ($VAR) { } + - pattern-not: | + switch ($VAR) { default: ... } + # improve output readability + - focus-metavariable: $VAR diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-return.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-return.c new file mode 100644 index 0000000..198322b --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-return.c @@ -0,0 +1,28 @@ +// Marco Ivaldi + +#include + +// ok: raptor-missing-return +int bad(); + +// ok: raptor-missing-return +int baddie(int foo); + +// ruleid: raptor-missing-return +int bad1(void) +{ + printf("Hello, World!"); +} + +// ok: raptor-missing-return +void good1(void) +{ + printf("Hello, World!"); +} + +// ok: raptor-missing-return +int main(int argc, char **argv) +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-return.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-return.yaml new file mode 100644 index 0000000..dad9f9f --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/missing-return.yaml @@ -0,0 +1,43 @@ +rules: + - id: raptor-missing-return + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Other Security + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - c + - cpp + cwe: + - "CWE-393: Return of Wrong Status Code" + - "CWE-394: Unexpected Status Code or Return Value" + owasp: + - A08:2025 - Software or Data Integrity Failures + references: + - https://stackoverflow.com/questions/10858391/why-do-programs-in-c-compile-even-when-the-return-statement-is-missing + message: >- + A non-void function does not have a return statement. Hence, its + return value can be considered undefined. + severity: INFO + languages: + - c + - cpp + # NOTE: C++ class declarations should also be excluded, but apparently this pattern is not supported by Semgrep. + patterns: + - pattern: $_ $FUN(...) { ... } + # exclude function declarations + - pattern-not: $_ $FUN(...); + # exclude functions with return statement + - pattern-not: $_ $FUN(...) { ... return $_; } + # exclude main function + - pattern-not: int main(...) { ... } + # exclude void functions + - pattern-not: void $FUN(...) { ... } + # improve output readability + - focus-metavariable: $FUN + # exclude else if (commented-out for performance reasons) + # - pattern-not: ... if ($COND) { ... } diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/off-by-one.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/off-by-one.c new file mode 100644 index 0000000..04d12db --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/off-by-one.c @@ -0,0 +1,390 @@ +// Marco Ivaldi + +#include +#include +#include + +#define BUFSIZE 256 + +void bad1(char *string) +{ + char buf[BUFSIZE]; + + strncpy(buf, string, BUFSIZE); + // ruleid: raptor-off-by-one + buf[BUFSIZE] = '\0'; +} + +void good1(char *string) +{ + char buf[BUFSIZE]; + + strncpy(buf, string, BUFSIZE); + // ok: raptor-off-by-one + buf[BUFSIZE - 1] = '\0'; +} + +void bad2(char *string) +{ + char firstname[20]; + char lastname[20]; + char fullname[40]; + + fullname[0] = '\0'; + + // ruleid: raptor-off-by-one + strncat(fullname, firstname, 40); +} + +void good2(char *string) +{ + char firstname[20]; + char lastname[20]; + char fullname[40]; + + fullname[0] = '\0'; + + // ok: raptor-off-by-one + strncat(fullname, firstname, sizeof(fullname) - strlen(fullname) - 1); +} + +void bad3(char *string) +{ + char filename[BUFSIZE]; + + // commented-out because of too many false positives: raptor-off-by-one + for (int i = 0; i <= BUFSIZE; i++) + { + char c = getc(); + if (c == 'EOF') + { + filename[i] = '\0'; + } + filename[i] = getc(stdin); + } +} + +void good3(char *string) +{ + char filename[BUFSIZE]; + + // ok: raptor-off-by-one + for (int i = 0; i < BUFSIZE; i++) + { + char c = getc(); + if (c == 'EOF') + { + filename[i] = '\0'; + } + filename[i] = getc(stdin); + } +} + +void test_func() +{ + int id_sequence[3]; + + id_sequence[0] = 123; + id_sequence[1] = 234; + id_sequence[2] = 345; + // ruleid: raptor-off-by-one + id_sequence[3] = 456; +} + +void processRawStr(uint8_t *s, size_t sz) +{ + uint8_t buf[1024]; + memset(buf, 0x0, sizeof(buf)); + memcpy(buf, s, sizeof(buf)); + // ruleid: raptor-off-by-one + buf[sizeof(buf)] = '\0'; + // ... +} + +void process_string(char *src) +{ + char dest[32]; + + // commented-out because of too many false positives: raptor-off-by-one + for (i = 0; src[i] && (i <= sizeof(dest)); i++) + dest[i] = src[i]; + + // ... + + return; +} + +void get_user(char *user) +{ + char buf[1024]; + + // ruleid: raptor-off-by-one + if (strlen(user) > sizeof(buf)) + die("error: user string too long\n"); + + strcpy(buf, user); + // ... +} + +int get_mac(int fd, struct session *session) +{ + unsigned int i, n; + + n = read_network_integer(fd); + if (n > MAX_MAC) + return 1; + + // commented-out because of too many false positives: raptor-off-by-one + for (i = 0; i <= n; i++) + session->mac[i] = read_network_integer(fd); + return 0; +} + +int variant1(int argc, char *argv[]) +{ + char buf[10]; + + // ruleid: raptor-off-by-one + *(buf + 10) = 'A'; + + return 0; +} + +int variant2(int argc, char *argv[]) +{ + char bStr[10]; + // commented-out because of too many false positives: raptor-off-by-one + for (unsigned i = 1; i <= 10; ++i) + { + bStr[i] = (char)i + 'a'; + } + return 0; +} + +static LabelText *text_create(char *orig_str, int char_width) +{ + int i, j; + char line[256]; /* a line should not exceed this length */ + int pos; + int last_space; + int new_line; + LabelText *text = 0; + char *str = 0; + text = calloc(1, sizeof(LabelText)); + + str = strdup(orig_str); + + if (char_width > 0) + { + for (i = 0; i < strlen(str); i++) + if (str[i] == 10) + text->count++; + + // ruleid: raptor-off-by-one + if (str[strlen(str) - 1] != 10) + text->count++; + } + + return NULL; +} + +static LabelText *text_create2(char *orig_str, int char_width) +{ + int i, j; + char line[256]; /* a line should not exceed this length */ + int pos; + int last_space; + int new_line; + LabelText *text = 0; + char *str = 0; + int length; + text = calloc(1, sizeof(LabelText)); + + str = strdup(orig_str); + length = strlen(str); + + if (char_width > 0) + { + for (i = 0; i < strlen(str); i++) + if (str[i] == 10) + text->count++; + + // ruleid: raptor-off-by-one + if (str[strlen(str) - 1] != 10) + text->count++; + } + + return NULL; +} + +void addLineAfter(struct line *whichLine, char *data) +{ + struct line *temp = whichLine->next; + struct line *newLine = (struct line *)malloc(sizeof(struct line)); + temp->prev = newLine; + whichLine->next = newLine; + newLine->next = temp; + newLine->prev = whichLine; + // ruleid: raptor-off-by-one + newLine->data = (char *)malloc(strlen(data)); + strcpy(newLine->data, data); + newLine->length = strlen(data); + countTabs(newLine); + currentBuffer->numLines++; +} + +void addLineAfter_fixed(struct line *whichLine, char *data) +{ + struct line *temp = whichLine->next; + struct line *newLine = (struct line *)malloc(sizeof(struct line)); + temp->prev = newLine; + whichLine->next = newLine; + newLine->next = temp; + newLine->prev = whichLine; + // ok: raptor-off-by-one + newLine->data = (char *)malloc(strlen(data) + 1); + strcpy(newLine->data, data); + newLine->length = strlen(data); + countTabs(newLine); + currentBuffer->numLines++; +} + +void flawed_strdup(const char *input) +{ + char *copy; + + // ruleid: raptor-off-by-one + copy = (char *)malloc(strlen(input)); + strcpy(copy, input); + return copy; +} + +void ok_strdup(const char *input) +{ + char *copy; + + // ok: raptor-off-by-one + copy = (char *)malloc(strlen(input) + 1); + strcpy(copy, input); + return copy; +} + +void flawed_strdup2(const char *input) +{ + char *copy; + + int len = strlen(input); + + // ruleid: raptor-off-by-one + copy = (char *)malloc(len); + strcpy(copy, input); + return copy; +} + +void ok_strdup2(const char *input) +{ + char *copy; + + int len = strlen(input); + + // ok: raptor-off-by-one + copy = (char *)malloc(len + 1); + strcpy(copy, input); + return copy; +} + +int two_dimensions(int argc, char *argv[]) +{ + char buffer[1][256]; + // ruleid: raptor-off-by-one + buffer[0][256] = '!'; + // ruleid: raptor-off-by-one + buffer[1][1] = '!'; + // ok: raptor-off-by-one + buffer[0][255] = '!'; + return 0; +} + +void f(const char *str) +{ + // ruleid: raptor-off-by-one + char *buffer = malloc(strlen(str)); + free(buffer); +} + +void f(const char *str) +{ + // ok: raptor-off-by-one + char *buffer = malloc(strlen(str) + 1); + free(buffer); +} + +void f(const char *str) +{ + // ok: raptor-off-by-one + char *buffer = malloc(strlen(str) + 1); + free(buffer); +} + +void f(const char *str) +{ + size_t len = strlen(str); + // ruleid: raptor-off-by-one + char *buffer = malloc(len); + free(buffer); +} + +void f(const char *str) +{ + size_t len = strlen(str); + // ok: raptor-off-by-one + char *buffer = malloc(len + 1); + free(buffer); +} + +void f(const char *str) +{ + size_t len; + len = strlen(str); + // ruleid: raptor-off-by-one + char *buffer = malloc(len); + free(buffer); +} + +void f(const char *str) +{ + size_t len = strlen(str); + len += 1; + // todook: raptor-off-by-one + char *buffer = malloc(len); + free(buffer); +} + +void f(const char *str) +{ + size_t len = strlen(str); + if (nondet) + { + len += 1; + } + // ruleid: raptor-off-by-one + char *buffer = malloc(len); + free(buffer); +} + +void f(const char *str) +{ + size_t len = strlen(str); + if (len) + { + // ruleid: raptor-off-by-one + char *buffer = malloc(len); + free(buffer); + } +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/off-by-one.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/off-by-one.yaml new file mode 100644 index 0000000..d32d7d8 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/off-by-one.yaml @@ -0,0 +1,107 @@ +rules: + - id: raptor-off-by-one + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-193: Off-by-one Error" + - "CWE-787: Out-of-bounds Write" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + message: >- + The software calculates or uses an incorrect maximum or minimum value + that is 1 more, or 1 less, than the correct value. + severity: WARNING + languages: + - c + - cpp + # NOTE: C++ `new` operator and some heap allocation functions are not covered. + # NOTE: some string and memory copy functions are not covered. + # NOTE: `memcpy(dst + 1, p, len)` and similar scenarios are not covered. + # NOTE: pattern `{$len=snprintf(_); malloc($len);}` is not covered. + # NOTE: some other ways to create an array are not covered. + # NOTE: refer also to `metavariable-comparison` to catch larger indexes as in https://github.com/parsiya/semgrep-hotspots/blob/main/cpp/arrays-out-of-bounds-access.yaml + # NOTE: refer also to `cpp.lang.security.strings.alloc-strlen.alloc-strlen` and `cpp.lang.security.strings.missing-nul-cpp-string-memcpy.missing-nul-cpp-string-memcpy`. + pattern-either: + # array access + - pattern: $BUF[sizeof($BUF)] = ... + - patterns: + - pattern: $BUF[$LEN] = ... + - pattern-either: + - pattern-inside: | + $_ $BUF[$LEN]; + ... + - pattern-inside: | + $_ $BUF[$LEN] = ...; + ... + - patterns: + - pattern: | + *($BUF + $LEN) = ... + - pattern-either: + - pattern-inside: | + $_ $BUF[$LEN]; + ... + - pattern-inside: | + $_ $BUF[$LEN] = ...; + ... + # two-dimentional array access + - patterns: + - pattern: $BUF[$X][$Y] = ... + - pattern-either: + - pattern-inside: | + $_ $BUF[$_][$Y]; + ... + - pattern-inside: | + $_ $BUF[$X][$_]; + ... + # - pattern: for (<... $I = $NUM ...>; <... $I <= $LEN ...>; <... $I++ ...>) ... + # - pattern: for (<... $I = $NUM ...>; <... $I <= $LEN ...>; <... ++$I ...>) ... + # suspicious loops + # <... $I = 0 ...> is still not supported by Semgrep as of 2025-11-22 + # - pattern: for ($_ $I = $NUM; <... $I <= $LEN ...>; <... $I++ ...>) ... + # - pattern: for ($_ $I = $NUM; <... $I <= $LEN ...>; <... ++$I ...>) ... + # - pattern: while (<... $I <= $LEN ...>) ... + # - pattern: do ... while (<... $I <= $LEN ...>); + # strlen vs. sizeof + - pattern: strlen($SRC) > sizeof($DST) + - pattern: strlen($SRC) <= sizeof($DST) + - pattern: sizeof($DST) < strlen($SRC) + - pattern: sizeof($DST) >= strlen($SRC) + # potential strncat misuse + - patterns: + - pattern: strncat($_, $_, $LEN) + - metavariable-pattern: + metavariable: $LEN + patterns: + - pattern-not: $_ - 1 + # out-of-bound indexing: strlen($STR) con be 0 leading to a -1 index + - pattern: $STR[strlen($STR) - 1] + - patterns: + - pattern-inside: | + $LEN = strlen($STR) - 1; + ... + - pattern: $STR[$LEN] + - patterns: + - pattern-inside: | + $LEN = strlen($STR); + ... + - pattern: $STR[$LEN - 1] + # no space allocated for NUL terminator + - pattern: malloc(strlen($STR)) + - patterns: + - pattern-inside: | + $LEN = strlen($STR); + ... + - pattern: malloc($LEN) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/overlapping-source-destination.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/overlapping-source-destination.c new file mode 100644 index 0000000..498fb5c --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/overlapping-source-destination.c @@ -0,0 +1,74 @@ +// Marco Ivaldi + +#include +#include + +#define SIZE 256 + +int test1() +{ + // ... + for (oct_cnt = 1; oct_cnt < 7; oct_cnt++) + { + oct = (u_int8_t)retrieve_rand_int(0xFF); + if (oct_cnt != 1) + // ruleid: raptor-overlapping-source-destination + sprintf(eaddr, "%s:%0x", eaddr, oct); + else + sprintf(eaddr, "%0x", oct); + } + return eaddr; +} + +int test2() +{ + char buf[SIZE]; + + // ruleid: raptor-overlapping-source-destination + sprintf(buf, "%s:%s:%s", prepend, buf, append); + + // ruleid: raptor-overlapping-source-destination + snprintf(buf, SIZE, "%s:%s", prepend, buf); + + // ruleid: raptor-overlapping-source-destination + sprintf(buf, "%s some further text", buf); + + return 0; +} + +int test2_ok(void) +{ + char tmp[SIZE]; + + // ok: raptor-overlapping-source-destination + snprintf(tmp, SIZE, "%s:%s:%s", prepend, buf, append); + // ok: raptor-overlapping-source-destination + strlcpy(buf, tmp, SIZE); + + // ok: raptor-overlapping-source-destination + snprintf(tmp, SIZE, "%s:%s", prepend, buf); + // ok: raptor-overlapping-source-destination + strlcpy(buf, tmp, SIZE); + + // ok: raptor-overlapping-source-destination + snprintf(tmp, SIZE, "%s some further text", buf); + // ok: raptor-overlapping-source-destination + strlcpy(buf, tmp, SIZE); + + return 0; +} + +int test3(char *buf) +{ + // ruleid: raptor-overlapping-source-destination + memcpy(buf, buf, 16); + + // ruleid: raptor-overlapping-source-destination + strcpy(buf, buf); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/overlapping-source-destination.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/overlapping-source-destination.yaml new file mode 100644 index 0000000..ed218d2 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/overlapping-source-destination.yaml @@ -0,0 +1,80 @@ +rules: + - id: raptor-overlapping-source-destination + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: LOW + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-1260: Improper Handling of Overlap Between Protected Memory Ranges" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://linux.die.net/man/3/sprintf + message: >- + C standards specify that the results are undefined if a call to + copy functions, with the exception of memmove(), would cause copying + to take place between objects that overlap (e.g., if the target + string array and one of the supplied input arguments refer to the + same buffer). + severity: WARNING + languages: + - c + - cpp + # NOTE: `vsprintf`, `vsnprintf`, `swprintf`, and `vswprintf` are not covered. + # NOTE: `strcpy_s`, `strcat_s`, and similar variants are not covered. + pattern-either: + - patterns: + - pattern: $FUN($DST, $DST, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + # strcpy + - pattern: strcpy + - pattern: strncpy + - pattern: stpcpy + - pattern: stpncpy + - pattern: strlcpy + - pattern: strscpy + - pattern: wcscpy + - pattern: wcsncpy + - pattern: wcpcpy + - pattern: wcpncpy + - pattern: wcslcpy + - pattern: _mbscpy + - pattern: _mbsncpy + - pattern: _mbpcpy + - pattern: _mbpncpy + - pattern: _mbslcpy + - pattern: strccpy + - pattern: strcadd + - pattern: streadd + - pattern: strecpy + # strcat + - pattern: strcat + - pattern: strncat + - pattern: strlcat + - pattern: wcscat + - pattern: wcsncat + - pattern: wcslcat + - pattern: _mbscat + - pattern: _mbsncat + - pattern: _mbslcat + # memcpy + - pattern: memcpy + - pattern: memccpy + - pattern: wmemcpy + - pattern: mempcpy + - pattern: wmempcpy + # bcopy + - pattern: bcopy + # sprintf + - pattern: sprintf($DST, ..., $DST, ...) + - pattern: snprintf($DST, $_, ..., $DST, ...) diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/pointer-subtraction.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/pointer-subtraction.c new file mode 100644 index 0000000..35529a3 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/pointer-subtraction.c @@ -0,0 +1,63 @@ +// Marco Ivaldi + +#include +#include +#include + +void bad1(char *tmp, char *ptr1, char *ptr2) +{ + // ruleid: raptor-pointer-subtraction + memcpy(tmp, ptr1, (ptr2 - ptr1) - 1); +} + +int good1(char *tmp, char *ptr1, char *ptr2) +{ + if (!tmp || !ptr1 || !ptr2) + return -1; + + if (ptr2 <= ptr1) + return -1; // negative or zero-length copy + + // the rule should arguably check for this pattern of pointer subtraction with a length check, + // which is a common pattern for safely handling pointer subtraction + // todook: raptor-pointer-subtraction + size_t len = (size_t)(ptr2 - ptr1) - 1; + if (len == 0) + return -1; + + memcpy(tmp, ptr1, len); + return 0; +} + +void bad2(char *ptr1, char *ptr2) +{ + // ruleid: raptor-pointer-subtraction + char *tmp = (char *)malloc(ptr2 - ptr1); +} + +struct node +{ + int data; + struct node *next; +}; + +int size(struct node *head) +{ + struct node *current = head; + struct node *tail; + + while (current != NULL) + { + tail = current; + current = current->next; + } + + // ruleid: raptor-pointer-subtraction + return tail - head; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/pointer-subtraction.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/pointer-subtraction.yaml new file mode 100644 index 0000000..e1edb3a --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/pointer-subtraction.yaml @@ -0,0 +1,65 @@ +rules: + - id: raptor-pointer-subtraction + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-469: Use of Pointer Subtraction to Determine Size" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://github.com/struct/mms + message: >- + The software subtracts one pointer from another in order to determine + size, but this calculation can be incorrect if the pointers do not + exist in the same memory chunk. + severity: WARNING + languages: + - c + - cpp + # NOTE: some types and combinations are missing; also, function calls are not covered. + pattern-either: + # type-based patterns + - pattern: (char * $_) - (char * $_) + - pattern: (int * $_) - (int * $_) + - pattern: (float * $_) - (float * $_) + - pattern: (double * $_) - (double * $_) + # other patterns + - patterns: + - pattern-either: + - pattern: $PTR1 - $PTR2 + - pattern: $PTR2 - $PTR1 + - pattern-either: + - pattern-inside: | + $_ * $PTR1; + $_ * $PTR2; + ... + - pattern-inside: | + $_ * $PTR1 = ...; + $_ * $PTR2 = ...; + ... + - pattern-inside: | + $_ * $PTR1 = ...; + $_ * $PTR2; + ... + - pattern-inside: | + $_ * $PTR1; + $_ * $PTR2 = ...; + ... + - pattern-inside: | + $_ * $PTR3 = $PTR1; + $_ * $PTR2; + ... + - pattern-inside: | + $_ * $PTR2; + $_ * $PTR3 = $PTR1; + ... diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/putenv-stack-var.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/putenv-stack-var.c new file mode 100644 index 0000000..a30c40e --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/putenv-stack-var.c @@ -0,0 +1,49 @@ +// Marco Ivaldi + +#include +#include +#include + +#define STR_MAX 256 + +int putName_bad() +{ + char name[STR_MAX]; + + fillInName(name); + + // ruleid: raptor-putenv-stack-var + putenv(name); + + return 0; +} + +int putName_good() +{ + char *name = (char *)malloc(STR_MAX); + + fillInName(name); + + // ok: raptor-putenv-stack-var + putenv(name); + + return 0; +} + +int putName_good2() +{ + static char name[STR_MAX]; + + fillInName(name); + + // ok: raptor-putenv-stack-var + putenv(name); + + return 0; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/putenv-stack-var.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/putenv-stack-var.yaml new file mode 100644 index 0000000..7f90369 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/putenv-stack-var.yaml @@ -0,0 +1,85 @@ +rules: + - id: raptor-putenv-stack-var + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-686: Function Call With Incorrect Argument Type" + - "CWE-562: Return of Stack Variable Address" + owasp: + - A06:2025 - Insecure Design + references: + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: >- + The software calls putenv() with a variable that has a short lifetime, + such as a pointer to an automatic variable allocated on the stack. The + correct behavior is to call putenv() with a static/global string. + severity: INFO + languages: + - c + - cpp + # NOTE: global variables declared outside functions and not explicitly tagged as static are not supported. + # NOTE: multi-dimensional arrays and other ways to create an array are not covered. + # NOTE: multiple pointer assignments and other ways to persist after function returns (e.g., output parameter) are not covered. + patterns: + - pattern: putenv($PTR) + - pattern-either: + # array + - patterns: + - pattern-inside: | + $_ $PTR[$_]; + ... + - pattern-not-inside: | + static $_ $PTR[$_]; + ... + - patterns: + - pattern-inside: | + $_ $PTR[$_] = ...; + ... + - pattern-not-inside: | + static $_ $PTR[$_] = ...; + ... + - patterns: + - pattern-inside: | + $_ $PTR[] = ...; + ... + - pattern-not-inside: | + static $_ $PTR[] = ...; + ... + # pointer to array + - patterns: + - pattern-inside: | + $_ $ARR[$_]; + ... + $PTR = $ARR; + ... + - pattern-not-inside: | + static $_ $ARR[$_]; + ... + - patterns: + - pattern-inside: | + $_ $ARR[$_] = ...; + ... + $PTR = $ARR; + ... + - pattern-not-inside: | + static $_ $ARR[$_] = ...; + ... + - patterns: + - pattern-inside: | + $_ $ARR[] = ...; + ... + $PTR = $ARR; + ... + - pattern-not-inside: | + static $_ $ARR[] = ...; + ... diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/regex-dos.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/regex-dos.c new file mode 100644 index 0000000..584785e --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/regex-dos.c @@ -0,0 +1,57 @@ +// Marco Ivaldi + +// semgrep is currently unable to catch this +// todoruleid: raptor-regex-dos +#define REGEX "^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$" + +int regex1() +{ + regex_t r1, r2, r3; + int ret; + // ruleid: raptor-regex-dos + char regex[] = "^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$" + + ret = regcomp(&r1, + // ruleid: raptor-regex-dos + "^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$", + 0); + if (ret) + return 1; + + if (ret = regcomp(&r2, + // ruleid: raptor-regex-dos + "^([a-zA-Z0-9])(([\-.]|[_]+)?" + "([a-zA-Z0-9]+))*(@){1}[a-z0-9]+" + "[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$", + 0)) + return 1; + + ret = regcomp(&r3, regex, 0); + if (ret) + return 1; + + return 0; +} + +int regex2() +{ + regex_t r; + int value; + + // ok: raptor-regex-dos + value = regcomp(&r, "[:word:]", 0); + + if (!value) + { + printf("RegEx compiled successfully."); + return 1; + } + printf("Compilation error."); + return 0; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/regex-dos.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/regex-dos.yaml new file mode 100644 index 0000000..764eb7c --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/regex-dos.yaml @@ -0,0 +1,55 @@ +rules: + - id: raptor-regex-dos + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Denial-of-Service (DoS) + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-1333: Inefficient Regular Expression Complexity" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://semgrep.dev/docs/writing-rules/metavariable-analysis + - https://github.com/semgrep/semgrep/pull/4672 + message: >- + The software uses a regular expression with an inefficient, possibly + exponential worst-case computational complexity that consumes excessive + CPU cycles. Poorly constructed regular expressions that exhibit + exponential runtime when fed specifically crafted inputs can cause RegEx + denial of service (ReDoS). + severity: WARNING + languages: + - c + - cpp + # NOTE: the C++ `std::regex` library is not covered. + patterns: + - pattern-either: + - pattern: $FUN($_, $REGEX, $_) + - pattern: | + $STRING = $REGEX; + ... + <... $FUN($_, $STRING, $_) ...>; + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: regcomp + - pattern: regncomp + - pattern: regwcomp + - pattern: regwncomp + - pattern: regcomp_l + - pattern: regncomp_l + - pattern: regwcomp_l + - pattern: regwncomp_l + - metavariable-analysis: + analyzer: redos + metavariable: $REGEX + # improve output readability + - focus-metavariable: $REGEX diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/ret-stack-address.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/ret-stack-address.c new file mode 100644 index 0000000..fa20a3c --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/ret-stack-address.c @@ -0,0 +1,85 @@ +// Marco Ivaldi + +#include +#include +#include + +#define STR_MAX 256 + +char *getName_bad() +{ + char name[STR_MAX]; + + fillInName(name); + // ruleid: raptor-ret-stack-address + return name; +} + +char *getName_good() +{ + char *name = (char *)malloc(STR_MAX); + + fillInName(name); + // ok: raptor-ret-stack-address + return name; +} + +char *getName_good2() +{ + static char name[STR_MAX]; + + fillInName(name); + // ok: raptor-ret-stack-address + return name; +} + +char *findF(char *b) +{ + char tmpbuf[1024]; + char *p = tmpbuf; + memcpy(tmpbuf, b, 1024); + + while (*p != '\0') + { + if (*p == 'F') + // ruleid: raptor-ret-stack-address + return p; + p++; + } + return NULL; +} + +void fillMem() +{ + char a[2048]; + memset(a, 'Z', sizeof(a)); +} + +void recvStr(char *str) +{ + char *fPtr = findF(str); + + fillMem(); + if (fPtr == NULL) + { + printf("No F!"); + } + else + { + printf("F = %s", fPtr); + } +} + +int *f(void) +{ + int local_auto; + + // ruleid: raptor-ret-stack-address + return &local_auto; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/ret-stack-address.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/ret-stack-address.yaml new file mode 100644 index 0000000..627ec7f --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/ret-stack-address.yaml @@ -0,0 +1,141 @@ +rules: + - id: raptor-ret-stack-address + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: LOW + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-562: Return of Stack Variable Address" + owasp: + - A06:2025 - Insecure Design + references: + - https://github.com/struct/mms + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + - https://rules.sonarsource.com/c/type/Bug/RSPEC-946 + message: >- + A function returns the address of a stack variable, which will cause + unintended program behavior, typically in the form of a crash. + severity: INFO + languages: + - c + - cpp + # NOTE: global variables declared outside functions and not explicitly tagged as static are not supported. + # NOTE: multi-dimensional arrays and other ways to create an array are not covered. + # NOTE: multiple pointer assignments and other ways to persist after function returns (e.g., output parameter) are not covered. + # NOTE: a dedicated rule for C++ types/constructs should be implemented (see `cpp.lang.security.strings.return-c-str.return-c-str` and `cpp.lang.security.containers.std-return-data.std-return-data`). + pattern-either: + - patterns: + - pattern: return $PTR; + - pattern-either: + # array + - patterns: + - pattern-inside: | + $_ $PTR[$_]; + ... + - pattern-not-inside: | + static $_ $PTR[$_]; + ... + - patterns: + - pattern-inside: | + $_ $PTR[$_] = ...; + ... + - pattern-not-inside: | + static $_ $PTR[$_] = ...; + ... + - patterns: + - pattern-inside: | + $_ $PTR[] = ...; + ... + - pattern-not-inside: | + static $_ $PTR[] = ...; + ... + # pointer to array + - patterns: + - pattern-inside: | + $_ $ARR[$_]; + ... + $PTR = $ARR; + ... + - pattern-not-inside: | + static $_ $ARR[$_]; + ... + - patterns: + - pattern-inside: | + $_ $ARR[$_] = ...; + ... + $PTR = $ARR; + ... + - pattern-not-inside: | + static $_ $ARR[$_] = ...; + ... + - patterns: + - pattern-inside: | + $_ $ARR[] = ...; + ... + $PTR = $ARR; + ... + - pattern-not-inside: | + static $_ $ARR[] = ...; + ... + - patterns: + # address of local variable + - pattern: return &$VAR; + - pattern-either: + - patterns: + - pattern-inside: | + $_ $VAR; + ... + - pattern-not-inside: | + static $_ $VAR; + ... + - patterns: + - pattern-inside: | + $_ $VAR = ...; + ... + - pattern-not-inside: | + static $_ $VAR = ...; + ... + - patterns: + - pattern-inside: | + $_ $VAR[$_]; + ... + - pattern-not-inside: | + static $_ $VAR[$_]; + ... + - patterns: + - pattern-inside: | + $_ $VAR[$_] = ...; + ... + - pattern-not-inside: | + static $_ $VAR[$_] = ...; + ... + - patterns: + - pattern-inside: | + $_ $VAR[] = ...; + ... + - pattern-not-inside: | + static $_ $VAR[] = ...; + ... + - patterns: + - pattern-inside: | + $_ * $VAR; + ... + - pattern-not-inside: | + static $_ * $VAR; + ... + - patterns: + - pattern-inside: | + $_ * $VAR = ...; + ... + - pattern-not-inside: | + static $_ * $VAR = ...; + ... diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.c new file mode 100644 index 0000000..c5e54b4 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.c @@ -0,0 +1,239 @@ +// Marco Ivaldi + +#include +#include + +// https://pwning.systems/posts/php_filter_var_shenanigans/ +static int _php_filter_validate_domain(char *domain, int len, zend_long flags) +{ + char *e, *s, *t; + size_t l; + int hostname = flags & FILTER_FLAG_HOSTNAME; + unsigned char i = 1; + + s = domain; + // ruleid: raptor-signed-unsigned-conversion + l = len; + e = domain + l; + t = e - 1; + + // ... + return 0; +} + +// https://blog.quarkslab.com/heap-overflow-in-openbsds-slaacd-via-router-advertisement.html +char * +parse_dnssl(char *data, int datalen) +{ + int len, pos; + char *nssl, *nsslp; + + // ruleid: raptor-signed-unsigned-conversion + if ((nssl = calloc(1, datalen + 1)) == NULL) + { // false positive + log_warn("malloc"); + return NULL; + } + nsslp = nssl; + + pos = 0; + + do + { + len = data[pos]; + if (len > 63 || len + pos + 1 > datalen) + { + free(nssl); + log_warnx("invalid label in DNSSL"); + return NULL; + } + if (len == 0) + { + if (pos < datalen && data[pos + 1] != 0) + *nsslp++ = ' '; + else + break; + } + else + { + if (pos != 0 && data[pos - 1] != 0) + *nsslp++ = '.'; + // ruleid: raptor-signed-unsigned-conversion + memcpy(nsslp, data + pos + 1, len); + nsslp += len; + } + pos += len + 1; + } while (pos < datalen); + if (len != 0) + { + free(nssl); + log_warnx("invalid label in DNSSL"); + return NULL; + } + return nssl; +} + +// http://www.phrack.org/issues/60/10.html#article +int copy_something1(char *buf, int len) +{ + char kbuf[800]; + + if (len > sizeof(kbuf)) + { + return -1; + } + + // ruleid: raptor-signed-unsigned-conversion + return memcpy(kbuf, buf, len); +} + +int copy_something2(char *buf, size_t len) +{ + char kbuf[800]; + + if (!buf || len == 0 || len > sizeof(kbuf)) + return -1; + + // ok: raptor-signed-unsigned-conversion + memcpy(kbuf, buf, len); + return 0; +} + +// ruleid: raptor-signed-unsigned-conversion +unsigned int readdata() +{ + int amount = 0; + + if (result == ERROR) + amount = -1; + + return amount; +} + +// ruleid: raptor-signed-unsigned-conversion +unsigned int readdata2() +{ + int amount = 0; + + amount = accessmainframe(); + + return amount; +} + +void copy_memory() +{ + int size = 256; + + // ruleid: raptor-signed-unsigned-conversion + memcpy(destBuf, srcBuf, size); +} + +void test_func(int argc, char **argv) +{ + char path[256]; + char *input; + int i; + unsigned int sz; + + i = GetUntrustedInt(); + + if (i > 256) + { + DiePainfully("go away!\n"); + } + + // ruleid: raptor-signed-unsigned-conversion + sz = i; + + // ruleid: raptor-signed-unsigned-conversion + strncpy(path, input, i); + path[255] = '\0'; + printf("Path is: %s\n", path); +} + +void blowup_stack() +{ + int a = 5, b = 6; + // ruleid: raptor-signed-unsigned-conversion + size_t len = a - b; + char buf[len]; +} + +void disaster() +{ + int len; + + len = get_len_field(); + // ruleid: raptor-signed-unsigned-conversion + snprintf(dst, len, "%s", src); +} + +int watch_dns_ptr() +{ + char *indx; + int count; + char nameStr[256]; + + // ... + memset(nameStr, '\0', sizeof(nameStr)); + // ... + indx = (char *)(pkt + rr_offset); + count = (char)*indx; + + while (count) + { + (char *)indx++; + // ruleid: raptor-signed-unsigned-conversion + strncat(nameStr, (char *)indx, count); + indx += count; + count = (char)*indx; + // there's also a strncat() misuse here + strncat(nameStr, ".", sizeof(nameStr) - strlen(nameStr)); + } + nameStr[strlen(nameStr) - 1] = '\0'; + + return 0; +} + +// https://vulncat.fortify.com/ +void TypeConvert() +{ + char input[MAX]; + char output[MAX]; + + fillBuffer(input); + int len = getInputLength(); + + if (len <= MAX) + { + // ruleid: raptor-signed-unsigned-conversion + memcpy(output, input, len); + } + // ... +} + +// https://vulncat.fortify.com/ +char *processNext(char *strm) +{ + char buf[512]; + int len = *(int *)strm; + + strm += sizeof(len); + if (len <= 512) + { + // ruleid: raptor-signed-unsigned-conversion + memcpy(buf, strm, len); + process(buf); + return strm + len; + } + else + { + return -1; + } +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.cpp b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.cpp new file mode 100644 index 0000000..0456647 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.cpp @@ -0,0 +1,22 @@ +// Marco Ivaldi + +#include + +SharedMemory *SharedMemory::New(Plugin *plugin, off_t length) +{ + void *map_addr = NULL; + // ruleid: raptor-signed-unsigned-conversion + size_t size = static_cast(length); + NaClHandle handle = nacl::CreateMemoryObject(size); + struct NaClDescImcShm *imc_desc = reinterpret_cast(malloc(sizeof(*imc_desc))); + struct NaClDesc *desc = reinterpret_cast(imc_desc); + dprintf(("SharedMemory::New(%p, 0x%08x)\n ", plugin, (unsigned)length)); + NaClDescImcShmCtor(imc_desc, handle, length); + return New(plugin, desc); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.yaml new file mode 100644 index 0000000..28ab2ad --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/signed-unsigned-conversion.yaml @@ -0,0 +1,145 @@ +rules: + - id: raptor-signed-unsigned-conversion + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Other Security + likelihood: MEDIUM + impact: MEDIUM + confidence: LOW + technology: + - c + - cpp + cwe: + - "CWE-195: Signed to Unsigned Conversion Error" + - "CWE-196: Unsigned to Signed Conversion Error" + - "CWE-194: Unexpected Sign Extension" + - "CWE-191: Integer Underflow (Wrap or Wraparound)" + - "CWE-681: Incorrect Conversion between Numeric Types" + - "CWE-789: Memory Allocation with Excessive Size Value" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - http://www.phrack.org/issues/60/10.html#article + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + message: >- + The software uses a signed primitive and performs a cast to an + unsigned primitive, or uses an unsigned primitive and performs a cast + to a signed primitive, which can produce an unexpected value. + When the result of a function is to be used as a size parameter, + using negative return values can have unexpected results. + Although less frequent an issue, unsigned-to-signed conversion can be + the precursor to buffer underwrite conditions. Buffer underwrites + occur frequently when large unsigned values are cast to signed values, + and then used as indexes into a buffer or for pointer arithmetic. + severity: WARNING + languages: + - c + - cpp + # NOTE: the deep expression operator is necessary to catch some matches because C/C++ integer promotions do not seem entirely supported by Semgrep; this may generate lots of false positives. + # NOTE: some types (e.g. `char`, `short`, `long`), functions (e.g., widechar and some alloc functions, custom wrappers), and use cases (e.g., comparisons) are not covered. + # NOTE: `wmemcpy`, `wmemmove`, and `wmemset` are not covered. + # NOTE: `memcpy_s`, `memmove_s`, `memset_explicit`, and similar variants are not covered. + # NOTE: `strcpy_s`, `strcat_s`, and similar variants are not covered. + # NOTE: try to avoid false positives where possible. + pattern-either: + # signed to unsigned + - patterns: + - pattern-either: + - pattern: (unsigned int $_) = <... (int $_) ...> + - pattern: (unsigned $_) = <... (int $_) ...> + - pattern: (size_t $_) = <... (int $_) ...> + - pattern: (size_t $_) = <... (off_t $_) ...> + - pattern-not: $_ = 0 + - patterns: + - pattern-either: + - pattern: | + unsigned int $FUN(...) + { + ... + return (int $_); + } + - pattern: | + unsigned $FUN(...) + { + ... + return (int $_); + } + - pattern: | + size_t $FUN(...) + { + ... + return (int $_); + } + - pattern: | + size_t $FUN(...) + { + ... + return (off_t $_); + } + # improve output readability + - focus-metavariable: $FUN + - pattern: strncpy($_, $_, (int $_)) + - pattern: stpncpy($_, $_, (int $_)) + - pattern: strncat($_, $_, (int $_)) + - pattern: strlcpy($_, $_, (int $_)) + - pattern: strscpy($_, $_, (int $_)) + - pattern: strlcat($_, $_, (int $_)) + - pattern: snprintf($_, (int $_), ...) + - pattern: vsnprintf($_, (int $_), ...) + - pattern: swprintf($_, (int $_), ...) + - pattern: vswprintf($_, (int $_), ...) + - pattern: getcwd($_, (int $_)) + - pattern: memcpy($_, $_, (int $_)) + - pattern: mempcpy($_, $_, (int $_)) + - pattern: memccpy($_, $_, $_, (int $_)) + - pattern: memmove($_, $_, (int $_)) + - pattern: memset($_, $_, (int $_)) + - pattern: bcopy($_, $_, (int $_)) + - pattern: alloca((int $_)) + - pattern: malloc((int $_)) + - pattern: calloc($_, (int $_)) + - pattern: calloc((int $_), $_) + - pattern: realloc($_, (int $_)) + - pattern: read($_, $_, (int $_)) + - pattern: recv($_, $_, (int $_), $_) + - pattern: recvfrom($_, $_, (int $_), $_, ...) + - pattern: fread($_, (int $_), $_, $_) + # unsigned to signed + - pattern: (int $_) = <... (unsigned int $_) ...> + - pattern: (int $_) = <... (unsigned $_) ...> + - pattern: (int $_) = <... (size_t $_) ...> + - pattern: (off_t $_) = <... (size_t $_) ...> + - patterns: + - pattern-either: + - pattern: | + int $FUN(...) + { + ... + return (unsigned int $_); + } + - pattern: | + int $FUN(...) + { + ... + return (unsigned $_); + } + - pattern: | + int $FUN(...) + { + ... + return (size_t $_); + } + - pattern: | + off_t $FUN(...) + { + ... + return (size_t $_); + } + # improve output readability + - focus-metavariable: $FUN diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/suspicious-assert.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/suspicious-assert.c new file mode 100644 index 0000000..c352fd9 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/suspicious-assert.c @@ -0,0 +1,107 @@ +// Marco Ivaldi + +void bt_mesh_beacon_priv_random_get(uint8_t *random, size_t size) +{ + // ruleid: raptor-suspicious-assert + __ASSERT(size <= sizeof(priv_random.val), "Invalid random value size %u", size); + memcpy(random, priv_random.val, size); +} + +static inline int send_sf(struct isotp_send_ctx *ctx) +{ + /* ... */ + if (ctx->tx_addr.use_ext_addr) + { + frame.data[index++] = ctx->tx_addr.ext_addr; + } + + frame.data[index++] = ISOTP_PCI_TYPE_SF | len; + + // ruleid: raptor-suspicious-assert + __ASSERT_NO_MSG(len <= ISOTP_CAN_DL - index); + memcpy(&frame.data[index], data, len); + + /* ... */ + + return 0; +} + +static inline void assert_buf_len(int need, int have) +{ + // ruleid: raptor-suspicious-assert + __ASSERT(need < have, "OOM at build command: need:%d have:%d", + need, have); +} + +static int line_out_drop_mode(void) +{ + /* line cannot be empty */ + // ruleid: raptor-suspicious-assert + __ASSERT_NO_MSG(line_pos > line_buf); + + /* Handle the case if line contains only '\n' */ + if (line_pos - line_buf == 1) + { + line_pos++; + } + + *(line_pos - 1) = '\r'; + *line_pos++ = '\n'; + + if (drop_cnt > 0 && !drop_warn) + { + int cnt = MIN(drop_cnt, DROP_MAX); + + // ruleid: raptor-suspicious-assert + __ASSERT_NO_MSG(line_pos - line_buf <= MESSAGE_SIZE); + + memmove(line_buf + DROP_MSG_LEN, line_buf, line_pos - line_buf); + (void)memcpy(line_buf, drop_msg, DROP_MSG_LEN); + line_pos += DROP_MSG_LEN; + drop_warn = 1; + + /* ... */ + } + return 0; +} + +void arch_irq_offload(irq_offload_routine_t routine, const void *parameter) +{ + offload_params[CURR_CPU].fn = routine; + offload_params[CURR_CPU].arg = parameter; + compiler_barrier(); + + z_arc_v2_aux_reg_write(_ARC_V2_AUX_IRQ_HINT, IRQ_OFFLOAD_LINE); + + /* ... */ + + /* If _current was aborted in the offload routine, we shouldn't be here */ + // ok: raptor-suspicious-assert + __ASSERT_NO_MSG((_current->base.thread_state & _THREAD_DEAD) == 0); +} + +int process_sub(FILE *data_file, FILE *struct_file) +{ + FIND_T fInfo; + FIND_RET_T fret; + int filesProcessed = 0; + + if (processSubs) + { + /* process subs recursively */ + size_t sublen = strlen(curSubdir); + size_t freelen = sizeof(curSubdir) - sublen - 1; + // ruleid: raptor-suspicious-assert + LWIP_ASSERT("sublen < sizeof(curSubdir)", sublen < sizeof(curSubdir)); + fret = FINDFIRST_DIR("*", &fInfo); + /* ... */ + } + + return 0; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/suspicious-assert.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/suspicious-assert.yaml new file mode 100644 index 0000000..e855fb6 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/suspicious-assert.yaml @@ -0,0 +1,41 @@ +rules: + - id: raptor-suspicious-assert + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Other Security + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-754: Improper Check for Unusual or Exceptional Conditions" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://legends2k.github.io/note/assert_vs_if/ + - https://github.com/struct/mms + message: >- + Most codebases define assertion macros which compile to a no-op on + non-debug builds. If assertions are the only line of defense against + untrusted input, the software may be exposed to attacks that leverage + the lack of proper input checks. + severity: WARNING + languages: + - c + - cpp + # NOTE: other conditions (i.e., equality and inequality) might be security-relevant as well. + # NOTE: other kinds of assertion macros (e.g., `REQUIRE`, `DCHECK`, `ENSURE`, etc.) and custom wrappers are not covered. + patterns: + - pattern-either: + - pattern: $ASSERT(..., <... $_ < $_ ...>, ...) + - pattern: $ASSERT(..., <... $_ <= $_ ...>, ...) + - pattern: $ASSERT(..., <... $_ > $_ ...>, ...) + - pattern: $ASSERT(..., <... $_ >= $_ ...>, ...) + - metavariable-regex: + metavariable: $ASSERT + regex: '(?i)^\w*assert\w*\s*$' diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/typos.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/typos.c new file mode 100644 index 0000000..7435ef5 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/typos.c @@ -0,0 +1,283 @@ +// Marco Ivaldi + +#include +#include +#include + +void bad1() +{ + char *src, *dst; + int left; + + while (*src && left) + { + *dst++ = *src++; + // ruleid: raptor-typos + if (left = 0) + { + die("badlen"); + } + left--; + } +} + +void good1(char *path, char *dir, char *obj) +{ + char *last; + + // ok: raptor-typos + if ((last = strrchr(path, '/')) != NULL) + { + strcpy(obj, last + 1); + if (last == path) + { + strcpy(dir, "/"); + } + else + { + *last = '\0'; + strcpy(dir, path); + *last = '/'; + } + } + else + { + dir[0] = dir[0] = '\0'; + } +} + +int bad2(char *username) +{ + int f; + f = get_security_flags(username); + + // ruleid: raptor-typos + if (f = FLAG_AUTHENTICATED) + { + return LOGIN_OK; + } + return LOGIN_FAILED; +} + +void bad3(char *src, char *dst) +{ + // ruleid: raptor-typos + if (get_string(src) && + check_for_overflow(src) & copy_string(dst, src)) + { + printf("string safely copied\n"); + } +} + +void bad4(char *src, int len) +{ + char dst[256]; + + // ruleid: raptor-typos + if (len > 0 && len <= sizeof(dst)) + ; + memcpy(dst, src, len); +} + +void bad5(char *src, char *dst) +{ + int i; + // ruleid: raptor-typos + for (i == 5; src[i] && i < 10; i++) + { + dst[i - 5] = src[i]; + } +} + +void bad6(char *userinput) +{ + // ruleid: raptor-typos + char buf[040]; + + // ok: raptor-typos + char buf[0x40]; + + snprintf(buf, 40, "%s", userinput); +} + +void bad7() +{ + // ruleid: raptor-typos + if (frag_len & + !BUF_MEM_grow_clean(s->init_buf, (int)frag_len + + DTLS1_HM_HEADER_LENGTH + s->init_num)) + { + SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, ERR_R_BUF_LIB); + goto err; + } +} + +void bad8(int j) +{ + int i = 10; + + // ruleid: raptor-typos + i = +j; +} + +int isValid(int value) +{ + // ruleid: raptor-typos + if (value = 100) + { + printf("Value is valid\n"); + return (1); + } + + printf("Value is not valid\n"); + return (0); +} + +void processString(char *str) +{ + int i; + + for (i = 0; i < strlen(str); i++) + { + if (isalnum(str[i])) + { + processChar(str[i]); + } + // ruleid: raptor-typos + else if (str[i] = ':') + { + movingToNewInput(); + } + } +} + +#define SIZE 50 +int *tos, *p1, stack[SIZE]; + +void push(int i) +{ + p1++; + if (p1 == (tos + SIZE)) + { + printf("Print stack overflow error message and exit\n"); + } + // ruleid: raptor-typos + *p1 == i; +} + +int pop(void) +{ + if (p1 == tos) + { + printf("Print stack underflow error message and exit\n"); + } + p1--; + return *(p1 + 1); +} + +void test1() +{ + // ruleid: raptor-typos + if ((nowtok == tok_mb_cur_max && result->mb_cur_max != 0) || (nowtok == tok_mb_cur_max && result->mb_cur_max != 0)) + lr_error(cmfile, _("duplicate definition of <%s>"), nowtok == tok_mb_cur_min ? "mb_cur_min" : "mb_cur_max"); +} + +int test2() +{ + e = borg_extract_dir(y1, x1, y2, x2); + + // ruleid: raptor-typos + if ((ay <= 1) && (ay <= 1)) + return (e); + + if (ay > ax) + { + d = (y1 < y2) ? 2 : 8; + if (borg_cave_floor_bold(y1 + ddy[d], x1 + ddx[d])) + return (d); + } +} + +void test3() +{ + char *at; + char mntfrombuf[MNAMELEN]; + char *mntfromptr; + + mntfromptr = mp->f_mntfromname; + + switch (mp->f_type) + { + case MOUNT_TYPE_NFS: + case MOUNT_TYPE_NFS3: + at = strchr(mp->f_mntfromname, '@'); + // ruleid: raptor-typos + if (at != '\0') + { + xstrlcpy(mntfrombuf, (at + 1), sizeof(mntfrombuf)); + } + } +} + +int test4() +{ + fsa_node_addr *prev_node = NULL; + char *cur = nodes_arg; /* point to start of string */ + + for (int i = 0; i < strlen(nodes_arg); i++) + { + if (nodes_arg[i] != ',' && (nodes_arg[i] < '0' || nodes_arg[i] > '9')) + { + fsa_error(LOG_ERR, "Invalid nodes argument: %s\n", nodes_arg); + return 1; + } + } + // ruleid: raptor-typos + while (cur != NULL && cur != '\0') + { + int node_num = (int)strtol(cur, (char **)NULL, 10); + if (node_num == 0 && errno != 0) + { + do_someting(); + } + } +} + +void test5() +{ + // ruleid: raptor-typos + if (strcpy(szbuf1, "Manager") == 0) + { + do_something(); + } +} + +void test6() +{ + // ... + + // ok: raptor-typos + assert("in this state, the rx chain should be empty", state->rx == NULL); +} + +int wgetnstr(WINDOW *win, char *str, int n) +{ + char *_str; + int c; + + if (n == 0) + { + // ruleid: raptor-typos + str = '\0'; + return OK; + } + _str = str; +} + +int main(int argc, char *argv[]) +{ + tos = stack; + p1 = stack; + // ... + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/typos.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/typos.yaml new file mode 100644 index 0000000..0634e43 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/typos.yaml @@ -0,0 +1,105 @@ +rules: + - id: raptor-typos + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Other Security + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - c + - cpp + cwe: + - "CWE-480: Use of Incorrect Operator" + - "CWE-481: Assigning instead of Comparing" + - "CWE-482: Comparing instead of Assigning" + - "CWE-483: Incorrect Block Delimitation" + - "CWE-705: Incorrect Control Flow Scoping" + - "CWE-561: Dead Code" + - "CWE-1164: Irrelevant Code" + owasp: + - A08:2025 - Software or Data Integrity Failures + references: + - https://g.co/kgs/PCHQjJ + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: >- + The programmer accidentally uses the wrong operator, which changes + the application logic in security-relevant ways. This rule also covers + some other common typo patterns. + severity: INFO + languages: + - c + - cpp + # NOTE: common issues with comments are not covered. + # NOTE: consider adding a `focus-metavariable` where applicable to improve output readability. + # NOTE: custom wrappers to assertion macros are not covered. + pattern-either: + # == instead of = in assignment (the ternary operator is not supported by Semgrep) + # NOTE: the semicolon at the end of the pattern should be removed, but this would generate many false positives on top of those already generated by the current pattern, so we keep it for now. + - pattern: for ($_ == $_; $_; $_) ... + - patterns: + - pattern: $_ == $_; + - pattern-not-inside: return $_; + - pattern-not-inside: assert(...); + # = instead of == in comparison + - patterns: + - pattern: if (<... $EXPR1 = $EXPR2 ...>) ... + - pattern-not-inside: if (<... ($EXPR1 = $EXPR2) == $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 = $EXPR2) != $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 = $EXPR2) < $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 = $EXPR2) <= $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 = $EXPR2) > $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 = $EXPR2) >= $_ ...>) ... + # & instead of && in comparison + - patterns: + - pattern: if (<... $EXPR1 & $EXPR2 ...>) ... + - pattern-not-inside: if (<... ($EXPR1 & $EXPR2) == $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 & $EXPR2) != $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 & $EXPR2) < $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 & $EXPR2) <= $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 & $EXPR2) > $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 & $EXPR2) >= $_ ...>) ... + # | instead of || in comparison + - patterns: + - pattern: if (<... $EXPR1 | $EXPR2 ...>) ... + - pattern-not-inside: if (<... ($EXPR1 | $EXPR2) == $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 | $EXPR2) != $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 | $EXPR2) < $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 | $EXPR2) <= $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 | $EXPR2) > $_ ...>) ... + - pattern-not-inside: if (<... ($EXPR1 | $EXPR2) >= $_ ...>) ... + # =+ instead of += (and =- instead of -=) + - pattern: $_ =+ $_ + # - pattern: $EXPR1 =- $EXPR2 + # duplicate expressions + - pattern: ($EXPR && $EXPR) + - pattern: ($EXPR || $EXPR) + - pattern: ($EXPR == $EXPR) + - pattern: ($EXPR != $EXPR) + - pattern: ($EXPR < $EXPR) + - pattern: ($EXPR <= $EXPR) + - pattern: ($EXPR > $EXPR) + - pattern: ($EXPR >= $EXPR) + # assigning or comparing a char literal to a pointer (some types and literals are missing) + - pattern: (char * $_) = '\0' + - pattern: (char * $_) == '\0' + - pattern: (char * $_) != '\0' + # use of a string copy function instead of a string compare function in a condition + - pattern: if (<... strcpy(...) ...>) ... + - pattern: if (<... strncpy(...) ...>) ... + # ; at the end of if or for statement (empty else block not covered) + - pattern: if ($_); + - pattern: for ($_; $_; $_); + # accidental octal conversion + - patterns: + - pattern-either: + - pattern: $_ $_[$LEN]; + - pattern: $_ $_[$LEN] = ...; + - metavariable-regex: + metavariable: $LEN + regex: "^0[^xX].*" + # missing {} in if statement (too many false positives) + # - pattern: if ($COND) $BODY; diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-malloc.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-malloc.c new file mode 100644 index 0000000..2fe52db --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-malloc.c @@ -0,0 +1,99 @@ +// Marco Ivaldi + +#include +#include + +#define MEMSIZE 256 + +void alloc_memory() +{ + // ruleid: raptor-unchecked-ret-malloc + char *ptr = (char *)malloc(MEMSIZE); +} + +int alloc_memory_and_check1() +{ + // ok: raptor-unchecked-ret-malloc + char *ptr = (char *)malloc(MEMSIZE); + if (ptr == NULL) + return -1; + + // ... + return 0; +} + +int alloc_memory_and_check2() +{ + char *ptr; + + // ok: raptor-unchecked-ret-malloc + if ((ptr = (char *)malloc(MEMSIZE)) != NULL) + { + // ... + return 0; + } + return -1; +} + +int alloc_memory_and_check3() +{ + // ok: raptor-unchecked-ret-malloc + char *ptr = (char *)malloc(MEMSIZE); + if (!ptr) + return -1; + + // ... + return 0; +} + +int alloc_memory_and_check4() +{ + char *ptr; + + // ok: raptor-unchecked-ret-malloc + if (!(ptr = (char *)malloc(MEMSIZE))) + return -1; + + // ... + return 0; +} + +void test_func() +{ + // ruleid: raptor-unchecked-ret-malloc + buf = (char *)malloc(req_size); + strncpy(buf, xfer, req_size); +} + +void test_func2() +{ + // ruleid: raptor-unchecked-ret-malloc + AStruct *s = (AStruct *)malloc(user_len); + s[user_offset] = 0xff; +} + +int append_data(struct databuf *buf, char *src, size_t len) +{ + size_t new_size = buf->used + len + EXTRA; + + if (new_size < len) + return -1; + + if (new_size > buf->allocated_length) + { + // ruleid: raptor-unchecked-ret-malloc + buf->data = (char *)realloc(buf->data, new_size); + buf->allocated_length = new_size; + } + + memcpy(buf->data + buf->used, src, len); + buf->used += len; + + return 0; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-malloc.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-malloc.yaml new file mode 100644 index 0000000..d75ec2b --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-malloc.yaml @@ -0,0 +1,77 @@ +rules: + - id: raptor-unchecked-ret-malloc + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-252: Unchecked Return Value" + - "CWE-690: Unchecked Return Value to NULL Pointer Dereference" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://github.com/struct/mms + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: >- + The software does not check the return value from a method or + function, which can prevent it from detecting unexpected states and + conditions. + severity: WARNING + languages: + - c + - cpp + # NOTE: custom wrappers are not covered. + # NOTE: for another approach to NULL pointer dereferencing detection, refer to `cpp.lang.security.memory.null-deref.null-library-function.null-library-function`. + patterns: + - pattern-either: + - pattern: $RET = $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: malloc + - pattern: calloc + - pattern: realloc + - pattern: reallocf + - pattern: valloc + - pattern: aligned_alloc + - pattern: strdup + - pattern: strndup + - pattern-not-inside: | + $FUN(...); + ... + if (<... $RET ...>) ... + # no need to explicitly check the following patterns, as the deep expression operator above will already match them + # - pattern-not-inside: | + # $FUN(...); + # ... + # if (<... $RET == NULL ...>) ... + # - pattern-not-inside: | + # $FUN(...); + # ... + # if (<... NULL == $RET ...>) ... + # - pattern-not-inside: | + # $FUN(...); + # ... + # if (<... $RET != NULL ...>) ... + # - pattern-not-inside: | + # $FUN(...); + # ... + # if (<... NULL != $RET ...>) ... + # - pattern-not-inside: | + # $FUN(...); + # ... + # if (<... !$RET ...>) ... + - pattern-not-inside: <... $_ == NULL ...> + - pattern-not-inside: <... NULL == $_ ...> + - pattern-not-inside: <... $_ != NULL ...> + - pattern-not-inside: <... NULL != $_ ...> + - pattern-not-inside: <... !$_ ...> diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-scanf.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-scanf.c new file mode 100644 index 0000000..e285122 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-scanf.c @@ -0,0 +1,68 @@ +// Marco Ivaldi + +#include +#include +#include +#include +#include +#include + +static int +parseuid_bad(const char *s, uid_t *uid) +{ + struct passwd *pw; + const char *errstr; + + if ((pw = getpwnam(s)) != NULL) + { + *uid = pw->pw_uid; + return 0; + } +#if !defined(__linux__) && !defined(__NetBSD__) + *uid = strtonum(s, 0, UID_MAX, &errstr); +#else + // ruleid: raptor-unchecked-ret-scanf + sscanf(s, "%d", uid); +#endif + if (errstr) + return -1; + return 0; +} + +static int +parseuid_good(const char *s, uid_t *uid) +{ + struct passwd *pw; +#if !defined(__linux__) && !defined(__NetBSD__) + const char *errstr = NULL; +#else + int status; +#endif + + if ((pw = getpwnam(s)) != NULL) + { + *uid = pw->pw_uid; + return 0; + } +#if !defined(__linux__) && !defined(__NetBSD__) + *uid = strtonum(s, 0, UID_MAX, &errstr); + if (errstr) + return -1; +#else + // ok: raptor-unchecked-ret-scanf + status = sscanf(s, "%d", uid); + if (status != 1) + return -1; +#endif + return 0; +} + +int main(int argc, char *argv[]) +{ + int i = 0, j = 0; + printf("Enter two numbers:\n"); + // ruleid: raptor-unchecked-ret-scanf + scanf("%d %d", &i, &j); + printf("Result = %d\n", i / j); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-scanf.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-scanf.yaml new file mode 100644 index 0000000..d4d6cca --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-scanf.yaml @@ -0,0 +1,65 @@ +rules: + - id: raptor-unchecked-ret-scanf + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Other Security + likelihood: MEDIUM + impact: LOW + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-252: Unchecked Return Value" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://codeql.github.com/codeql-query-help/cpp/cpp-missing-check-scanf/ + message: >- + The software does not check the return value from a method or + function, which can prevent it from detecting unexpected states and + conditions. + severity: WARNING + languages: + - c + - cpp + patterns: + - pattern: $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: scanf + - pattern: __isoc99_scanf + - pattern: vscanf + - pattern: __isoc99_vscanf + - pattern: fscanf + - pattern: __isoc99_fscanf + - pattern: vfscanf + - pattern: __isoc99_vfscanf + - pattern: sscanf + - pattern: __isoc99_sscanf + - pattern: vsscanf + - pattern: __isoc99_vsscanf + - pattern: wscanf + - pattern: vwscanf + - pattern: fwscanf + - pattern: vfwscanf + - pattern: swscanf + - pattern: vswscanf + - pattern-not-inside: $_ = $FUN(...) + - pattern-not-inside: <... $FUN(...) == $_ ...> + - pattern-not-inside: <... $_ == $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) != $_ ...> + - pattern-not-inside: <... $_ != $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) < $_ ...> + - pattern-not-inside: <... $_ > $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) <= $_ ...> + - pattern-not-inside: <... $_ >= $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) > $_ ...> + - pattern-not-inside: <... $_ < $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) >= $_ ...> + - pattern-not-inside: <... $_ <= $FUN(...) ...> + - pattern-not-inside: return $FUN(...); diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-setuid-seteuid.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-setuid-seteuid.c new file mode 100644 index 0000000..23d2842 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-setuid-seteuid.c @@ -0,0 +1,42 @@ +// Marco Ivaldi + +#include +#include + +void drop_priv_perm() +{ + // ruleid: raptor-unchecked-ret-setuid-seteuid + setuid(getuid()); +} + +int drop_priv_perm2() +{ + // ok: raptor-unchecked-ret-setuid-seteuid + if (!setuid(getuid())) + { + // ... + return 0; + } + return -1; +} + +void drop_priv_temp() +{ + // ruleid: raptor-unchecked-ret-setuid-seteuid + seteuid(getuid()); +} + +int drop_priv_temp2() +{ + // ok: raptor-unchecked-ret-setuid-seteuid + if (seteuid(getuid()) < 0) + return -1; + + // ... +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-setuid-seteuid.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-setuid-seteuid.yaml new file mode 100644 index 0000000..da21f83 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unchecked-ret-setuid-seteuid.yaml @@ -0,0 +1,49 @@ +rules: + - id: raptor-unchecked-ret-setuid-seteuid + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Improper Authorization + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-252: Unchecked Return Value" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://lwn.net/Articles/451985/ + - https://www.usenix.org/legacy/events/sec02/full_papers/chen/chen.pdf + - https://www.openwall.com/lists/oss-security/2023/12/30/4 + message: >- + The software does not check the return value from a method or + function, which can prevent it from detecting unexpected states and + conditions. If the program calls a function to drop privileges but + does not check the return code to ensure that privileges were + successfully dropped, then the program will continue to operate with + the higher privileges. + severity: WARNING + languages: + - c + - cpp + patterns: + - pattern: $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: setuid + - pattern: seteuid + - pattern-not-inside: $_ = $FUN(...) + - pattern-not-inside: <... $FUN(...) == $_ ...> + - pattern-not-inside: <... $_ == $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) != $_ ...> + - pattern-not-inside: <... $_ != $FUN(...) ...> + - pattern-not-inside: <... $FUN(...) < $_ ...> + - pattern-not-inside: <... $_ > $FUN(...) ...> + - pattern-not-inside: <... !$FUN(...) ...> + - pattern-not-inside: return $FUN(...); diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-snprintf-vsnprintf.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-snprintf-vsnprintf.c new file mode 100644 index 0000000..3699835 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-snprintf-vsnprintf.c @@ -0,0 +1,297 @@ +// Marco Ivaldi + +#include + +#define BUFSIZE 256 +#define SIZE(x, y) (sizeof(x)((y)(x))) + +void copy_string(char *string) +{ + char buf[BUFSIZE]; + size_t length; + + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + length = snprintf(buf, BUFSIZE, "%s", string); + + // use length to access buf +} + +void bad() +{ + char buf[1024], *ptr; + ptr = buf; + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + ptr += snprintf(ptr, SIZE(buf, ptr), "user: %s\n", username); + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + ptr += snprintf(ptr, SIZE(buf, ptr), "pass: %s\n", password); +} + +#define PRIx64 "llx" + +void bad2() +{ + // ... + + // excluded due to the format string regex used to reduce false positives + // todoruled: raptor-unsafe-ret-snprintf-vsnprintf + len = snprintf(buf, sizeof(buf) - 1, + "Fluent Bit has been running: " + " %i day%s, %i hour%s, %i minute%s and %i second%s", + days, (days > 1) ? "s" : "", hours, + (hours > 1) ? "s" : "", minutes, + (minutes > 1) ? "s" : "", seconds, + (seconds > 1) ? "s" : ""); + + // ... +} + +int log(int fd, char *fmt, ...) +{ + char buffer[BUFSIZE]; + int n; + va_list ap; + + va_start(ap, fmt); + + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + n = vsnprintf(buffer, sizeof(buffer), fmt, ap); + + if (n >= BUFSIZE - 2) + buffer[sizeof(buffer) - 2] = '\0'; + + strcat(buffer, "\n"); + + va_end(ap); + + write_log(fd, buffer, strlen(buffer)); + + return 0; +} + +#include + +int test() +{ + char myname[5]; + // there is an overflow, but the source buffer is constant, so we're not really interested in this case + // ok: raptor-unsafe-ret-snprintf-vsnprintf + int ret = snprintf(myname, 10, "0123456789"); + + char name2[5] = "1234"; + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(0, 0, "My name is: %s", name2); + char *p = (char *)malloc(len); + snprintf(p, len, "My name is: %s", name2); + + // prints 123 + std::cout << p; + + return 0; +} + +char *f(const char *input) +{ + char buf[128]; + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(buf, 128, "%s", input); + + char *out = malloc(len + 1); + // This isn't technically a vulnerability but it is suspicious: + // * `snprintf(...)` will not return `-1` because the format string is valid + // * `buf` will be NUL-terminated, because `128 > 0` + // * `strncpy(...)` will only copy `max(strlen(buf), len + 1)` characters + // * `strlen(buf)` is less than `len + 1`, so `out` will be NUL-terminated + strncpy(out, buf, len + 1); + + // OOB read + memcpy(out, buf, len + 1); + + return out; +} + +char *non_string(const char *input, size_t n) +{ + char buf[128]; + // ok: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(buf, 128, "%u", n); + + memcpy(out, buf, len + 1); + + return out; +} + +char *f(const char *input) +{ + char buf[128]; + // there is a length check below + // todook: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(buf, 128, "any_cmd '%s'", input); + if (len < 0 || len > 128 - 1) + { + return NULL; + } + + char *out = malloc(len); + strncpy(out, buf, len); + return out; +} + +char *f(const char *input) +{ + char buf[128]; + // there is a length check below + // todook: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(buf, 128, "any_cmd '%s'", input); + if (len >= sizeof(buf)) + { + return NULL; + } + + char *out = malloc(len); + strncpy(out, buf, len); + return out; +} + +char *f(const char *input) +{ + char buf[128]; + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(buf, 128, "any_cmd '%s'", input); + snprintf(buf, 128 - len, "foo"); +} + +char *f(const char *input) +{ + char buf[128]; + // there is a length check below + // todook: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(buf, 128, "any_cmd '%s'", input); + if (sizeof(buf) <= len) + { + return NULL; + } + + char *out = malloc(len); + strncpy(out, buf, len); + return out; +} + +size_t f(const char *input) +{ + char buf[128]; + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(buf, 128, "input=%s", input); + return strnlen(buf, len); +} + +size_t f() +{ + char buf[128]; + // ok: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(buf, 128, "foo"); + return strnlen(buf, len); +} + +size_t f(const char *input) +{ + char buf[128]; + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + int len = snprintf(buf, 128, "input=%s", input); + return strncasecmp(buf, "input=foo", len); +} + +void f(const char *input) +{ + char buf[128]; + int len = 0; + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + len += snprintf(&buf[len], 128, "input=%s, input"); + return &buf[len] - buf; +} + +void wide_strings(const wchar_t *input) +{ + wchar_t buf[128]; + int len = 0; + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + len += snprintf(&buf[len], 128, "input=%ls, input"); + return &buf[len] - buf; +} + +static char *gen_text(const char *prefix, const char *sub_prefix, char *buf, size_t sz) +{ + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + int x = snprintf(buf, sz, "%s-%s-", prefix, sub_prefix); + + // This isn't sanitized because of the `sz - 1` on the RHS + for (; (size_t)x < sz - 1; x++) + buf[x] = *prefix; + + buf[x++] = 'x'; + buf[x] = '\0'; + return buf; +} + +static char * +int_to_roman(int number, const char *p) +{ + int len; + // ruleid: raptor-unsafe-ret-snprintf-vsnprintf + len = snprintf(numstr, sizeof(numstr), "%s", p); + + for (p = numstr; *p != '\0'; p++, --len) + { + foo(); + } + + for (p = numstr; *p != '\0'; p++, len--) + { + foo(); + } + + // TODO: `i < len` is a sanitizer so we can't match on it being used as a + // loop condition + + for (; i < len;) + { + foo(); + } + + for (i = 0; i < len;) + { + foo(); + } + + for (; i < len; i++) + { + foo(); + } + + for (i = 0; i < len; i++) + { + foo(); + } + + for (int i = 0; i < len;) + { + foo(); + } + + for (int i = 0; i < len; i++) + { + foo(); + } + + for (int i = 0, j = 0; i < len; i++) + { + foo(); + } + + return result; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-snprintf-vsnprintf.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-snprintf-vsnprintf.yaml new file mode 100644 index 0000000..4a5c51d --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-snprintf-vsnprintf.yaml @@ -0,0 +1,48 @@ +rules: + - id: raptor-unsafe-ret-snprintf-vsnprintf + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-131: Incorrect Calculation of Buffer Size" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://lwn.net/Articles/507319/ + - https://g.co/kgs/PCHQjJ + - https://dustri.org/b/playing-with-weggli.html + message: >- + The snprintf() and vsnprintf() functions return the total length of + the string they tried to create. Therefore, this return value can be + larger than the size of the destination buffer. If it is used + unsafely, e.g. as an index to write to the destination buffer, memory + corruption might occur. + severity: WARNING + languages: + - c + - cpp + # NOTE: for another approach that uses taint mode, refer to `cpp.lang.security.strings.snprintf-return-value-length.snprintf-return-value-length`. + patterns: + - pattern-either: + - pattern: $_ = $FUN($_, $_, $FMT, ...) + - pattern: $_ += $FUN($_, $_, $FMT, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: snprintf + - pattern: vsnprintf + # swprintf and vswprintf return a negative value if n or more + # widechars were requested to be written, thus behaving more safely + - metavariable-regex: + metavariable: $FMT + # NOTE: some format string specifiers are not handled + regex: '(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)' diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-strlcpy-strlcat.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-strlcpy-strlcat.c new file mode 100644 index 0000000..a6490c6 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-strlcpy-strlcat.c @@ -0,0 +1,61 @@ +// Marco Ivaldi + +#include +#include + +#define BUFSIZE 256 + +void copy_string1(char *string) +{ + char buf[BUFSIZE]; + size_t length; + + // ruleid: raptor-unsafe-ret-strlcpy-strlcat + length = strlcpy(buf, string, BUFSIZE); + + // use length to access buf, e.g. with strncat() +} + +int copy_string2(const char *string) +{ + char buf[BUFSIZE]; + + if (!string) + return -1; + + // ok: raptor-unsafe-ret-strlcpy-strlcat + if (strlcpy(buf, string, BUFSIZE) >= BUFSIZE) + return -1; // truncation + + // safely use buf here, knowing it is complete and null-terminated + + return 0; +} + +void append_string(char *string) +{ + char buf[BUFSIZE]; + size_t length; + + // ruleid: raptor-unsafe-ret-strlcpy-strlcat + length = strlcat(buf, string, BUFSIZE); + + // use length to access buf +} + +void qualify_username(char *username) +{ + char buf[1024]; + size_t length; + + // ruleid: raptor-unsafe-ret-strlcpy-strlcat + length = strlcpy(buf, username, sizeof(buf)); + strncat(buf, "@127.0.0.1", sizeof(buf) - length); + // ... +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-strlcpy-strlcat.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-strlcpy-strlcat.yaml new file mode 100644 index 0000000..269178c --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-ret-strlcpy-strlcat.yaml @@ -0,0 +1,46 @@ +rules: + - id: raptor-unsafe-ret-strlcpy-strlcat + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-131: Incorrect Calculation of Buffer Size" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://lwn.net/Articles/507319/ + - https://g.co/kgs/PCHQjJ + message: >- + The strlcpy() and strlcat() functions return the total length of the + string they tried to create. For strlcpy() that means the length of + the source string. For strlcat() that means the initial length of the + destination string plus the length of of the source string. + Therefore, this return value can be larger than the size of the + destination buffer. If it is used unsafely, e.g. as an index to write + to the destination buffer, memory corruption might occur. + severity: WARNING + languages: + - c + - cpp + patterns: + - pattern-either: + - pattern: $_ = $FUN(...) + - pattern: $_ += $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strlcpy + - pattern: strlcat + - pattern: wcslcpy + - pattern: wcslcat + - pattern: _mbslcpy + - pattern: _mbslcat diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-strlen.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-strlen.c new file mode 100644 index 0000000..fbceb2b --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-strlen.c @@ -0,0 +1,30 @@ +// Marco Ivaldi + +#include +#include + +int get_length1(char *string) +{ + short length; + + // ruleid: raptor-unsafe-strlen + length = strlen(string); + + return length; +} + +int get_length2(char *string) +{ + unsigned int length; + + // ok: raptor-unsafe-strlen + length = strlen(string); + + return length; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-strlen.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-strlen.yaml new file mode 100644 index 0000000..0f2d59c --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unsafe-strlen.yaml @@ -0,0 +1,52 @@ +rules: + - id: raptor-unsafe-strlen + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Other Security + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-190: Integer Overflow or Wraparound" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://github.com/struct/mms + message: >- + The software performs a calculation that can produce an integer + overflow or wraparound, when the logic assumes that the resulting + value will always be larger than the original value. This can + introduce other weaknesses when the calculation is used for resource + management or execution control. When influenced by the size of an + input it is often easier to overflow a short than an int. + severity: WARNING + languages: + - c + - cpp + patterns: + - pattern-either: + # signed and unsigned short + - pattern: (short $_) = $FUN(...) + - pattern: (short int $_) = $FUN(...) + - pattern: (unsigned short $_) = $FUN(...) + - pattern: (unsigned short int $_) = $FUN(...) + # signed int + # - pattern: (int $LEN) = $FUN(...); + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strlen + - pattern: lstrlen + - pattern: strnlen + - pattern: wcslen + - pattern: wcsnlen + # - pattern: _mbslen + # - pattern: _mbstrlen + # - pattern: _mbsnlen + # - pattern: _mbstrnlen diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unterminated-string-strncpy.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unterminated-string-strncpy.c new file mode 100644 index 0000000..4010b13 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unterminated-string-strncpy.c @@ -0,0 +1,124 @@ +// Marco Ivaldi + +#include +#include + +#define BUFSIZE 256 + +void copy_string1(char *string) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-unterminated-string-strncpy + strncpy(buf, string, BUFSIZE); +} + +void copy_string2(char *string) +{ + char buf[BUFSIZE]; + + // ruleid: raptor-unterminated-string-strncpy + stpncpy(buf, string, BUFSIZE); +} + +void copy_string3(char *string) +{ + char buf[BUFSIZE]; + + // ok: raptor-unterminated-string-strncpy + strncpy(buf, string, BUFSIZE); + buf[BUFSIZE - 1] = '\0'; +} + +int test_func() +{ + char longString[] = "String signifying nothing"; + char shortString[16]; + + // ruleid: raptor-unterminated-string-strncpy + strncpy(shortString, longString, 16); + printf("The last character in shortString is: %c (%1$x)\n", shortString[15]); + return 0; +} + +void test_func2(int argc, char **argv) +{ + char Filename[256]; + char Pattern[32]; + + // ... + + // ruleid: raptor-unterminated-string-strncpy + strncpy(Filename, argv[1], sizeof(Filename)); + // ruleid: raptor-unterminated-string-strncpy + strncpy(Pattern, argv[2], sizeof(Pattern)); + + printf("Searching file: %s for the pattern: %s\n", Filename, Pattern); + Scan_File(Filename, Pattern); +} + +void authenticate(int sockfd) +{ + char user[1024], *buffer; + size_t size; + int n, cmd; + + cmd = read_integer(sockfd); + size = read_integer(sockfd); + if (size > MAX_PACKET) + return -1; + + buffer = (char *)calloc(size + 1, sizeof(char)); + if (!buffer) + return -1; + + read_string(buffer, size); + + switch (cmd) + { + case USERNAME: + // ruleid: raptor-unterminated-string-strncpy + strncpy(user, buffer, sizeof(user)); + if (!is_username_valid(user)) + goto fail; + break; + // ... + } +} + +int process_email(char *email) +{ + char buf[1024], *domain; + + // ruleid: raptor-unterminated-string-strncpy + strncpy(buf, email, sizeof(buf)); + + domain = strchr(buf, '@'); + if (!domain) + return -1; + + *domain++ = '\0'; + + // ... + return 0; +} + +int test() +{ + char *hello = "HELLO WORLD"; + char dest[10]; + memset(dest, '\xAA', 10); + // ruleid: raptor-unterminated-string-strncpy + strncpy(dest, hello, 5); + + // to print contents of `dest` in hex + for (int i = 0; i < 10; ++i) + printf("%hhx ", dest[i]); + printf("\n"); +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unterminated-string-strncpy.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unterminated-string-strncpy.yaml new file mode 100644 index 0000000..cc61eca --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/unterminated-string-strncpy.yaml @@ -0,0 +1,56 @@ +rules: + - id: raptor-unterminated-string-strncpy + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-170: Improper Null Termination" + - "CWE-126: Buffer Over-read" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://g.co/kgs/PCHQjJ + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + message: >- + If there is no NUL character byte in the first n bytes of the source + string, strncpy() and stpncpy() do not NUL-terminate the destination + buffer. If the program does not explicitly terminate the destination + buffer, this will almost certainly result in information disclosure, + and possibly a buffer overflow condition. + severity: WARNING + languages: + - c + - cpp + # NOTE: other functions that do not `NUL`-terminate the destination buffer are not covered (e.g., `read`, `readlink`, `fread`, `memcpy`, etc.). + # NOTE: try to avoid false positives when `sizeof(dest) - 1` is used and in other similar cases. + patterns: + - pattern: $FUN(...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strncpy + - pattern: stpncpy + - pattern: wcsncpy + - pattern: wcpncpy + - pattern: _mbsncpy + - pattern-not-inside: | + $FUN($DST, $_, $_); + ... + $DST[$_] = NULL; + - pattern-not-inside: | + $FUN($DST, $_, $_); + ... + $DST[$_] = '\0'; + - pattern-not-inside: | + $FUN($DST, $_, $_); + ... + $DST[$_] = 0; diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-after-free.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-after-free.c new file mode 100644 index 0000000..81a3dc9 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-after-free.c @@ -0,0 +1,360 @@ +// Marco Ivaldi + +#include +#include + +#define MEMSIZE 256 + +void alloc_and_free1() +{ + int err = 1, bailout = 0; + char *ptr = (char *)malloc(MEMSIZE); + + // this should be caught but it isn't, due to a documented limitation in semgrep + // https://semgrep.dev/docs/writing-rules/pattern-syntax/#ellipses-and-statement-blocks + // todoruleid: raptor-use-after-free + if (err) + { + bailout = 1; + free(ptr); + } + if (bailout) + fprintf(stderr, "error: %p\n", ptr); + + free(ptr); + // ruleid: raptor-use-after-free + fprintf(stderr, "error: %p\n", ptr); +} + +void alloc_and_free2() +{ + char *ptr = (char *)malloc(MEMSIZE); + + free(ptr); + ptr = (char *)malloc(MEMSIZE); + // ok: raptor-use-after-free + fprintf(stderr, "error: %p\n", ptr); +} + +void uaf(int argc, char **argv) +{ + char *buf1R1; + char *buf2R1; + char *buf2R2; + char *buf3R2; + buf1R1 = (char *)malloc(BUFSIZER1); + buf2R1 = (char *)malloc(BUFSIZER1); + free(buf2R1); + buf2R2 = (char *)malloc(BUFSIZER2); + buf3R2 = (char *)malloc(BUFSIZER2); + // ruleid: raptor-use-after-free + strncpy(buf2R1, argv[1], BUFSIZER1 - 1); + free(buf1R1); + free(buf2R2); + free(buf3R2); +} + +// https://docs.microsoft.com/en-us/cpp/sanitizers/error-heap-use-after-free +int heap_use_after_free() +{ + char *x = (char *)malloc(10 * sizeof(char)); + free(x); + + // ... + + // ruleid: raptor-use-after-free + return x[5]; +} + +char test() +{ + char *ptr = (char *)malloc(10 * sizeof(char)); + free(ptr); + + // ruleid: raptor-use-after-free + return *ptr; +} + +#include +#include +#include + +typedef struct name +{ + char *myname; + void (*func)(char *str); +} NAME; + +void other_func(char *ignored) {} +void refreencode(char *ignored) {} + +int bad_code1() +{ + NAME *var; + char buf[10]; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + // ruleid: raptor-use-after-free + strcpy(buf, (char *)var); + // ruleid: raptor-use-after-free + other_func((char *)(*var)); + // ruleid: raptor-use-after-free + other_func((char *)var[0]); + // ruleid: raptor-use-after-free + var->func(var->myname); + return 0; +} + +int bad_code2() +{ + NAME *var; + char buf[10]; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + // ruleid: raptor-use-after-free + strcpy(buf, (char *)*var); + // ruleid: raptor-use-after-free + other_func((char *)var); + // ruleid: raptor-use-after-free + other_func((char *)var->myname); + return 0; +} + +int okay_code1() +{ + NAME *var; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + var = NULL; + // This will segmentation fault + // ok: raptor-use-after-free + other_func((char *)var); + other_func((char *)var->myname); + other_func((char *)*var); + return 0; +} + +int okay_code2() +{ + NAME *var; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + var = NULL; + var = (NAME *)malloc(sizeof(struct name)); + // ok: raptor-use-after-free + other_func((char *)var); + other_func((char *)var->myname); + other_func((char *)*var); + return 0; +} + +#include +#include + +typedef struct name +{ + char *myname; + void (*func)(char *str); +} NAME; + +void other_func(char *ignored) {} + +int bad_code1() +{ + NAME *var; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + // ruleid: raptor-use-after-free + var->func("use after free"); + return 0; +} + +int okay_code1() +{ + NAME *var; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + var = NULL; + // This will segmentation fault + // ok: raptor-use-after-free + var->func("use after free"); + return 0; +} + +int bad_code2() +{ + NAME *var; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + // ruleid: raptor-use-after-free + other_func(var->myname); + return 0; +} + +int okay_code2() +{ + NAME *var; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + var = NULL; + // This will segmentation fault + // ok: raptor-use-after-free + other_func(var->myname); + return 0; +} + +struct NAME +{ + char first_name[32]; + int auth; +} s_auth; + +int bad_code3() +{ + struct NAME *var; + var = malloc(sizeof(s_auth)); + free(var); + // ruleid: raptor-use-after-free + if (var->auth) + { + printf("you have logged in already"); + } + else + { + printf("you do not have the permision to log in."); + } + return 0; +} + +int ok_code3() +{ + struct NAME *var; + var = malloc(sizeof(s_auth)); + free(var); + var = NULL; + // ok: raptor-use-after-free + if (var->auth) + { + printf("you have logged in already"); + } + else + { + printf("you do not have the permision to log in."); + } + return 0; +} + +struct lv +{ + int length; + char *value; +} lv; + +struct lv2 +{ + int length; + struct lv *lv; +} lv2; + +int bad_code4() +{ + int initial = 1000; + struct lv *lv = malloc(sizeof(*lv)); + lv->length = initial; + lv->value = malloc(initial); + free(lv); + // ruleid: raptor-use-after-free + free(lv->value); + return 0; +} + +int ok_code4() +{ + int initial = 1000; + struct lv *lv = malloc(sizeof(*lv)); + lv->length = initial; + lv->value = malloc(initial); + // ok: raptor-use-after-free + free(lv->value); + // ok: raptor-use-after-free + free(lv); + return 0; +} + +int bad_code5() +{ + int initial = 1000; + struct lv *lv = malloc(sizeof(*lv)); + lv->length = initial; + lv->value = malloc(initial); + + struct lv2 *lv2 = malloc(sizeof(*lv2)); + lv2->length = initial; + lv2->lv = lv; + // ok: raptor-use-after-free + free(lv2->lv); + // ruleid: raptor-use-after-free + free(lv2->lv->value); + // ok: raptor-use-after-free + free(lv2); + return 0; +} + +int ok_code5() +{ + int initial = 1000; + struct lv *lv = malloc(sizeof(*lv)); + lv->length = initial; + lv->value = malloc(initial); + + struct lv2 *lv2 = malloc(sizeof(*lv2)); + lv2->length = initial; + lv2->lv = lv; + // ok: raptor-use-after-free + free(lv2->lv->value); + // ok: raptor-use-after-free + free(lv2->lv); + // ok: raptor-use-after-free + free(lv2); + return 0; +} + +int bad_code6() +{ + NAME *var; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + // ruleid: raptor-use-after-free + (*var).func("use after free"); + return 0; +} + +int ok_code6() +{ + NAME *var; + var = (NAME *)malloc(sizeof(struct name)); + free(var); + var = (NAME *)malloc(sizeof(struct name)); + // ok: raptor-use-after-free + (*var).func("use after free"); + return 0; +} + +int bad_code7() +{ + char *var; + char buf[10]; + var = (char *)malloc(100); + free(var); + // ruleid: raptor-use-after-free + char buf[0] = var[0]; + // ruleid: raptor-use-after-free + strcpy(buf, var); + return 0; +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-after-free.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-after-free.yaml new file mode 100644 index 0000000..594b494 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-after-free.yaml @@ -0,0 +1,63 @@ +rules: + - id: raptor-use-after-free + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-416: Use After Free" + owasp: + - A10:2025 - Mishandling of Exceptional Conditions + references: + - https://github.com/struct/mms + - https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf + - https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples + message: >- + The use of previously-freed memory can have any number of adverse + consequences, ranging from the corruption of valid data to the + execution of arbitrary code, depending on the instantiation and + timing of the flaw. The simplest way data corruption may occur + involves the system's reuse of the freed memory. + severity: ERROR + languages: + - c + - cpp + # NOTE: C++ `delete` and `delete[]` operators are not covered (refer also to `cpp.lang.security.use-after-free.*`). + # NOTE: `realloc` is not covered. + patterns: + - pattern-either: + # generic use after free + - pattern: $PTR->$_ + - pattern: $PTR[$_] + - pattern: (*$PTR) + # use after free in return + - pattern: return $PTR; + # use after free in function calls + - patterns: + - pattern-either: + - pattern: $FUN(..., <... $PTR ...>, ...) + # no need to explicitly check the following patterns, as the deep expression operator above will already match them + # - pattern: $FUN(..., <... $PTR->$_ ...>, ...) + # - pattern: $FUN(..., <... $PTR[$_] ...>, ...) + # - pattern: $FUN(..., <... (*$PTR) ...>, ...) + # - pattern: $FUN(..., <... (*$PTR).$_ ...>, ...) + - pattern: $PTR->$FUN(...) + # filter out double free instances + - metavariable-pattern: + metavariable: $FUN + patterns: + - pattern-not: free + - pattern-inside: free($PTR); ... + - pattern-not-inside: | + free($PTR); + ... + $PTR = ...; + ... diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-of-source-size-in-copy.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-of-source-size-in-copy.c new file mode 100644 index 0000000..7bdfb6f --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-of-source-size-in-copy.c @@ -0,0 +1,1143 @@ +// Marco Ivaldi + +void test_func() +{ + char source[21] = "the character string"; + char dest[12]; + + // ok: raptor-use-of-source-size-in-copy + strncpy(dest, source, sizeof(source) - 1); // there's a bof but we don't control the input +} + +// https://raw.githubusercontent.com/illumos/illumos-gate/61aaa916808c601f9ee36d96c05ee9dac211d09e/usr/src/cmd/whodo/whodo.c +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* /proc header file */ +#include +#include +#include +#include +#include + +/* + * Use the full lengths from utmpx for user and line. + */ +#define NMAX (sizeof(((struct utmpx *)0)->ut_user)) +#define LMAX (sizeof(((struct utmpx *)0)->ut_line)) + +/* Print minimum field widths. */ +#define LOGIN_WIDTH 8 +#define LINE_WIDTH 8 + +#define DIV60(t) ((t + 30) / 60) /* x/60 rounded */ + +#ifdef ERR +#undef ERR +#endif +#define ERR (-1) + +#define DEVNAMELEN 14 +#define HSIZE 256 /* size of process hash table */ +#define PROCDIR "/proc" +#define INITPROCESS (pid_t)1 /* init process pid */ +#define NONE 'n' /* no state */ +#define RUNNING 'r' /* runnable process */ +#define ZOMBIE 'z' /* zombie process */ +#define VISITED 'v' /* marked node as visited */ + +static int ndevs; /* number of configured devices */ +static int maxdev; /* slots for configured devices */ +#define DNINCR 100 +static struct devl +{ /* device list */ + char dname[DEVNAMELEN]; /* device name */ + dev_t ddev; /* device number */ +} *devl; + +struct uproc +{ + pid_t p_upid; /* user process id */ + char p_state; /* numeric value of process state */ + dev_t p_ttyd; /* controlling tty of process */ + time_t p_time; /* ticks of user & system time */ + time_t p_ctime; /* ticks of child user & system time */ + int p_igintr; /* 1=ignores SIGQUIT and SIGINT */ + char p_comm[PRARGSZ + 1]; /* command */ + char p_args[PRARGSZ + 1]; /* command line arguments */ + struct uproc *p_child, /* first child pointer */ + *p_sibling, /* sibling pointer */ + *p_pgrplink, /* pgrp link */ + *p_link; /* hash table chain pointer */ +}; + +/* + * define hash table for struct uproc + * Hash function uses process id + * and the size of the hash table(HSIZE) + * to determine process index into the table. + */ +static struct uproc pr_htbl[HSIZE]; + +static struct uproc *findhash(pid_t); +static time_t findidle(char *); +static void clnarglist(char *); +static void showproc(struct uproc *); +static void showtotals(struct uproc *); +static void calctotals(struct uproc *); +static char *getty(dev_t); +static void prttime(time_t, int); +static void prtat(time_t *); + +static char *prog; +static int header = 1; /* true if -h flag: don't print heading */ +static int lflag = 0; /* true if -l flag: w command format */ +static char *sel_user; /* login of particular user selected */ +static time_t now; /* current time of day */ +static time_t uptime; /* time of last reboot & elapsed time since */ +static int nusers; /* number of users logged in now */ +static time_t idle; /* number of minutes user is idle */ +static time_t jobtime; /* total cpu time visible */ +static char doing[520]; /* process attached to terminal */ +static time_t proctime; /* cpu time of process in doing */ +static int empty; +static pid_t curpid; + +#if SIGQUIT > SIGINT +#define ACTSIZE SIGQUIT +#else +#define ACTSIZE SIGINT +#endif + +int main(int argc, char *argv[]) +{ + struct utmpx *ut; + struct utmpx *utmpbegin; + struct utmpx *utmpend; + struct utmpx *utp; + struct tm *tm; + struct uproc *up, *parent, *pgrp; + struct psinfo info; + struct sigaction actinfo[ACTSIZE]; + struct pstatus statinfo; + size_t size; + struct stat sbuf; + struct utsname uts; + DIR *dirp; + struct dirent *dp; + char pname[64]; + char *fname; + int procfd; + int i; + int days, hrs, mins; + int entries; + + /* + * This program needs the proc_owner privilege + */ + (void)__init_suid_priv(PU_CLEARLIMITSET, PRIV_PROC_OWNER, + (char *)NULL); + + (void)setlocale(LC_ALL, ""); +#if !defined(TEXT_DOMAIN) +#define TEXT_DOMAIN "SYS_TEST" +#endif + (void)textdomain(TEXT_DOMAIN); + + prog = argv[0]; + + while (argc > 1) + { + if (argv[1][0] == '-') + { + for (i = 1; argv[1][i]; i++) + { + switch (argv[1][i]) + { + + case 'h': + header = 0; + break; + + case 'l': + lflag++; + break; + + default: + (void)printf(gettext( + "usage: %s [ -hl ] [ user ]\n"), + prog); + exit(1); + } + } + } + else + { + if (!isalnum(argv[1][0]) || argc > 2) + { + (void)printf(gettext( + "usage: %s [ -hl ] [ user ]\n"), + prog); + exit(1); + } + else + sel_user = argv[1]; + } + argc--; + argv++; + } + + /* + * read the UTMPX_FILE (contains information about + * each logged in user) + */ + if (stat(UTMPX_FILE, &sbuf) == ERR) + { + (void)fprintf(stderr, gettext("%s: stat error of %s: %s\n"), + prog, UTMPX_FILE, strerror(errno)); + exit(1); + } + entries = sbuf.st_size / sizeof(struct futmpx); + size = sizeof(struct utmpx) * entries; + + if ((ut = malloc(size)) == NULL) + { + (void)fprintf(stderr, gettext("%s: malloc error of %s: %s\n"), + prog, UTMPX_FILE, strerror(errno)); + exit(1); + } + + (void)utmpxname(UTMPX_FILE); + + utmpbegin = ut; + /* LINTED pointer cast may result in improper alignment */ + utmpend = (struct utmpx *)((char *)utmpbegin + size); + + setutxent(); + while ((ut < utmpend) && ((utp = getutxent()) != NULL)) + (void)memcpy(ut++, utp, sizeof(*ut)); + endutxent(); + + (void)time(&now); /* get current time */ + + if (header) + { /* print a header */ + if (lflag) + { /* w command format header */ + prtat(&now); + for (ut = utmpbegin; ut < utmpend; ut++) + { + if (ut->ut_type == USER_PROCESS) + { + nusers++; + } + else if (ut->ut_type == BOOT_TIME) + { + uptime = now - ut->ut_xtime; + uptime += 30; + days = uptime / (60 * 60 * 24); + uptime %= (60 * 60 * 24); + hrs = uptime / (60 * 60); + uptime %= (60 * 60); + mins = uptime / 60; + + (void)printf(dcgettext(NULL, + "up %d day(s), %d hr(s), " + "%d min(s)", + LC_TIME), + days, hrs, mins); + } + } + + ut = utmpbegin; /* rewind utmp data */ + (void)printf(dcgettext(NULL, + " %d user(s)\n", LC_TIME), + nusers); + (void)printf(dcgettext(NULL, "User tty " + "login@ idle JCPU PCPU what\n", + LC_TIME)); + } + else + { /* standard whodo header */ + char date_buf[100]; + + /* + * print current time and date + */ + (void)strftime(date_buf, sizeof(date_buf), + "%c", localtime(&now)); + (void)printf("%s\n", date_buf); + + /* + * print system name + */ + (void)uname(&uts); + (void)printf("%s\n", uts.nodename); + } + } + + /* + * loop through /proc, reading info about each process + * and build the parent/child tree + */ + if (!(dirp = opendir(PROCDIR))) + { + (void)fprintf(stderr, gettext("%s: could not open %s: %s\n"), + prog, PROCDIR, strerror(errno)); + exit(1); + } + + while ((dp = readdir(dirp)) != NULL) + { + if (dp->d_name[0] == '.') + continue; + retry: + (void)snprintf(pname, sizeof(pname), + "%s/%s/", PROCDIR, dp->d_name); + fname = pname + strlen(pname); + (void)strcpy(fname, "psinfo"); + if ((procfd = open(pname, O_RDONLY)) < 0) + continue; + if (read(procfd, &info, sizeof(info)) != sizeof(info)) + { + int err = errno; + (void)close(procfd); + if (err == EAGAIN) + goto retry; + if (err != ENOENT) + (void)fprintf(stderr, gettext("%s: read() failed on %s: %s\n"), + prog, pname, strerror(err)); + continue; + } + (void)close(procfd); + + up = findhash(info.pr_pid); + up->p_ttyd = info.pr_ttydev; + up->p_state = (info.pr_nlwp == 0 ? ZOMBIE : RUNNING); + up->p_time = 0; + up->p_ctime = 0; + up->p_igintr = 0; + // ruleid: raptor-use-of-source-size-in-copy + (void)strncpy(up->p_comm, info.pr_fname, + sizeof(info.pr_fname)); + up->p_args[0] = 0; + + if (up->p_state != NONE && up->p_state != ZOMBIE) + { + (void)strcpy(fname, "status"); + + /* now we need the proc_owner privilege */ + (void)__priv_bracket(PRIV_ON); + + procfd = open(pname, O_RDONLY); + + /* drop proc_owner privilege after open */ + (void)__priv_bracket(PRIV_OFF); + + if (procfd < 0) + continue; + + if (read(procfd, &statinfo, sizeof(statinfo)) != sizeof(statinfo)) + { + int err = errno; + (void)close(procfd); + if (err == EAGAIN) + goto retry; + if (err != ENOENT) + (void)fprintf(stderr, gettext("%s: read() failed on %s: %s \n"), + prog, pname, strerror(err)); + continue; + } + (void)close(procfd); + + up->p_time = statinfo.pr_utime.tv_sec + + statinfo.pr_stime.tv_sec; + up->p_ctime = statinfo.pr_cutime.tv_sec + + statinfo.pr_cstime.tv_sec; + + (void)strcpy(fname, "sigact"); + + /* now we need the proc_owner privilege */ + (void)__priv_bracket(PRIV_ON); + + procfd = open(pname, O_RDONLY); + + /* drop proc_owner privilege after open */ + (void)__priv_bracket(PRIV_OFF); + + if (procfd < 0) + continue; + if (read(procfd, actinfo, sizeof(actinfo)) != sizeof(actinfo)) + { + int err = errno; + (void)close(procfd); + if (err == EAGAIN) + goto retry; + if (err != ENOENT) + (void)fprintf(stderr, gettext("%s: read() failed on %s: %s \n"), + prog, pname, strerror(err)); + continue; + } + (void)close(procfd); + + up->p_igintr = + actinfo[SIGINT - 1].sa_handler == SIG_IGN && + actinfo[SIGQUIT - 1].sa_handler == SIG_IGN; + + up->p_args[0] = 0; + + /* + * Process args if there's a chance we'll print it. + */ + if (lflag) + { /* w command needs args */ + clnarglist(info.pr_psargs); + (void)strcpy(up->p_args, info.pr_psargs); + if (up->p_args[0] == 0 || + up->p_args[0] == '-' && + up->p_args[1] <= ' ' || + up->p_args[0] == '?') + { + (void)strcat(up->p_args, " ("); + (void)strcat(up->p_args, up->p_comm); + (void)strcat(up->p_args, ")"); + } + } + } + + /* + * link pgrp together in case parents go away + * Pgrp chain is a single linked list originating + * from the pgrp leader to its group member. + */ + if (info.pr_pgid != info.pr_pid) + { /* not pgrp leader */ + pgrp = findhash(info.pr_pgid); + up->p_pgrplink = pgrp->p_pgrplink; + pgrp->p_pgrplink = up; + } + parent = findhash(info.pr_ppid); + + /* if this is the new member, link it in */ + if (parent->p_upid != INITPROCESS) + { + if (parent->p_child) + { + up->p_sibling = parent->p_child; + up->p_child = 0; + } + parent->p_child = up; + } + } + + /* revert to non-privileged user */ + (void)__priv_relinquish(); + + (void)closedir(dirp); + (void)time(&now); /* get current time */ + + /* + * loop through utmpx file, printing process info + * about each logged in user + */ + for (ut = utmpbegin; ut < utmpend; ut++) + { + time_t tim; + + if (ut->ut_type != USER_PROCESS) + continue; + if (sel_user && strncmp(ut->ut_name, sel_user, NMAX) != 0) + continue; /* we're looking for somebody else */ + if (lflag) + { /* -l flag format (w command) */ + /* print login name of the user */ + (void)printf("%-*.*s ", LOGIN_WIDTH, (int)NMAX, + ut->ut_name); + + /* print tty user is on */ + (void)printf("%-*.*s ", LINE_WIDTH, (int)LMAX, + ut->ut_line); + + /* print when the user logged in */ + tim = ut->ut_xtime; + (void)prtat(&tim); + + /* print idle time */ + idle = findidle(ut->ut_line); + prttime(idle, 8); + showtotals(findhash((pid_t)ut->ut_pid)); + } + else + { /* standard whodo format */ + tim = ut->ut_xtime; + tm = localtime(&tim); + (void)printf("\n%-*.*s %-*.*s %2.1d:%2.2d\n", + LINE_WIDTH, (int)LMAX, ut->ut_line, + LOGIN_WIDTH, (int)NMAX, ut->ut_name, tm->tm_hour, + tm->tm_min); + showproc(findhash((pid_t)ut->ut_pid)); + } + } + + return (0); +} + +/* + * Used for standard whodo format. + * This is the recursive routine descending the process + * tree starting from the given process pointer(up). + * It used depth-first search strategy and also marked + * each node as printed as it traversed down the tree. + */ +static void +showproc(struct uproc *up) +{ + struct uproc *zp; + + if (up->p_state == VISITED) /* we already been here */ + return; + /* print the data for this process */ + if (up->p_state == ZOMBIE) + (void)printf(" %-*.*s %5d %4.1ld:%2.2ld %s\n", + LINE_WIDTH, (int)LMAX, " ?", (int)up->p_upid, 0L, 0L, + ""); + else if (up->p_state != NONE) + { + (void)printf(" %-*.*s %5d %4.1ld:%2.2ld %s\n", + LINE_WIDTH, (int)LMAX, getty(up->p_ttyd), (int)up->p_upid, + up->p_time / 60L, up->p_time % 60L, + up->p_comm); + } + up->p_state = VISITED; + + /* descend for its children */ + if (up->p_child) + { + showproc(up->p_child); + for (zp = up->p_child->p_sibling; zp; zp = zp->p_sibling) + { + showproc(zp); + } + } + + /* print the pgrp relation */ + if (up->p_pgrplink) + showproc(up->p_pgrplink); +} + +/* + * Used for -l flag (w command) format. + * Prints the CPU time for all processes & children, + * and the cpu time for interesting process, + * and what the user is doing. + */ +static void +showtotals(struct uproc *up) +{ + jobtime = 0; + proctime = 0; + empty = 1; + curpid = -1; + (void)strcpy(doing, "-"); /* default act: normally never prints */ + calctotals(up); + + /* print CPU time for all processes & children */ + /* and need to convert clock ticks to seconds first */ + prttime((time_t)jobtime, 8); + + /* print cpu time for interesting process */ + /* and need to convert clock ticks to seconds first */ + prttime((time_t)proctime, 8); + + /* what user is doing, current process */ + (void)printf("%-.32s\n", doing); +} + +/* + * Used for -l flag (w command) format. + * This recursive routine descends the process + * tree starting from the given process pointer(up). + * It used depth-first search strategy and also marked + * each node as visited as it traversed down the tree. + * It calculates the process time for all processes & + * children. It also finds the "interesting" process + * and determines its cpu time and command. + */ +static void +calctotals(struct uproc *up) +{ + struct uproc *zp; + + if (up->p_state == VISITED) + return; + up->p_state = VISITED; + if (up->p_state == NONE || up->p_state == ZOMBIE) + return; + jobtime += up->p_time + up->p_ctime; + proctime += up->p_time; + + if (empty && !up->p_igintr) + { + empty = 0; + curpid = -1; + } + + if (up->p_upid > curpid && (!up->p_igintr || empty)) + { + curpid = up->p_upid; + (void)strcpy(doing, up->p_args); + } + + /* descend for its children */ + if (up->p_child) + { + calctotals(up->p_child); + for (zp = up->p_child->p_sibling; zp; zp = zp->p_sibling) + calctotals(zp); + } +} + +static char * +devadd(char *name, dev_t ddev) +{ + struct devl *dp; + int leng, start, i; + + if (ndevs == maxdev) + { + maxdev += DNINCR; + dp = realloc(devl, maxdev * sizeof(struct devl)); + if (!dp) + { + (void)fprintf(stderr, + gettext("%s: out of memory!: %s\n"), + prog, strerror(errno)); + exit(1); + } + devl = dp; + } + dp = &devl[ndevs++]; + + dp->ddev = ddev; + if (name == NULL) + { + (void)strcpy(dp->dname, " ? "); + return (dp->dname); + } + + leng = strlen(name); + if (leng < DEVNAMELEN + 4) + { + /* strip off "/dev/" */ + (void)strcpy(dp->dname, &name[5]); + } + else + { + /* strip enough off the front to fit */ + start = leng - DEVNAMELEN - 1; + + for (i = start; i < leng && name[i] != '/'; i++) + ; + if (i == leng) + (void)strncpy(dp->dname, &name[start], DEVNAMELEN); + else + (void)strncpy(dp->dname, &name[i + 1], DEVNAMELEN); + } + return (dp->dname); +} + +static char * +devlookup(dev_t ddev) +{ + struct devl *dp; + int i; + + for (dp = devl, i = 0; i < ndevs; dp++, i++) + { + if (dp->ddev == ddev) + return (dp->dname); + } + return (NULL); +} + +/* + * This routine gives back a corresponding device name + * from the device number given. + */ +static char * +getty(dev_t dev) +{ + extern char *_ttyname_dev(dev_t, char *, size_t); + char devname[TTYNAME_MAX]; + char *retval; + + if (dev == PRNODEV) + return (" ? "); + + if ((retval = devlookup(dev)) != NULL) + return (retval); + + retval = _ttyname_dev(dev, devname, sizeof(devname)); + return (devadd(retval, dev)); +} + +/* + * Findhash finds the appropriate entry in the process + * hash table (pr_htbl) for the given pid in case that + * pid exists on the hash chain. It returns back a pointer + * to that uproc structure. If this is a new pid, it allocates + * a new node, initializes it, links it into the chain (after + * head) and returns a structure pointer. + */ +static struct uproc * +findhash(pid_t pid) +{ + struct uproc *up, *tp; + + tp = up = &pr_htbl[(int)pid % HSIZE]; + if (up->p_upid == 0) + { /* empty slot */ + up->p_upid = pid; + up->p_state = NONE; + up->p_child = up->p_sibling = up->p_pgrplink = up->p_link = 0; + return (up); + } + if (up->p_upid == pid) + { /* found in hash table */ + return (up); + } + for (tp = up->p_link; tp; tp = tp->p_link) + { /* follow chain */ + if (tp->p_upid == pid) + { + return (tp); + } + } + tp = malloc(sizeof(*tp)); /* add new node */ + if (!tp) + { + (void)fprintf(stderr, gettext("%s: out of memory!: %s\n"), + prog, strerror(errno)); + exit(1); + } + (void)memset((char *)tp, 0, sizeof(*tp)); + tp->p_upid = pid; + tp->p_state = NONE; + tp->p_child = tp->p_sibling = tp->p_pgrplink = (pid_t)0; + tp->p_link = up->p_link; /* insert after head */ + up->p_link = tp; + return (tp); +} + +#define HR (60 * 60) +#define DAY (24 * HR) +#define MON (30 * DAY) +#define PRINTF(a) (void)printf a + +/* + * Prttime prints an elapsed time in hours, minutes, or seconds, + * right-justified with the rightmost column always blank. + * The second argument is the minimum field width. + */ +static void +prttime(time_t tim, int width) +{ + char value[36]; + + if (tim >= 36 * 60) + { + (void)snprintf(value, sizeof(value), "%d:%02d:%02d", + (int)tim / HR, (int)(tim % HR) / 60, (int)tim % 60); + } + else if (tim >= 60) + { + (void)snprintf(value, sizeof(value), "%d:%02d", + (int)tim / 60, (int)tim % 60); + } + else if (tim > 0) + { + (void)snprintf(value, sizeof(value), "%d", (int)tim); + } + else + { + (void)strcpy(value, "0"); + } + width = (width > 2) ? width - 1 : 1; + PRINTF(("%*s ", width, value)); +} + +/* + * Prints the ISO date or time given a pointer to a time of day, + * left-justfied in a 12-character expanding field with the + * rightmost column always blank. + * Includes a dcgettext() override in case a message catalog is needed. + */ +static void +prtat(time_t *time) +{ + struct tm *p; + + p = localtime(time); + if (now - *time <= 18 * HR) + { + char timestr[50]; + + (void)strftime(timestr, sizeof(timestr), + dcgettext(NULL, "%T", LC_TIME), p); + PRINTF(("%-11s ", timestr)); + } + else if (now - *time <= 7 * DAY) + { + char weekdaytime[20]; + + (void)strftime(weekdaytime, sizeof(weekdaytime), + dcgettext(NULL, "%a %H:%M", LC_TIME), p); + PRINTF(("%-11s ", weekdaytime)); + } + else + { + char monthtime[20]; + + (void)strftime(monthtime, sizeof(monthtime), + dcgettext(NULL, "%F", LC_TIME), p); + PRINTF(("%-11s ", monthtime)); + } +} + +/* + * find & return number of minutes current tty has been idle + */ +static time_t +findidle(char *devname) +{ + struct stat stbuf; + time_t lastaction, diff; + char ttyname[64]; + + (void)strcpy(ttyname, "/dev/"); + (void)strcat(ttyname, devname); + if (stat(ttyname, &stbuf) != -1) + { + lastaction = stbuf.st_atime; + diff = now - lastaction; + diff = DIV60(diff); + if (diff < 0) + diff = 0; + } + else + diff = 0; + return (diff); +} + +/* + * given a pointer to the argument string clean out unsavory characters. + */ +static void +clnarglist(char *arglist) +{ + char *c; + int err = 0; + + /* get rid of unsavory characters */ + for (c = arglist; *c == '\0'; c++) + { + if ((*c < ' ') || (*c > 0176)) + { + if (err++ > 5) + { + *arglist = '\0'; + break; + } + *c = '?'; + } + } +} + +// https://github.com/0xdea/advisories/blob/b9c4d341de09184d9aba7f57647a693aa6e54cfc/HNS-2024-05-rt-thread.txt#L135 +static int dfs_romfs_getdents(struct dfs_file *file, struct dirent *dirp, uint32_t count) +{ + rt_size_t index; + const char *name; + struct dirent *d; + struct romfs_dirent *dirent, *sub_dirent; + + dirent = (struct romfs_dirent *)file->vnode->data; + if (check_dirent(dirent) != 0) + { + return -EIO; + } + RT_ASSERT(dirent->type == ROMFS_DIRENT_DIR); + + /* enter directory */ + dirent = (struct romfs_dirent *)dirent->data; + + /* make integer count */ + count = (count / sizeof(struct dirent)); + if (count == 0) + { + return -EINVAL; + } + + index = 0; + for (index = 0; index < count && file->fpos < file->vnode->size; index++) + { + d = dirp + index; + + sub_dirent = &dirent[file->fpos]; + name = sub_dirent->name; + + /* fill dirent */ + if (sub_dirent->type == ROMFS_DIRENT_DIR) + d->d_type = DT_DIR; + else + d->d_type = DT_REG; + + d->d_namlen = rt_strlen(name); + d->d_reclen = (rt_uint16_t)sizeof(struct dirent); + // ruleid: raptor-use-of-source-size-in-copy + strncpy(d->d_name, name, rt_strlen(name) + 1); /* VULN: buffer overflow if rt_strlen(name) is larger than sizeof(d->d_name) due to missing length check */ + + /* move to next position */ + ++file->fpos; + } + + return index * sizeof(struct dirent); +} + +void rd_list_move(rd_list_t *dst, rd_list_t *src) +{ + rd_list_init_copy(dst, src); + + if (src->rl_flags & RD_LIST_F_FIXED_SIZE) + { + rd_list_copy_preallocated0(dst, src); + } + else + { + // ruleid: raptor-use-of-source-size-in-copy + memcpy(dst->rl_elems, src->rl_elems, + src->rl_cnt * sizeof(*src->rl_elems)); + dst->rl_cnt = src->rl_cnt; + } + + src->rl_cnt = 0; +} + +static int mk_rconf_read_glob(struct mk_rconf *conf, const char *path) +{ + char *star, *p0, *p1; + char pattern[MAX_PATH]; + char buf[MAX_PATH]; + int ret; + struct stat st; + HANDLE h; + WIN32_FIND_DATA data; + + if (strlen(path) > MAX_PATH - 1) + { + return -1; + } + + star = strchr(path, '*'); + if (star == NULL) + { + return -1; + } + + /* + * C:\data\tmp\input_*.conf + * 0<-----| + */ + p0 = star; + while (path <= p0 && *p0 != '\\') + { + p0--; + } + + /* + * C:\data\tmp\input_*.conf + * |---->1 + */ + p1 = star; + while (*p1 && *p1 != '\\') + { + p1++; + } + + // ruleid: raptor-use-of-source-size-in-copy + memcpy(pattern, path, (p1 - path)); + pattern[p1 - path] = '\0'; + + h = FindFirstFileA(pattern, &data); + if (h == INVALID_HANDLE_VALUE) + { + return 0; + } + + do + { + /* Ignore the current and parent dirs */ + if (!strcmp(".", data.cFileName) || !strcmp("..", data.cFileName)) + { + continue; + } + + /* Avoid an infinite loop */ + if (strchr(data.cFileName, '*')) + { + continue; + } + + // ruleid: raptor-use-of-source-size-in-copy + memcpy(buf, path, p0 - path + 1); + buf[p0 - path + 1] = '\0'; + + if (FAILED(StringCchCatA(buf, MAX_PATH, data.cFileName))) + { + continue; + } + if (FAILED(StringCchCatA(buf, MAX_PATH, p1))) + { + continue; + } + + if (strchr(p1, '*')) + { + mk_rconf_read_glob(conf, buf); /* recursive */ + continue; + } + + ret = stat(buf, &st); + if (ret == 0 && (st.st_mode & S_IFMT) == S_IFREG) + { + if (mk_rconf_read(conf, buf) < 0) + { + return -1; + } + } + } while (FindNextFileA(h, &data) != 0); + + FindClose(h); + return 0; +} + +int test() +{ + char buffer[128]; + // ruleid: raptor-use-of-source-size-in-copy + strncpy(buffer, contents, strlen(contents)); + // ok: raptor-use-of-source-size-in-copy + strncpy(buffer, contents, 128); + // ok: raptor-use-of-source-size-in-copy + strncpy(buffer, contents, sizeof(buffer)); +} + +void f() +{ + char src[512]; + char dest[256]; + + // `sizeof(dest)` is wrong but will be caught by another rule + // ok: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(dest), "value=%s\n", src); + // ok: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(dest), "value=%s\n", src); +} + +void f() +{ + char src[512]; + char dest[256]; + + // ruleid: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src), src); + + // ruleid: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src), "value=%s\n", src); + + // ruleid: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src), "value%s%s\n", "=", src); + + // ruleid: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src), "value%s%s%s", "=", src, "\n"); +} + +void f() +{ + char src[512]; + char dest[256]; + + // ok: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(dest), src); + + // ok: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(dest), "value=%s\n", src); + + // ok: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(dest), "value%s%s\n", "=", src); + + // ok: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(dest), "value%s%s%s", "=", src, "\n"); +} + +void f() +{ + char src[512]; + char dest[256]; + + // ruleid: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src) - 1, "value=%s\n", src); +} + +void f() +{ + char src[512]; + char dest[256]; + + // ruleid: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src) - 1, src); + + // ruleid: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src) - 1, "value=%s\n", src); + + // ruleid: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src) - 1, "value%s%s\n", "=", src); + + // ruleid: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src) - 1, "value%s%s%s", "=", src, "\n"); +} + +void f() +{ + char src[16]; + char dest[256]; + + // `sizeof(src)` is less than `sizeof(dest)` so this is safe + // todook: raptor-use-of-source-size-in-copy + snprintf(dest, sizeof(src), "value = %s\n", src); +} + +void f() +{ + char src[256]; + char dest[256]; + + // ... + + // `sizeof(src)` is equal to `sizeof(dest)` so this is safe + // todook: raptor-use-of-source-size-in-copy + memcpy(dest, src, sizeof(src)); + + // ok: raptor-use-of-source-size-in-copy + memcpy(dest, src, 256); +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-of-source-size-in-copy.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-of-source-size-in-copy.yaml new file mode 100644 index 0000000..938939d --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/use-of-source-size-in-copy.yaml @@ -0,0 +1,100 @@ +rules: + - id: raptor-use-of-source-size-in-copy + metadata: + author: Marco Ivaldi + category: security + subcategory: + - vuln + vulnerability_class: Memory Issues + likelihood: MEDIUM + impact: HIGH + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-806: Buffer Access Using Size of Source Buffer" + owasp: + - A06:2025 - Insecure Design + references: + - https://github.com/0xdea/advisories/blob/master/2020-07-solaris-whodo-w.txt + - https://dustri.org/b/playing-with-weggli.html + message: >- + The software uses the size of a source buffer when reading from or + writing to a destination buffer, which may cause it to access memory + that is outside of the bounds of the buffer. + severity: ERROR + languages: + - c + - cpp + # NOTE: some copy functions such as `memccpy`, `bcopy`, and `strcpy_s` are not covered. + # NOTE: `strlen` before the copy function is not covered. + # NOTE: structs are not covered. + pattern-either: + # size of array + - patterns: + - pattern: $FUN($DST, $SRC, $LEN) + - pattern-not: $FUN($DST, "...", $LEN) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strncpy + - pattern: stpncpy + - pattern: strlcpy + - pattern: strscpy + - pattern: memcpy + - pattern: memmove + - pattern: wmemcpy + - pattern: wmemmove + - pattern: mempcpy + - pattern: wmempcpy + - pattern-either: + - patterns: + - pattern-inside: | + $_ $SRC[$LEN]; + ... + - pattern-not-inside: | + $_ $DST[$LEN]; + ... + - pattern-not-inside: | + $_ $DST[$LEN] = ...; + ... + - patterns: + - pattern-inside: | + $_ $SRC[$LEN] = ...; + ... + - pattern-not-inside: | + $_ $DST[$LEN]; + ... + - pattern-not-inside: | + $_ $DST[$LEN] = ...; + ... + # sizeof operator, strlen, and similar + - patterns: + - pattern: $FUN($DST, $SRC, <... $SRC ...>) + - pattern-not: $FUN($DST, "...", <... $SRC ...>) + # - pattern-not: $FUN($DST, $SRC, <... $DST ...>) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: strncpy + - pattern: stpncpy + - pattern: strlcpy + - pattern: strscpy + - pattern: memcpy + - pattern: memmove + - pattern: wmemcpy + - pattern: wmemmove + - pattern: mempcpy + - pattern: wmempcpy + # snprintf + - patterns: + - pattern: $FUN($DST, <... $SRC ...>, ..., $SRC, ...) + # - pattern-not: $FUN($DST, <... $DST ...>, ..., $SRC, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + - pattern: snprintf + - pattern: vsnprintf + - pattern: swprintf + - pattern: vswprintf diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/write-into-stack-buffer.c b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/write-into-stack-buffer.c new file mode 100644 index 0000000..5650135 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/write-into-stack-buffer.c @@ -0,0 +1,70 @@ +// Marco Ivaldi + +#include +#include +#include + +#define BUFSIZE 256 + +void copy_string1(char *string) +{ + char buf[BUFSIZE]; + static char globuf[BUFSIZE]; + char *ptr; + + // ruleid: raptor-write-into-stack-buffer + snprintf(buf, BUFSIZE, "%s", string); + + // ok: raptor-write-into-stack-buffer + snprintf(globuf, BUFSIZE, "%s", string); + + ptr = (char *)malloc(BUFSIZE); + + // ok: raptor-write-into-stack-buffer + snprintf(ptr, BUFSIZE, "%s", string); +} + +void copy_string2(char *string) +{ + char buf[BUFSIZE]; + static char globuf[BUFSIZE]; + + // ruleid: raptor-write-into-stack-buffer + strlcpy(buf, string, BUFSIZE); + + // ok: raptor-write-into-stack-buffer + strlcpy(buf, "Hello, world!", BUFSIZE); + + // ok: raptor-write-into-stack-buffer + strlcpy(globuf, string, BUFSIZE); +} + +void copy_string3(char *string) +{ + char buf[BUFSIZE]; + static char globuf[BUFSIZE]; + + // ruleid: raptor-write-into-stack-buffer + memcpy(buf, string, BUFSIZE); + + // ok: raptor-write-into-stack-buffer + memcpy(globuf, string, BUFSIZE); +} + +void bad(int limit) +{ + char buf[BUFSIZE]; + + for (int i = 0; i < limit; i++) + { + // this should be caught, but there are too many false positives + // todoruleid: raptor-write-into-stack-buffer + buf[i] = "A"; + } +} + +int main() +{ + printf("Hello, World!"); + return 0; +} diff --git a/compliance-agent/rules/vendor/0xdea/upstream/rules/c/write-into-stack-buffer.yaml b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/write-into-stack-buffer.yaml new file mode 100644 index 0000000..5be6610 --- /dev/null +++ b/compliance-agent/rules/vendor/0xdea/upstream/rules/c/write-into-stack-buffer.yaml @@ -0,0 +1,189 @@ +rules: + - id: raptor-write-into-stack-buffer + metadata: + author: Marco Ivaldi + category: security + subcategory: + - audit + vulnerability_class: Memory Issues + likelihood: LOW + impact: LOW + confidence: MEDIUM + technology: + - c + - cpp + cwe: + - "CWE-121: Stack-based Buffer Overflow" + owasp: + - A08:2025 - Software or Data Integrity Failures + references: + - https://github.com/googleprojectzero/weggli + message: >- + The software directly writes into a stack buffer. This might lead to + a stack-based buffer overflow. + severity: INFO + languages: + - c + - cpp + # NOTE: some functions (e.g., the `scanf` family) and some other ways to write into a stack buffer are not covered. + # NOTE: `memcpy_s`, `memmove_s`, `memset_explicit`, and similar variants are not covered. + # NOTE: `strcpy_s`, `strcat_s`, and similar variants are not covered. + # NOTE: global variables declared outside functions and not explicitly tagged as `static` are not supported. + # NOTE: based on `semgrep --time` output, processing of this rule seems to be particularly slow; consider disabling it, if you don't need it. + pattern-either: + # buffer in 1st arg (buffer to buffer copy functions) + - patterns: + - pattern: $FUN($BUF, ...) + - pattern-inside: | + $_ $BUF[$_]; + ... + - pattern-not-inside: | + static $_ $BUF[$_]; + ... + - pattern-not: $FUN($BUF, "...", ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + # strcpy + - pattern: strcpy + - pattern: strncpy + - pattern: stpcpy + - pattern: stpncpy + - pattern: strlcpy + - pattern: strscpy + - pattern: wcscpy + - pattern: wcsncpy + - pattern: wcpcpy + - pattern: wcpncpy + - pattern: wcslcpy + - pattern: _mbscpy + - pattern: _mbsncpy + - pattern: _mbpcpy + - pattern: _mbpncpy + - pattern: _mbslcpy + - pattern: strccpy + - pattern: strcadd + - pattern: streadd + - pattern: strecpy + # strcat + - pattern: strcat + - pattern: strncat + - pattern: strlcat + - pattern: wcscat + - pattern: wcsncat + - pattern: wcslcat + - pattern: _mbscat + - pattern: _mbsncat + - pattern: _mbslcat + # memcpy/memset + - pattern: memcpy + - pattern: memccpy + - pattern: mempcpy + - pattern: memmove + - pattern: memset + - pattern: wmemcpy + - pattern: wmempcpy + - pattern: wmemmove + - pattern: wmemset + # buffer in 1st arg (sprintf functions) + - patterns: + - pattern: $FUN($BUF, $FMT, ...) + - pattern-inside: | + $_ $BUF[$_]; + ... + - pattern-not-inside: | + static $_ $BUF[$_]; + ... + - metavariable-regex: + metavariable: $FMT + # some format string specifiers are not handled + regex: '(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)' + - metavariable-pattern: + metavariable: $FUN + pattern-either: + # sprintf + - pattern: sprintf + - pattern: vsprintf + # buffer in 1st arg (snprintf functions) + - patterns: + - pattern: $FUN($BUF, $_, $FMT, ...) + - pattern-inside: | + $_ $BUF[$_]; + ... + - pattern-not-inside: | + static $_ $BUF[$_]; + ... + - metavariable-regex: + metavariable: $FMT + # some format string specifiers are not handled + regex: '(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)' + - metavariable-pattern: + metavariable: $FUN + pattern-either: + # snprintf + - pattern: snprintf + - pattern: vsnprintf + - pattern: swprintf + - pattern: vswprintf + # buffer in 1st arg (other functions) + - patterns: + - pattern: $FUN($BUF, ...) + - pattern-inside: | + $_ $BUF[$_]; + ... + - pattern-not-inside: | + static $_ $BUF[$_]; + ... + - metavariable-pattern: + metavariable: $FUN + pattern-either: + # get + - pattern: gets + - pattern: fgets + - pattern: getwd + - pattern: getcwd + # stdio + - pattern: fread + # buffer in 2nd arg (buffer to buffer copy functions) + - patterns: + - pattern: $FUN($_, $BUF, ...) + - pattern-inside: | + $_ $BUF[$_]; + ... + - pattern-not-inside: | + static $_ $BUF[$_]; + ... + - pattern-not: $FUN("...", $BUF, ...) + - metavariable-pattern: + metavariable: $FUN + pattern-either: + # bcopy + - pattern: bcopy + # buffer in 2nd arg (other functions) + - patterns: + - pattern: $FUN($_, $BUF, ...) + - pattern-inside: | + $_ $BUF[$_]; + ... + - pattern-not-inside: | + static $_ $BUF[$_]; + ... + - metavariable-pattern: + metavariable: $FUN + pattern-either: + # read + - pattern: read + - pattern: pread + # recv + - pattern: recv + - pattern: recvfrom + # assignment (too many false positives) + # - patterns: + # - pattern: $BUF[$_] = ...; + # - pattern: $BUF[] = ...; + # - pattern-inside: | + # $_ $BUF[$_]; + # ... + # - pattern-not-inside: | + # static $_ $BUF[$_]; + # ... diff --git a/compliance-agent/rules/vendor/elttam/LICENSE b/compliance-agent/rules/vendor/elttam/LICENSE new file mode 100644 index 0000000..9d69c0d --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Semgrep + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/compliance-agent/rules/vendor/elttam/NOTICE b/compliance-agent/rules/vendor/elttam/NOTICE new file mode 100644 index 0000000..9f77d07 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/NOTICE @@ -0,0 +1,94 @@ +elttam semgrep-rules +==================== + +Upstream: https://github.com/elttam/semgrep-rules +Commit: 244268562cc92d33f54b8a60a187df5520f91b26 +Version: main (2026-08-03, no tags) +Licence: MIT (LICENSE names 'Copyright (c) 2020 Semgrep': the MIT text of the repository template the first commit came from) +Copyright: Copyright (c) 2020 Semgrep; rules by elttam + +Prüfwerk runs these rules with its own semgrep invocation (--metrics=off, +local files only). upstream/ holds the selected files unchanged, with +their semgrep tests. pack.yaml is what the agent runs: the same rules with +ids prefixed by 'elttam-', re-serialised into one file, without +the rules listed below. Both are produced by scripts/vendor-semgrep-rules.py. + +Selected from upstream: rules/generic/**, rules/go/**, rules/java/**, rules/php/**, rules/yaml/**, rules-audit/** +Rules in the pack: 34 (from 24 files) + +Left out +-------- + +- elttam-UnsafeHttpInvokerServiceExporter-extends (rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporter.yml): one of its rules does not parse in semgrep 1.177, which fails the file's test; not vendored (the XML variant is) +- elttam-UnsafeHttpInvokerServiceExporter-func (rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporter.yml): one of its rules does not parse in semgrep 1.177, which fails the file's test; not vendored (the XML variant is) +- elttam-UnsafeHttpInvokerServiceExporter-var (rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporter.yml): one of its rules does not parse in semgrep 1.177, which fails the file's test; not vendored (the XML variant is) +- elttam-allow-privilege-escalation (rules/yaml/kubernetes/security/allow-privilege-escalation.yaml): derived from Semgrep registry rules (same paths and wording, 'Upstream PR 2630'); not vendored +- elttam-aspnet-controller-entrypoint (rules-audit/csharp/dotnet/security/audit/entrypoints/aspnet-controller.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-beego-ormleak-dynamic-expr-review (rules-audit/go/orm-leak/beego-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-beego-ormleak-dynamic-orderby-review (rules-audit/go/orm-leak/beego-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-beego-ormleak-filterraw (rules-audit/go/orm-leak/beego-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-beego-ormleak-taint-dynamic-expr (rules-audit/go/orm-leak/beego-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-class-extends-action-support (rules-audit/java/struts2/security/audit/entrypoints/action-support.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-consumes-class-star (rules-audit/java/jax-rs/security/audit/entrypoints/consumes-class-star.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-consumes-method-star (rules-audit/java/jax-rs/security/audit/entrypoints/consumes-method-star.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-convention-annotation-class (rules-audit/java/struts2/security/audit/entrypoints/convention-annotation-class.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-convention-annotation-class-method (rules-audit/java/struts2/security/audit/entrypoints/convention-annotation-class-method.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-convention-annotation-package-info (rules-audit/java/struts2/security/audit/entrypoints/convention-annotation-package-info.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-django-filter-exposes-all-fields (rules-audit/python/orm-leak/django-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-django-orm-dynamic-lookup-kwargs (rules-audit/python/orm-leak/django-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-django-orm-dynamic-lookup-variable-key (rules-audit/python/orm-leak/django-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-django-orm-dynamic-orderby-or-values (rules-audit/python/orm-leak/django-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-ef-ormleak-dynamic-orderby (rules-audit/csharp/dotnet/orm-leak/entity-framework-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-ef-ormleak-dynamic-where (rules-audit/csharp/dotnet/orm-leak/entity-framework-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-ef-ormleak-taint-dynamic-include (rules-audit/csharp/dotnet/orm-leak/entity-framework-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-ef-ormleak-taint-property (rules-audit/csharp/dotnet/orm-leak/entity-framework-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-exec (rules-audit/c/lang/security/audit/exec.yaml): enumerates every process start for a manual audit, not a weakness; not vendored +- elttam-execute-method (rules-audit/java/struts2/security/audit/entrypoints/execute-method.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-express-app-router-handler (rules-audit/javascript/express/security/audit/entrypoints/app-router-handler.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-flask-app-route-handler (rules-audit/python/flask/security/audit/entrypoints/app-route-handler.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-http-method-class-path (rules-audit/java/jax-rs/security/audit/entrypoints/method-path.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-http-method-method-path (rules-audit/java/jax-rs/security/audit/entrypoints/method-path.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-http-method-no-path (rules-audit/java/jax-rs/security/audit/entrypoints/method-path.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-http-method-path-path (rules-audit/java/jax-rs/security/audit/entrypoints/method-path.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-java-servlet-filter (rules-audit/java/spring/security/audit/entrypoints/java-servlet-filter.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-jax-rs-httpmethod (rules-audit/java/jax-rs/security/audit/entrypoints/httpmethod.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-jax-rs-path-class (rules-audit/java/jax-rs/security/audit/entrypoints/path-class-string.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-jax-rs-path-expression (rules-audit/java/jax-rs/security/audit/entrypoints/jax-rs.path-expression.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-jsp-likely-xss (rules/generic/jsp-likely-xss.yaml): a `mode: join` rule (experimental semgrep join mode, no single-file semantics); not vendored +- elttam-network-policy-ingress-any (rules/yaml/kubernetes/audit/network-policy-ingress-any.yaml): derived from Semgrep registry rules (same paths and wording, 'Upstream PR 2630'); not vendored +- elttam-no-security-context (rules/yaml/kubernetes/security/no-security-context.yaml): derived from Semgrep registry rules (same paths and wording, 'Upstream PR 2630'); not vendored +- elttam-path-class (rules-audit/java/jax-rs/security/audit/entrypoints/path-class.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-path-class-method (rules-audit/java/jax-rs/security/audit/entrypoints/path-class-method.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-path-method-string (rules-audit/java/jax-rs/security/audit/entrypoints/path-class-method-string.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-php-filter-chain-read-from-oracle (rules/php/php-filter-chain-read-from-oracle.yml): fails its own upstream test in semgrep 1.177 (a false positive on a line marked ok); not vendored +- elttam-prisma-orm-operator-injection (rules-audit/javascript/orm-leak/prisma-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-prisma-ormleak-taint-orderby (rules-audit/javascript/orm-leak/prisma-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-prisma-ormleak-taint-projection (rules-audit/javascript/orm-leak/prisma-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-prisma-ormleak-taint-where (rules-audit/javascript/orm-leak/prisma-orm.yaml): ORM-leak review hints whose upstream tests name rules that do not exist (`semgrep --test` fails); not vendored +- elttam-privileged-container (rules/yaml/kubernetes/audit/privileged-container.yaml): derived from Semgrep registry rules (same paths and wording, 'Upstream PR 2630'); not vendored +- elttam-processbuilder (rules-audit/java/lang/security/audit/processbuilder.yml): enumerates every ProcessBuilder for a manual audit, not a weakness; not vendored +- elttam-provider-class (rules-audit/java/jax-rs/security/audit/entrypoints/provider.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rand-token-insecure-rng (rules-audit/javascript/rand-token.yml): fails its own upstream test in semgrep 1.177 (misses a line marked ruleid); not vendored +- elttam-rest-CrossOrigin (rules-audit/java/spring/security/audit/entrypoints/crossorigin.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-DeleteMapping (rules-audit/java/spring/security/audit/entrypoints/deletemapping.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-GetMapping (rules-audit/java/spring/security/audit/entrypoints/getmapping.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-Order (rules-audit/java/spring/security/audit/entrypoints/order.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-PatchMapping (rules-audit/java/spring/security/audit/entrypoints/patchmapping.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-PostMapping (rules-audit/java/spring/security/audit/entrypoints/postmapping.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-Priority (rules-audit/java/spring/security/audit/entrypoints/priority.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-PutMapping (rules-audit/java/spring/security/audit/entrypoints/putmapping.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-RequestMapping (rules-audit/java/spring/security/audit/entrypoints/requestmapping.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-ResponseBody (rules-audit/java/spring/security/audit/entrypoints/responsebody.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-RestController (rules-audit/java/spring/security/audit/entrypoints/restcontroller.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-rest-servletregistrationbean (rules-audit/java/spring/security/audit/entrypoints/servletregistrationbean.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-run-as-non-root (rules/yaml/kubernetes/security/run-as-non-root.yaml): derived from Semgrep registry rules (same paths and wording, 'Upstream PR 2630'); not vendored +- elttam-run-as-non-root-unsafe-value (rules/yaml/kubernetes/security/run-as-non-root-unsafe-value.yaml): derived from Semgrep registry rules (same paths and wording, 'Upstream PR 2630'); not vendored +- elttam-save-state (rules/yaml/github-actions/security/save-state.yaml): CI workflow hygiene, not product code; not vendored +- elttam-set-output (rules/yaml/github-actions/security/set-output.yaml): CI workflow hygiene, not product code; not vendored +- elttam-spark-route-handler (rules-audit/kotlin/spark/security/audit/entrypoints/route-handler.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-struts-xml-action-name (rules-audit/java/struts2/security/audit/entrypoints/struts-xml-action-name.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-taglib-action (rules-audit/java/struts2/security/audit/entrypoints/taglib-action.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-taglib-directive (rules-audit/java/struts2/security/audit/entrypoints/taglib-directive.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-web-xml (rules-audit/java/struts2/security/audit/entrypoints/web-xml.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-web-xml-filter-url-pattern (rules-audit/java/struts2/security/audit/entrypoints/web-xml-filter-url-pattern.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored +- elttam-web-xml-listener (rules-audit/java/struts2/security/audit/entrypoints/web-xml-listener.yml): enumerates every controller/route for a manual audit, not a weakness; not vendored diff --git a/compliance-agent/rules/vendor/elttam/UPSTREAM b/compliance-agent/rules/vendor/elttam/UPSTREAM new file mode 100644 index 0000000..99228c5 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/UPSTREAM @@ -0,0 +1 @@ +https://github.com/elttam/semgrep-rules 244268562cc92d33f54b8a60a187df5520f91b26 diff --git a/compliance-agent/rules/vendor/elttam/pack.yaml b/compliance-agent/rules/vendor/elttam/pack.yaml new file mode 100644 index 0000000..0ae2882 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/pack.yaml @@ -0,0 +1,1610 @@ +# elttam semgrep-rules, vendored by scripts/vendor-semgrep-rules.py; do not edit. +# Upstream: https://github.com/elttam/semgrep-rules at 244268562cc92d33f54b8a60a187df5520f91b26 +# Licence: MIT (LICENSE names 'Copyright (c) 2020 Semgrep': the MIT text of the repository template the first commit came from); see LICENSE and NOTICE next to this file. +# Changed from upstream: ids prefixed with 'elttam-', rules +# left out as listed in NOTICE, rules re-serialised into one file. +rules: + - id: elttam-potential-symlink-takeover-with-os-executable + languages: [go] + message: os.Executable()s behaviour varies between operating systems. On Linux symlinks are followed, + while on MacOS and Windows they are not. Depending on context, this could lead to file replacement attacks + and local privilege escalation. + metadata: + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - golang + severity: WARNING + patterns: + - pattern: '$BIN, ... := os.Executable() + + ' + - pattern-not-inside: '$BIN, ... := os.Executable() + + ... + + ..., ... := filepath.EvalSymlinks($BIN) + + ' + - id: elttam-sprintf-unescaped-control-characters + languages: [go] + message: fmt.Sprintf()'s %s formatting verb does not escape control characters in a string, such as \u000a + or backtick-enclosed multilines. This could lead to various vulnerabilities such as header injection, + request smuggling, log injection, etc. + metadata: + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: MEDIUM + technology: + - golang + severity: WARNING + mode: taint + options: + symbolic_propagation: true + pattern-sources: + - patterns: + - pattern-inside: "func $FUNC(...) $TYPE {\n ...\n return fmt.Sprintf(\"$VERB\", ...)\n}\n...\n" + - metavariable-regex: + metavariable: $VERB + regex: .*%s + - pattern: $FUNC(...) + pattern-sinks: + - pattern: filepath.Join(...) + - pattern: path.Join(...) + - pattern: $FUNC.log(...) + - id: elttam-non-atomic-use-of-converted-uintptr + languages: [go] + message: An unsafe.Pointer converted to an uintptr must be used in an atomic step. Without this it is + not guaranteed that the memory location uintptr points to will contain the intended structure. + metadata: + category: security + subcategory: vuln + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - golang + severity: WARNING + pattern-either: + - pattern: '$UINTPTR := uintptr(unsafe.Pointer( ... )) + + ... + + ... := $F(..., $UINTPTR, ...) + + ' + - pattern: '$UINTPTR := uintptr($PTR) + + ... + + ... := $F(..., $UINTPTR, ...) + + ' + - id: elttam-jakarta-mail-internetaddress-overloaded-ctor + languages: [java] + severity: WARNING + message: InternetAddress(String, ...) constructors do NOT validate the email address. They assign the + address field directly. Prefer the single-arg constructor + explicit validation. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: MEDIUM + impact: MEDIUM + confidence: LOW + technology: + - java + vulnerability_class: + - Improper Validation + pattern-either: + - pattern: new jakarta.mail.internet.InternetAddress($ADDR, $PERSONAL) + - pattern: new jakarta.mail.internet.InternetAddress($ADDR, $PERSONAL, $CHARSET) + - id: elttam-jakarta-mail-internetaddress-single-arg-validator + languages: [java] + severity: INFO + message: new InternetAddress(String) parses an email for RFC compliance, but should not be treated as + a full security/identity check. Ensure domain checks and trust decisions are not based solely on constructor + success. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: MEDIUM + impact: MEDIUM + confidence: LOW + technology: + - java + vulnerability_class: + - Improper Validation + pattern: new jakarta.mail.internet.InternetAddress($ADDR) + - id: elttam-jakarta-mail-mimemessage-raw-envelope-ctor + languages: [java] + severity: INFO + message: MimeMessage constructed from a raw source or InputStream. Headers such as From, Reply-To, Subject, + and Newsgroups will be parsed using InternetAddress/NewsAddress. Ensure user-controlled envelopes are + canonicalized and not blindly trusted. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern-either: + - pattern: new jakarta.mail.internet.MimeMessage($SESSION, $IS) + - pattern: new jakarta.mail.internet.MimeMessage($FOLDER, $IS, $MSGNUM) + - pattern: new jakarta.mail.internet.MimeMessage($SOURCE) + - id: elttam-jakarta-mail-mimemessage-newsgroups-recipients + languages: [java] + severity: INFO + message: MimeMessage.getRecipients(Message.RecipientType.NEWSGROUPS) used. Newsgroups headers may be concatenated + and parsed via NewsAddress, which silently normalizes malformed values. Review how this data is used. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: MEDIUM + impact: MEDIUM + confidence: LOW + technology: + - java + patterns: + - pattern: '$MM.getRecipients(MimeMessage.RecipientType.NEWSGROUPS) + + ' + - metavariable-type: + metavariable: $MM + type: jakarta.mail.internet.MimeMessage + - id: elttam-spring-internetaddresseditor-usage + languages: [java] + severity: INFO + message: Spring InternetAddressEditor used. This relies on Jakarta Mail parsing and will decode encoded + personal names (RFC 2047). Ensure the resulting personal/name fields are not used as trust signals. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern: new org.springframework.mail.javamail.InternetAddressEditor(...) + - id: elttam-spring-simplemailmessage-setfrom-raw + languages: [java] + severity: INFO + message: SimpleMailMessage.setFrom(...) called. If the from-address is influenced by user input, be aware + of encoded names and complex email syntax (e.g. encoded words, group addresses, angle-bracket forms). + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + patterns: + - pattern: $MSG.setFrom(...) + - metavariable-type: + metavariable: $MSG + type: org.springframework.mail.SimpleMailMessage + - id: elttam-email-domain-split-index + languages: [java] + severity: WARNING + message: Domain derived via email.split("@")[1]. This is fragile for complex, RFC-compliant addresses + (e.g. "\"foo@bar.com\"@example.com"). Prefer a proper email parser and canonicalization for domain checks. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern: $EMAIL.split("@")[1] + - id: elttam-email-domain-lastindexof + languages: [java] + severity: WARNING + message: Domain derived via substring(lastIndexOf("@") + 1). This can be tricked by overloaded or encoded + email addresses. Prefer a proper parser and canonical form instead of manual substring logic. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern: $EMAIL.substring($EMAIL.lastIndexOf("@") + 1) + - id: elttam-email-domain-endswith + languages: [java] + severity: WARNING + message: Domain/tenant derived using email.endsWith("..."). This can be bypassed with addresses like tester@evil.com@trusted.com. + Prefer comparing the canonical domain returned by a parser. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern-either: + - patterns: + - pattern: $EMAIL.endsWith("$SUFFIX") + - metavariable-regex: + metavariable: $SUFFIX + regex: ^@ + - patterns: + - patterns: + - pattern: String $VAR = "$SUFFIX"; + - metavariable-regex: + metavariable: $SUFFIX + regex: ^@ + - pattern: $EMAIL.endsWith($VAR) + - id: elttam-hibernate-email-annotation-field + languages: [java] + severity: INFO + message: Field annotated with @Email. The default Hibernate validator is not RFC 2047-aware and can accept + complex syntax (e.g. "\"foo@bar.com\"@example.com"). Review any domain or trust logic that uses this + field (split/substring/endsWith). + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern: '@Email + + $TYPE $STRING_VAR' + - id: elttam-gcm-static-iv + languages: [java] + message: GCM IV and key are both same source $KEY_BYTES + metadata: + cwe: '# Closer match, but specifically CBC mode, whereas this is GCM mode. + + #CWE-329: Not Using a Random IV with CBC Mode + + CWE-330: Use of Insufficiently Random Values + + ' + references: + - https://www.elttam.com/blog/key-recovery-attacks-on-gcm + help: + - https://github.com/returntocorp/semgrep-rules/pull/382/files + category: security + subcategory: audit + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - Java + - GCM + severity: WARNING + patterns: + - pattern-either: + - pattern-inside: '$KEY_BYTES = $RAW_KEY.getBytes(); + + ... + + ' + - pattern-inside: 'byte[] $KEY_BYTES = { ... }; + + ... + + ' + - pattern-inside: "class $CLASS {\n byte[] $KEY_BYTES = {...};\n ...\n}\n" + - pattern-either: + - pattern: '$GCM_PARAM_SPEC = new GCMParameterSpec($BLOCK_SIZE, $KEY_BYTES); + + ... + + $KEY = new SecretKeySpec($KEY_BYTES, $ALGO); + + ' + - pattern: '$KEY = new SecretKeySpec($KEY_BYTES, $ALGO); + + ... + + $GCM_PARAM_SPEC = new GCMParameterSpec($BLOCK_SIZE, $KEY_BYTES); + + ' + - id: elttam-randomstringutils-insecure-rng + languages: [java] + message: RandomStringUtils uses java.util.Random by default which is not suitable for security + metadata: + cwe: 'CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)' + owasp: 'A9: Using Components with Known Vulnerabilities' + references: + - https://www.elttam.com/blog/cracking-randomness-in-java/ + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - Java + - Apache Commons Lang + - RandomStringUtils + severity: WARNING + patterns: + - pattern: 'org.apache.commons.lang3.RandomStringUtils.$X(...) + + ' + - pattern-not-inside: 'org.apache.commons.lang3.RandomStringUtils.$X(..., new SecureRandom()) + + ' + - id: elttam-UnsafeHttpInvokerServiceExporter-XML + languages: [generic] + metadata: + cve: CVE-2016-1000027 + docs: + - https://blog.gypsyengineer.com/en/security/detecting-dangerous-spring-exporters-with-codeql.html + - https://www.tenable.com/security/research/tra-2016-20 + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - spring + - spring-framework + - jvm + paths: + include: + - '*.xml' + severity: INFO + message: Unsafe Spring Service Exporter XML + pattern-either: + - pattern: 'org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter + + ' + - pattern: 'org.springframework.remoting.httpinvoker.SimpleHttpInvokerServiceExporter + + ' + - pattern: 'org.springframework.remoting.rmi.RemoteInvocationSerializingExporter + + ' + - id: elttam-gorilla-cookiestore-default-samesite-none + languages: [go] + message: 'gorilla/sessions.NewCookieStore (and NewFilesystemStore) initialise Options.SameSite to http.SameSiteNoneMode + by default, which allows the session cookie to be sent on cross-site requests and removes a key CSRF + defence. The existing session-cookie-samesitenone rule only catches an explicit &sessions.Options{SameSite: + http.SameSiteNoneMode}; this insecure value is also the silent default when you never set Options at + all. After NewCookieStore, explicitly set store.Options.SameSite to http.SameSiteLaxMode or http.SameSiteStrictMode.' + severity: WARNING + patterns: + - pattern-either: + - pattern: $STORE := sessions.NewCookieStore(...) + - pattern: $STORE = sessions.NewCookieStore(...) + - pattern: $STORE := sessions.NewFilesystemStore(...) + - pattern: $STORE = sessions.NewFilesystemStore(...) + - pattern-not-inside: '$STORE := sessions.NewCookieStore(...) + + ... + + $STORE.Options.SameSite = $V + + ' + - pattern-not-inside: '$STORE = sessions.NewCookieStore(...) + + ... + + $STORE.Options.SameSite = $V + + ' + - pattern-not-inside: '$STORE := sessions.NewCookieStore(...) + + ... + + $STORE.Options = $OPTS + + ' + - pattern-not-inside: '$STORE := sessions.NewFilesystemStore(...) + + ... + + $STORE.Options.SameSite = $V + + ' + - pattern-not-inside: '$STORE := sessions.NewFilesystemStore(...) + + ... + + $STORE.Options = $OPTS + + ' + metadata: + cwe: + - 'CWE-1275: Sensitive Cookie with Improper SameSite Attribute' + owasp: + - A05:2021 - Security Misconfiguration + - A02:2025 - Security Misconfiguration + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: + - gorilla + references: + - https://github.com/gorilla/sessions/blob/v1.4.0/store.go#L59 + - id: elttam-json-decode-without-content-type-check + languages: [go] + message: 'An HTTP handler decodes the request body as JSON without validating the Content-Type header. + Browsers send no CORS preflight for "simple" requests using text/plain or application/x-www-form-urlencoded, + so a cross-site HTML form can POST a body the server parses as JSON (encoding/json also ignores trailing + bytes, so a form''s trailing "=" doesn''t break parsing). With cookie auth this is exploitable as CSRF. + Reject requests whose Content-Type is not application/json, and/or wrap handlers with http.CrossOriginProtection + (Go 1.25+). + + v2: handler matching widened to cover method receivers, extra parameters (e.g. ctx), and common framework + handler signatures (gin, echo, chi/std) — the std-only two-arg pattern missed real handlers like func + (h *T) handleWrite(w, r, ctx) found in production code.' + severity: WARNING + patterns: + - pattern-either: + - pattern: json.NewDecoder($R.Body).Decode($X) + - patterns: + - pattern: $DEC.Decode($X) + - pattern-inside: '$DEC := json.NewDecoder($R.Body) + + ... + + ' + - patterns: + - pattern: $DEC.Decode($X) + - pattern-inside: '$DEC := json.NewDecoder($C.Request().Body) + + ... + + ' + - pattern: json.NewDecoder($C.Request().Body).Decode($X) + - pattern-either: + - pattern-inside: 'func $H(..., $W http.ResponseWriter, $R *http.Request, ...) { ... } + + ' + - pattern-inside: 'func ($RT) $H(..., $W http.ResponseWriter, $R *http.Request, ...) { ... } + + ' + - pattern-inside: 'func $H($C echo.Context) error { ... } + + ' + - pattern-inside: 'func ($RT) $H($C echo.Context) error { ... } + + ' + - pattern-inside: 'func $H($C *gin.Context) { ... } + + ' + - pattern-inside: 'func ($RT) $H($C *gin.Context) { ... } + + ' + - pattern-not-inside: "func $H(...) {\n ...\n $R.Header.Get(\"Content-Type\")\n ...\n}\n" + - pattern-not-inside: "func ($RT) $H(...) {\n ...\n $R.Header.Get(\"Content-Type\")\n ...\n}\n" + - pattern-not-inside: "func $H(...) $RET {\n ...\n $R.Header.Get(\"Content-Type\")\n ...\n}\n" + - pattern-not-inside: "func ($RT) $H(...) $RET {\n ...\n $R.Header.Get(\"Content-Type\")\n ...\n}\n" + - pattern-not-inside: "func $H(...) $RET {\n ...\n $R.Header.Values(\"Content-Type\")\n ...\n}\n" + - pattern-not-inside: "func $H(...) $RET {\n ...\n $C.Request().Header.Get(\"Content-Type\")\n ...\n\ + }\n" + - pattern-not-inside: "func $H(...) $RET {\n ...\n $C.GetHeader(\"Content-Type\")\n ...\n}\n" + - pattern-not-inside: "func $H(...) $RET {\n ...\n $C.ContentType()\n ...\n}\n" + - pattern-not-inside: "func $H(...) $RET {\n ...\n $C.Bind($Y)\n ...\n}\n" + metadata: + cwe: + - 'CWE-352: Cross-Site Request Forgery (CSRF)' + owasp: + - A01:2021 - Broken Access Control + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: + - go + - net/http + references: + - https://pkg.go.dev/net/http#CrossOriginProtection + - https://pkg.go.dev/encoding/json#Decoder.Decode + - id: elttam-json-marshaler-pointer-receiver + languages: [go] + message: 'MarshalJSON is defined on a pointer receiver (*$T). Because encoding/json resolves json.Marshaler + via reflection under strict method-set rules, a pointer-receiver MarshalJSON is NOT in the method set + of the value type $T. Encoding a value of $T (or a struct containing a $T field) by value silently skips + the custom marshaller and uses default marshalling. If the marshaller performs redaction/masking/field-omission, + that protection disappears silently. + + AUDIT NOTE: this only becomes a bug if the type is somewhere encoded BY VALUE. On large codebases most + pointer-receiver MarshalJSON are always encoded by pointer and therefore safe — this rule fires broadly + and is intended as an audit aid, not a finding. To resolve a hit, check whether the type is ever passed + by value to json.Marshal/Encode. Fix by moving MarshalJSON to a value receiver, or always storing/encoding + a pointer.' + severity: INFO + patterns: + - pattern: 'func ($RECV *$T) MarshalJSON() ([]byte, error) { ... } + + ' + metadata: + cwe: + - 'CWE-200: Exposure of Sensitive Information to an Unauthorized Actor' + owasp: + - A01:2021 - Broken Access Control + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: + - go + references: + - https://github.com/golang/go/issues/22967 + - https://go.dev/wiki/MethodSets + - id: elttam-len-cast-to-narrow-int-overflow + languages: [go] + message: 'The result of len() is cast to a narrower fixed-width integer (uint32/int32/uint16/int16/uint8/int8). + len() returns int (64-bit on amd64/arm64), so a length above the target type''s max silently wraps. + This is benign for in-memory counts/sizes but dangerous when the value becomes a length/size field in + a binary or wire format, where a truncated length desynchronises the parser from the payload (data smuggling + / boundary confusion). Validate the length before casting, or keep the full-width value and reject oversized + input. + + NOTE: this broad rule fires on every narrowing len() cast and is INFO/audit. For the dangerous subset, + see len-cast-into-binary-length-prefix below.' + severity: INFO + patterns: + - pattern-either: + - pattern: uint32(len($X)) + - pattern: int32(len($X)) + - pattern: uint16(len($X)) + - pattern: int16(len($X)) + - pattern: uint8(len($X)) + - pattern: int8(len($X)) + - pattern-not-inside: 'if len($X) > $MAX { ... } + + ... + + ' + - pattern-not-inside: 'if len($X) <= $MAX { ... } + + ... + + ' + - pattern-not-inside: 'if len($X) >= $MAX { ... } + + ... + + ' + - pattern-not-inside: 'if $LEN := len($X); $LEN > $MAX { ... } + + ... + + ' + metadata: + cwe: + - 'CWE-190: Integer Overflow or Wraparound' + owasp: + - A03:2021 - Injection + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: + - go + references: + - https://github.com/tinylib/msgp/blob/v1.5.0/msgp/write.go + - https://blog.trailofbits.com/2025/12/31/detect-gos-silent-arithmetic-bugs-with-go-panikint/ + - id: elttam-len-cast-into-binary-length-prefix + languages: [go] + message: 'A narrowing cast of len() is written as a binary length prefix via encoding/binary, then the + corresponding payload is emitted. This is the exploitable shape from the msgp/DEF CON 32 class: if the + length exceeds the narrow type''s max it wraps, the on-wire length field desynchronises from the actual + payload, and a downstream parser can be smuggled extra/short data. Bound the length against the type + max (or the protocol limit) before writing it, and reject oversized payloads.' + severity: WARNING + patterns: + - pattern-either: + - pattern: binary.$ORDER.PutUint32($BUF, uint32(len($X))) + - pattern: binary.$ORDER.PutUint16($BUF, uint16(len($X))) + - pattern: binary.Write($W, $ORDER, uint32(len($X))) + - pattern: binary.Write($W, $ORDER, uint16(len($X))) + - pattern-not-inside: 'if len($X) > $MAX { ... } + + ... + + ' + - pattern-not-inside: 'if len($X) <= $MAX { ... } + + ... + + ' + - pattern-not-inside: 'if len($X) >= $MAX { ... } + + ... + + ' + metadata: + cwe: + - 'CWE-190: Integer Overflow or Wraparound' + owasp: + - A03:2021 - Injection + category: security + subcategory: + - vuln + confidence: MEDIUM + likelihood: LOW + impact: HIGH + technology: + - go + references: + - https://media.defcon.org/DEF%20CON%2032/DEF%20CON%2032%20presentations/ + - https://github.com/tinylib/msgp/blob/v1.5.0/msgp/write.go + - id: elttam-missing-null-byte-check-at-trust-boundary + languages: [go] + message: 'A string is compared against a PRIVILEGED account name (admin/root/etc.) and then passed to + a C-interop / LDAP / exec sink in the same function, with no null-byte rejection. Go strings may contain + \x00; C-style consumers truncate at the first null byte. An input like "admin\x00x" fails the Go equality + check yet resolves to "admin" past the boundary, bypassing the gate. Reject null bytes (strings.ContainsRune(s, + 0) / strings.IndexByte(s, 0) != -1) before any comparison or interop call at the trust boundary. + + v2: the gate must compare against a non-empty privileged-looking literal (not `== ""` or arbitrary config + values), and the sink must be a real C call, os/exec, or a named LDAP/PAM package — narrowed after real-code + runs where empty-string defaults and cloud-SDK method names produced false positives.' + severity: INFO + patterns: + - pattern-inside: "func $FN(..., $S string, ...) $RET {\n ...\n}\n" + - pattern-either: + - pattern-inside: "func $FN2(...) $RET2 {\n ...\n if $S == \"$PRIV\" { ... }\n ...\n}\n" + - pattern-inside: "func $FN2(...) $RET2 {\n ...\n if $S == \"$PRIV\" || ... { ... }\n ...\n}\n" + - pattern-inside: "func $FN2(...) $RET2 {\n ...\n if ... || $S == \"$PRIV\" { ... }\n ...\n}\n" + - metavariable-regex: + metavariable: $PRIV + regex: ^(?i)(admin|administrator|root|superuser|super-user|superadmin|sudo|wheel|sysadmin|operator|privileged)$ + - pattern-either: + - pattern: C.$CFUNC(...) + - pattern: exec.Command($S, ...) + - pattern: exec.CommandContext($CTX, $S, ...) + - pattern: ldap.EscapeFilter(...) + - pattern: $LDAP.Search(...) + - pattern: $LDAP.Bind(...) + - pattern: pam.$PAMFUNC(...) + - pattern-not-inside: "func $FN(...) $RET {\n ...\n if strings.ContainsRune(...) { ... }\n ...\n}\n" + - pattern-not-inside: "func $FN(...) $RET {\n ...\n if strings.ContainsRune(...) || ... { ... }\n ...\n\ + }\n" + - pattern-not-inside: "func $FN(...) $RET {\n ...\n if ... || strings.ContainsRune(...) { ... }\n ...\n\ + }\n" + - pattern-not-inside: "func $FN(...) $RET {\n ...\n if strings.ContainsAny(...) { ... }\n ...\n}\n" + - pattern-not-inside: "func $FN(...) $RET {\n ...\n if strings.IndexByte(...) != -1 { ... }\n ...\n\ + }\n" + - pattern-not-inside: "func $FN(...) $RET {\n ...\n if strings.IndexByte(...) >= 0 { ... }\n ...\n\ + }\n" + - pattern-not-inside: "func $FN(...) $RET {\n ...\n if strings.Contains($X, \"\\x00\") { ... }\n ...\n\ + }\n" + metadata: + cwe: + - 'CWE-158: Improper Neutralization of Null Byte or NUL Character' + owasp: + - A07:2021 - Identification and Authentication Failures + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: HIGH + technology: + - go + references: + - https://www.elttam.com/blog/golang-codereview + - id: elttam-net-url-pointer-alias-mutation + languages: [go] + message: 'A *url.URL pointer held in a variable or field is aliased (not copied) and then a field of it + is mutated. Assigning a *url.URL copies the pointer, not the struct, so the write mutates the shared + original. If that original is package-level, a struct field, or otherwise shared across requests or + goroutines, this corrupts the URL seen elsewhere (open-redirect / parameter-smuggling / data race). + + This rule only fires when the alias source is a bare identifier (e.g. `u := s.someURL`) — the shape + most likely to be a shared pointer. It does NOT fire on fresh allocations, which are safe: value composite + literals (`url.URL{}`), dereference copies (`*p`), or any function/method call result (`url.Parse(...)`, + `r.URL()`, `x.Copy()`, `ResolveReference(...)`), because those return a new value/struct that is not + shared. + + Fix: copy the struct (`u := *original`) or build a fresh &url.URL{...}.' + severity: INFO + patterns: + - pattern-inside: 'import "net/url" + + ... + + ' + - pattern: $U := $SRC + - metavariable-pattern: + metavariable: $SRC + patterns: + - pattern-not: '*$X' + - pattern-not: $T{...} + - pattern-not: '&$T{...}' + - pattern-not: $F(...) + - pattern-not: $R.$M(...) + - pattern-not: $R[...] + - pattern-either: + - pattern-inside: '$U := $SRC + + ... + + $U.RawQuery = $V + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.Path = $V + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.Host = $V + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.Scheme = $V + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.RawPath = $V + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.Fragment = $V + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.RawFragment = $V + + ' + - pattern-either: + - pattern-inside: '$U := $SRC + + ... + + $U.Query() + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.String() + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.Hostname() + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.Redacted() + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.ResolveReference(...) + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.RawQuery = $W + + ' + - pattern-inside: '$U := $SRC + + ... + + $U.RawPath = $W + + ' + metadata: + cwe: + - 'CWE-362: Concurrent Execution using Shared Resource with Improper Synchronization (''Race Condition'')' + owasp: + - A01:2021 - Broken Access Control + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: + - go + references: + - https://pkg.go.dev/net/url#URL + - id: elttam-polymorphic-typing + languages: [java] + message: 'Jackson Polymorphic Typing: This rule is to detect any instances of polymorphic typing to aid + in determining vulnerable Jackson deserialization issues. Check if deserializing untrusted JSON to a + nominal type such as `java.lang.Object` or permissive tag interfaces such as `java.io.Serializable` + or `java.lang.Comparable` is occuring.' + severity: INFO + metadata: + cwe: 'CWE-502: Deserialization of Untrusted Data' + owasp: 'A8: Insecure Deserialization' + docs: + - https://github.com/mbechler/marshalsec/blob/master/marshalsec.pdf + - https://www.nccgroup.trust/globalassets/our-research/us/whitepapers/2018/jackson_deserialization.pdf + - https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062 + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - jackson + - jackson-databind + - spring + - spring-boot + - spring-framework + - JSON + pattern-either: + - pattern: '(com.fasterxml.jackson.databind.ObjectMapper $X).enableDefaultTyping(...) + + ' + - pattern: '(com.fasterxml.jackson.databind.ObjectMapper $X).activateDefaultTyping(...) + + ' + - pattern: '@JsonTypeInfo(...) + + ' + - pattern: '@JsonSubTypes(...) + + ' + - id: elttam-type-resolver-override + languages: [java] + message: '$X Jackson Polymorphic Typing: Polymorphic typing may have been introduced through overriding + the default Jackson type resolver.' + severity: INFO + metadata: + cwe: 'CWE-502: Deserialization of Untrusted Data' + owasp: 'A8: Insecure Deserialization' + docs: + - https://github.com/mbechler/marshalsec/blob/master/marshalsec.pdf + - https://www.nccgroup.trust/globalassets/our-research/us/whitepapers/2018/jackson_deserialization.pdf + - https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062 + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - jackson + - jackson-databind + - spring + - spring-boot + - spring-framework + - JSON + pattern-either: + - pattern: 'com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder $X; + + ' + - pattern: '(com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder $X) = ...; + + ' + - id: elttam-default-properties-devmode + languages: [generic] + message: default.properties struts.devMode = $MODE + severity: WARNING + metadata: + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - default.properties + - default-properties-devmode.properties + patterns: + - pattern: 'struts.devMode = $MODE + + ' + - metavariable-regex: + metavariable: $MODE + regex: (true|1) + - id: elttam-struts-xml-devmode + languages: [generic] + message: struts.xml devMode = "$...MODE" + severity: WARNING + metadata: + docs: + - https://struts.apache.org/core-developers/constant-configuration + - https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - struts*.xml + patterns: + - pattern-either: + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - metavariable-regex: + metavariable: $...MODE + regex: (true|1) + - id: elttam-web-xml-devmode + languages: [generic] + message: web.xml devMode = $MODE + severity: WARNING + metadata: + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - web.xml + - web-xml-devmode.xml + patterns: + - pattern: "\n ...\n struts.devMode\n ...\n $MODE\n\ + \ ...\n\n" + - metavariable-regex: + metavariable: $MODE + regex: (true|1) + - id: elttam-struts-xml-action-dmi + languages: [generic] + message: struts.xml action $...NAME either using Dynamic Method Invocation or Wildcard Method feature + severity: WARNING + metadata: + docs: + - https://struts.apache.org/core-developers/action-configuration.html#dynamic-method-invocation + - https://struts.apache.org/core-developers/action-configuration.html#wildcard-method + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - struts*.xml + patterns: + - pattern-either: + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - metavariable-regex: + metavariable: $...MODE + regex: (true|1) + - id: elttam-taglib-action-dmi + languages: [generic] + message: JSTL taglib directive either Dynamic Method Invocation (DMI) or Wildcard Method feature prefix="$...PREFIX" + uri="$...URI" action="$...ACTION" + severity: INFO + metadata: + docs: + - https://struts.apache.org/core-developers/action-configuration.html#dynamic-method-invocation + - https://struts.apache.org/core-developers/action-configuration.html#wildcard-method + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + - JSTL + - taglib + paths: + include: + - '*.jsp' + patterns: + - pattern-either: + - pattern-inside: '<%@ taglib prefix=''$...PREFIX'' ... uri=''$...URI'' + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ' + - pattern-inside: '<%@ taglib prefix="$...PREFIX" ... uri="$...URI" + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ' + - pattern-inside: '<%@ taglib uri=''$...URI'' ... prefix=''$...PREFIX'' + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ' + - pattern-inside: '<%@ taglib uri="$...URI" ... prefix="$...PREFIX" + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ... + + ' + - pattern-either: + - pattern: '<$...PREFIX:... ... action=''$...ACTION'' + + ' + - pattern: '<$...PREFIX:... ... action="$...ACTION" + + ' + - metavariable-regex: + metavariable: $...ACTION + regex: .*!.* + - id: elttam-struts-xml-always-select-full-namespace + languages: [generic] + message: struts.xml using alwaysSelectFullNamespace + severity: WARNING + metadata: + docs: + - https://cwiki.apache.org/confluence/display/WW/S2-057 + - https://nvd.nist.gov/vuln/detail/CVE-2018-11776 + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - struts*.xml + patterns: + - pattern-inside: ' + + ' + - pattern-either: + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - pattern: ' + + ' + - metavariable-regex: + metavariable: $...MODE + regex: (true|1) + - id: elttam-fromXML + languages: [java] + metadata: + cwe: 'CWE-502: Deserialization of Untrusted Data' + owasp: 'A8: Insecure Deserialization' + docs: + - https://x-stream.github.io/javadoc/index.html?com/thoughtworks/xstream/XStream.html + - https://www.baeldung.com/java-xstream-remote-code-execution + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - XML + - XStream + pattern: (com.thoughtworks.xstream.XStream $XSTREAM).fromXML(...); + message: 'XStream XML Deserialzation: Check that they have correctly set an allow-list and if an attacker + can control input.' + severity: WARNING + - id: elttam-express-mongodb-nosqli + languages: [javascript, typescript] + message: Depending on the context, using (user-controlled) request data directly in a MongoDB query can + lead to a NoSQLi vulnerability. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A03:2021 – Injection + references: + - https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection + category: security + technology: + - javascript + subcategory: vuln + likelihood: LOW + impact: MEDIUM + confidence: MEDIUM + interfile: true + severity: WARNING + mode: taint + pattern-sources: + - patterns: + - pattern: function($REQ, ...) { ... } + - pattern-either: + - pattern: $REQ.$USERDATA + - pattern: let { $USERDATA } = $REQ + - focus-metavariable: $REQ + - metavariable-regex: + metavariable: $REQ + regex: req + - metavariable-regex: + metavariable: $USERDATA + regex: (body|params|query|cookies|headers) + pattern-sanitizers: + - patterns: + - pattern: $X.toString() + - focus-metavariable: $X + pattern-sinks: + - patterns: + - pattern-inside: '$MODEL = require(''$IMPORT'') + + ... + + ' + - metavariable-regex: + metavariable: $IMPORT + regex: .*(db|models|data|schema|mongo).* + - pattern-either: + - pattern: new $MODEL(...) + - patterns: + - pattern: $MODEL.$FUNC(...) + - metavariable-regex: + metavariable: $FUNC + regex: (find|delete|update|replace|where|create|insert|map|bulk|aggregate|count).* diff --git a/compliance-agent/rules/vendor/elttam/rules.json b/compliance-agent/rules/vendor/elttam/rules.json new file mode 100644 index 0000000..7a7d073 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/rules.json @@ -0,0 +1,241 @@ +[ + { + "id": "elttam-potential-symlink-takeover-with-os-executable", + "languages": [ + "go" + ], + "cwe": null + }, + { + "id": "elttam-sprintf-unescaped-control-characters", + "languages": [ + "go" + ], + "cwe": null + }, + { + "id": "elttam-non-atomic-use-of-converted-uintptr", + "languages": [ + "go" + ], + "cwe": null + }, + { + "id": "elttam-jakarta-mail-internetaddress-overloaded-ctor", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-jakarta-mail-internetaddress-single-arg-validator", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-jakarta-mail-mimemessage-raw-envelope-ctor", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-jakarta-mail-mimemessage-newsgroups-recipients", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-spring-internetaddresseditor-usage", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-spring-simplemailmessage-setfrom-raw", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-email-domain-split-index", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-email-domain-lastindexof", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-email-domain-endswith", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-hibernate-email-annotation-field", + "languages": [ + "java" + ], + "cwe": "CWE-20" + }, + { + "id": "elttam-gcm-static-iv", + "languages": [ + "java" + ], + "cwe": null + }, + { + "id": "elttam-randomstringutils-insecure-rng", + "languages": [ + "java" + ], + "cwe": "CWE-338" + }, + { + "id": "elttam-UnsafeHttpInvokerServiceExporter-XML", + "languages": [ + "generic" + ], + "cwe": null + }, + { + "id": "elttam-gorilla-cookiestore-default-samesite-none", + "languages": [ + "go" + ], + "cwe": "CWE-1275" + }, + { + "id": "elttam-json-decode-without-content-type-check", + "languages": [ + "go" + ], + "cwe": "CWE-352" + }, + { + "id": "elttam-json-marshaler-pointer-receiver", + "languages": [ + "go" + ], + "cwe": "CWE-200" + }, + { + "id": "elttam-len-cast-to-narrow-int-overflow", + "languages": [ + "go" + ], + "cwe": "CWE-190" + }, + { + "id": "elttam-len-cast-into-binary-length-prefix", + "languages": [ + "go" + ], + "cwe": "CWE-190" + }, + { + "id": "elttam-missing-null-byte-check-at-trust-boundary", + "languages": [ + "go" + ], + "cwe": "CWE-158" + }, + { + "id": "elttam-net-url-pointer-alias-mutation", + "languages": [ + "go" + ], + "cwe": "CWE-362" + }, + { + "id": "elttam-polymorphic-typing", + "languages": [ + "java" + ], + "cwe": "CWE-502" + }, + { + "id": "elttam-type-resolver-override", + "languages": [ + "java" + ], + "cwe": "CWE-502" + }, + { + "id": "elttam-default-properties-devmode", + "languages": [ + "generic" + ], + "cwe": null + }, + { + "id": "elttam-struts-xml-devmode", + "languages": [ + "generic" + ], + "cwe": null + }, + { + "id": "elttam-web-xml-devmode", + "languages": [ + "generic" + ], + "cwe": null + }, + { + "id": "elttam-struts-xml-action-dmi", + "languages": [ + "generic" + ], + "cwe": null + }, + { + "id": "elttam-struts-xml-dmi", + "languages": [ + "generic" + ], + "cwe": null + }, + { + "id": "elttam-taglib-action-dmi", + "languages": [ + "generic" + ], + "cwe": null + }, + { + "id": "elttam-struts-xml-always-select-full-namespace", + "languages": [ + "generic" + ], + "cwe": null + }, + { + "id": "elttam-fromXML", + "languages": [ + "java" + ], + "cwe": "CWE-502" + }, + { + "id": "elttam-express-mongodb-nosqli", + "languages": [ + "javascript", + "typescript" + ], + "cwe": "CWE-20" + } +] diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/gorilla/security/audit/gorilla-cookiestore-default-samesite-none.go b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/gorilla/security/audit/gorilla-cookiestore-default-samesite-none.go new file mode 100644 index 0000000..18f5292 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/gorilla/security/audit/gorilla-cookiestore-default-samesite-none.go @@ -0,0 +1,71 @@ +package tests + +import ( + "net/http" + + "github.com/gorilla/sessions" +) + +var secretKey = []byte("very-secret-key-32-bytes-minimum") + +// Bad: NewCookieStore with no SameSite override — default is SameSiteNone. +func badCookieStoreNoOverride() *sessions.CookieStore { + // ruleid: gorilla-cookiestore-default-samesite-none + store := sessions.NewCookieStore(secretKey) + return store +} + +// Bad: NewFilesystemStore with no SameSite override. +func badFilesystemStoreNoOverride() *sessions.FilesystemStore { + // ruleid: gorilla-cookiestore-default-samesite-none + store := sessions.NewFilesystemStore("/tmp/sessions", secretKey) + return store +} + +// Bad: assignment (=) form — no SameSite set on globalStore afterwards. +var globalStore *sessions.CookieStore + +func badCookieStoreAssignForm() { + // ruleid: gorilla-cookiestore-default-samesite-none + globalStore = sessions.NewCookieStore(secretKey) +} + +// Good: SameSite set to Lax after NewCookieStore. +func goodCookieStoreSameSiteLax() *sessions.CookieStore { + // ok: gorilla-cookiestore-default-samesite-none + store := sessions.NewCookieStore(secretKey) + store.Options.SameSite = http.SameSiteLaxMode + return store +} + +// Good: SameSite set to Strict. +func goodCookieStoreSameSiteStrict() *sessions.CookieStore { + // ok: gorilla-cookiestore-default-samesite-none + store := sessions.NewCookieStore(secretKey) + store.Options.SameSite = http.SameSiteStrictMode + return store +} + +// Good: Options struct replaced entirely (guarantees SameSite is set explicitly). +func goodCookieStoreOptionsReplaced() *sessions.CookieStore { + // ok: gorilla-cookiestore-default-samesite-none + store := sessions.NewCookieStore(secretKey) + store.Options = &sessions.Options{SameSite: http.SameSiteLaxMode} + return store +} + +// Good: FilesystemStore with SameSite set explicitly. +func goodFilesystemStoreSameSiteLax() *sessions.FilesystemStore { + // ok: gorilla-cookiestore-default-samesite-none + store := sessions.NewFilesystemStore("/tmp/sessions", secretKey) + store.Options.SameSite = http.SameSiteLaxMode + return store +} + +// Good: FilesystemStore with Options replaced entirely. +func goodFilesystemStoreOptionsReplaced() *sessions.FilesystemStore { + // ok: gorilla-cookiestore-default-samesite-none + store := sessions.NewFilesystemStore("/tmp/sessions", secretKey) + store.Options = &sessions.Options{SameSite: http.SameSiteStrictMode} + return store +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/gorilla/security/audit/gorilla-cookiestore-default-samesite-none.yaml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/gorilla/security/audit/gorilla-cookiestore-default-samesite-none.yaml new file mode 100644 index 0000000..a4d39ff --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/gorilla/security/audit/gorilla-cookiestore-default-samesite-none.yaml @@ -0,0 +1,59 @@ +rules: + - id: gorilla-cookiestore-default-samesite-none + message: >- + gorilla/sessions.NewCookieStore (and NewFilesystemStore) initialise + Options.SameSite to http.SameSiteNoneMode by default, which allows the + session cookie to be sent on cross-site requests and removes a key CSRF + defence. The existing session-cookie-samesitenone rule only catches an + explicit &sessions.Options{SameSite: http.SameSiteNoneMode}; this insecure + value is also the silent default when you never set Options at all. + After NewCookieStore, explicitly set store.Options.SameSite to + http.SameSiteLaxMode or http.SameSiteStrictMode. + languages: [go] + severity: WARNING + patterns: + - pattern-either: + - pattern: $STORE := sessions.NewCookieStore(...) + - pattern: $STORE = sessions.NewCookieStore(...) + - pattern: $STORE := sessions.NewFilesystemStore(...) + - pattern: $STORE = sessions.NewFilesystemStore(...) + # the store's SameSite is never overridden afterwards + - pattern-not-inside: | + $STORE := sessions.NewCookieStore(...) + ... + $STORE.Options.SameSite = $V + - pattern-not-inside: | + $STORE = sessions.NewCookieStore(...) + ... + $STORE.Options.SameSite = $V + - pattern-not-inside: | + $STORE := sessions.NewCookieStore(...) + ... + $STORE.Options = $OPTS + - pattern-not-inside: | + $STORE := sessions.NewFilesystemStore(...) + ... + $STORE.Options.SameSite = $V + - pattern-not-inside: | + $STORE := sessions.NewFilesystemStore(...) + ... + $STORE.Options = $OPTS + metadata: + cwe: + - "CWE-1275: Sensitive Cookie with Improper SameSite Attribute" + owasp: + - A05:2021 - Security Misconfiguration + - A02:2025 - Security Misconfiguration + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: + - gorilla + references: + - https://github.com/gorilla/sessions/blob/v1.4.0/store.go#L59 + # v2: logic unchanged. 0 hits across 34 scanned projects because none call + # sessions.NewCookieStore in-tree; validate against code-search-sourced + # consumers (application code, not libraries) rather than flagship repos. diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-decode-without-content-type-check.go b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-decode-without-content-type-check.go new file mode 100644 index 0000000..ee34b37 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-decode-without-content-type-check.go @@ -0,0 +1,84 @@ +package tests + +import ( + "encoding/json" + "net/http" +) + +type payload struct { + Name string + Value int +} + +// Bad: inline NewDecoder+Decode in a std handler with no Content-Type check. +func badHandlerInlineDecode(w http.ResponseWriter, r *http.Request) { + var v payload + // ruleid: json-decode-without-content-type-check + json.NewDecoder(r.Body).Decode(&v) +} + +// Bad: split NewDecoder + Decode, no Content-Type check. +func badHandlerSplitDecode(w http.ResponseWriter, r *http.Request) { + var v payload + dec := json.NewDecoder(r.Body) + // ruleid: json-decode-without-content-type-check + dec.Decode(&v) +} + +// Bad: method-receiver handler, no Content-Type check. +type WriteHandler struct{} + +func (h *WriteHandler) badMethodHandler(w http.ResponseWriter, r *http.Request) { + var v payload + // ruleid: json-decode-without-content-type-check + json.NewDecoder(r.Body).Decode(&v) +} + +// Bad: handler with extra parameters (non-standard signature), no Content-Type check. +type ctxKey struct{} + +func badHandlerExtraParam(w http.ResponseWriter, r *http.Request, extra string) { + var v payload + // ruleid: json-decode-without-content-type-check + json.NewDecoder(r.Body).Decode(&v) +} + +// Good: handler validates Content-Type via r.Header.Get before decoding. +func goodHandlerContentTypeCheck(w http.ResponseWriter, r *http.Request) { + ct := r.Header.Get("Content-Type") + if ct != "application/json" { + http.Error(w, "unsupported content type", http.StatusUnsupportedMediaType) + return + } + var v payload + // ok: json-decode-without-content-type-check + json.NewDecoder(r.Body).Decode(&v) +} + +// Good: method receiver validates Content-Type. +func (h *WriteHandler) goodMethodHandlerWithCheck(w http.ResponseWriter, r *http.Request) { + r.Header.Get("Content-Type") + var v payload + // ok: json-decode-without-content-type-check + json.NewDecoder(r.Body).Decode(&v) +} + +// Good: split NewDecoder+Decode but Content-Type check is present. +func goodHandlerSplitDecodeWithCheck(w http.ResponseWriter, r *http.Request) { + r.Header.Get("Content-Type") + var v payload + dec := json.NewDecoder(r.Body) + // ok: json-decode-without-content-type-check + dec.Decode(&v) +} + +// Good: handler uses Header.Values instead of Header.Get — also suppresses the rule. +// Note: the rule's Header.Values pattern-not-inside requires a return type ($RET), +// so this function must declare one for the suppression to apply. +func goodHandlerContentTypeValues(w http.ResponseWriter, r *http.Request) error { + _ = r.Header.Values("Content-Type") + var v payload + // ok: json-decode-without-content-type-check + json.NewDecoder(r.Body).Decode(&v) + return nil +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-decode-without-content-type-check.yaml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-decode-without-content-type-check.yaml new file mode 100644 index 0000000..c79a19f --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-decode-without-content-type-check.yaml @@ -0,0 +1,119 @@ +rules: + - id: json-decode-without-content-type-check + message: >- + An HTTP handler decodes the request body as JSON without validating the + Content-Type header. Browsers send no CORS preflight for "simple" requests + using text/plain or application/x-www-form-urlencoded, so a cross-site HTML + form can POST a body the server parses as JSON (encoding/json also ignores + trailing bytes, so a form's trailing "=" doesn't break parsing). With cookie + auth this is exploitable as CSRF. Reject requests whose Content-Type is not + application/json, and/or wrap handlers with http.CrossOriginProtection + (Go 1.25+). + + v2: handler matching widened to cover method receivers, extra parameters + (e.g. ctx), and common framework handler signatures (gin, echo, chi/std) — + the std-only two-arg pattern missed real handlers like + func (h *T) handleWrite(w, r, ctx) found in production code. + languages: [go] + severity: WARNING + patterns: + # the body is decoded as JSON from the request + - pattern-either: + - pattern: json.NewDecoder($R.Body).Decode($X) + - patterns: + - pattern: $DEC.Decode($X) + - pattern-inside: | + $DEC := json.NewDecoder($R.Body) + ... + - patterns: + - pattern: $DEC.Decode($X) + - pattern-inside: | + $DEC := json.NewDecoder($C.Request().Body) + ... + - pattern: json.NewDecoder($C.Request().Body).Decode($X) + # inside some handler-shaped function (std, method, extra params, or framework) + - pattern-either: + - pattern-inside: | + func $H(..., $W http.ResponseWriter, $R *http.Request, ...) { ... } + - pattern-inside: | + func ($RT) $H(..., $W http.ResponseWriter, $R *http.Request, ...) { ... } + - pattern-inside: | + func $H($C echo.Context) error { ... } + - pattern-inside: | + func ($RT) $H($C echo.Context) error { ... } + - pattern-inside: | + func $H($C *gin.Context) { ... } + - pattern-inside: | + func ($RT) $H($C *gin.Context) { ... } + # no Content-Type validation anywhere in the enclosing function + - pattern-not-inside: | + func $H(...) { + ... + $R.Header.Get("Content-Type") + ... + } + - pattern-not-inside: | + func ($RT) $H(...) { + ... + $R.Header.Get("Content-Type") + ... + } + - pattern-not-inside: | + func $H(...) $RET { + ... + $R.Header.Get("Content-Type") + ... + } + - pattern-not-inside: | + func ($RT) $H(...) $RET { + ... + $R.Header.Get("Content-Type") + ... + } + - pattern-not-inside: | + func $H(...) $RET { + ... + $R.Header.Values("Content-Type") + ... + } + - pattern-not-inside: | + func $H(...) $RET { + ... + $C.Request().Header.Get("Content-Type") + ... + } + - pattern-not-inside: | + func $H(...) $RET { + ... + $C.GetHeader("Content-Type") + ... + } + - pattern-not-inside: | + func $H(...) $RET { + ... + $C.ContentType() + ... + } + - pattern-not-inside: | + func $H(...) $RET { + ... + $C.Bind($Y) + ... + } + metadata: + cwe: + - "CWE-352: Cross-Site Request Forgery (CSRF)" + owasp: + - A01:2021 - Broken Access Control + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: + - go + - net/http + references: + - https://pkg.go.dev/net/http#CrossOriginProtection + - https://pkg.go.dev/encoding/json#Decoder.Decode diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-marshaler-pointer-receiver.go b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-marshaler-pointer-receiver.go new file mode 100644 index 0000000..5866698 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-marshaler-pointer-receiver.go @@ -0,0 +1,41 @@ +package tests + +import "encoding/json" + +// ----- Types used in tests ----- + +type SecretData struct { + Token string + Password string +} + +type PublicData struct { + Name string + Score int +} + +type NestedWrapper struct { + Inner SecretData +} + +// ----- Bad: pointer-receiver MarshalJSON — custom marshaller silently skipped +// when the type is encoded by value ----- + +// ruleid: json-marshaler-pointer-receiver +func (s *SecretData) MarshalJSON() ([]byte, error) { + return []byte(`{"token":"[REDACTED]"}`), nil +} + +// ruleid: json-marshaler-pointer-receiver +func (w *NestedWrapper) MarshalJSON() ([]byte, error) { + return json.Marshal(struct{ Inner string }{Inner: "[REDACTED]"}) +} + +// ----- Good: value-receiver MarshalJSON — always reachable regardless of how +// the value is passed to json.Marshal ----- + +// ok: json-marshaler-pointer-receiver +func (p PublicData) MarshalJSON() ([]byte, error) { + type Alias PublicData + return json.Marshal(Alias(p)) +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-marshaler-pointer-receiver.yaml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-marshaler-pointer-receiver.yaml new file mode 100644 index 0000000..8fa4809 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/json-marshaler-pointer-receiver.yaml @@ -0,0 +1,41 @@ +rules: + - id: json-marshaler-pointer-receiver + message: >- + MarshalJSON is defined on a pointer receiver (*$T). Because encoding/json + resolves json.Marshaler via reflection under strict method-set rules, a + pointer-receiver MarshalJSON is NOT in the method set of the value type $T. + Encoding a value of $T (or a struct containing a $T field) by value silently + skips the custom marshaller and uses default marshalling. If the marshaller + performs redaction/masking/field-omission, that protection disappears + silently. + + AUDIT NOTE: this only becomes a bug if the type is somewhere encoded BY + VALUE. On large codebases most pointer-receiver MarshalJSON are always + encoded by pointer and therefore safe — this rule fires broadly and is + intended as an audit aid, not a finding. To resolve a hit, check whether + the type is ever passed by value to json.Marshal/Encode. Fix by moving + MarshalJSON to a value receiver, or always storing/encoding a pointer. + languages: [go] + severity: INFO + patterns: + - pattern: | + func ($RECV *$T) MarshalJSON() ([]byte, error) { ... } + metadata: + cwe: + - "CWE-200: Exposure of Sensitive Information to an Unauthorized Actor" + owasp: + - A01:2021 - Broken Access Control + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: + - go + references: + - https://github.com/golang/go/issues/22967 + - https://go.dev/wiki/MethodSets + # v2: downgraded WARNING -> INFO. Real-code runs: 78 hits on consul, 44/31 + # across other batches, essentially all benign (type always encoded by + # pointer). Audit-surfacing only; per-hit by-value check required. diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/len-cast-to-narrow-int-overflow.go b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/len-cast-to-narrow-int-overflow.go new file mode 100644 index 0000000..c7c9d46 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/len-cast-to-narrow-int-overflow.go @@ -0,0 +1,104 @@ +package tests + +import ( + "encoding/binary" + "errors" + "math" +) + +// ============================================================ +// Rule: len-cast-to-narrow-int-overflow (INFO — broad audit) +// ============================================================ + +// Bad: unchecked narrowing cast of len() to uint32. +func badUncheckedUint32(data []byte) uint32 { + // ruleid: len-cast-to-narrow-int-overflow + return uint32(len(data)) +} + +// Bad: unchecked cast to int32. +func badUncheckedInt32(data []byte) int32 { + // ruleid: len-cast-to-narrow-int-overflow + return int32(len(data)) +} + +// Bad: unchecked cast to uint16. +func badUncheckedUint16(data []byte) uint16 { + // ruleid: len-cast-to-narrow-int-overflow + return uint16(len(data)) +} + +// Bad: unchecked cast to uint8 — tiny bound, easy overflow. +func badUncheckedUint8(s string) uint8 { + // ruleid: len-cast-to-narrow-int-overflow + return uint8(len(s)) +} + +// Good: len checked with > MAX before casting. +func goodCheckedGreaterThan(data []byte) (uint32, error) { + if len(data) > math.MaxUint32 { + return 0, errors.New("payload too large") + } + // ok: len-cast-to-narrow-int-overflow + return uint32(len(data)), nil +} + +// Good: len checked with <= MAX before casting (inverted guard style). +func goodCheckedLessOrEqual(data []byte) (uint32, error) { + if len(data) <= math.MaxUint32 { + // ok: len-cast-to-narrow-int-overflow + return uint32(len(data)), nil + } + return 0, errors.New("payload too large") +} + +// Good: guard uses intermediate variable form. +func goodCheckedIntermediateVar(data []byte) (uint32, error) { + if n := len(data); n > math.MaxUint32 { + return 0, errors.New("payload too large") + } + // ok: len-cast-to-narrow-int-overflow + return uint32(len(data)), nil +} + +// ============================================================ +// Rule: len-cast-into-binary-length-prefix (WARNING — high signal) +// ============================================================ + +// Bad: uint32 length prefix written to binary framing without bounds check. +// Both rules fire: the inner uint32(len()) cast triggers len-cast-to-narrow-int-overflow, +// and the full PutUint32 call triggers len-cast-into-binary-length-prefix. +func badBinaryLengthPrefixPutUint32(buf []byte, data []byte) { + // ruleid: len-cast-to-narrow-int-overflow, len-cast-into-binary-length-prefix + binary.LittleEndian.PutUint32(buf, uint32(len(data))) + copy(buf[4:], data) +} + +// Bad: uint16 length prefix — even smaller cap, easier to trigger. +func badBinaryLengthPrefixPutUint16(buf []byte, data []byte) { + // ruleid: len-cast-to-narrow-int-overflow, len-cast-into-binary-length-prefix + binary.BigEndian.PutUint16(buf, uint16(len(data))) + copy(buf[2:], data) +} + +// Good: bounds check before writing the length prefix. +func goodBinaryLengthPrefixChecked(buf []byte, data []byte) error { + if len(data) > math.MaxUint32 { + return errors.New("frame too large") + } + // ok: len-cast-into-binary-length-prefix + binary.LittleEndian.PutUint32(buf, uint32(len(data))) + copy(buf[4:], data) + return nil +} + +// Good: upper-bound check (inverted guard). +func goodBinaryLengthPrefixInvertedCheck(buf []byte, data []byte) error { + if len(data) <= math.MaxUint16 { + // ok: len-cast-into-binary-length-prefix + binary.BigEndian.PutUint16(buf, uint16(len(data))) + copy(buf[2:], data) + return nil + } + return errors.New("frame exceeds uint16 max") +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/len-cast-to-narrow-int-overflow.yaml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/len-cast-to-narrow-int-overflow.yaml new file mode 100644 index 0000000..8cecc81 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/len-cast-to-narrow-int-overflow.yaml @@ -0,0 +1,97 @@ +rules: + # ---- broad audit rule (unchanged logic; INFO so it doesn't dominate CI) ---- + - id: len-cast-to-narrow-int-overflow + message: >- + The result of len() is cast to a narrower fixed-width integer + (uint32/int32/uint16/int16/uint8/int8). len() returns int (64-bit on + amd64/arm64), so a length above the target type's max silently wraps. This + is benign for in-memory counts/sizes but dangerous when the value becomes a + length/size field in a binary or wire format, where a truncated length + desynchronises the parser from the payload (data smuggling / boundary + confusion). Validate the length before casting, or keep the full-width value + and reject oversized input. + + NOTE: this broad rule fires on every narrowing len() cast and is INFO/audit. + For the dangerous subset, see len-cast-into-binary-length-prefix below. + languages: [go] + severity: INFO + patterns: + - pattern-either: + - pattern: uint32(len($X)) + - pattern: int32(len($X)) + - pattern: uint16(len($X)) + - pattern: int16(len($X)) + - pattern: uint8(len($X)) + - pattern: int8(len($X)) + - pattern-not-inside: | + if len($X) > $MAX { ... } + ... + - pattern-not-inside: | + if len($X) <= $MAX { ... } + ... + - pattern-not-inside: | + if len($X) >= $MAX { ... } + ... + - pattern-not-inside: | + if $LEN := len($X); $LEN > $MAX { ... } + ... + metadata: + cwe: + - "CWE-190: Integer Overflow or Wraparound" + owasp: + - A03:2021 - Injection + category: security + subcategory: [audit] + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: [go] + references: + - https://github.com/tinylib/msgp/blob/v1.5.0/msgp/write.go + - https://blog.trailofbits.com/2025/12/31/detect-gos-silent-arithmetic-bugs-with-go-panikint/ + + # ---- high-signal companion: cast feeds a binary length prefix ---- + - id: len-cast-into-binary-length-prefix + message: >- + A narrowing cast of len() is written as a binary length prefix via + encoding/binary, then the corresponding payload is emitted. This is the + exploitable shape from the msgp/DEF CON 32 class: if the length exceeds the + narrow type's max it wraps, the on-wire length field desynchronises from the + actual payload, and a downstream parser can be smuggled extra/short data. + Bound the length against the type max (or the protocol limit) before writing + it, and reject oversized payloads. + languages: [go] + severity: WARNING + patterns: + - pattern-either: + - pattern: binary.$ORDER.PutUint32($BUF, uint32(len($X))) + - pattern: binary.$ORDER.PutUint16($BUF, uint16(len($X))) + - pattern: binary.Write($W, $ORDER, uint32(len($X))) + - pattern: binary.Write($W, $ORDER, uint16(len($X))) + - pattern-not-inside: | + if len($X) > $MAX { ... } + ... + - pattern-not-inside: | + if len($X) <= $MAX { ... } + ... + - pattern-not-inside: | + if len($X) >= $MAX { ... } + ... + metadata: + cwe: + - "CWE-190: Integer Overflow or Wraparound" + owasp: + - A03:2021 - Injection + category: security + subcategory: [vuln] + confidence: MEDIUM + likelihood: LOW + impact: HIGH + technology: [go] + references: + - https://media.defcon.org/DEF%20CON%2032/DEF%20CON%2032%20presentations/ + - https://github.com/tinylib/msgp/blob/v1.5.0/msgp/write.go + # v2: split out from the broad rule. Real-code runs showed every genuine + # bug-shape (moby stdcopy, k8s framer, minio s3select/grid, caddy fastcgi) + # writes the cast as a binary length prefix; the ~100 benign hits were + # in-memory counts that never reach encoding/binary. diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/missing-null-byte-check-at-trust-boundary.go b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/missing-null-byte-check-at-trust-boundary.go new file mode 100644 index 0000000..af00bd8 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/missing-null-byte-check-at-trust-boundary.go @@ -0,0 +1,91 @@ +package tests + +import ( + "errors" + "os/exec" + "strings" +) + +// Bad: function compares username against a privileged literal and passes it +// to exec.Command without rejecting null bytes first. +// "admin\x00x" passes the == check in Go but resolves to "admin" in C/exec. +func badRunAsUser(username string) error { + if username == "admin" { + return errors.New("admin not allowed") + } + // ruleid: missing-null-byte-check-at-trust-boundary + cmd := exec.Command(username, "--version") + return cmd.Run() +} + +// Bad: same pattern with "root" and exec.CommandContext. +func badRunAsRoot(ctx interface{ Done() <-chan struct{} }, username string) error { + if username == "root" { + return errors.New("root not allowed") + } + // ruleid: missing-null-byte-check-at-trust-boundary + cmd := exec.Command(username, "--help") + return cmd.Run() +} + +// Bad: "superuser" literal — privileged regex still matches. +func badSuperuserExec(username string) error { + if username == "superuser" { + return errors.New("superuser not allowed") + } + // ruleid: missing-null-byte-check-at-trust-boundary + cmd := exec.Command(username, "status") + return cmd.Run() +} + +// Good: null-byte guard using strings.ContainsRune before the privileged check. +func goodRunAsUserContainsRune(username string) error { + if strings.ContainsRune(username, 0) { + return errors.New("invalid character in username") + } + if username == "admin" { + return errors.New("admin not allowed") + } + // ok: missing-null-byte-check-at-trust-boundary + cmd := exec.Command(username, "--version") + return cmd.Run() +} + +// Good: null-byte guard using strings.IndexByte != -1. +func goodRunAsUserIndexByte(username string) error { + if strings.IndexByte(username, 0) != -1 { + return errors.New("null byte in username") + } + if username == "root" { + return errors.New("root not allowed") + } + // ok: missing-null-byte-check-at-trust-boundary + cmd := exec.Command(username, "--status") + return cmd.Run() +} + +// Good: null-byte guard using strings.Contains with explicit \x00 literal. +func goodRunAsUserContainsNul(username string) error { + if strings.Contains(username, "\x00") { + return errors.New("null byte in username") + } + if username == "administrator" { + return errors.New("administrator not allowed") + } + // ok: missing-null-byte-check-at-trust-boundary + cmd := exec.Command(username, "--info") + return cmd.Run() +} + +// Good: guard using strings.IndexByte >= 0 (alternative comparison form). +func goodRunAsUserIndexByteGE(username string) error { + if strings.IndexByte(username, 0) >= 0 { + return errors.New("null byte detected") + } + if username == "admin" { + return errors.New("admin not allowed") + } + // ok: missing-null-byte-check-at-trust-boundary + cmd := exec.Command(username, "--check") + return cmd.Run() +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/missing-null-byte-check-at-trust-boundary.yaml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/missing-null-byte-check-at-trust-boundary.yaml new file mode 100644 index 0000000..597e988 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/missing-null-byte-check-at-trust-boundary.yaml @@ -0,0 +1,113 @@ +rules: + - id: missing-null-byte-check-at-trust-boundary + message: >- + A string is compared against a PRIVILEGED account name (admin/root/etc.) + and then passed to a C-interop / LDAP / exec sink in the same function, + with no null-byte rejection. Go strings may contain \x00; C-style consumers + truncate at the first null byte. An input like "admin\x00x" fails the Go + equality check yet resolves to "admin" past the boundary, bypassing the + gate. Reject null bytes (strings.ContainsRune(s, 0) / strings.IndexByte(s, + 0) != -1) before any comparison or interop call at the trust boundary. + + v2: the gate must compare against a non-empty privileged-looking literal + (not `== ""` or arbitrary config values), and the sink must be a real C + call, os/exec, or a named LDAP/PAM package — narrowed after real-code runs + where empty-string defaults and cloud-SDK method names produced false + positives. + languages: [go] + severity: INFO + patterns: + - pattern-inside: | + func $FN(..., $S string, ...) $RET { + ... + } + # gate: equality against a PRIVILEGED literal (not "" or generic config values) + - pattern-either: + - pattern-inside: | + func $FN2(...) $RET2 { + ... + if $S == "$PRIV" { ... } + ... + } + - pattern-inside: | + func $FN2(...) $RET2 { + ... + if $S == "$PRIV" || ... { ... } + ... + } + - pattern-inside: | + func $FN2(...) $RET2 { + ... + if ... || $S == "$PRIV" { ... } + ... + } + - metavariable-regex: + metavariable: $PRIV + regex: ^(?i)(admin|administrator|root|superuser|super-user|superadmin|sudo|wheel|sysadmin|operator|privileged)$ + # sink: real C-interop, os/exec, or named LDAP/PAM packages only + - pattern-either: + - pattern: C.$CFUNC(...) + - pattern: exec.Command($S, ...) + - pattern: exec.CommandContext($CTX, $S, ...) + - pattern: ldap.EscapeFilter(...) + - pattern: $LDAP.Search(...) + - pattern: $LDAP.Bind(...) + - pattern: pam.$PAMFUNC(...) + # no null-byte guard anywhere in the function + - pattern-not-inside: | + func $FN(...) $RET { + ... + if strings.ContainsRune(...) { ... } + ... + } + - pattern-not-inside: | + func $FN(...) $RET { + ... + if strings.ContainsRune(...) || ... { ... } + ... + } + - pattern-not-inside: | + func $FN(...) $RET { + ... + if ... || strings.ContainsRune(...) { ... } + ... + } + - pattern-not-inside: | + func $FN(...) $RET { + ... + if strings.ContainsAny(...) { ... } + ... + } + - pattern-not-inside: | + func $FN(...) $RET { + ... + if strings.IndexByte(...) != -1 { ... } + ... + } + - pattern-not-inside: | + func $FN(...) $RET { + ... + if strings.IndexByte(...) >= 0 { ... } + ... + } + - pattern-not-inside: | + func $FN(...) $RET { + ... + if strings.Contains($X, "\x00") { ... } + ... + } + metadata: + cwe: + - "CWE-158: Improper Neutralization of Null Byte or NUL Character" + owasp: + - A07:2021 - Identification and Authentication Failures + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: HIGH + technology: + - go + references: + - https://www.elttam.com/blog/golang-codereview diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/net-url-pointer-alias-mutation.go b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/net-url-pointer-alias-mutation.go new file mode 100644 index 0000000..e5b6378 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/net-url-pointer-alias-mutation.go @@ -0,0 +1,91 @@ +package tests + +import "net/url" + +// Shared struct used across tests — simulates a server holding a *url.URL field. +type Server struct { + serviceURL *url.URL +} + +func (s *Server) copyURL() *url.URL { + c := *s.serviceURL + return &c +} + +func mustParseURL(raw string) *url.URL { + u, _ := url.Parse(raw) + return u +} + +// Bad: bare selector alias — $SRC is `s.serviceURL`, not excluded by any pattern-not. +// Writing to `u.RawQuery` mutates the shared *url.URL held by the server. +func badAliasRawQuery(s *Server) string { + // ruleid: net-url-pointer-alias-mutation + u := s.serviceURL + u.RawQuery = "debug=1" + return u.String() +} + +// Bad: alias then mutate Path — still a bare selector source. +func badAliasPath(s *Server) string { + // ruleid: net-url-pointer-alias-mutation + u := s.serviceURL + u.Path = "/v2" + return u.String() +} + +// Bad: bare variable alias (not a selector, still a bare identifier). +func badBareVarAlias(shared *url.URL) string { + // ruleid: net-url-pointer-alias-mutation + u := shared + u.Host = "attacker.example.com" + return u.String() +} + +// Bad: alias then mutate Scheme. +func badAliasScheme(s *Server) string { + // ruleid: net-url-pointer-alias-mutation + u := s.serviceURL + u.Scheme = "http" + return u.String() +} + +// Good: dereference copy — the write goes to a fresh copy, not the original. +func goodDereferenceCopy(s *Server) string { + // ok: net-url-pointer-alias-mutation + u := *s.serviceURL + u.RawQuery = "debug=1" + return u.String() +} + +// Good: value composite literal — fresh url.URL struct, no aliasing. +func goodCompositeURLLiteral() string { + // ok: net-url-pointer-alias-mutation + u := url.URL{Scheme: "https", Host: "example.com", Path: "/api"} + u.RawQuery = "v=1" + return u.String() +} + +// Good: pointer composite literal — also a fresh allocation. +func goodPointerCompositeURL() string { + // ok: net-url-pointer-alias-mutation + u := &url.URL{Scheme: "https", Host: "example.com"} + u.RawQuery = "foo=bar" + return u.String() +} + +// Good: plain function call result — $F(...) is excluded. +func goodFunctionCallResult(raw string) string { + // ok: net-url-pointer-alias-mutation + u := mustParseURL(raw) + u.RawQuery = "clean=1" + return u.String() +} + +// Good: method call result — $R.$M(...) is excluded (returns a new value). +func goodMethodCallResult(s *Server) string { + // ok: net-url-pointer-alias-mutation + u := s.copyURL() + u.RawQuery = "debug=1" + return u.String() +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/net-url-pointer-alias-mutation.yaml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/net-url-pointer-alias-mutation.yaml new file mode 100644 index 0000000..7659081 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/go/lang/security/audit/net-url-pointer-alias-mutation.yaml @@ -0,0 +1,112 @@ +rules: + - id: net-url-pointer-alias-mutation + message: >- + A *url.URL pointer held in a variable or field is aliased (not copied) and + then a field of it is mutated. Assigning a *url.URL copies the pointer, not + the struct, so the write mutates the shared original. If that original is + package-level, a struct field, or otherwise shared across requests or + goroutines, this corrupts the URL seen elsewhere (open-redirect / + parameter-smuggling / data race). + + This rule only fires when the alias source is a bare identifier (e.g. + `u := s.someURL`) — the shape most likely to be a shared pointer. It does + NOT fire on fresh allocations, which are safe: value composite literals + (`url.URL{}`), dereference copies (`*p`), or any function/method call result + (`url.Parse(...)`, `r.URL()`, `x.Copy()`, `ResolveReference(...)`), because + those return a new value/struct that is not shared. + + Fix: copy the struct (`u := *original`) or build a fresh &url.URL{...}. + languages: [go] + severity: INFO + patterns: + - pattern-inside: | + import "net/url" + ... + # alias source must be a bare identifier (var or selector), not an allocation + - pattern: $U := $SRC + - metavariable-pattern: + metavariable: $SRC + patterns: + - pattern-not: "*$X" # deref copy - safe + - pattern-not: "$T{...}" # value composite literal - safe (fresh) + - pattern-not: "&$T{...}" # pointer composite literal - safe (fresh) + - pattern-not: "$F(...)" # function-call result - safe (fresh) + - pattern-not: "$R.$M(...)" # method-call result (.Copy()/.URL()/ResolveReference) - safe (fresh) + - pattern-not: "$R[...]" # index expression + # a url.URL-distinctive field is then mutated on the alias + - pattern-either: + - pattern-inside: | + $U := $SRC + ... + $U.RawQuery = $V + - pattern-inside: | + $U := $SRC + ... + $U.Path = $V + - pattern-inside: | + $U := $SRC + ... + $U.Host = $V + - pattern-inside: | + $U := $SRC + ... + $U.Scheme = $V + - pattern-inside: | + $U := $SRC + ... + $U.RawPath = $V + - pattern-inside: | + $U := $SRC + ... + $U.Fragment = $V + - pattern-inside: | + $U := $SRC + ... + $U.RawFragment = $V + # confirm $U is used as a url.URL (distinctive method or raw field write) + - pattern-either: + - pattern-inside: | + $U := $SRC + ... + $U.Query() + - pattern-inside: | + $U := $SRC + ... + $U.String() + - pattern-inside: | + $U := $SRC + ... + $U.Hostname() + - pattern-inside: | + $U := $SRC + ... + $U.Redacted() + - pattern-inside: | + $U := $SRC + ... + $U.ResolveReference(...) + - pattern-inside: | + $U := $SRC + ... + $U.RawQuery = $W + - pattern-inside: | + $U := $SRC + ... + $U.RawPath = $W + metadata: + cwe: + - "CWE-362: Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')" + owasp: + - A01:2021 - Broken Access Control + category: security + subcategory: + - audit + confidence: LOW + likelihood: LOW + impact: MEDIUM + technology: + - go + references: + - https://pkg.go.dev/net/url#URL + # v2: narrowed to bare-identifier sources after real-code runs showed ~13:1 + # false positives from value literals, call results, and .Copy() idioms. diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/polymorphic-typing.java b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/polymorphic-typing.java new file mode 100644 index 0000000..413033f --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/polymorphic-typing.java @@ -0,0 +1,54 @@ +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; +import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; + +import java.io.Serializable; + +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/test") +public class TestController { + + @PostMapping("/message") + public Foo create(@RequestBody Foo data) { + final ObjectMapper om = new ObjectMapper(); + // ruleid: polymorphic-typing + om.activateDefaultTyping(null); + // ruleid: polymorphic-typing + om.enableDefaultTyping(); + + TypeResolverBuilder tr = new TypeResolverBuilder>() { + // ... + }; + + TypeResolverBuilder trb; + + return data; + } + +} + +// ruleid: polymorphic-typing +@JsonTypeInfo(use=Id.CLASS) +public class Foo extends Bar implements Serializable { + + // ruleid: polymorphic-typing + @JsonTypeInfo(use = Id.CLASS) + private Object blaa; + + // ruleid: polymorphic-typing + @JsonTypeInfo(use = Id.CLASS) + protected Serializable y; + + // ruleid: polymorphic-typing + @JsonTypeInfo(use = Id.CLASS) + public Comparable z; +} + +public class Bar implements Comparable { + // ... +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/polymorphic-typing.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/polymorphic-typing.yml new file mode 100644 index 0000000..78eaffd --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/polymorphic-typing.yml @@ -0,0 +1,36 @@ +rules: + - id: polymorphic-typing + message: >- + Jackson Polymorphic Typing: This rule is to detect any instances of polymorphic typing to aid in determining vulnerable + Jackson deserialization issues. Check if deserializing untrusted JSON to a nominal type such as `java.lang.Object` or + permissive tag interfaces such as `java.io.Serializable` or `java.lang.Comparable` is occuring. + severity: INFO + languages: [java] + metadata: + cwe: 'CWE-502: Deserialization of Untrusted Data' + owasp: 'A8: Insecure Deserialization' + docs: + - https://github.com/mbechler/marshalsec/blob/master/marshalsec.pdf + - https://www.nccgroup.trust/globalassets/our-research/us/whitepapers/2018/jackson_deserialization.pdf + - https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062 + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - jackson + - jackson-databind + - spring + - spring-boot + - spring-framework + - JSON + pattern-either: + - pattern: | + (com.fasterxml.jackson.databind.ObjectMapper $X).enableDefaultTyping(...) + - pattern: | + (com.fasterxml.jackson.databind.ObjectMapper $X).activateDefaultTyping(...) + - pattern: | + @JsonTypeInfo(...) + - pattern: | + @JsonSubTypes(...) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/type-resolver-override.java b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/type-resolver-override.java new file mode 100644 index 0000000..732bc4a --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/type-resolver-override.java @@ -0,0 +1,50 @@ +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; +import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; + +import java.io.Serializable; + +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/test") +public class TestController { + + @PostMapping("/message") + public Foo create(@RequestBody Foo data) { + final ObjectMapper om = new ObjectMapper(); + om.activateDefaultTyping(null); + om.enableDefaultTyping(); + + // ruleid: type-resolver-override + TypeResolverBuilder tr = new TypeResolverBuilder>() { + // ... + }; + + // ruleid: type-resolver-override + TypeResolverBuilder trb; + + return data; + } + +} + +@JsonTypeInfo(use=Id.CLASS) +public class Foo extends Bar implements Serializable { + + @JsonTypeInfo(use = Id.CLASS) + private Object blaa; + + @JsonTypeInfo(use = Id.CLASS) + protected Serializable y; + + @JsonTypeInfo(use = Id.CLASS) + public Comparable z; +} + +public class Bar implements Comparable { + // ... +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/type-resolver-override.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/type-resolver-override.yml new file mode 100644 index 0000000..6afc611 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/jackson/type-resolver-override.yml @@ -0,0 +1,32 @@ +rules: + - id: type-resolver-override + message: >- + $X + Jackson Polymorphic Typing: Polymorphic typing may have been introduced through overriding the default Jackson type + resolver. + severity: INFO + languages: [java] + metadata: + cwe: 'CWE-502: Deserialization of Untrusted Data' + owasp: 'A8: Insecure Deserialization' + docs: + - https://github.com/mbechler/marshalsec/blob/master/marshalsec.pdf + - https://www.nccgroup.trust/globalassets/our-research/us/whitepapers/2018/jackson_deserialization.pdf + - https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062 + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - jackson + - jackson-databind + - spring + - spring-boot + - spring-framework + - JSON + pattern-either: + - pattern: | + com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder $X; + - pattern: | + (com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder $X) = ...; diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/default-properties-devmode.properties b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/default-properties-devmode.properties new file mode 100644 index 0000000..2e30452 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/default-properties-devmode.properties @@ -0,0 +1,286 @@ +# Copied from repo: https://github.com/apache/struts +# file: core/src/main/resources/org/apache/struts2/default.properties +# rev: heads/master-0-g735bbc283 +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# +### START SNIPPET: complete_file + +### Struts default properties +### (can be overridden by a struts.properties file in the root of the classpath) +### + +### This can be used to set your default locale and encoding scheme +# struts.locale=en_US +struts.i18n.encoding=UTF-8 + +### if specified, the default object factory can be overridden here +### Note: short-hand notation is supported in some cases, such as "spring" +### Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here +# struts.objectFactory = spring + +### specifies the autoWiring logic when using the SpringObjectFactory. +### valid values are: name, type, auto, and constructor (name is the default) +struts.objectFactory.spring.autoWire = name + +### indicates to the struts-spring integration if Class instances should be cached +### this should, until a future Spring release makes it possible, be left as true +### unless you know exactly what you are doing! +### valid values are: true, false (true is the default) +struts.objectFactory.spring.useClassCache = true + +### ensures the autowire strategy is always respected. +### valid values are: true, false (false is the default) +struts.objectFactory.spring.autoWire.alwaysRespect = false + +### By default SpringObjectFactory doesn't support AOP +### This flag was added just temporally to check if nothing is broken +### See https://issues.apache.org/jira/browse/WW-4110 +struts.objectFactory.spring.enableAopSupport = false + +### if specified, the default object type determiner can be overridden here +### Note: short-hand notation is supported in some cases, such as "tiger" or "notiger" +### Alternatively, you can provide a com.opensymphony.xwork2.util.ObjectTypeDeterminer implementation name here +### Note: By default, com.opensymphony.xwork2.util.DefaultObjectTypeDeterminer is used which handles type detection +### using generics. com.opensymphony.xwork2.util.GenericsObjectTypeDeterminer was deprecated since XWork 2, it's +### functions are integrated in DefaultObjectTypeDeterminer now. +### To disable tiger support use the "notiger" property value here. +# struts.objectTypeDeterminer = tiger +# struts.objectTypeDeterminer = notiger + +### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data +# struts.multipart.parser=cos +# struts.multipart.parser=pell +# struts.multipart.parser=jakarta-stream +struts.multipart.parser=jakarta +### Uses javax.servlet.context.tempdir by default +struts.multipart.saveDir= +struts.multipart.maxSize=2097152 + +### Load custom property files (does not override struts.properties!) +# struts.custom.properties=application,org/apache/struts2/extension/custom + +### How request URLs are mapped to and from actions +### Vy default 'struts' name is used which maps to DefaultActionMapper +# struts.mapper.class=restful + +### Used by the DefaultActionMapper +### You may provide a comma separated list, e.g. struts.action.extension=action,jnlp,do +### The blank extension allows you to match directory listings as well as pure action names +### without interfering with static resources, which can be specified as an empty string +### prior to a comma e.g. struts.action.extension=, or struts.action.extension=x,y,z,, +struts.action.extension=action,, + +### Used by Dispatcher +### If true then Struts serves static content from inside its jar. +### If false then the static content must be available at /static +struts.serve.static=true + +### A path from which a static content is served, it must start with "/" +### and it cannot end with "/" +struts.ui.staticContentPath=/static + +### Used by FilterDispatcher +### This is good for development where one wants changes to the static content be +### fetch on each request. +### NOTE: This will only have effect if struts.serve.static=true +### If true -> Struts will write out header for static contents such that they will +### be cached by web browsers (using Date, Cache-Content, Pragma, Expires) +### headers). +### If false -> Struts will write out header for static contents such that they are +### NOT to be cached by web browser (using Cache-Content, Pragma, Expires +### headers) +struts.serve.static.browserCache=true + +### Set this to false if you wish to disable implicit dynamic method invocation +### via the URL request. This includes URLs like foo!bar.action, as well as params +### like method:bar (but not action:foo). +### An alternative to implicit dynamic method invocation is to use wildcard +### mappings, such as +struts.enable.DynamicMethodInvocation = false + +### Set this to true if you wish to allow slashes in your action names. If false, +### Actions names cannot have slashes, and will be accessible via any directory +### prefix. This is the traditional behavior expected of WebWork applications. +### Setting to true is useful when you want to use wildcards and store values +### in the URL, to be extracted by wildcard patterns, such as +### to match "/foo/edit" or +### "/foo/save". +struts.enable.SlashesInActionNames = false + +### Disables support for action: prefix +struts.mapper.action.prefix.enabled = false + +### Blocks access to actions in other namespace than current with action: prefix +struts.mapper.action.prefix.crossNamespaces = false + +### when set to true, Struts will act much more friendly for developers. This +### includes: +### - struts.i18n.reload = true +### - struts.configuration.xml.reload = true +### - raising various debug or ignorable problems to errors +### For example: normally a request to foo.action?someUnknownField=true should +### be ignored (given that any value can come from the web and it +### should not be trusted). However, during development, it may be +### useful to know when these errors are happening and be told of +### them right away. +# ruleid: default-properties-devmode +struts.devMode = true + +### when set to true, resource bundles will be reloaded on _every_ request. +### this is good during development, but should never be used in production +# struts.i18n.reload=false + +### Standard UI theme +### Change this to reflect which path should be used for JSP control tag templates by default +struts.ui.theme=xhtml +struts.ui.templateDir=template +### Change this to use a different token to indicate template theme expansion +struts.ui.theme.expansion.token=~~~ +### Sets the default template type. Either ftl, vm, or jsp +struts.ui.templateSuffix=ftl + +### Sets a global flag which will escape html body of Anchor, Submit and Component tag +### You can control this flag per tag, e.g.: ... +### and this take precedence over the global flag +# struts.ui.escapeHtmlBody=true + +### Configuration reloading +### This will cause the configuration to reload struts.xml when it is changed +# struts.configuration.xml.reload=false + +### Location of velocity.properties file. defaults to velocity.properties +struts.velocity.configfile = velocity.properties + +### Comma separated list of VelocityContext classnames to chain to the StrutsVelocityContext +struts.velocity.contexts = + +### Location of the velocity toolbox +struts.velocity.toolboxlocation= + +### used to build URLs, such as the UrlTag +struts.url.http.port = 80 +struts.url.https.port = 443 +### possible values are: none, get or all +struts.url.includeParams = none + +### Load custom default resource bundles +# struts.custom.i18n.resources=testmessages,testmessages2 + +### Control whether to search the default resource bundes for messages first (if true) or not (if false). +### Default is false (when not set). +# struts.i18n.search.defaultbundles.first=false + +### workaround for some app servers that don't handle HttpServletRequest.getParameterMap() +### often used for WebLogic, Orion, and OC4J +struts.dispatcher.parametersWorkaround = false + +### configure the Freemarker Manager class to be used +### Allows user to plug-in customised Freemarker Manager if necessary +### MUST extends off org.apache.struts2.views.freemarker.FreemarkerManager +# struts.freemarker.manager.classname=org.apache.struts2.views.freemarker.FreemarkerManager + +### Enables caching of FreeMarker templates +### Has the same effect as copying the templates under WEB_APP/templates +# struts.freemarker.templatesCache=false + +### Enables caching of models on the BeanWrapper +struts.freemarker.beanwrapperCache=false + +### See the StrutsBeanWrapper javadocs for more information +struts.freemarker.wrapper.altMap=true + +### maxStrongSize for MruCacheStorage for freemarker, when set to 0 SoftCacheStorage which performs better in heavy loaded application +### check WW-3766 for more details +struts.freemarker.mru.max.strong.size=0 + +### configure the XSLTResult class to use stylesheet caching. +### Set to true for developers and false for production. +struts.xslt.nocache=false + +### Whether to always select the namespace to be everything before the last slash or not +struts.mapper.alwaysSelectFullNamespace=false + +### Whether to allow static field access in OGNL expressions or not +struts.ognl.allowStaticFieldAccess=true + +### Whether to allow static method access in OGNL expressions or not +struts.ognl.allowStaticMethodAccess=false + +### Whether to throw a RuntimeException when a property is not found +### in an expression, or when the expression evaluation fails +struts.el.throwExceptionOnFailure=false + +### Logs as Warnings properties that are not found (very verbose) +struts.ognl.logMissingProperties=false + +### Caches parsed OGNL expressions, but can lead to memory leaks +### if the application generates a lot of different expressions +struts.ognl.enableExpressionCache=true + +### Specify the OGNL expression cache factory and BeanInfo cache factory to use. +### Currently, the default implementations are used, but can be replaced with custom ones if desired. +struts.ognl.expressionCacheFactory=defaultOgnlExpressionCacheFactory +struts.ognl.beanInfoCacheFactory=defaultOgnlBeanInfoCacheFactory + +### Specify a limit to the number of entries in the OGNL expressionCache. +### For the standard expressionCache mode, when the limit is exceeded the entire cache's +### content will be cleared (can help prevent memory leaks). +### For expressionCacheLRUMode true, the limit will ensure the cache does not exceed +### that size, dropping the oldest (least-recently-used) expressions to add new ones. +### NOTE: If not set, the default is 25000, which may be excessive. +# struts.ognl.expressionCacheMaxSize=1000 + +### Indicates if the OGNL expressionCache should use LRU mode. +### NOTE: When true, make sure to set the expressionCacheMaxSize to a reasonable value +### for your application. Otherwise the default limit will never (practically) be reached. +# struts.ognl.expressionCacheLRUMode=false + +### Specify a limit to the number of entries in the OGNL beanInfoCache. +### For the standard beanInfoCache mode, when the limit is exceeded the entire cache's +### content will be cleared (can help prevent memory leaks). +### For beanInfoCacheLRUMode true, the limit will ensure the cache does not exceed +### that size, dropping the oldest (least-recently-used) expressions to add new ones. +### NOTE: If not set, the default is 25000, which may be excessive. +# struts.ognl.beanInfoCacheMaxSize=1000 + +### Indicates if the OGNL beanInfoCache should use LRU mode. +### NOTE: When true, make sure to set the beanInfoCacheMaxSize to a reasonable value +### for your application. Otherwise the default limit will never (practically) be reached. +# struts.ognl.beanInfoCacheLRUMode=false + +### Indicates if Dispatcher should handle unexpected exceptions by calling sendError() +### or simply rethrow it as a ServletException to allow future processing by other frameworks like Spring Security +struts.handle.exception=true + +### Applies maximum length allowed on OGNL expressions for security enhancement (optional) +### +### **WARNING**: If developers change this option (by configuration) they should make sure that they understand +### the implications of setting 'struts.ognl.expressionMaxLength'. They must choose a value large enough to permit +### ALL valid OGNL expressions used within the application. Values larger than the 200-400 range have diminishing +### security value (at which point it is really only a "style guard" for long OGNL expressions in an application. +### Setting a value of null or "" will also disable the feature. +struts.ognl.expressionMaxLength=256 + +### Defines which named instance of DateFormatter to use, there are two instances: +### - simpleDateFormatter (based on SimpleDateFormat) +### - dateTimeFormatter (based on Java 8 Date/Time API) +### These formatters are using a slightly different patterns, please check JavaDocs of both and more details is in WW-5016 +struts.date.formatter=dateTimeFormatter + +### END SNIPPET: complete_file diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/default-properties-devmode.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/default-properties-devmode.yml new file mode 100644 index 0000000..ec0eb87 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/default-properties-devmode.yml @@ -0,0 +1,30 @@ +rules: + - id: default-properties-devmode + message: >- + default.properties struts.devMode = $MODE + severity: WARNING + # There is no proper tree-sitter-ini + languages: [generic] + metadata: + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - default.properties + # Need to include test file + - default-properties-devmode.properties + patterns: + - pattern: | + struts.devMode = $MODE + # XXX Is this coerced or can in only be "true" or "false" + # XXX Is it case insensitive? + - metavariable-regex: + metavariable: $MODE + regex: >- + (true|1) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/struts-xml-devmode.xml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/struts-xml-devmode.xml new file mode 100644 index 0000000..aeb4e34 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/struts-xml-devmode.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + WEB-INF/index.jsp + + + + Chain from A to B + + actionB + + + + + WEB-INF/ActionB.jsp + + + + + + diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/struts-xml-devmode.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/struts-xml-devmode.yml new file mode 100644 index 0000000..5656067 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/struts-xml-devmode.yml @@ -0,0 +1,53 @@ +rules: + - id: struts-xml-devmode + message: >- + struts.xml devMode = "$...MODE" + severity: WARNING + # There is no proper tree-sitter-xml + # Only this https://github.com/unhammer/tree-sitter-xml + languages: [generic] + metadata: + docs: + - https://struts.apache.org/core-developers/constant-configuration + - https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - struts*.xml + patterns: + - pattern-either: + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + # XXX support value substitutions like `"${env.STRUTS_DEV_MODE:false}"` + # and `"${os.name}"`. Semgrep fails to match if source file has a `"$` in + # it, even with a permissive regex... + - metavariable-regex: + metavariable: $...MODE + regex: >- + (true|1) + # (true|1|\$\{.*\}) + # \s*.* + # Below alternative regex limits to just env and valid system + # properties. But I think its safer to just wildcard + # (true|1|\$\{(env|file|java|line|os|path|user)\..*\}) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/web-xml-devmode.xml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/web-xml-devmode.xml new file mode 100644 index 0000000..ff2bd26 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/web-xml-devmode.xml @@ -0,0 +1,31 @@ + + + + annotations + + + struts2 + org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter + + + struts.devMode + true + + + + + struts2 + /* + + + + index.jsp + + + diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/web-xml-devmode.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/web-xml-devmode.yml new file mode 100644 index 0000000..3df394d --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/devmode/web-xml-devmode.yml @@ -0,0 +1,37 @@ +rules: + - id: web-xml-devmode + message: >- + web.xml devMode = $MODE + severity: WARNING + # There is no proper tree-sitter-xml + # Only this https://github.com/unhammer/tree-sitter-xml + languages: [generic] + metadata: + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - web.xml + # unit test + - web-xml-devmode.xml + patterns: + - pattern: | + + ... + struts.devMode + ... + $MODE + ... + + # XXX Is this coerced or can in only be "true" or "false" + # XXX Is it case insensitive? + - metavariable-regex: + metavariable: $MODE + regex: >- + (true|1) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-action-dmi.xml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-action-dmi.xml new file mode 100644 index 0000000..943f532 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-action-dmi.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + view.jsp + input.jsp + create,edit,saveOrUpdate,delete + + + + + view.jsp + input.jsp + runCreateThis + + + + + diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-action-dmi.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-action-dmi.yml new file mode 100644 index 0000000..f80e8d9 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-action-dmi.yml @@ -0,0 +1,34 @@ +rules: + - id: struts-xml-action-dmi + message: >- + struts.xml action $...NAME either using Dynamic Method Invocation or + Wildcard Method feature + severity: WARNING + # There is no proper tree-sitter-xml + # Only this https://github.com/unhammer/tree-sitter-xml + languages: [generic] + metadata: + docs: + - https://struts.apache.org/core-developers/action-configuration.html#dynamic-method-invocation + - https://struts.apache.org/core-developers/action-configuration.html#wildcard-method + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - struts*.xml + patterns: + - pattern-either: + - pattern: | + - + .*!.* diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-dmi.xml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-dmi.xml new file mode 100644 index 0000000..00d865a --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-dmi.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + WEB-INF/index.jsp + + + + Chain from A to B + + actionB + + + + + WEB-INF/ActionB.jsp + + + + + + diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-dmi.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-dmi.yml new file mode 100644 index 0000000..44806b6 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/struts-xml-dmi.yml @@ -0,0 +1,49 @@ +rules: + - id: struts-xml-dmi + message: >- + struts.xml Dynamic Method Invocation + severity: WARNING + # There is no proper tree-sitter-xml + # Only this https://github.com/unhammer/tree-sitter-xml + languages: [generic] + metadata: + docs: + - https://struts.apache.org/core-developers/action-configuration.html#dynamic-method-invocation + - https://cwiki.apache.org/confluence/display/WW/S2-019 + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - struts*.xml + patterns: + - pattern-either: + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + # XXX support value substitutions like `"${env.STRUTS_DEV_MODE:false}"` + # and `"${os.name}"`. Semgrep fails to match if source file has a `"$` in + # it, even with a permissive regex... + - metavariable-regex: + metavariable: $...MODE + regex: >- + (true|1) + # (true|1|\$\{.*\}) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/taglib-action-dmi.jsp b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/taglib-action-dmi.jsp new file mode 100644 index 0000000..f5e2e5c --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/taglib-action-dmi.jsp @@ -0,0 +1,22 @@ + +<%@ page contentType="text/html; charset=UTF-8" %> +<%@ taglib prefix="s" uri="/struts-tags" %> + + + Start + + + + + + + User name: + + + + + diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/taglib-action-dmi.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/taglib-action-dmi.yml new file mode 100644 index 0000000..e39f623 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/dmi/taglib-action-dmi.yml @@ -0,0 +1,177 @@ +rules: + - id: taglib-action-dmi + message: >- + JSTL taglib directive + either Dynamic Method Invocation (DMI) or Wildcard Method feature + prefix="$...PREFIX" + uri="$...URI" + action="$...ACTION" + severity: INFO + languages: [generic] + metadata: + docs: + - https://struts.apache.org/core-developers/action-configuration.html#dynamic-method-invocation + - https://struts.apache.org/core-developers/action-configuration.html#wildcard-method + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + - JSTL + - taglib + paths: + include: + - '*.jsp' + # NOTE: need to use `"$...URI"` etc to capture strings like `"/struts"`. + # Due to the `/`, which breaks the binding. + patterns: + - pattern-either: + - pattern-inside: | + <%@ taglib prefix='$...PREFIX' ... uri='$...URI' + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + - pattern-inside: | + <%@ taglib prefix="$...PREFIX" ... uri="$...URI" + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + - pattern-inside: | + <%@ taglib uri='$...URI' ... prefix='$...PREFIX' + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + - pattern-inside: | + <%@ taglib uri="$...URI" ... prefix="$...PREFIX" + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... + - pattern-either: + - pattern: | + <$...PREFIX:... ... action='$...ACTION' + - pattern: | + <$...PREFIX:... ... action="$...ACTION" + - metavariable-regex: + metavariable: $...ACTION + regex: >- + .*!.* + #- focus-metavariable: $...ACTION diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/struts-xml-always-select-full-namespace.xml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/struts-xml-always-select-full-namespace.xml new file mode 100644 index 0000000..3987221 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/struts-xml-always-select-full-namespace.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + index,show,create,update,destroy + + + {1} + /movie.jsp + + + + + diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/struts-xml-always-select-full-namespace.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/struts-xml-always-select-full-namespace.yml new file mode 100644 index 0000000..5e90ecb --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/struts2/security/audit/struts-xml-always-select-full-namespace.yml @@ -0,0 +1,51 @@ +rules: + - id: struts-xml-always-select-full-namespace + message: >- + struts.xml using alwaysSelectFullNamespace + severity: WARNING + # There is no proper tree-sitter-xml + # Only this https://github.com/unhammer/tree-sitter-xml + languages: [generic] + metadata: + docs: + - https://cwiki.apache.org/confluence/display/WW/S2-057 + - https://nvd.nist.gov/vuln/detail/CVE-2018-11776 + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - Struts2 + paths: + include: + - struts*.xml + patterns: + - pattern-inside: | + + - pattern-either: + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + - pattern: | + + # XXX support value substitutions like `"${env.STRUTS_DEV_MODE:false}"` + # and `"${os.name}"`. Semgrep fails to match if source file has a `"$` in + # it, even with a permissive regex... + - metavariable-regex: + metavariable: $...MODE + regex: >- + (true|1) + # (true|1|\$\{.*\}) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/xstream/security/audit/fromxml.java b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/xstream/security/audit/fromxml.java new file mode 100644 index 0000000..5cd4557 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/xstream/security/audit/fromxml.java @@ -0,0 +1,123 @@ +package com.example.springboot; + +import java.util.Arrays; + +// debugging +import java.util.PriorityQueue; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.Files; + + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; + +import com.thoughtworks.xstream.XStream; + +public class FoobarXStream { + + private XStream xstream = new XStream(); + + public FoobarXStream() { + + try { + // ruleid: fromXML + Object pq = xstream.fromXML(read); + } catch (Exception e) { + System.out.println(read); + System.out.println(e); + } + } + +} + +public class FoobarXStreamAgain { + + private XStream xstream; + + public FoobarXStreamAgain() { + xstream = new XStream(); + } + + public void doSmth() { + try { + // ruleid: fromXML + Object pq = xstream.fromXML(read); + } catch (Exception e) { + System.out.println(read); + System.out.println(e); + } + } +} + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public CommandLineRunner commandLineRunner(ApplicationContext ctx) { + return args -> { + + System.out.println("Let's inspect the beans provided by Spring Boot:"); + + String[] beanNames = ctx.getBeanDefinitionNames(); + Arrays.sort(beanNames); + for (String beanName : beanNames) { + System.out.println(beanName); + } + + // XXX Berney + System.out.println("XXX Berney Start of Stuff"); + // should launch an executable + //Egg egg = new Egg(); + + // https://x-stream.github.io/tutorial.html + System.out.println("XXX Berney XStream stuff"); + XStream xstream = new XStream(); + + Path path = Paths.get("bad.xml"); + String read = Files.readString(path); + System.out.format("\n\nRead: -\n%s\n\n", read); + try { + // ruleid: fromXML + Object pq = xstream.fromXML(read); + } catch (Exception e) { + System.out.println(read); + System.out.println(e); + } + + // Now, to make the XML outputted by XStream more concise, you can create aliases for your custom class names to XML element names + xstream.alias("person", Person.class); + //xstream.alias("phonenumber", PhoneNumber.class); + + // Serializing an object to XML + // Let's create an instance of Person and populate its fields: + Person joe = new Person("Joe", "Walnes"); + joe.setPhone(new PhoneNumber(123, "1234-456")); + joe.setFax(new PhoneNumber(123, "9999-999")); + + // Now, to convert it to XML, all you have to do is make a simple call to XStream: + String xml = xstream.toXML(joe); + System.out.println(xml); + + // Deserializing an object back from XML + // ruleid: fromXML + Person newJoe = (Person)xstream.fromXML(xml); + System.out.println("Deserialised newJoe"); + + // Deserialise Egg (should execute a process) + String maliciousXml = ""; + // Egg isn't a Person but we'll see if it still gets constructed before getting cast + // ruleid: fromXML + Person badJoe = (Person)xstream.fromXML(maliciousXml); + + }; + } + +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/xstream/security/audit/fromxml.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/xstream/security/audit/fromxml.yml new file mode 100644 index 0000000..dfd996b --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/java/xstream/security/audit/fromxml.yml @@ -0,0 +1,22 @@ +rules: + - id: fromXML + metadata: + cwe: 'CWE-502: Deserialization of Untrusted Data' + owasp: 'A8: Insecure Deserialization' + docs: + - https://x-stream.github.io/javadoc/index.html?com/thoughtworks/xstream/XStream.html + - https://www.baeldung.com/java-xstream-remote-code-execution + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - JVM + - XML + - XStream + pattern: (com.thoughtworks.xstream.XStream $XSTREAM).fromXML(...); + message: >- + XStream XML Deserialzation: Check that they have correctly set an allow-list and if an attacker can control input. + severity: WARNING + languages: [java] diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/javascript/express/security/audit/mongodb-nosqli.js b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/javascript/express/security/audit/mongodb-nosqli.js new file mode 100644 index 0000000..8cda98a --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/javascript/express/security/audit/mongodb-nosqli.js @@ -0,0 +1,25 @@ +const express = require('express') +const User = require('../models/user') + +const app = express() + +app.post('/register', async (req, res, next) => { + // ruleid: express-mongodb-nosqli + let user = new User(req.body) + await user.save() + return res.json(user) +}) + +app.post('/login', async (req, res, next) => { + let { username, password } = req.body + // ruleid: express-mongodb-nosqli + let user = User.findOne({ username, password }) + return res.json(user) +}) + +app.post('/secure-login', async (req, res, next) => { + let { username, password } = req.body + // ok: express-mongodb-nosqli + let user = User.findOne({ username: username.toString(), password: password.toString() }) + return res.json(user) +}) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules-audit/javascript/express/security/audit/mongodb-nosqli.yml b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/javascript/express/security/audit/mongodb-nosqli.yml new file mode 100644 index 0000000..945474a --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules-audit/javascript/express/security/audit/mongodb-nosqli.yml @@ -0,0 +1,58 @@ +rules: + - id: express-mongodb-nosqli + message: Depending on the context, using (user-controlled) request data directly in a MongoDB query can lead to a NoSQLi + vulnerability. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A03:2021 – Injection + references: + - https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection + category: security + technology: + - javascript + subcategory: vuln + likelihood: LOW + impact: MEDIUM + confidence: MEDIUM + interfile: true + languages: + # nosemgrep: yaml.semgrep.consistency.lang-consistency-js.lang-consistency-js + - javascript + # nosemgrep: yaml.semgrep.consistency.lang-consistency-ts.lang-consistency-ts + - typescript + severity: WARNING + mode: taint + pattern-sources: + - patterns: + - pattern: function($REQ, ...) { ... } + - pattern-either: + - pattern: $REQ.$USERDATA + - pattern: let { $USERDATA } = $REQ + - focus-metavariable: $REQ + - metavariable-regex: + metavariable: $REQ + regex: req + - metavariable-regex: + metavariable: $USERDATA + regex: (body|params|query|cookies|headers) + pattern-sanitizers: + - patterns: + - pattern: $X.toString() + - focus-metavariable: $X + pattern-sinks: + - patterns: + - pattern-inside: | + $MODEL = require('$IMPORT') + ... + - metavariable-regex: + metavariable: $IMPORT + regex: .*(db|models|data|schema|mongo).* + - pattern-either: + - pattern: new $MODEL(...) + - patterns: + - pattern: $MODEL.$FUNC(...) + - metavariable-regex: + metavariable: $FUNC + regex: (find|delete|update|replace|where|create|insert|map|bulk|aggregate|count).* diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/executable-symlink.go b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/executable-symlink.go new file mode 100644 index 0000000..38f1562 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/executable-symlink.go @@ -0,0 +1,62 @@ +package main + +import ( + "fmt" + "log" + "os" + "path/filepath" +) + +func withEval() string { + // ok: potential-symlink-takeover-with-os.executable + execBin, _ := os.Executable() + result, err := filepath.EvalSymlinks(execBin) + if err != nil { + log.Fatalf("error %v\n", err) + } + + path, err := filepath.Abs(filepath.Dir(result)) + if err != nil { + log.Fatalf("error %v\n", err) + } + fmt.Println("Path with filepath.EvalSymlinks():", path) + return path +} + +func withoutEval() string { + //ruleid: potential-symlink-takeover-with-os.executable + execBin, _ := os.Executable() + path, err := filepath.Abs(filepath.Dir(execBin)) + if err != nil { + log.Fatalf("error %v\n", err) + } + fmt.Println("Path without filepath.EvalSymlinks():", path) + return path +} + +func printFile(path string) { + fname := "test.txt" + abspath := filepath.Join(path, fname) + + file, err := os.Open(abspath) + if err != nil { + log.Fatal(err) + } + defer file.Close() + + fbytes := make([]byte, 16) + bytesRead, err := file.Read(fbytes) + if err != nil { + log.Fatal(err) + } + fmt.Printf("Number of bytes read: %d\n", bytesRead) + fmt.Printf("Bytes: %s\n", fbytes) +} + +func main() { + goodpath := withEval() + printFile(goodpath) + + badpath := withoutEval() + printFile(badpath) +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/executable-symlink.yaml b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/executable-symlink.yaml new file mode 100644 index 0000000..17b538d --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/executable-symlink.yaml @@ -0,0 +1,23 @@ +rules: + - id: potential-symlink-takeover-with-os.executable + message: >- + os.Executable()s behaviour varies between operating systems. + On Linux symlinks are followed, while on MacOS and Windows they are not. + Depending on context, this could lead to file replacement attacks and local privilege escalation. + metadata: + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - golang + severity: WARNING + languages: [go] + patterns: + - pattern: | + $BIN, ... := os.Executable() + - pattern-not-inside: | + $BIN, ... := os.Executable() + ... + ..., ... := filepath.EvalSymlinks($BIN) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/sprintf-plain-string.go b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/sprintf-plain-string.go new file mode 100644 index 0000000..b5233ab --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/sprintf-plain-string.go @@ -0,0 +1,44 @@ +package main + +import ( + "flag" + "fmt" + "path" + "path/filepath" +) + +func sformat(s string) string { + sstring := fmt.Sprintf("s-formatted string: %s asdf", s) + return sstring +} + +func qformat(s string) string { + sstring := fmt.Sprintf("s-formatted string: %q", s) + return sstring +} + + +func main() { + args := flag.String("string", "", "a test string") + flag.Parse() + + root := "/" + URL := "https://example.com/" + inject := "adsf\u000a" + + + // ruleid: sprintf-unescaped-control-characters + fmt.Println("path.join test: ", path.Join(URL, sformat(*args))) + // ruleid: sprintf-unescaped-control-characters + fmt.Println("filepath.join test: ", filepath.Join(root, sformat(*args))) + // ruleid: sprintf-unescaped-control-characters + fmt.Println("path.join test: ", path.Join(URL, sformat(inject))) + // ruleid: sprintf-unescaped-control-characters + fmt.Println("filepath.join test: ", filepath.Join(root, sformat(inject))) + + fmt.Println("path.join test: ", path.Join(URL, qformat(*args))) + fmt.Println("filepath.join test: ", filepath.Join(root, qformat(*args))) + fmt.Println("path.join test: ", path.Join(URL, qformat(inject))) + fmt.Println("filepath.join test: ", filepath.Join(root, qformat(inject))) + +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/sprintf-plain-string.yaml b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/sprintf-plain-string.yaml new file mode 100644 index 0000000..8f571d4 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/sprintf-plain-string.yaml @@ -0,0 +1,38 @@ +rules: + - id: sprintf-unescaped-control-characters + message: >- + fmt.Sprintf()'s %s formatting verb does not escape control characters + in a string, such as \u000a or backtick-enclosed multilines. This could + lead to various vulnerabilities such as header injection, request + smuggling, log injection, etc. + metadata: + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: MEDIUM + technology: + - golang + severity: WARNING + languages: + - go + mode: taint + options: + symbolic_propagation: true + pattern-sources: + - patterns: + # Need the `...` at the end outside of the function + - pattern-inside: | + func $FUNC(...) $TYPE { + ... + return fmt.Sprintf("$VERB", ...) + } + ... + - metavariable-regex: + metavariable: $VERB + regex: .*%s + - pattern: $FUNC(...) + pattern-sinks: + - pattern: filepath.Join(...) + - pattern: path.Join(...) + - pattern: $FUNC.log(...) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/uintptr-nonatomic.go b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/uintptr-nonatomic.go new file mode 100644 index 0000000..bad3ee6 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/uintptr-nonatomic.go @@ -0,0 +1,22 @@ +package main + +import ( + "syscall" + "unsafe" +) + +func main() { + // ruleid: non-atomic-use-of-converted-uintptr + argp := uintptr(unsafe.Pointer(attrp)) + _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), request, argp) + if errno != 0 { + panic(errno) + } + + // ok: non-atomic-use-of-converted-uintptr + ret, _, _ := syscall.Syscall(uintptr(globalMemoryStatusEx), 1, uintptr(unsafe.Pointer(&memoryStatusEx[0])), 0, 0) + if ret == 0 { + return 0 + } + +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/uintptr-nonatomic.yaml b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/uintptr-nonatomic.yaml new file mode 100644 index 0000000..ddb7ca5 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/go/lang/security/audit/uintptr-nonatomic.yaml @@ -0,0 +1,24 @@ +rules: + - id: non-atomic-use-of-converted-uintptr + message: >- + An unsafe.Pointer converted to an uintptr must be used in an atomic step. + Without this it is not guaranteed that the memory location uintptr points to will contain the intended structure. + metadata: + category: security + subcategory: vuln + likelihood: MEDIUM + impact: MEDIUM + confidence: MEDIUM + technology: + - golang + severity: WARNING + languages: [go] + pattern-either: + - pattern: | + $UINTPTR := uintptr(unsafe.Pointer( ... )) + ... + ... := $F(..., $UINTPTR, ...) + - pattern: | + $UINTPTR := uintptr($PTR) + ... + ... := $F(..., $UINTPTR, ...) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/java/audit/email-validation/jakarta-mail-email-primitives.yml b/compliance-agent/rules/vendor/elttam/upstream/rules/java/audit/email-validation/jakarta-mail-email-primitives.yml new file mode 100644 index 0000000..78cbe93 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/java/audit/email-validation/jakarta-mail-email-primitives.yml @@ -0,0 +1,303 @@ +rules: + ########################################################################## + # Jakarta Mail: InternetAddress primitives + ########################################################################## + + - id: jakarta-mail-internetaddress-overloaded-ctor + languages: [java] + severity: WARNING + message: >- + InternetAddress(String, ...) constructors do NOT validate the email + address. They assign the address field directly. Prefer the single-arg + constructor + explicit validation. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: MEDIUM + impact: MEDIUM + confidence: LOW + technology: + - java + vulnerability_class: + - Improper Validation + pattern-either: + - pattern: new jakarta.mail.internet.InternetAddress($ADDR, $PERSONAL) + - pattern: new jakarta.mail.internet.InternetAddress($ADDR, $PERSONAL, $CHARSET) + + - id: jakarta-mail-internetaddress-single-arg-validator + languages: [java] + severity: INFO + message: >- + new InternetAddress(String) parses an email for RFC compliance, but + should not be treated as a full security/identity check. Ensure domain + checks and trust decisions are not based solely on constructor success. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: MEDIUM + impact: MEDIUM + confidence: LOW + technology: + - java + vulnerability_class: + - Improper Validation + pattern: new jakarta.mail.internet.InternetAddress($ADDR) + + ########################################################################## + # Jakarta Mail: MimeMessage / NewsAddress / Newsgroups usage + ########################################################################## + + - id: jakarta-mail-mimemessage-raw-envelope-ctor + languages: [java] + severity: INFO + message: >- + MimeMessage constructed from a raw source or InputStream. Headers such + as From, Reply-To, Subject, and Newsgroups will be parsed using + InternetAddress/NewsAddress. Ensure user-controlled envelopes are + canonicalized and not blindly trusted. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern-either: + - pattern: new jakarta.mail.internet.MimeMessage($SESSION, $IS) + - pattern: new jakarta.mail.internet.MimeMessage($FOLDER, $IS, $MSGNUM) + - pattern: new jakarta.mail.internet.MimeMessage($SOURCE) + + - id: jakarta-mail-mimemessage-newsgroups-recipients + languages: [java] + severity: INFO + message: >- + MimeMessage.getRecipients(Message.RecipientType.NEWSGROUPS) used. + Newsgroups headers may be concatenated and parsed via NewsAddress, + which silently normalizes malformed values. Review how this data is used. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: MEDIUM + impact: MEDIUM + confidence: LOW + technology: + - java + patterns: + - pattern: | + $MM.getRecipients(MimeMessage.RecipientType.NEWSGROUPS) + - metavariable-type: + metavariable: $MM + type: jakarta.mail.internet.MimeMessage + + ########################################################################## + # Spring Framework mail wrappers + ########################################################################## + + - id: spring-internetaddresseditor-usage + languages: [java] + severity: INFO + message: >- + Spring InternetAddressEditor used. This relies on Jakarta Mail parsing + and will decode encoded personal names (RFC 2047). Ensure the resulting + personal/name fields are not used as trust signals. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern: new org.springframework.mail.javamail.InternetAddressEditor(...) + + - id: spring-simplemailmessage-setfrom-raw + languages: [java] + severity: INFO + message: >- + SimpleMailMessage.setFrom(...) called. If the from-address is influenced + by user input, be aware of encoded names and complex email syntax + (e.g. encoded words, group addresses, angle-bracket forms). + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + patterns: + - pattern: $MSG.setFrom(...) + - metavariable-type: + metavariable: $MSG + type: org.springframework.mail.SimpleMailMessage + + ########################################################################## + # Naive email domain parsing (split / lastIndexOf / endsWith) + ########################################################################## + + - id: email-domain-split-index + languages: [java] + severity: WARNING + message: >- + Domain derived via email.split("@")[1]. This is fragile for complex, + RFC-compliant addresses (e.g. "\"foo@bar.com\"@example.com"). Prefer a + proper email parser and canonicalization for domain checks. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern: $EMAIL.split("@")[1] + + - id: email-domain-lastindexof + languages: [java] + severity: WARNING + message: >- + Domain derived via substring(lastIndexOf("@") + 1). This can be tricked + by overloaded or encoded email addresses. Prefer a proper parser and + canonical form instead of manual substring logic. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern: $EMAIL.substring($EMAIL.lastIndexOf("@") + 1) + + - id: email-domain-endswith + languages: [java] + severity: WARNING + message: >- + Domain/tenant derived using email.endsWith("..."). This can be bypassed + with addresses like tester@evil.com@trusted.com. Prefer comparing the + canonical domain returned by a parser. + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern-either: + - patterns: + - pattern: $EMAIL.endsWith("$SUFFIX") + - metavariable-regex: + metavariable: $SUFFIX + regex: ^@ + - patterns: + - patterns: + - pattern: String $VAR = "$SUFFIX"; + - metavariable-regex: + metavariable: $SUFFIX + regex: ^@ + - pattern: $EMAIL.endsWith($VAR) + + ########################################################################## + # Hibernate Validator: @Email annotation hotspots + ########################################################################## + + - id: hibernate-email-annotation-field + languages: [java] + severity: INFO + message: >- + Field annotated with @Email. The default Hibernate validator is not + RFC 2047-aware and can accept complex syntax (e.g. "\"foo@bar.com\"@example.com"). + Review any domain or trust logic that uses this field (split/substring/endsWith). + metadata: + cwe: + - 'CWE-20: Improper Input Validation' + owasp: + - A04:2021 – Insecure Design + references: + - https://elttam.com/blog/jakarta-mail-primitives/ + - https://cwe.mitre.org/data/definitions/20.html + - https://owasp.org/Top10/A04_2021-Insecure_Design/ + category: security + subcategory: audit + likelihood: LOW + impact: MEDIUM + confidence: LOW + technology: + - java + pattern: |- + @Email + $TYPE $STRING_VAR diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/java/audit/email-validation/jakarta-mail-email-primitives/jakarta-mail-email-primitives.java b/compliance-agent/rules/vendor/elttam/upstream/rules/java/audit/email-validation/jakarta-mail-email-primitives/jakarta-mail-email-primitives.java new file mode 100644 index 0000000..ad93f09 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/java/audit/email-validation/jakarta-mail-email-primitives/jakarta-mail-email-primitives.java @@ -0,0 +1,76 @@ +package demo; + +import jakarta.mail.Message; +import jakarta.mail.Session; +import jakarta.mail.Folder; +import jakarta.mail.internet.InternetAddress; +import jakarta.mail.internet.MimeMessage; +import jakarta.mail.internet.NewsAddress; + +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.InternetAddressEditor; + +import jakarta.validation.constraints.Email; + +import java.io.InputStream; + +public class JakartaMailEmailPrimitivesDemo { + + //ruleid: hibernate-email-annotation-field + @Email + private String userEmail; + + public void demoInternetAddressConstructors() throws Exception { + String raw = "(blah)"; + String addr = "user@example.com"; + String personal = "User Name"; + + //ruleid: jakarta-mail-internetaddress-overloaded-ctor + InternetAddress overloaded1 = new InternetAddress(raw, personal); + //ruleid: jakarta-mail-internetaddress-overloaded-ctor + InternetAddress overloaded2 = new InternetAddress(raw, personal, "UTF-8"); + //ruleid: jakarta-mail-internetaddress-single-arg-validator + InternetAddress validated = new InternetAddress(addr); + } + + public void demoMimeMessageUsage(Session session, Folder folder, InputStream is) throws Exception { + //ruleid: jakarta-mail-mimemessage-raw-envelope-ctor + MimeMessage sourceMessage = new MimeMessage(session); + //ruleid: jakarta-mail-mimemessage-raw-envelope-ctor + MimeMessage m1 = new MimeMessage(session, is); + //ruleid: jakarta-mail-mimemessage-raw-envelope-ctor + MimeMessage m2 = new MimeMessage(folder, is, 1); + //ruleid: jakarta-mail-mimemessage-raw-envelope-ctor + MimeMessage m3 = new MimeMessage(sourceMessage); + + //ruleid: jakarta-mail-mimemessage-newsgroups-recipients + m1.getRecipients(MimeMessage.RecipientType.NEWSGROUPS); + } + + public void demoSpringMailUsage() { + //ruleid: spring-internetaddresseditor-usage + InternetAddressEditor editor = new InternetAddressEditor(); + editor.setAsText("=?UTF-8?Q?Administrator_=3Cadmin@example.com=3E?= "); + + SimpleMailMessage msg = new SimpleMailMessage(); + String from = "=?UTF-8?Q?Admin_=3Cadmin@example.com=3E?= "; + //ruleid: spring-simplemailmessage-setfrom-raw + msg.setFrom(from); + } + + public void demoNaiveDomainParsing() { + String email = "\"foo@bar.com\"@example.com"; + + //ruleid: email-domain-split-index + String domain1 = email.split("@")[1]; + + //ruleid: email-domain-lastindexof + String domain2 = email.substring(email.lastIndexOf("@") + 1); + + String EMAIL_DOMAIN = "@trusted.com"; + //ruleid: email-domain-endswith + if (email.endsWith(EMAIL_DOMAIN)) { + grantStaffAccess(); + } + } +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/gcm-static-iv.java b/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/gcm-static-iv.java new file mode 100644 index 0000000..c376c62 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/gcm-static-iv.java @@ -0,0 +1,117 @@ +package com.example.sparkdemo; + +import java.security.GeneralSecurityException; +import java.security.Key; + +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import javax.xml.bind.DatatypeConverter; + +public class Crypto1 { + + private Key key; + private GCMParameterSpec gcmParameterSpec; + + public Crypto1() { + byte[] keyBytes = "YELLOW_SUBMARINE".getBytes(); + byte[] blah = "blah".getBytes(); + // ruleid: gcm-static-iv + key = new SecretKeySpec(keyBytes, "AES"); + gcmParameterSpec = new GCMParameterSpec(128, keyBytes); + } + + private synchronized byte[] transform(byte[] data, int mode) { + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(mode, key, gcmParameterSpec); + return cipher.doFinal(data); + } catch (GeneralSecurityException ex) { + throw new RuntimeException(ex); + } + } + + public String encrypt(String data) { + return DatatypeConverter.printHexBinary(transform(data.getBytes(), Cipher.ENCRYPT_MODE)).toLowerCase(); + } + + public String decrypt(String data) { + return new String(transform(DatatypeConverter.parseHexBinary(data), Cipher.DECRYPT_MODE)); + } +} + +public class Crypto2 { + + private Key key; + private GCMParameterSpec gcmParameterSpec; + + public Crypto2() { + byte[] keyBytes = { + (byte) 0, (byte) 0, (byte) 0, (byte) 0, + (byte) 0, (byte) 0, (byte) 0, (byte) 0, + (byte) 0, (byte) 0, (byte) 0, (byte) 0, + (byte) 0, (byte) 0, (byte) 0, (byte) 0 + }; + byte[] blah = "blah".getBytes(); + // ruleid: gcm-static-iv + key = new SecretKeySpec(keyBytes, "AES"); + byte[] blahblah = "blahblah".getBytes(); + gcmParameterSpec = new GCMParameterSpec(128, keyBytes); + } + + private synchronized byte[] transform(byte[] data, int mode) { + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(mode, key, gcmParameterSpec); + return cipher.doFinal(data); + } catch (GeneralSecurityException ex) { + throw new RuntimeException(ex); + } + } + + public String encrypt(String data) { + return DatatypeConverter.printHexBinary(transform(data.getBytes(), Cipher.ENCRYPT_MODE)).toLowerCase(); + } + + public String decrypt(String data) { + return new String(transform(DatatypeConverter.parseHexBinary(data), Cipher.DECRYPT_MODE)); + } +} + +public class Crypto3 { + + + private Key key; + private GCMParameterSpec gcmParameterSpec; + byte[] iv = { + (byte) 0, (byte) 0, (byte) 0, (byte) 0, + (byte) 0, (byte) 0, (byte) 0, (byte) 0, + (byte) 0, (byte) 0, (byte) 0, (byte) 0, + (byte) 0, (byte) 0, (byte) 0, (byte) 0 + }; + + public Crypto3() { + byte[] blah = "blah".getBytes(); + // ruleid: gcm-static-iv + gcmParameterSpec = new GCMParameterSpec(128, iv); + key = new SecretKeySpec(iv, "AES"); + } + + private synchronized byte[] transform(byte[] data, int mode) { + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(mode, key, gcmParameterSpec); + return cipher.doFinal(data); + } catch (GeneralSecurityException ex) { + throw new RuntimeException(ex); + } + } + + public String encrypt(String data) { + return DatatypeConverter.printHexBinary(transform(data.getBytes(), Cipher.ENCRYPT_MODE)).toLowerCase(); + } + + public String decrypt(String data) { + return new String(transform(DatatypeConverter.parseHexBinary(data), Cipher.DECRYPT_MODE)); + } +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/gcm-static-iv.yml b/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/gcm-static-iv.yml new file mode 100644 index 0000000..a15200a --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/gcm-static-iv.yml @@ -0,0 +1,46 @@ +rules: + - id: gcm-static-iv + message: >- + GCM IV and key are both same source $KEY_BYTES + metadata: + cwe: | + # Closer match, but specifically CBC mode, whereas this is GCM mode. + #CWE-329: Not Using a Random IV with CBC Mode + CWE-330: Use of Insufficiently Random Values + references: + - https://www.elttam.com/blog/key-recovery-attacks-on-gcm + help: + # Similar rule + - https://github.com/returntocorp/semgrep-rules/pull/382/files + category: security + subcategory: audit + likelihood: MEDIUM + impact: MEDIUM + confidence: HIGH + technology: + - Java + - GCM + languages: [java] + severity: WARNING + patterns: + - pattern-either: + - pattern-inside: | + $KEY_BYTES = $RAW_KEY.getBytes(); + ... + - pattern-inside: | + byte[] $KEY_BYTES = { ... }; + ... + - pattern-inside: | + class $CLASS { + byte[] $KEY_BYTES = {...}; + ... + } + - pattern-either: + - pattern: | + $GCM_PARAM_SPEC = new GCMParameterSpec($BLOCK_SIZE, $KEY_BYTES); + ... + $KEY = new SecretKeySpec($KEY_BYTES, $ALGO); + - pattern: | + $KEY = new SecretKeySpec($KEY_BYTES, $ALGO); + ... + $GCM_PARAM_SPEC = new GCMParameterSpec($BLOCK_SIZE, $KEY_BYTES); diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/randomstringutils.java b/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/randomstringutils.java new file mode 100644 index 0000000..6c4b72e --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/randomstringutils.java @@ -0,0 +1,12 @@ +import org.apache.commons.lang3.RandomStringUtils; + +class Main { + public static void main(String[] args) { + // ruleid: randomstringutils-insecure-rng + String a = RandomStringUtils.randomAlphanumeric(32); + // ruleid: randomstringutils-insecure-rng + String b = RandomStringUtils.random(10, true, true); + // ok: randomstringutils-insecure-rng + String c = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom()); + } +} diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/randomstringutils.yml b/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/randomstringutils.yml new file mode 100644 index 0000000..d0f0fca --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/java/lang/security/audit/crypto/randomstringutils.yml @@ -0,0 +1,25 @@ +rules: + - id: randomstringutils-insecure-rng + message: >- + RandomStringUtils uses java.util.Random by default which is not suitable for security + metadata: + cwe: 'CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)' + owasp: 'A9: Using Components with Known Vulnerabilities' + references: + - https://www.elttam.com/blog/cracking-randomness-in-java/ + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - Java + - Apache Commons Lang + - RandomStringUtils + languages: [java] + severity: WARNING + patterns: + - pattern: | + org.apache.commons.lang3.RandomStringUtils.$X(...) + - pattern-not-inside: | + org.apache.commons.lang3.RandomStringUtils.$X(..., new SecureRandom()) diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporterXml.xml b/compliance-agent/rules/vendor/elttam/upstream/rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporterXml.xml new file mode 100644 index 0000000..bc696e7 --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporterXml.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/compliance-agent/rules/vendor/elttam/upstream/rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporterXml.yml b/compliance-agent/rules/vendor/elttam/upstream/rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporterXml.yml new file mode 100644 index 0000000..ac2d74c --- /dev/null +++ b/compliance-agent/rules/vendor/elttam/upstream/rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporterXml.yml @@ -0,0 +1,31 @@ +rules: + # This is in a separate file to avoid warnings about trying to parse XML files as Java + - id: UnsafeHttpInvokerServiceExporter-XML + metadata: + cve: CVE-2016-1000027 + docs: + - https://blog.gypsyengineer.com/en/security/detecting-dangerous-spring-exporters-with-codeql.html + - https://www.tenable.com/security/research/tra-2016-20 + category: security + subcategory: audit + likelihood: LOW + impact: LOW + confidence: LOW + technology: + - spring + - spring-framework + - jvm + languages: [generic] + paths: + include: + - '*.xml' + severity: INFO + message: >- + Unsafe Spring Service Exporter XML + pattern-either: + - pattern: | + org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter + - pattern: | + org.springframework.remoting.httpinvoker.SimpleHttpInvokerServiceExporter + - pattern: | + org.springframework.remoting.rmi.RemoteInvocationSerializingExporter diff --git a/compliance-agent/rules/vendor/gitlab/LICENSE b/compliance-agent/rules/vendor/gitlab/LICENSE new file mode 100644 index 0000000..e703dbc --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2011-present GitLab Inc. + +Portions of this software are licensed as follows: + +* All content residing under the "doc/" directory of this repository is licensed under "Creative Commons: CC BY-SA 4.0 license". +* All content that resides under the "ee/" directory of this repository, if that directory exists, is licensed under the license defined in "ee/LICENSE". +* All content that resides under the "jh/" directory of this repository, if that directory exists, is licensed under the license defined in "jh/LICENSE". +* All client-side JavaScript (when served directly or after being compiled, arranged, augmented, or combined), is licensed under the "MIT Expat" license. +* All third party components incorporated into the GitLab Software are licensed under the original license provided by the owner of the applicable component. +* Content outside of the above mentioned directories or restrictions above is available under the "MIT Expat" license as defined below. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/NOTICE b/compliance-agent/rules/vendor/gitlab/NOTICE new file mode 100644 index 0000000..3e03ccd --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/NOTICE @@ -0,0 +1,38 @@ +GitLab SAST rules +================= + +Upstream: https://gitlab.com/gitlab-org/security-products/sast-rules +Commit: 53bf5cf6df3c51b6c02110f5a638b5e6213666cd +Version: v2.10.1 (2026-09-21) +Licence: MIT (per-file header `License: MIT (c) GitLab Inc.`) +Copyright: Copyright (c) 2011-present GitLab Inc. + +Prüfwerk runs these rules with its own semgrep invocation (--metrics=off, +local files only). upstream/ holds the selected files unchanged, with +their semgrep tests. pack.yaml is what the agent runs: the same rules with +ids prefixed by 'gitlab-', re-serialised into one file, without +the rules listed below. Both are produced by scripts/vendor-semgrep-rules.py. + +Selected from upstream: csharp/**, java/**, javascript/**, python/**, go/crypto/rule-tlsversion.* +Rules in the pack: 148 (from 149 files) + +Not selected: +- c/: every file is GPL-2.0 (generated from flawfinder), not MIT +- go/ except crypto/rule-tlsversion: Apache-2.0 ports of gosec, not MIT +- scala/: MIT, but no Scala in the products we scan +- rules/lgpl/: LGPL-3.0 (njsscan/mobsfscan); mobsfscan runs separately +- rules/lgpl-cc/: LGPL with Commons Clause +- rules/gitlab/: GitLab EE licence + +Left out +-------- + +- gitlab-javascript_xss_rule-mustache-escape (javascript/xss/rule-mustache-escape.yml): matches a Semgrep registry rule (provenance spot-check); not vendored +- gitlab-python_assert_rule-assert-used (python/assert/rule-assert-used.yml): 16 hits in psf/requests, all in tests; a plain `assert` is not a weakness in our customers' Python +- gitlab-python_crypto_rule-crypto-encrypt-ec (python/crypto/rule-crypto-encrypt-ec.yml): matches a Semgrep registry rule (provenance spot-check); not vendored +- gitlab-python_deserialization_rule-dill (python/deserialization/rule-dill.yml): matches a Semgrep registry rule (provenance spot-check); not vendored +- gitlab-python_deserialization_rule-marshal (python/deserialization/rule-marshal.yml): matches a Semgrep registry rule (provenance spot-check); not vendored +- gitlab-python_exec_rule-start-process-with-no-shell (python/exec/rule-start-process-with-no-shell.yml): matches a Semgrep registry rule (provenance spot-check); not vendored +- gitlab-python_exec_rule-subprocess-popen-shell-true (python/exec/rule-subprocess-popen-shell-true.yml): matches a Semgrep registry rule (provenance spot-check); not vendored +- gitlab-python_flask_rule-app-debug (python/flask/rule-app-debug.yml): matches a Semgrep registry rule (provenance spot-check); not vendored +- gitlab-python_ssh_rule-ssh-nohost-key-verification (python/ssh/rule-ssh-nohost-key-verification.yml): matches a Semgrep registry rule (provenance spot-check); not vendored diff --git a/compliance-agent/rules/vendor/gitlab/UPSTREAM b/compliance-agent/rules/vendor/gitlab/UPSTREAM new file mode 100644 index 0000000..f6fc640 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/UPSTREAM @@ -0,0 +1 @@ +https://gitlab.com/gitlab-org/security-products/sast-rules 53bf5cf6df3c51b6c02110f5a638b5e6213666cd diff --git a/compliance-agent/rules/vendor/gitlab/pack.yaml b/compliance-agent/rules/vendor/gitlab/pack.yaml new file mode 100644 index 0000000..a978c6e --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/pack.yaml @@ -0,0 +1,9453 @@ +# GitLab SAST rules, vendored by scripts/vendor-semgrep-rules.py; do not edit. +# Upstream: https://gitlab.com/gitlab-org/security-products/sast-rules at 53bf5cf6df3c51b6c02110f5a638b5e6213666cd +# Licence: MIT (per-file header `License: MIT (c) GitLab Inc.`); see LICENSE and NOTICE next to this file. +# Changed from upstream: ids prefixed with 'gitlab-', rules +# left out as listed in NOTICE, rules re-serialised into one file. +rules: + - id: gitlab-csharp_cookies_rule-CookieWithoutHttpOnlyFlag + languages: [csharp] + mode: taint + pattern-sources: + - pattern: 'var $COOKIE = new HttpCookie(...); + + ' + pattern-sinks: + - pattern: $COOKIE + pattern-sanitizers: + - pattern: $COOKIE.HttpOnly = true; + message: 'The `HttpOnly` attribute when set to `true` protects the cookie value from being accessed by + + client side JavaScript such + + as reading the `document.cookie` values. By enabling this protection, a website that is + + vulnerable to + + Cross-Site Scripting (XSS) will be able to block malicious scripts from accessing the cookie + + value from JavaScript. + + + Example of protecting an HttpCookie: + + ``` + + // Create an HttpOnly cookie. + + HttpCookie someCookie = new HttpCookie("SomeCookieName", "SomeValue"); + + someCookie.HttpOnly = true; + + ``` + + + For more information see: + + https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcookie.httponly + + + Session cookies should be configured with the following security directives: + + + - [HTTPOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + + - [Secure](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + + - [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) + + ' + severity: WARNING + metadata: + shortDescription: Sensitive cookie without 'HttpOnly' flag + category: security + owasp: + - A5:2017-Broken Access Control + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + cwe: CWE-1004 + security-severity: Low + - id: gitlab-csharp_cookies_rule-CookieWithoutSSLFlag + languages: [csharp] + mode: taint + pattern-sources: + - pattern: 'var $COOKIE = new HttpCookie(...); + + ' + pattern-sinks: + - pattern: $COOKIE + pattern-sanitizers: + - pattern: $COOKIE.Secure = true; + message: 'The `Secure` attribute when set to `true` protects the cookie value from being being + + transmitted over clear text + + communication paths such as HTTP. By enabling this protection, the cookie will only be sent + + over HTTPS. + + + Example of protecting an HttpCookie: + + ``` + + // Create an HttpOnly cookie. + + HttpCookie someCookie = new HttpCookie("SomeCookieName", "SomeValue"); + + someCookie.Secure = true; + + ``` + + + For more information see: + + https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcookie.secure + + + Session cookies should be configured with the following security directives: + + + - [HTTPOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + + - [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) + + - [Secure](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + + ' + severity: WARNING + metadata: + shortDescription: Sensitive cookie in HTTPS session without 'Secure' attribute + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + cwe: CWE-614 + security-severity: Low + - id: gitlab-csharp_crypto_rule-CertificateValidationDisabled + languages: [csharp] + patterns: + - pattern-inside: 'using System.Net; + + ... + + ' + - pattern: ServicePointManager.ServerCertificateValidationCallback += $CALLBACK; + - metavariable-pattern: + metavariable: $CALLBACK + patterns: + - pattern-either: + - pattern: $RETURNTYPE $FUNC(...) { return true; } + - pattern: (...) => true; + message: 'The `ServicePointManager.ServerCertificateValidationCallback` event has been set + + to always return `true`, which effectively disables the validation of server + + certificates. + + + This allows for an adversary who is in between the application and the target host to intercept + + potentially sensitive information or transmit malicious data. + + + Remove the callback function that is returning true to allow normal certificate validation to + + proceed. + + When no callback is provided, the client will validate that the certificate name matches the + + hostname + + that was used when creating the request. + + + For more information on the `ServerCertificateValidationCallback` property see: + + https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.servercertificatevalidationcallback + + ' + severity: WARNING + metadata: + shortDescription: Certificate validation disabled + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + cwe: CWE-295 + security-severity: Medium + - id: gitlab-csharp_crypto_rule-WeakCipherAlgorithm + languages: [csharp] + patterns: + - pattern-inside: 'using System.Security.Cryptography; + + ... + + ' + - pattern-either: + - pattern-regex: .*DES\.Create\(\); + - pattern: new DESCryptoServiceProvider(); + - pattern-regex: .*TripleDES\.Create\(\); + - pattern: new TripleDESCryptoServiceProvider(); + - pattern-regex: .*RC2\.Create\(\); + - pattern: new RC2CryptoServiceProvider(); + message: "DES, TripleDES and RC2 are all considered broken or insecure cryptographic algorithms.\nIf using\ + \ .NET Framework greater than version 6.0 consider using `ChaCha20Poly1305`\ninstead as it is easier\ + \ and faster than the alternatives such as `AES-256-GCM`.\n\nFor older applications, `AES-256-GCM` is\ + \ recommended, however it has many drawbacks:\n- Slower than `ChaCha20Poly1305`.\n- Catastrophic failure\ + \ if nonce values are reused.\n\nExample using `ChaCha20Poly1305`:\n```\n// Generate a random key\n\ + byte[] key = new byte[32];\nRandomNumberGenerator.Fill(key);\n\n// Note nonce values _must_ be regenerated\ + \ every time they are used.\nbyte[] nonce = new byte[12];\nRandomNumberGenerator.Fill(nonce);\n\nbyte[]\ + \ authTag = new byte[16];\nbyte[] cipherText;\n\nusing (ChaCha20Poly1305 encryptor = new ChaCha20Poly1305(key))\n\ + {\n byte[] plainText = System.Text.Encoding.UTF8.GetBytes(\"Secret text to encrypt\");\n cipherText\ + \ = new byte[plainText.Length];\n encryptor.Encrypt(nonce, plainText, cipherText, authTag);\n}\n\n\ + using (ChaCha20Poly1305 decryptor = new ChaCha20Poly1305(key))\n{\n byte[] output = new byte[cipherText.Length];\n\ + \ decryptor.Decrypt(nonce, cipherText, authTag, output);\n Console.WriteLine(\"Output: {0}\",\ + \ System.Text.Encoding.UTF8.GetString(output));\n}\n```\n\nExample using `AES-256-GCM`:\n```\n// Generate\ + \ a random key\nbyte[] key = new byte[32];\nRandomNumberGenerator.Fill(key);\n\n// Note nonce values\ + \ _must_ be regenerated every time they are used.\nbyte[] nonce = new byte[AesGcm.NonceByteSizes.MaxSize];\n\ + RandomNumberGenerator.Fill(nonce);\n\nbyte[] authTag = new byte[AesGcm.TagByteSizes.MaxSize];\nbyte[]\ + \ cipherText;\n\nusing (AesGcm encryptor = new AesGcm(key))\n{\n byte[] plainText = Encoding.UTF8.GetBytes(\"\ + Secret text to encrypt\");\n cipherText = new byte[plainText.Length];\n encryptor.Encrypt(nonce,\ + \ plainText, cipherText, authTag);\n}\n\nusing (AesGcm decryptor = new AesGcm(key))\n{\n byte[] output\ + \ = new byte[cipherText.Length];\n decryptor.Decrypt(nonce, cipherText, authTag, output);\n Console.WriteLine(\"\ + Output: {0}\", Encoding.UTF8.GetString(output));\n}\n```\n" + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + cwe: CWE-327 + security-severity: Medium + - id: gitlab-csharp_crypto_rule-WeakCipherMode + languages: [csharp] + patterns: + - pattern-inside: 'using System.Security.Cryptography; + + ... + + ' + - metavariable-regex: + metavariable: $CIPHER + regex: ^(ECB|CBC|OFB|CFB|CTS)$ + - pattern: CipherMode.$CIPHER + message: "Cryptographic algorithms provide many different modes of operation, only some of which provide\n\ + message integrity. Without message integrity it could be possible for an adversary to attempt\nto tamper\ + \ with the ciphertext which could lead to compromising the encryption key. Newer\nalgorithms\napply\ + \ message integrity to validate ciphertext has not been tampered with.\n\nInstead of using an algorithm\ + \ that requires configuring a `CipherMode`, an algorithm\nthat has built-in message integrity should\ + \ be used. If using .NET Framework greater\nthan version 6.0 consider using `ChaCha20Poly1305` or `AES-256-GCM`.\n\ + \nFor older applications, `AES-256-GCM` is recommended, however it has many drawbacks:\n- Slower than\ + \ `ChaCha20Poly1305`.\n- Catastrophic failure if nonce values are re-used.\n\nExample using `ChaCha20Poly1305`:\n\ + ```\n// Generate a random key\nbyte[] key = new byte[32];\nRandomNumberGenerator.Fill(key);\n\nChaCha20Poly1305\ + \ encryptor = new ChaCha20Poly1305(key);\n\n// Note nonce values _must_ be regenerated every time they\ + \ are used.\nvar nonce = new byte[12];\nRandomNumberGenerator.Fill(nonce);\n\nbyte[] plainText = System.Text.Encoding.UTF8.GetBytes(\"\ + Secret text to encrypt\");\nbyte[] cipherText = new byte[plainText.Length];\nvar authTag = new byte[16];\n\ + \nencryptor.Encrypt(nonce, plainText, cipherText, authTag);\nbyte[] output = new byte[cipherText.Length];\n\ + encryptor.Decrypt(nonce, cipherText, authTag, output);\nConsole.WriteLine(\"Output: {0}\", System.Text.Encoding.UTF8.GetString(output));\n\ + ```\n\nExample using `AES-256-GCM`:\n```\nvar plaintextBytes = Encoding.UTF8.GetBytes(\"Secret text\ + \ to encrypt\");\nvar key = new byte[32];\nRandomNumberGenerator.Fill(key);\n\nusing var aes = new AesGcm(key);\n\ + var nonce = new byte[AesGcm.NonceByteSizes.MaxSize];\nRandomNumberGenerator.Fill(nonce);\n\nvar cipherText\ + \ = new byte[plaintextBytes.Length];\nvar tag = new byte[AesGcm.TagByteSizes.MaxSize];\n\naes.Encrypt(nonce,\ + \ plaintextBytes, cipherText, tag);\n\n// Decrypt\nusing (var decrypt = new AesGcm(key))\n{\n var\ + \ decryptedBytes = new byte[cipherText.Length];\n\n decrypt.Decrypt(nonce, cipherText, tag, decryptedBytes);\n\ + \n Console.WriteLine(\"Decrypted: {0}\", Encoding.UTF8.GetString(decryptedBytes));\n}\n```\n" + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + cwe: CWE-327 + security-severity: Medium + - id: gitlab-csharp_crypto_rule-WeakHashingFunction + languages: [csharp] + patterns: + - pattern-either: + - patterns: + - metavariable-regex: + metavariable: $HASH_PROVIDER + regex: ^(SHA1CryptoServiceProvider|MD5CryptoServiceProvider)$ + - pattern: new $HASH_PROVIDER + - patterns: + - metavariable-regex: + metavariable: $HASH_CLASS + regex: ^System.Security.Cryptography.(SHA1|MD5)$ + - pattern: $HASH_CLASS.$METHOD(); + message: "Both MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions.\n\ + This means\nthat two different values, when hashed, can lead to the same hash value. If the application\ + \ is\ntrying\nto use these hash methods for storing passwords, then it is recommended to switch to a\n\ + password hashing\nalgorithm such as Argon2id or PBKDF2. Currently there is no vetted Argon2id implementation\ + \ for\nC# so\nit is recommended that PBKDF2 be used until one is available.\n\nExample using PBKDF2\ + \ to generate and compare passwords:\n```\nconst int SaltSize = 24;\nconst int HashSize = 24;\n// number\ + \ of pbkdf2 iterations, Rfc2898DeriveBytes uses hmac-sha1\n// so set a high iteration count\nconst int\ + \ Iterations = 1_300_000;\nbyte[] salt = new byte[SaltSize];\nRandomNumberGenerator.Fill(salt);\n\n\ + Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(\"some password\", salt, Iterations);\nbyte[] hashBytes\ + \ = pbkdf2.GetBytes(HashSize);\n// Store salt and hashedBytes in a data store such as database for authentication\n\ + Console.WriteLine(\"Hash {0}\", BitConverter.ToString(hashBytes).Replace(\"-\", \"\"));\n// Do a constant\ + \ time comparison as to not leak data based on timing\nif (CryptographicOperations.FixedTimeEquals(hashBytes,\ + \ hashBytes)) {\n Console.WriteLine(\"hashes are equal\");\n}\n```\nFor more information on PBKDF2\ + \ see:\nhttps://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes\n\ + \nFor more information on secure password storage see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html\n" + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm (SHA1/MD5) + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + cwe: CWE-327 + security-severity: Medium + - id: gitlab-csharp_crypto_rule-WeakRNG + languages: [csharp] + patterns: + - pattern: (Random $RNG).$METHOD(...); + - focus-metavariable: $RNG + message: 'Depending on the context, generating weak random numbers may expose cryptographic functions + + which rely on these numbers to be exploitable. When generating numbers for sensitive values + + such as tokens, nonces, and cryptographic keys, it is recommended that the + + `RandomNumberGenerator` class be used. + + + Example `RandomNumberGenerator` usage: + + ``` + + Int32 randInt = RandomNumberGenerator.GetInt32(32000); + + byte[] randomBytes = new byte[64]; + + RandomNumberGenerator.Fill(randomBytes); + + Console.WriteLine("Random Int32: {0}", randInt); + + Console.WriteLine("Random Bytes: {0}", BitConverter.ToString(randomBytes).Replace("-", "")); + + ``` + + + For more information see: + + https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator + + ' + severity: WARNING + metadata: + shortDescription: Use of cryptographically weak Pseudo-Random Number Generator (PRNG) + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + cwe: CWE-338 + security-severity: Medium + - id: gitlab-csharp_csrf_rule-Csrf + languages: [csharp] + patterns: + - pattern: "[$HTTPMETHOD]\npublic $RET $FOO(...) {\n ...\n}\n" + - pattern-not: "[ValidateAntiForgeryToken]\npublic $RET $FOO(...) {\n ...\n}\n" + - pattern-not-inside: "[AutoValidateAntiforgeryToken]\nclass $CLASS{\n ...\n}\n" + - pattern-not-inside: "[ValidateAntiForgeryToken]\nclass $CLASS{\n ...\n}\n" + - metavariable-regex: + metavariable: $HTTPMETHOD + regex: Http(Post|Delete|Patch|Put) + message: 'The application failed to protect against Cross-Site Request Forgery (CSRF) + + due to not including the `[ValidateAntiForgeryToken]` attribute on an + + HTTP method handler that could change user state (usually in the form of POST or PUT + + methods). + + + The vulnerability can be exploited by an adversary creating a link or form on a third + + party site and tricking an authenticated victim to access them. + + + Add the `[ValidateAntiForgeryToken]` to all methods which take in user data and change + + user state (such as updating a database with a new value). This is especially true for + + functionality such as updating passwords or other security sensitive functions. + + + Alternatively, applications can enable a global + + [AutoValidateAntiforgeryTokenAttribute](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.autovalidateantiforgerytokenattribute) + + filter. + + + For more information on ValidateAntiForgeryToken and other CSRF protections in .NET + + see the following URL: + + https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery + + + Additionally, consider setting all session cookies to have the `SameSite=Strict` attribute. + + It should be noted that this may impact usability when sharing links across other mediums. + + It is recommended that a two cookie based approach is taken, as outlined in the + + [Top level + + navigations](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-08#section-8.8.2) + + section + + of the SameSite RFC. + + + For more information on CSRF see OWASP''s guide: + + https://owasp.org/www-community/attacks/csrf + + ' + severity: WARNING + metadata: + shortDescription: Potential Cross-Site Request Forgery (CSRF) + category: security + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + cwe: CWE-352 + security-severity: Medium + - id: gitlab-csharp_deserialization_rule-InsecureDeserialization + languages: [csharp] + mode: taint + pattern-sources: + - pattern: Request.Cookies[...] + - pattern: Request.Cookies.Get(...) + - pattern: Request.Form[...] + - pattern: Request.Form.Get(...) + - pattern: Request.Headers[...] + - pattern: Request.Headers.Get(...) + - pattern: Request.QueryString[...] + - pattern: Request.QueryString.Get(...) + - pattern: Request.Body + - pattern: $CTX.Request.Cookies[...] + - pattern: $CTX.Request.Cookies.Get(...) + - pattern: $CTX.Request.Form[...] + - pattern: $CTX.Request.Form.Get(...) + - pattern: $CTX.Request.Headers[...] + - pattern: $CTX.Request.Headers.Get(...) + - pattern: $CTX.Request.QueryString[...] + - pattern: $CTX.Request.QueryString.Get(...) + - pattern: $CTX.Request.Body + - pattern: System.IO.File.ReadAllText(...) + - pattern: System.IO.File.ReadAllTextAsync(...) + - pattern: System.IO.File.ReadAllLines(...) + - pattern: System.IO.File.ReadAllLinesAsync(...) + - pattern: System.IO.File.ReadAllBytes(...) + - pattern: System.IO.File.ReadAllBytesAsync(...) + - pattern: System.IO.File.ReadLines(...) + - pattern: System.IO.File.ReadLinesAsync(...) + - pattern: System.Environment.GetEnvironmentVariable(...) + pattern-sinks: + - pattern: (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $OBJ).Deserialize(...) + - pattern: (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $OBJ).UnsafeDeserialize(...) + - pattern: (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $OBJ).UnsafeDeserializeMethod(...) + - pattern: (System.Runtime.Serialization.Formatters.Soap.SoapFormatter $OBJ).Deserialize(...) + - pattern: (System.Runtime.Serialization.NetDataContractSerializer $OBJ).Deserialize(...) + - pattern: (System.Web.UI.LosFormatter $OBJ).Deserialize(...) + message: "Deserialization attacks exploit the process of reading serialized data and turning it back into\ + \ an\nobject. By constructing malicious objects and serializing them, an adversary may attempt to:\n\ + \n- Inject code that is executed upon object construction, which occurs during the deserialization process.\n\ + - Exploit mass assignment by including fields that are not normally a part of the serialized data but\ + \ are\n read in during deserialization.\n\nMicrosoft recommends no longer using the following serialization\ + \ formats:\n\n- BinaryFormatter\n- SoapFormatter\n- NetDataContractSerializer\n- LosFormatter\n- ObjectStateFormatter\n\ + \nConsider safer alternatives such as serializing data in the JSON format. Ensure any format chosen\ + \ allows\nthe application to specify exactly which object types are allowed to be deserialized. Additionally,\ + \ when\ndeserializing, never deserialize to base object types like `Object` and only cast to the exact\ + \ object\ntype that is expected.\n\nTo protect against mass assignment, only allow deserialization of\ + \ the specific fields that are required.\nIf this is not easily done, consider creating an intermediary\ + \ type that can be serialized with only the\nnecessary fields exposed.\n\nFor more information see Microsoft's\ + \ deserialization security guide:\nhttps://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide\n\ + \nFor more details on deserialization attacks in general, see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n\ + \nIt should be noted that [tools exist](https://github.com/pwntester/ysoserial.net) to automatically\ + \ create\nexploit code for these vulnerabilities.\n" + metadata: + shortDescription: Deserialization of potentially untrusted data + category: security + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + - A08:2025-Software or Data Integrity Failures + security-severity: High + severity: WARNING + - id: gitlab-csharp_endpoint_rule-UnvalidatedRedirect + languages: [csharp] + mode: taint + pattern-sources: + - patterns: + - pattern: $SRC + - pattern-inside: 'public $RET $FUNC(...,$SRC,...){...} + + ' + - patterns: + - pattern: $SRC + - pattern-inside: 'if (Uri.TryCreate(..., ..., $SRC)){ + + ... + + } + + ' + pattern-sanitizers: + - pattern: Url.Action(...) + - pattern: Url.HttpRouteUrl(...) + - pattern: Url.RouteUrl(...) + pattern-sinks: + - patterns: + - pattern-either: + - patterns: + - pattern-either: + - pattern: return $METHOD(...) + - pattern: return new $METHOD(...) + - pattern: "if (!Url.IsLocalUrl(...)) {\n ...\n return $METHOD(...)\n}\n" + - patterns: + - pattern-not-inside: "if (Url.IsLocalUrl(...)) {\n ...\n}\n" + - pattern-not-inside: "if (!Url.IsLocalUrl(...)) {\n return $X\n}\n...\n" + - pattern-either: + - pattern: $METHOD(...) + - pattern: new $METHOD(...) + - metavariable-pattern: + metavariable: $METHOD + pattern-either: + - pattern: Redirect + - pattern: RedirectPermanent + - pattern: RedirectToRoute + - pattern: RedirectToRoutePermanent + - pattern: RedirectResult + message: 'The application may allow open redirects if created using user supplied input. Open redirects + + are + + commonly + + abused in phishing attacks where the original domain or URL looks like a legitimate link, but + + then + + redirects a user to a malicious site. An example would be + + `https://example.com/redirect?url=https://%62%61%64%2e%63%6f%6d%2f%66%61%6b%65%6c%6f%67%69%6e` + + which, + + when decoded, turns into `bad.com/fakelogin`. + + + Never redirect a client based on user input. It is recommended that the list of target links + + to + + redirect a user to are contained server side, and retrieved using a numerical value + + as an index to return the link to be redirected to. For example, `/redirect?id=1` would cause + + the + + application to look up the `1` index and return a URL such as `https://example.com`. This URL + + would + + then be used to redirect the user, using the 301 response code and `Location` header. + + + For more information on open redirects see OWASP''s guide: + + https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html + + ' + metadata: + shortDescription: URL redirection to untrusted site 'open redirect' + category: security + owasp: + - A1:2017-Injection + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + cwe: CWE-601 + security-severity: Info + severity: WARNING + - id: gitlab-csharp_injection_rule-CommandInjection + languages: [csharp] + patterns: + - pattern-either: + - patterns: + - pattern-inside: '... + + (System.Diagnostics.Process $PROC).Start(...); + + ' + - pattern-either: + - patterns: + - pattern: (System.Diagnostics.Process $PROC).StartInfo.FileName = <...$ARG...>; + - pattern-not: (System.Diagnostics.Process $PROC).StartInfo.FileName = "..."; + - patterns: + - pattern: (System.Diagnostics.Process $PROC).StartInfo.Arguments = <...$ARG...>; + - pattern-not: (System.Diagnostics.Process $PROC).StartInfo.Arguments = "..."; + - patterns: + - pattern: System.Diagnostics.Process.Start($ARG); + - pattern-not: System.Diagnostics.Process.Start("..."); + - patterns: + - pattern-not: $PSINFO.Arguments = "..."; + - pattern-not: $PSINFO.FileName = "..."; + - pattern-not: new System.Diagnostics.ProcessStartInfo("..."); + - pattern-not: new System.Diagnostics.ProcessStartInfo(); + - pattern-either: + - pattern: new System.Diagnostics.ProcessStartInfo(...); + - pattern: $PSINFO.Arguments = <...$ARG...>; + - pattern: $PSINFO.FileName = <...$ARG...>; + - patterns: + - pattern-inside: 'new System.Diagnostics.ProcessStartInfo{ + + ... + + } + + ' + - pattern-not: Arguments = "..." + - pattern-not: FileName = "..." + - pattern-either: + - pattern: Arguments = ... + - pattern: FileName = ... + message: "OS command injection is a critical vulnerability that can lead to a full system\ncompromise\ + \ as it may allow an adversary to pass in arbitrary commands or arguments\nto be executed.\n\nUser input\ + \ should never be used in constructing commands or command arguments\nto functions which execute OS\ + \ commands. This includes filenames supplied by\nuser uploads or downloads.\n\nEnsure your application\ + \ does not:\n\n- Use user-supplied information in the process name to execute.\n- Use user-supplied\ + \ information in an OS command execution function which does\nnot escape shell meta-characters.\n- Use\ + \ user-supplied information in arguments to OS commands.\n\nThe application should have a hardcoded\ + \ set of arguments that are to be passed\nto OS commands. If filenames are being passed to these functions,\ + \ it is\nrecommended that a hash of the filename be used instead, or some other unique\nidentifier.\ + \ It is strongly recommended that a native library that implements\nthe same functionality be used instead\ + \ of using OS system commands, due to the\nrisk of unknown attacks against third party commands.\n\n\ + When specifying the OS command, ensure the application uses the full path\ninformation, otherwise the\ + \ OS may attempt to look up which process to execute\nand could be vulnerable to untrusted search path\ + \ vulnerabilities (CWE-426).\n\nExample of safely executing an OS command:\n```\npublic void ExecuteCommand(string\ + \ userFileData) {\n // generate a random filename, do not using user input\n string fileName =\ + \ \"C:\\\\Temp\\\\\" + Guid.NewGuid();\n File.WriteAllText(fileName, userFileData);\n\n using\ + \ (Process process = new Process())\n {\n // hardcode the full process path\n ProcessStartInfo\ + \ processInfo = new ProcessStartInfo(\"C:\\\\App\\\\FileReader.exe\");\n // only pass in trust\ + \ arguments, and never direct user input.\n processInfo.Arguments = fileName;\n processInfo.UseShellExecute\ + \ = false;\n process.StartInfo = processInfo;\n process.Start();\n }\n}\n```\n\nFor\ + \ more information on OS command injection, see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html\n" + severity: ERROR + metadata: + shortDescription: Improper neutralization of special elements used in an OS command ('OS Command Injection') + category: security + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + cwe: CWE-78 + security-severity: High + - id: gitlab-csharp_injection_rule-LdapInjection + languages: [csharp] + mode: taint + pattern-sources: + - patterns: + - pattern-inside: '$RET $METHOD(...,$VAR,...){...} + + ' + - pattern: $VAR + pattern-sinks: + - pattern: System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(...) + - pattern: new System.DirectoryServices.DirectoryEntry(...) + - pattern: new System.DirectoryServices.DirectorySearcher(...) + - pattern: new System.DirectoryServices.Protocols.SearchRequest(...) + - patterns: + - focus-metavariable: $TAINTED + - pattern-either: + - pattern: (System.DirectoryServices.DirectoryEntry $SOURCE).Path = $TAINTED + - pattern: (System.DirectoryServices.DirectorySearcher $SEARCHER).Filter = $TAINTED + - pattern: (System.DirectoryServices.Protocols.SearchRequest $SEARCHREQ).Filter = $TAINTED + - pattern: (System.DirectoryServices.Protocols.SearchRequest $SEARCHREQ).DistinguishedName = $TAINTED + - pattern: (System.DirectoryServices.AccountManagement.UserPrincipal $SEARCHREQ).$PROP = $TAINTED + message: "LDAP injection attacks exploit LDAP queries to influence how data is returned by\nthe LDAP,\ + \ or in this case an Active Directory server.\n\nIt is recommended that newer applications use the `System.DirectoryServices.AccountManagement`\n\ + API instead of `DirectorySearcher` API as it hides the complexity of querying LDAP directly.\nHowever,\n\ + the `AccountManagement` API is still susceptible to LDAP injection if a user inputs LDAP\nqueries,\n\ + including LDAP filter characters such as `*`.\n\nIt is recommended that all input passed to LDAP querying\ + \ systems encode the following values:\n\n- Any occurrence of the null character must be escaped as\ + \ “\\00”.\n- Any occurrence of the open parenthesis character must be escaped as “\\28”.\n- Any occurrence\ + \ of the close parenthesis character must be escaped as “\\29”.\n- Any occurrence of the asterisk character\ + \ must be escaped as “\\2a”.\n- Any occurrence of the backslash character must be escaped as “\\5c”.\n\ + \nExample code that safely encodes input for use in an LDAP query using the `AccountManagement`\nAPI:\n\ + ```\nusing System.DirectoryServices.AccountManagement;\n\nstring EncodeLDAPString(string input) {\n\ + \ // Note the \\ character is replaced first\n char[] chars = new char[] { '\\\\', '\\0', '(',\ + \ ')', '*' };\n string[] encoded = new string[] { \"\\\\5c\", \"\\\\00\", \"\\\\28\", \"\\\\29\"\ + , \"\\\\2a\" };\n\n for (int i = 0; i < chars.Length; i++)\n {\n input = input.Replace(chars[i].ToString(),\ + \ encoded[i]);\n }\n\n return input;\n}\n\n// unsafe, do not use without encoding first\nstring\ + \ userInput = \"Administrator\";\nPrincipalContext AD = new PrincipalContext(ContextType.Domain, \"\ + ad.example.dev\");\n\nUserPrincipal u = new UserPrincipal(AD);\nstring encodedUserName = EncodeLDAPString(userInput);\n\ + \n// The AD search term, encoded prior to calling search\nu.SamAccountName = encodedUserName;\n\n//\ + \ Search for user\nPrincipalSearcher search = new PrincipalSearcher(u);\n\n// Use FindOne to only return\ + \ a single result\nUserPrincipal result = (UserPrincipal)search.FindOne();\nsearch.Dispose();\n\n//\ + \ show some details\nif (result != null) {\n Console.WriteLine(\"User: {0}\", result.DisplayName);\n\ + } else {\n Console.WriteLine(\"user not found\");\n}\n```\n\nThe same encoding method shown in `EncodeLDAPString`\ + \ can also be used when using the\nolder `DirectorySearcher` API.\n\nFor more information see OWASP's\ + \ guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html\n" + severity: WARNING + metadata: + shortDescription: Improper neutralization of special elements used in an LDAP query ('LDAP Injection') + category: security + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + cwe: CWE-90 + security-severity: Medium + - id: gitlab-csharp_injection_rule-SQLInjection + languages: [csharp] + patterns: + - pattern-either: + - patterns: + - metavariable-pattern: + metavariable: $FUNC + pattern-either: + - pattern: SqlQuery + - pattern: ExecuteSqlCommand + - pattern: ExecuteSqlCommandAsync + - pattern: ExecuteSqlRaw + - pattern: ExecuteSqlRawAsync + - pattern: FromSqlRaw + - pattern: FromSql + - pattern: GetSqlStringCommand + - pattern: ExecuteDataSet + - pattern: ExecuteReader + - pattern: ExecuteNonQuery + - pattern: ExecuteScalar + - pattern: CreateSQLQuery + - pattern-either: + - pattern: $DB.$FUNC($ARG, ...) + - pattern: $DB.$FUNC<$CC>($ARG, ...) + - pattern-not: $DB.$FUNC("...", ...) + - pattern-not: $DB.$FUNC<$CC>("...", ...) + - patterns: + - pattern-inside: 'using System.Data.Linq; + + ... + + ' + - pattern-either: + - patterns: + - pattern: (DataContext $CTX).ExecuteQuery<$TRESULT>($ARG, ...) + - pattern-not: (DataContext $CTX).ExecuteQuery<$TRESULT>("...", ...) + - patterns: + - pattern: (DataContext $CTX).ExecuteQuery($TYPE, $ARG, ...) + - pattern-not: (DataContext $CTX).ExecuteQuery($TYPE, "...", ...) + - patterns: + - pattern: (DataContext $CTX).ExecuteCommand($ARG, ...) + - pattern-not: (DataContext $CTX).ExecuteCommand("...", ...) + - patterns: + - metavariable-pattern: + metavariable: $IMPL + pattern-either: + - pattern: SqlCommand + - pattern: OracleCommand + - pattern: NpgsqlCommand + - pattern: MySqlCommand + - pattern: EntityCommand + - pattern: OdbcCommand + - pattern: OleDbCommand + - pattern: SqliteCommand + - pattern-either: + - patterns: + - pattern: new $IMPL($ARG, ...); + - pattern-not: new $IMPL("...", ...); + - patterns: + - pattern: ($IMPL $CMD).CommandText = <...$ARG...>; + - pattern-not: ($IMPL $CMD).CommandText = "..."; + - patterns: + - metavariable-pattern: + metavariable: $FUNC + pattern-either: + - pattern: ExecuteDataRow + - pattern: ExecuteDataRowAsync + - pattern: ExecuteDataset + - pattern: ExecuteDatasetAsync + - pattern: ExecuteNonQuery + - pattern: ExecuteNonQueryAsync + - pattern: ExecuteReader + - pattern: ExecuteReaderAsync + - pattern: ExecuteScalar + - pattern: ExecuteScalarAsync + - pattern: UpdateDataSet + - pattern: UpdateDataSetAsync + - pattern-inside: 'using MySql.Data.MySqlClient; + + ... + + ' + - pattern: MySqlHelper.$FUNC($CONN, $ARG, ...) + - pattern-not: MySqlHelper.$FUNC($CONN, "...", ...) + - patterns: + - pattern-inside: 'using Cassandra; + + ... + + ' + - pattern-not: $SESS.Execute("...", ...) + - pattern-either: + - pattern: (Session $SESS).Execute($ARG, ...) + - patterns: + - pattern-inside: 'var $SESS = $CLUSTER.Connect(...); + + ... + + ' + - pattern: $SESS.Execute($ARG, ...) + message: "SQL Injection is a critical vulnerability that can lead to data or system compromise. By\ndynamically\ + \ generating SQL query strings, user input may be able to influence the logic of\nthe SQL statement.\ + \ This could lead to an adversary accessing information they should\nnot have access to, or in some\ + \ circumstances, being able to execute OS functionality or code.\n\nReplace all dynamically generated\ + \ SQL queries with parameterized queries. In situations where\ndynamic queries must be created, never\ + \ use direct user input, but instead use a map or\ndictionary of valid values and resolve them using\ + \ a user supplied key.\n\nFor example, some database drivers do not allow parameterized queries for\ + \ `>` or `<` comparison\noperators. In these cases, do not use a user supplied `>` or `<` value, but\ + \ rather have the\nuser\nsupply a `gt` or `lt` value. The alphabetical values are then used to look\ + \ up the `>` and `<`\nvalues to be used in the construction of the dynamic query. The same goes for\ + \ other queries\nwhere\ncolumn or table names are required but cannot be parameterized.\n\nExample using\ + \ parameterized queries with `SqlCommand`:\n```\nstring userInput = \"someUserInput\";\nstring connectionString\ + \ = ...;\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n connection.Open();\n\ + \ String sql = \"SELECT name, value FROM table where name=@Name\";\n\n using (SqlCommand command\ + \ = new SqlCommand(sql, connection))\n {\n command.Parameters.Add(\"@Name\", System.Data.SqlDbType.NVarChar);\n\ + \ command.Parameters[\"@Name\"].Value = userInput;\n using (SqlDataReader reader = command.ExecuteReader())\n\ + \ {\n while (reader.Read())\n {\n Console.WriteLine(\"{0}\ + \ {1}\", reader.GetString(0), reader.GetString(1));\n }\n }\n }\n}\n```\n\nFor\ + \ more information on SQL Injection see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\n" + severity: WARNING + metadata: + shortDescription: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') + category: security + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + cwe: CWE-89 + security-severity: Medium + - id: gitlab-csharp_injection_rule-XPathInjection + languages: [csharp] + patterns: + - pattern-inside: 'using System.Xml; + + ... + + ' + - pattern-either: + - patterns: + - metavariable-regex: + metavariable: $FUNC + regex: ^(SelectNodes|SelectSingleNode|Compile|Evaluate|Matches|Select|SelectAncestors|SelectChildren|SelectDescendants)$ + - metavariable-regex: + metavariable: $TY + regex: ^(XPathNavigator|XmlDocument|XmlNode|XmlDocumentXPathExtensions)$ + - pattern: ($TY $VAR).$FUNC(<...$ARG...>, ...) + - pattern-not: ($TY $VAR).$FUNC("...", ...) + - patterns: + - pattern-inside: 'using System.Xml.Linq; + + ... + + ' + - metavariable-regex: + metavariable: $FUNC + regex: ^(XPathEvaluate|XPathSelectElement|XPathSelectElements)$ + - pattern: $VAR.$FUNC(<...$ARG...>, ...) + - pattern-not: $VAR.$FUNC("...", ...) + - patterns: + - pattern-inside: 'using System.Xml.Schema; + + ... + + ' + - pattern-either: + - patterns: + - pattern: $VAR.XPath = <...$ARG...>; + - pattern-not: $VAR.XPath = "..." + - patterns: + - pattern: new XmlSchemaXPath { XPath = <...$ARG...> }; + - focus-metavariable: $ARG + message: "XPath injection is a vulnerability that can allow an adversary to inject or modify how an XML\n\ + query\nis structured. Depending on the logic of the original query, this could lead to adversaries\n\ + extracting unauthorized information or in rare cases bypassing authorization checks.\n\nIt is recommended\ + \ that LINQ to XML is used instead of XPath for querying XML documents. Care\nmust be taken to **not**\ + \ call these LINQ functions with user input as they can still lead to\nXPath\ninjection:\n\n- `XPathEvaluate`\n\ + - `XPathSelectElement`\n- `XPathSelectElements`\n\nExample using LINQ to XML to safely extract the first\ + \ user from a list of users:\n```\n// XDocument is safe from XXE attacks as the resolver is disabled\ + \ by default\nXDocument doc = XDocument.Load(\"users.xml\");\nXNamespace ns = \"urn:users-schema\";\n\ + \nstring userInput = \"LastName\";\n\n// Get all the users.\nvar user = doc.Descendants(ns + \"user\"\ + )\n .Select(u => new {\n FirstName = (string)u.Element(ns + \"first-name\"\ + ),\n LastName = (string)u.Element(ns + \"last-name\")\n }).Where(u =>\ + \ u.LastName == userInput).FirstOrDefault();\n\nConsole.WriteLine(user.FirstName + \" \" + user.LastName);\n\ + ```\n\nFor more information on LINQ to XML security see:\nhttps://learn.microsoft.com/en-us/dotnet/standard/linq/linq-xml-security\n\ + \nFor more information on XML security see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net\n" + severity: INFO + metadata: + shortDescription: Improper neutralization of data within XPath expressions ('XPath Injection') + category: security + cwe: CWE-643 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + security-severity: Medium + - id: gitlab-csharp_injection_rule-XmlDocumentXXEInjection + languages: [csharp] + mode: taint + pattern-sinks: + - patterns: + - pattern-not-inside: '(XmlDocument $DOC).XmlResolver = null; + + ... + + ' + - pattern-either: + - pattern: (XmlDocument $DOC).Load(...); + - pattern: (XmlDocument $DOC).LoadXml(...); + pattern-sources: + - pattern: var $DOC = new System.Xml.XmlDocument(...); + - patterns: + - pattern: var $DOC = new System.Xml.XmlDocument {...}; + - pattern-not: var $DOC = new System.Xml.XmlDocument {...,XmlResolver = null,...}; + message: 'External XML entities are a feature of XML parsers that allow documents to contain references + + to + + other documents or data. This feature can be abused to read files, communicate with external + + hosts, + + exfiltrate data, or cause a Denial of Service (DoS). + + + XML parsers and document loaders must be configured to not resolve entities. This can be done + + by: + + - Ensuring you are running a version of .NET Framework greater than 4.5.2 (released in 2014). + + - Using `XDocument` which disables entity resolution and is generally safe from DoS. + + - Setting `XmlDocument`''s `XmlResolver` to null. + + + Example of safely loading an XML file using `XmlDocument`: + + ``` + + XmlDocument document = new XmlDocument(); + + document.XmlResolver = null; + + document.Load("users.xml"); + + ``` + + + For more information on XML security, see OWASP''s guide: + + https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net + + ' + severity: WARNING + metadata: + shortDescription: Improper restriction of XML external entity reference ('XXE') + category: security + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + security-severity: Medium + - id: gitlab-csharp_injection_rule-XmlReaderXXEInjection + languages: [csharp] + mode: taint + pattern-sinks: + - patterns: + - pattern-either: + - pattern-inside: '$SETTINGS.ProhibitDtd = false; + + ... + + ' + - pattern-inside: '$SETTINGS.DtdProcessing = DtdProcessing.Parse; + + ... + + ' + - pattern: System.Xml.XmlReader.Create(..., $SETTINGS); + pattern-sources: + - pattern: var $SETTINGS = new XmlReaderSettings(); + message: 'External XML entities are a feature of XML parsers that allow documents to contain references + + to + + other documents or data. This feature can be abused to read files, communicate with external + + hosts, + + exfiltrate data, or cause a Denial of Service (DoS). + + + XML parsers and document loaders must be configured to not resolve entities. This can be done + + by: + + - Ensuring you are running a version of .NET Framework greater than 4.5.2 (released in 2014). + + - Setting `XmlTextReader`''s `ProhibitDtd` to `true` + + - Setting `XmlReaderSettings` `DtdProcessing` to `DtdProcessing.Prohibit` + + + Example of safely loading an XML file using `XmlDocument`: + + ``` + + var settings = new XmlReaderSettings(); + + settings.DtdProcessing = DtdProcessing.Prohibit; + + XmlReader reader = XmlReader.Create(path, settings); + + ``` + + + For more information on XML security, see OWASP''s guide: + + https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net + + ' + severity: WARNING + metadata: + shortDescription: Improper restriction of XML external entity reference ('XXE') + category: security + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + security-severity: MEDIUM + - id: gitlab-csharp_other_rule-UnsafeXSLTSettingUsed + languages: [csharp] + patterns: + - pattern-either: + - patterns: + - pattern: new XsltSettings() {...,$OPTIONS,...}; + - metavariable-pattern: + metavariable: $OPTIONS + pattern-either: + - pattern: EnableDocumentFunction = true + - pattern: EnableScript = true + - patterns: + - pattern: $SETTINGS.$OPT = true; + - pattern: 'var $SETTINGS = new XsltSettings(); + + ... + + $SETTINGS.$OPT = true; + + ' + - metavariable-pattern: + metavariable: $OPT + pattern-either: + - pattern: EnableDocumentFunction + - pattern: EnableScript + message: 'By setting `XsltSettings.EnableScript` to true, an adversary who is able to influence the + + loaded + + XSL document could directly inject code to compromise the system. It is strongly + + recommended that an alternative approach is used to work with XML data. + + + For increased security: + + + - Never process user-supplied XSL style sheets + + - Ensure `XsltSettings.EnableScript` is set to false + + - Ensure `XsltSettings.EnableDocumentFunction` is set to false + + + If the application must calculate values from XML input, instead of using XSL scripts to + + execute functions, modify the XML document prior to running the + + `XslCompiledTransform.Transform` method. + + + Example of modifying the XML prior to running `Transform`: + + ``` + + const String filename = "number.xml"; + + const String stylesheet = "calc.xsl"; + + + // Compile the style sheet. + + XsltSettings xslt_settings = new XsltSettings(); + + xslt_settings.EnableScript = false; // disable script + + xslt_settings.EnableDocumentFunction = false; // disable document() function + + XslCompiledTransform xslt = new XslCompiledTransform(); + + XmlResolver resolver = null; // set a null entity resolver + + xslt.Load(stylesheet, xslt_settings, resolver); + + + // Load the XML source file, using XDocument for safety + + XDocument doc = XDocument.Load(filename); + + + // do our modifications to the document before the transformation + + // instead of inside of a script. + + doc.Element("data").Add(new XElement("circle", new XElement("radius", 12))); + + + // Create an XmlWriter. + + XmlWriterSettings settings = new XmlWriterSettings(); + + settings.OmitXmlDeclaration = true; + + settings.Indent = true; + + XmlWriter writer = XmlWriter.Create("output.xml", settings); + + // Finally, execute the transformation. + + xslt.Transform(doc.CreateReader(), writer); + + writer.Close(); + + ``` + + + For more information on security considerations when using XSL see the following URLs: + + - https://learn.microsoft.com/en-us/dotnet/standard/data/xml/xslt-security-considerations + + - https://learn.microsoft.com/en-us/dotnet/api/system.xml.xsl.xslcompiledtransform?view=net-7.0#security-considerations + + ' + severity: WARNING + metadata: + shortDescription: XML injection (aka Blind XPath injection) + category: security + cwe: CWE-91 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + security-severity: High + - id: gitlab-csharp_password_rule-PasswordComplexity + languages: [csharp] + pattern-either: + - pattern: $OPT.Password.RequireDigit = false; + - pattern: $OPT.Password.RequireLowercase = false; + - pattern: $OPT.Password.RequireNonAlphanumeric = false; + - pattern: $OPT.Password.RequireUppercase = false; + - patterns: + - pattern: $OPT.Password.RequiredLength = $LEN; + - metavariable-comparison: + metavariable: $LEN + comparison: $LEN < 8 + - patterns: + - pattern: $OPT.Password.RequiredUniqueChars = $LEN; + - metavariable-comparison: + metavariable: $LEN + comparison: $LEN < 1 + message: "The application's `PasswordValidator.RequiredLength` property allows passwords\nto be less than\ + \ 8 characters. Consider requiring a length of at least 8 or more\ncharacters to reduce the chance of\ + \ passwords being brute forced.\n\nExample of setting the RequiredLength to 8 in ASP.NET Core Identity:\n\ + ```\nbuilder.Services.Configure(options =>\n{\n // Default Password settings.\n\ + \ options.Password.RequireDigit = true;\n options.Password.RequireLowercase = true;\n options.Password.RequireNonAlphanumeric\ + \ = true;\n options.Password.RequireUppercase = true;\n options.Password.RequiredLength = 8;\n\ + \ options.Password.RequiredUniqueChars = 1;\n});\n```\n\nFor more information on configuring ASP.NET\ + \ Core Identity see:\nhttps://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration\n" + severity: WARNING + metadata: + shortDescription: Weak password requirements + category: security + cwe: CWE-521 + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + security-severity: Info + - id: gitlab-csharp_path_rule-PathTraversal + languages: [csharp] + mode: taint + pattern-sources: + - patterns: + - pattern-inside: "public class $CLASS : Controller {\n ...\n}\n" + - pattern: $PARAM + - pattern-either: + - patterns: + - metavariable-regex: + metavariable: $HTTP_ANNO + regex: ^(Http) + - pattern-inside: '[$HTTP_ANNO] + + public string $METHOD(...,$PARAM,...){...} + + ' + - pattern-inside: 'public IActionResult $METHOD(...,$PARAM,...){...} + + ' + pattern-sanitizers: + - pattern-either: + - pattern: (Microsoft.Extensions.FileProviders.PhysicalFileProvider $E).GetFileInfo(...) + - pattern: (System.Web.HttpServerUtility $E).MapPath(...) + - pattern: (System.Web.HttpServerUtilityBase $E).MapPath(...) + - pattern: (System.Web.HttpRequest $E).MapPath(...) + pattern-sinks: + - pattern-either: + - pattern: System.IO.Directory.Delete(...) + - pattern: System.IO.Directory.GetFiles(...) + - pattern: System.IO.Directory.Move(...) + - pattern: System.IO.File.AppendAllLines(...) + - pattern: System.IO.File.AppendAllLinesAsync(...) + - pattern: System.IO.File.AppendAllText(...) + - pattern: System.IO.File.AppendAllTextAsync(...) + - pattern: System.IO.File.AppendText(...) + - pattern: System.IO.File.Copy(...) + - pattern: System.IO.File.Create(...) + - pattern: System.IO.File.CreateText(...) + - pattern: System.IO.File.Delete(...) + - pattern: System.IO.File.Move(...) + - pattern: System.IO.File.Open(...) + - pattern: System.IO.File.OpenRead(...) + - pattern: System.IO.File.OpenText(...) + - pattern: System.IO.File.OpenWrite(...) + - pattern: System.IO.File.ReadAllBytes(...) + - pattern: System.IO.File.ReadAllBytesAsync(...) + - pattern: System.IO.File.ReadAllLines(...) + - pattern: System.IO.File.ReadAllLinesAsync(...) + - pattern: System.IO.File.ReadAllText(...) + - pattern: System.IO.File.ReadAllTextAsync(...) + - pattern: System.IO.File.ReadLines(...) + - pattern: System.IO.File.Replace(...) + - pattern: System.IO.File.SetAccessControl(...) + - pattern: System.IO.File.WriteAllBytes(...) + - pattern: System.IO.File.WriteAllBytesAsync(...) + - pattern: System.IO.File.WriteAllLines(...) + - pattern: System.IO.File.WriteAllLinesAsync(...) + - pattern: System.IO.File.WriteAllText(...) + - pattern: System.IO.File.WriteAllTextAsync(...) + - pattern: new System.IO.FileInfo(...) + - pattern: (System.IO.FileInfo $E).CopyTo(...) + - pattern: (System.IO.FileInfo $E).MoveTo(...) + - pattern: (System.IO.FileInfo $E).Replace(...) + - pattern: System.Reflection.Assembly.LoadFile(...) + - pattern: System.Reflection.Assembly.LoadFrom(...) + - pattern: System.Reflection.Assembly.ReflectionOnlyLoadFrom(...) + - pattern: System.Reflection.Assembly.UnsafeLoadFrom(...) + - pattern: System.AppDomain.AppendPrivatePath(...) + - pattern: System.Xml.XmlReader.Create(...) + - pattern: new System.IO.StreamReader.ctor(...) + - pattern: new System.IO.StreamWriter.ctor(...) + - pattern: new System.IO.FileStream.ctor(...) + - pattern: new System.Web.Mvc.FilePathResult(...) + - pattern: new Microsoft.AspNetCore.Mvc.PhysicalFileResult(...) + - pattern: (Microsoft.AspNetCore.Mvc.RazorPages.PageModel $E).PhysicalFile(...) + - pattern: (System.Web.UI.WebControls.FileUpload $E).SaveAs(...) + - pattern: (System.Web.HttpResponse $E).TransmitFile(...) + - pattern: (System.Web.HttpResponse $E).WriteFile(...) + - pattern: (System.Web.HttpResponseBase $E).TransmitFile(...) + - pattern: (System.Web.HttpResponseBase $E).WriteFile(...) + - pattern: (System.IO.Compression.ZipFileExtensions $E).CreateEntryFromFile(...) + - pattern: (System.IO.Compression.ZipFileExtensions $E).ExtractToFile(...) + - pattern: (System.IO.Compression.ZipFileExtensions $E).ExtractToDirectory(...) + - pattern: (System.Net.WebClient $E).DownloadFile(...) + - pattern: (System.Net.WebClient $E).DownloadFileAsync(...) + - pattern: (System.Net.WebClient $E).DownloadFileTaskAsync(...) + message: "The application dynamically constructs file or path information. If the path\ninformation comes\ + \ from user input, it could be abused to read sensitive files,\naccess other users data, or aid in exploitation\ + \ to gain further system access.\n\nUser input should never be used in constructing paths or files for\ + \ interacting\nwith the filesystem. This includes filenames supplied by user uploads or downloads.\n\ + If possible consider hashing user input or replacing it with unique values and\nuse `System.IO.Path.GetFullPath`\ + \ to resolve and validate the path information\nprior to processing any file functionality.\n\nExample\ + \ using `Path.GetFullPath` and not allowing direct user input:\n```\n// store user input alongside an\ + \ ID we control\nstruct userData\n{\n public string userFilename;\n public Guid id;\n}\n\nclass\ + \ Program\n{\n public static void Main()\n {\n userData data = new userData();\n \ + \ // user input, saved only as a reference\n data.userFilename = \"..\\\\test.txt\";\n\n \ + \ // random id as the filename\n data.id = Guid.NewGuid();\n\n // restrict all file\ + \ processing to this directory only\n string basePath = \"C:\\\\Restricted\\\\\";\n\n \ + \ // resolve the full path, but only use our random generated id\n string fullPath = Path.GetFullPath(basePath\ + \ + data.id);\n\n // verify the path is contained within our basePath\n if (!fullPath.StartsWith(basePath))\ + \ {\n Console.WriteLine(\"Invalid path specified!\");\n return;\n }\n \ + \ // process / work with file\n }\n}\n```\n\nFor more information on path traversal issues\ + \ see OWASP:\nhttps://owasp.org/www-community/attacks/Path_Traversal\n" + metadata: + shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal') + category: security + cwe: CWE-22 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + security-severity: Medium + severity: WARNING + - id: gitlab-csharp_validation_rule-InputValidation + languages: [csharp] + patterns: + - pattern: "[ValidateInput(false)]\npublic $RET $FOO(...)\n{\n ...\n}\n" + message: "By using the `[ValidateInput(false)]` attribute in a controller\nclass, the application will\ + \ disable request validation for that\nmethod. This disables ASP.NET from examining requests for injection\n\ + attacks such as Cross-Site-Scripting (XSS).\n\nIf possible, re-enable validation by using `ValidateInput(true)`.\n\ + In some cases this may not be possible, in which case ensure how the\nrequest data used is validated\ + \ and this method does not\noutput user input directly into the view.\n\nFor more information on protecting\ + \ ASP.NET Core applications from XSS see:\nhttps://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting\n\ + \nExample of enabling `ValidateInput` attribute:\n```\nclass ControllerClass\n{\n [ValidateInput(true)]\n\ + \ public void SomeActionMethod()\n {\n }\n}\n```\n\nFor more information on ASP.NET request\ + \ validation see OWASP:\nhttps://owasp.org/www-community/ASP-NET_Request_Validation\n" + severity: WARNING + metadata: + shortDescription: ASP.NET input validation disabled + category: security + cwe: CWE-554 + owasp: + - A6:2017-Security Misconfiguration + - A04:2021-Insecure Design + - A05:2025-Injection + security-severity: Info + - id: gitlab-csharp_xss_rule-HtmlElementXss + languages: [csharp] + mode: taint + pattern-sources: + - patterns: + - pattern: $PARAM + - pattern-inside: '$RET $METHOD(...,$PARAM,...){...} + + ' + - pattern: Request.Cookies[...] + - pattern: Request.Cookies.Get(...) + - pattern: Request.Form[...] + - pattern: Request.Form.Get(...) + - pattern: Request.Headers[...] + - pattern: Request.Headers.Get(...) + - pattern: Request.QueryString[...] + - pattern: Request.QueryString.Get(...) + - pattern: Request.Params[...] + - pattern: Request.RawUrl + - pattern: Request.Url + - pattern: Request.Path + - pattern: Request.Body + - pattern: $CTX.Request.Cookies[...] + - pattern: $CTX.Request.Cookies.Get(...) + - pattern: $CTX.Request.Form[...] + - pattern: $CTX.Request.Form.Get(...) + - pattern: $CTX.Request.Headers[...] + - pattern: $CTX.Request.Headers.Get(...) + - pattern: $CTX.Request.QueryString[...] + - pattern: $CTX.Request.QueryString.Get(...) + - pattern: $CTX.Request.Body + pattern-sanitizers: + - patterns: + - metavariable-regex: + metavariable: $FUNC + regex: (SerializeObject|HtmlAttributeEncode|HtmlEncode|HtmlFormUrlEncode|UrlEncode|UrlPathEncode|XmlAttributeEncode|XmlEncode|Encode) + - pattern: $CLASS.$FUNC(...) + pattern-sinks: + - pattern: (System.Web.Mvc.HtmlHelper $E).Raw(...) + - pattern: (Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper $E).Raw(...) + - pattern: Response.Write(...) + - pattern: (System.Web.UI.HtmlTextWriter $E).AddAttribute(...) + - pattern: (System.Web.UI.HtmlTextWriter $E).AddStyleAttribute(...) + - pattern: (System.Web.UI.HtmlTextWriter $E).RenderBeginTag(...) + - pattern: (System.Web.UI.HtmlTextWriter $E).Write(...) + - pattern: (System.Web.UI.HtmlTextWriter $E).WriteAttribute(...) + - pattern: (System.Web.UI.HtmlTextWriter $E).WriteBeginTag(...) + - pattern: (System.Web.UI.HtmlTextWriter $E).WriteEndTag(...) + - pattern: (System.Web.UI.HtmlTextWriter $E).WriteFullBeginTag(...) + - pattern: (System.Web.UI.HtmlTextWriter $E).WriteStyleAttribute(...) + message: 'Cross Site Scripting (XSS) is an attack which exploits a web application or system to treat + + user input + + as markup or script code. It is important to encode the data depending on the specific context + + it + + is used in. There are at least six context types: + + + - Inside HTML tags `
context 1
` + + - Inside attributes: `
` + + - Inside event attributes `` + + - Inside script blocks: `` + + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + + - Inside URLs: `link` + + User input that is displayed within the application must be encoded, sanitized or validated + + to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be + + taken + + to not mix server-side templating with client-side templating, as the server-side templating + + will + + not encode things like {{ 7*7 }} which may execute client-side templating features. + + + It is _NOT_ advised to encode user input prior to inserting into a data store. The data will + + need to be + + encoded depending on context of where it is output. It is much safer to force the displaying + + system to + + handle the encoding and not attempt to guess how it should be encoded. + + + Consider using built-in framework capabilities for automatically encoding user input. + + Depending + + on output context, consider using the following `System.Text.Encodings.Web` encoders: + + + - [HtmlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.htmlencoder) + + - [JavaScriptEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder) + + - [UrlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.urlencoder) + + + For more information on protecting ASP.NET Core applications from XSS see: + + https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting#accessing-encoders-in-code + + ' + metadata: + shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting') + category: security + cwe: CWE-79 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + - A05:2025-Injection + security-severity: Medium + severity: WARNING + - id: gitlab-csharp_xss_rule-ScriptXss + languages: [csharp] + mode: taint + pattern-sources: + - patterns: + - pattern: $PARAM + - pattern-inside: '$RET $METHOD(...,$PARAM,...){...} + + ' + - pattern: Request.Cookies[...] + - pattern: Request.Cookies.Get(...) + - pattern: Request.Form[...] + - pattern: Request.Form.Get(...) + - pattern: Request.Headers[...] + - pattern: Request.Headers.Get(...) + - pattern: Request.QueryString[...] + - pattern: Request.QueryString.Get(...) + - pattern: Request.Params[...] + - pattern: Request.RawUrl + - pattern: Request.Url + - pattern: Request.Path + - pattern: Request.Body + - pattern: $CTX.Request.Cookies[...] + - pattern: $CTX.Request.Cookies.Get(...) + - pattern: $CTX.Request.Form[...] + - pattern: $CTX.Request.Form.Get(...) + - pattern: $CTX.Request.Headers[...] + - pattern: $CTX.Request.Headers.Get(...) + - pattern: $CTX.Request.QueryString[...] + - pattern: $CTX.Request.QueryString.Get(...) + - pattern: $CTX.Request.Body + - pattern: $ELE.Text + pattern-sanitizers: + - patterns: + - metavariable-regex: + metavariable: $FUNC + regex: (SerializeObject|HtmlAttributeEncode|HtmlEncode|HtmlFormUrlEncode|UrlEncode|UrlPathEncode|XmlAttributeEncode|XmlEncode|Encode) + - pattern: $CLASS.$FUNC(...) + pattern-propagators: + - pattern: (StringBuilder $OUT).Append($IN) + from: $IN + to: $OUT + pattern-sinks: + - pattern: $SCRIPTMANAGER.RegisterStartupScript(...) + - pattern: $SCRIPTMANAGER.RegisterClientScriptBlock(...) + - pattern: System.Web.UI.RegisterStartupScript(...) + - pattern: System.Web.UI.RegisterClientScriptBlock(...) + message: 'Cross Site Scripting (XSS) is an attack which exploits a web application or system to treat + + user input + + as markup or script code. It is important to encode the data depending on the specific context + + it + + is used in. + + + User input that is used within the application scripts must be encoded, sanitized or validated + + to ensure it cannot change the behavior of the Javascript code. + + + It is _NOT_ advised to encode user input prior to inserting into a data store. The data will + + need to be + + encoded depending on context of where it is output. It is much safer to force the displaying + + system to + + handle the encoding and not attempt to guess how it should be encoded. + + + Consider using built-in framework capabilities for automatically encoding user input. + + Depending + + on output context, consider using the following `System.Text.Encodings.Web` encoders: + + + - [HtmlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.htmlencoder) + + - [JavaScriptEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder) + + - [UrlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.urlencoder) + + + For more information on protecting ASP.NET Core applications from XSS see: + + https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting#accessing-encoders-in-code + + ' + metadata: + shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting') + category: security + cwe: CWE-79 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + - A05:2025-Injection + security-severity: MEDIUM + severity: WARNING + - id: gitlab-go_crypto_rule-tlsversion + languages: [go] + pattern-either: + - patterns: + - pattern-either: + - patterns: + - pattern-inside: 'tls.Config{...} + + ' + - pattern: 'MinVersion: $VAL + + ' + - patterns: + - pattern-inside: '$VAR = uint16($VAL) + + ... + + ' + - pattern-inside: 'tls.Config{...} + + ' + - pattern: 'MinVersion: $VAR + + ' + - metavariable-pattern: + metavariable: $VAL + pattern-either: + - pattern: tls.VersionTLS11 + - pattern: tls.VersionTLS10 + - patterns: + - pattern-inside: 'tls.Config{...} + + ' + - pattern: 'MaxVersion: $ANYVAL + + ' + - pattern-not-inside: 'tls.Config{..., MinVersion: ..., ...} + + ' + message: "TLS versions 1.1 and 1.0 were deprecated by the IETF in June 2018 due to \na number of attacks\ + \ against the vulnerable versions. Use of a deprecated \nTLS version may result in the unauthorized\ + \ retrieval of sensitive \ninformation. It is strongly recommended that all TLS connections\nuse TLS\ + \ 1.3 as Go will automatically choose the most secure cipher when \nnegotiating the TLS handshake with\ + \ client or servers. TLS 1.3 cipher suites \nare configured to require Perfect Forward Secrecy (PFS).\ + \ PFS is an important \nproperty as it will ensure that past encrypted transmissions could not be\n\ + decrypted if the TLS certificate was compromised.\n\nExample using TLS 1.3 for a Go server:\n```\ncert,\ + \ err := tls.LoadX509KeyPair(\"server.crt\", \"server.key\")\nif err != nil {\n log.Fatal(err)\n}\n\ + \ncfg := &tls.Config{Certificates: []tls.Certificate{cert}, \n MinVersion: tls.VersionTLS13}\n\ + \nsrv := &http.Server{\n Addr: \":8999\",\n TLSConfig: cfg,\n ReadTimeout: time.Minute,\n\ + \ WriteTimeout: time.Minute,\n}\nlog.Fatal(srv.ListenAndServeTLS(\"cert.pem\", \"key.pem\"))\n```\n" + metadata: + shortDescription: Selection of less-secure algorithm during negotiation ('algorithm downgrade') + cwe: CWE-757 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + security-severity: Medium + category: security + severity: WARNING + - id: gitlab-java_cookie_rule-CookieInsecure + languages: [java] + patterns: + - pattern: '$X.servlet.http.Cookie $C = new $X.servlet.http.Cookie(..., ...); + + ... + + ($X.servlet.http.HttpServletResponse $RESP).addCookie($C); + + ' + - pattern-not-inside: '$X.servlet.http.Cookie $C = new $X.servlet.http.Cookie(..., ...); + + ... + + $C.setSecure(true); + + ... + + ($X.servlet.http.HttpServletResponse $RESP).addCookie($C); + + ' + message: 'The `Secure` attribute when set to `true` protects the cookie value from being being + + transmitted over clear text + + communication paths such as HTTP. By enabling this protection, the cookie will only be sent + + over HTTPS. + + + Example of protecting a `Cookie`: + + ``` + + // Create an Secure cookie. + + Cookie someCookie = new Cookie("SomeCookieName", "SomeValue"); + + // Set Secure flag to true + + someCookie.setSecure(true); + + ``` + + + For more information see: + + https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/http/cookie#setSecure-boolean- + + + Session cookies should be configured with the following security directives: + + + - [HTTPOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + + - [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) + + - [Secure](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + + ' + severity: WARNING + metadata: + shortDescription: Sensitive cookie in HTTPS session without 'Secure' attribute + category: security + cwe: CWE-614 + owasp: + - A3:2017-Sensitive Data Exposure + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + technology: + - java + security-severity: Low + - id: gitlab-java_cookie_rule-HttpResponseSplitting + languages: [java] + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: '$STR.replaceAll($REPLACER, "..."); + + ... + + ' + - pattern: $STR + - metavariable-regex: + metavariable: $REPLACER + regex: .*\[(?=.*\\r)(?=.*\\n).*\]\+ + - pattern: org.apache.commons.text.StringEscapeUtils.escapeJava($STR); + pattern-sinks: + - pattern: new javax.servlet.http.Cookie("$KEY", ...); + - patterns: + - pattern-inside: '$C = new javax.servlet.http.Cookie("$KEY", ...); + + ... + + ' + - pattern: $C.setValue(...); + pattern-sources: + - pattern: (javax.servlet.http.HttpServletRequest $REQ).getParameter(...); + - pattern: (javax.servlet.http.HttpServletRequest $REQ).getParameterNames(); + - pattern: (javax.servlet.http.HttpServletRequest $REQ).getParameterValues(...); + - pattern: (javax.servlet.http.HttpServletRequest $REQ).getParameterMap(); + - pattern: (javax.servlet.http.HttpServletRequest $REQ).getHeader(...); + - pattern: (javax.servlet.http.HttpServletRequest $REQ).getPathInfo(); + message: "HTTP Response Splitting is a vulnerability where Carriage Return (CR `\\r`) and Line Feed (LF\n\ + `\\n`)\ncharacters are introduced into an HTTP header from user-supplied input. By injecting the\n`\\\ + r\\n`\ncharacter sequence, an adversary could potentially modify how the response is interpreted by\n\ + the\nclient or any downstream caching services. This could allow an adversary to poison the cache\n\ + data or execute Cross-Site Scripting (XSS) attacks.\n\nSome Java application servers such as [Apache\ + \ Tomcat](https://tomcat.apache.org/) as of version\n8.0, newer versions of Jetty and other servers\ + \ that implement the [RFC 6265 Standard](https://datatracker.ietf.org/doc/html/rfc6265) will\ndisallow\ + \ `\\r' and '\\n` characters characters from being set in cookies. If your application server does not\n\ + automatically provide this functionality, user-supplied input that is used in cookie keys or\nvalues\ + \ must be validated.\n\nExample of validating cookies to only allow valid characters:\n```\n// throws\ + \ an IllegalArgumentException if the provided value contains invalid characters\npublic void validateRfc6265CookieValue(String\ + \ value) throws IllegalArgumentException {\n char[] chars = value.toCharArray();\n\n // iterate\ + \ over every character\n for (int i = 0; i < chars.length; i++) {\n char c = chars[i];\n\n\ + \ // check for any characters below 0x21 as well as: '\"' ',' ';' '\\' and 0x7f.\n if\ + \ (c < 0x21 || c == '\"' || c == ',' || c == ';' || c == '\\\\' || c == 0x7f) {\n throw new\ + \ IllegalArgumentException(\"Invalid character in cookie detected:\n{0}\".format(Integer.toString(c)));\n\ + \ }\n }\n}\n```\n\nAlternatively, you could use a string escape package such as\n[Apache Commons\ + \ Text](https://commons.apache.org/proper/commons-text/) to escape the input:\n```\npublic String escapeValue(String\ + \ value) {\n return StringEscapeUtils.escapeJava(value);\n}\n```\n\nFor more information on response\ + \ splitting attacks see OWASP:\nhttps://owasp.org/www-community/attacks/HTTP_Response_Splitting\n" + severity: WARNING + metadata: + shortDescription: Improper neutralization of CRLF sequences in HTTP headers ('HTTP Response Splitting') + category: security + cwe: CWE-113 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + technology: + - java + security-severity: High + - id: gitlab-java_cookie_rule-RequestParamToHeader + languages: [java] + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: '$STR.replaceAll("$INPUT", "..."); + + ... + + ' + - pattern: $STR + - metavariable-regex: + metavariable: $INPUT + regex: .*\[(?=.*\\r)(?=.*\\n).*\]\+ + - pattern: org.apache.commons.text.StringEscapeUtils.unescapeJava(...); + pattern-sinks: + - pattern: ($X.servlet.http.HttpServletResponse $RES).setHeader("$KEY", ...); + - pattern: ($X.servlet.http.HttpServletResponse $RES).addHeader("$KEY", ...); + - pattern: ($X.servlet.http.HttpServletResponseWrapper $WRP).setHeader("$KEY", ...); + - pattern: ($X.servlet.http.HttpServletResponseWrapper $WRP).addHeader("$KEY", ...); + pattern-sources: + - pattern: ($X.servlet.http.HttpServletRequest $REQ).getParameter(...); + - pattern: ($X.servlet.http.HttpServletRequest $REQ).getParameterNames(); + - pattern: ($X.servlet.http.HttpServletRequest $REQ).getParameterValues(...); + - pattern: ($X.servlet.http.HttpServletRequest $REQ).getParameterMap(); + - pattern: ($X.servlet.http.HttpServletRequest $REQ).getHeader(...); + - pattern: ($X.servlet.http.HttpServletRequest $REQ).getPathInfo(); + message: "HTTP Response Splitting is a vulnerability where Carriage Return (CR `\\r`) and Line Feed (LF\n\ + `\\n`)\ncharacters are introduced into an HTTP header from user-supplied input. By injecting the\n`\\\ + r\\n`\ncharacter sequence, an adversary could potentially modify how the response is interpreted by\n\ + the\nclient or any down stream caching services. This could allow an adversary to poison the cache\n\ + data or execute Cross-Site Scripting (XSS) attacks.\n\nSome Java application servers such as [Apache\ + \ Tomcat](https://tomcat.apache.org/) will\nautomatically encode\ncharacters from being set in response\ + \ headers as a space `0x20` character. If your application\nserver does\nnot automatically provide this\ + \ functionality, user-supplied input that is used in header keys\nor values must be\nvalidated.\n\n\ + Example of validating headers to only allow valid characters:\n```\n// throws an IllegalArgumentException\ + \ if the provided value contains invalid characters\npublic void validateHeader(String value) throws\ + \ IllegalArgumentException {\n char[] chars = value.toCharArray();\n\n // iterate over every character\n\ + \ for (int i = 0; i < chars.length; i++) {\n char c = chars[i];\n\n // check for any\ + \ characters below 0x21 as well as: '\"' ',' ';' '\\' and 0x7f.\n if (c < 0x21 || c == '\"' ||\ + \ c == ',' || c == ';' || c == '\\\\' || c == 0x7f) {\n throw new IllegalArgumentException(\"\ + Invalid character in cookie detected:\n{0}\".format(Integer.toString(c)));\n }\n }\n}\n```\n\ + \nAlternatively, you could use a string escape package such as\n[Apache Commons Text](https://commons.apache.org/proper/commons-text/)\ + \ to escape the input:\n```\npublic String escapeValue(String value) {\n return StringEscapeUtils.escapeJava(value);\n\ + }\n```\n\nFor more information on response splitting attacks see OWASP:\nhttps://owasp.org/www-community/attacks/HTTP_Response_Splitting\n" + severity: ERROR + metadata: + shortDescription: Improper neutralization of CRLF sequences in HTTP headers ('HTTP Response Splitting') + category: security + cwe: CWE-113 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + technology: + - java + security-severity: High + - id: gitlab-java_cors_rule-PermissiveCORSInjection + languages: [java] + mode: taint + pattern-sources: + - pattern: (HttpServletRequest $REQ).getParameter(...) + - pattern: (HttpServletRequest $REQ).getHeader(...) + - pattern: (HttpServletRequest $REQ).getPathInfo() + - pattern: (HttpServletRequest $REQ).getQueryString() + - pattern: (HttpServletRequest $REQ).getAttribute(...) + - pattern: (HttpServletRequest $REQ).getSession().getAttribute(...) + - pattern: (HttpServletRequest $REQ).getServletContext().getAttribute(...) + - pattern: (HttpServletRequest $REQ).getParameterValues(...) + - pattern: (HttpServletRequest $REQ).getParameterNames() + - pattern: (HttpServletRequest $REQ).getParameterMap() + pattern-sinks: + - patterns: + - pattern-either: + - pattern: (HttpServletResponse $RES).setHeader("$HEADER", ...) + - pattern: (HttpServletResponse $RES).addHeader("$HEADER", ...) + - metavariable-regex: + metavariable: $HEADER + regex: (?i)(Access-Control-Allow-Origin) + message: "This application potentially allows user-supplied input into the value of the\n`Access-Control-Allow-Origin`\ + \ response header. This header is part of the\n[Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)\ + \ CORS\nspecification. By allowing user input to specify which domains can communicate with this\nserver,\n\ + an adversary could exploit a weakness in this server to force clients to send credentials (such\nas\ + \ session\nidentifiers) to the adversary's server.\n\nFor the above attack to work, the application\ + \ would need to suffer from an additional\nvulnerability,\nsuch as Cross-Site Scripting (XSS).\n\nTo\ + \ remediate this issue, do not use user-supplied information when calling\n`HttpServletResponse.setHeader`\ + \ or `HttpServletResponse.addHeader`\nfor the `Access-Control-Allow-Origin` header's value. Instead,\ + \ hardcode the allowed domain(s)\nand reference them in a lookup\ntable:\nExample allowing dynamic but\ + \ safe domains in `Access-Control-Allow-Origin`:\n\n```\n // this data should be in the class constructor\ + \ or taken from a trusted datasource\n Map allowedDomains = new HashMap();\n allowedDomains.put(\"\ + sub1\", \"sub1.example.com\");\n allowedDomains.put(\"sub2\", \"sub2.example.com\");\n\n // extract\ + \ the allowedDomain parameters value as a key to look up which domain to provide\nvia the allowedDomains\ + \ map\n // if not found, sets sub1 as the default\n String headerValue = allowedDomains.getOrDefault(request.getParameter(\"\ + allowedDomain\"),\nallowedDomains.get(\"sub1\"));\n\n // add the header with our trusted sub1.example.com\ + \ or sub2.example.com domains.\n response.addHeader(\"Access-Control-Allow-Origin\", headerValue);\n\ + }\n```\n\nFor more information on `Access-Control-Allow-Origin` see:\nhttps://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin\n" + severity: ERROR + metadata: + shortDescription: Permissive cross-domain policy with untrusted domains + cwe: CWE-942 + category: security + owasp: + - A5:2017-Broken Access Control + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + technology: + - java + security-severity: Low + - id: gitlab-java_crypto_rule-BlowfishKeySize + languages: [java] + patterns: + - pattern-inside: '$KEYGEN = javax.crypto.KeyGenerator.getInstance("Blowfish", ...); + + ... + + ' + - pattern: $KEYGEN.init($KEY_SIZE) + - metavariable-comparison: + comparison: int($KEY_SIZE) < 128 + metavariable: $KEY_SIZE + message: "The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created\ + \ in\n1993. Smaller key sizes may make the ciphertext vulnerable to [birthday\nattacks](https://en.wikipedia.org/wiki/Birthday_attack).\ + \ While no known attacks against\nBlowfish\nexist, it should never be used to encrypt files over 4GB\ + \ in size. If possible consider\nusing AES as the instance of `KeyGenerator` instead of Blowfish.\n\n\ + To remediate the small key size, pass a value such as 256 to the `KeyGenerator.init(keySize)`\nmethod.\n\ + \nExample setting a larger key size and changing to `KeyGenerator` to AES:\n```\npublic static void\ + \ aesKeyGenerator() throws java.security.NoSuchAlgorithmException {\n // Use the AES algorithm for\ + \ key generation\n KeyGenerator keyGenerator = KeyGenerator.getInstance(\"AES\");\n\n // Set the\ + \ key size here\n keyGenerator.init(256);\n\n // get the raw bytes of the key\n byte[] key\ + \ = keyGenerator.generateKey().getEncoded();\n\n // pass the key bytes to create a SecretKeySpec\n\ + \ SecretKeySpec secretKeySpec = new SecretKeySpec(key, \"AES\");\n}\n```\n\nExample setting a larger\ + \ key size for Blowfish:\n```\npublic static void blowFishKeyGenerator() throws java.security.NoSuchAlgorithmException\ + \ {\n // Use the Blowfish algorithm for key generation\n KeyGenerator keyGenerator = KeyGenerator.getInstance(\"\ + Blowfish\");\n\n // Set the key size here\n keyGenerator.init(256);\n\n // get the raw bytes\ + \ of the key\n byte[] key = keyGenerator.generateKey().getEncoded();\n\n // pass the key bytes\ + \ to create a SecretKeySpec\n SecretKeySpec secretKeySpec = new SecretKeySpec(key, \"Blowfish\");\n\ + }\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n" + severity: WARNING + metadata: + category: security + shortDescription: Inadequate encryption strength + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + cwe: CWE-326 + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-CipherDESInsecure + languages: [java] + patterns: + - pattern-either: + - pattern: javax.crypto.Cipher.getInstance("$ALG", ...) + - pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG"); + + ... + + javax.crypto.Cipher.getInstance($PROP, ...); + + ' + - metavariable-regex: + metavariable: $ALG + regex: ^DES(/|$) + message: "DES, TripleDES and RC2 are all considered broken or insecure cryptographic algorithms.\nNewer\ + \ algorithms apply message integrity to validate ciphertext has not been tampered\nwith. Consider using\ + \ `ChaCha20Poly1305` instead as it is easier and faster than the\nalternatives such as `AES-256-GCM`.\n\ + \nFor older applications that don't have support for `ChaCha20Poly1305`,\n`AES-256-GCM` is recommended,\ + \ however it has many drawbacks:\n- Slower than `ChaCha20Poly1305`.\n- Catastrophic failure if nonce\ + \ values are reused.\n\nExample using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n\ + \ chaChaEncryption(\"Secret text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom\ + \ getSecureRandomDRBG() throws NoSuchAlgorithmException {\n // Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\ + \ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\ + \ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\ + \ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\ + \ personalization string (optional, not necessary)\n \"some_personalization_string\"\ + .getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\ + \ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\ + \ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\ + \ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\ + ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\ + \ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \ + \ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\ + \ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\ + \ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\ + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\ + \ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\ + \ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\ + \ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\ + \ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\ + \n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \ + \ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\ + \ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\ + encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\ + \ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\ + \n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\ + \ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\ + \ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\ + \ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n" + severity: WARNING + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-CipherDESedeInsecure + languages: [java] + patterns: + - pattern-either: + - pattern: javax.crypto.Cipher.getInstance("$ALG", ...) + - pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG"); + + ... + + javax.crypto.Cipher.getInstance($PROP, ...); + + ' + - metavariable-regex: + metavariable: $ALG + regex: DESede(/|$) + message: "DES, TripleDES and RC2 are all considered broken or insecure cryptographic algorithms.\nNewer\ + \ algorithms apply message integrity to validate ciphertext has not been tampered\nwith. Consider using\ + \ `ChaCha20Poly1305` instead as it is easier and faster than the\nalternatives such as `AES-256-GCM`.\n\ + \nFor older applications that don't have support for `ChaCha20Poly1305`,\n`AES-256-GCM` is recommended,\ + \ however it has many drawbacks:\n- Slower than `ChaCha20Poly1305`.\n- Catastrophic failure if nonce\ + \ values are reused.\n\nExample using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n\ + \ chaChaEncryption(\"Secret text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom\ + \ getSecureRandomDRBG() throws NoSuchAlgorithmException {\n // Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\ + \ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\ + \ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\ + \ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\ + \ personalization string (optional, not necessary)\n \"some_personalization_string\"\ + .getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] nonceKey,\ + \ byte[] secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\n\ + InvalidAlgorithmParameterException {\n // Get a DRBG random number generator instance\n SecureRandom\ + \ random = getSecureRandomDRBG();\n // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher\ + \ = Cipher.getInstance(\"ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using\ + \ our nonceKey\n AlgorithmParameterSpec parameterSpec = new IvParameterSpec(nonceKey);\n // Create\ + \ a SecretKeySpec using our secretKey\n SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey,\ + \ \"ChaCha20\");\n // Initialize and return the cipher for the provided mode\n chaChaCipher.init(mode,\ + \ secretKeySpec, parameterSpec, random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[]\ + \ plainText) throws NoSuchAlgorithmException,\nNoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException\ + \ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\ + \ // Create secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n \ + \ // Create an IV nonceKey\n byte[] nonceKey = new byte[12];\n random.nextBytes(nonceKey);\n\ + \ // Create a chaCha encryption cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE,\ + \ nonceKey, secretKey);\n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n\ + \ try {\n cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException\ + \ | BadPaddingException e) {\n System.out.println(\"failed to encrypt text\");\n return;\n\ + \ }\n System.out.println(\"encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\ + \ // Create a chaCha decryption cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE,\ + \ nonceKey, secretKey);\n // Decrypt the text\n byte[] decryptedText = null;\n try {\n \ + \ decryptedText = chaChaDecryptor.doFinal(cipherText);\n } catch (IllegalBlockSizeException |\ + \ BadPaddingException e) {\n System.out.println(\"failed to decrypt text\");\n return;\n\ + \ }\n System.out.println(\"decrypted: \" + new String(decryptedText, StandardCharsets.UTF_8));\n\ + }\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n" + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-CipherECBMode + languages: [java] + patterns: + - pattern-either: + - pattern: javax.crypto.Cipher.getInstance("$ALG", ...) + - pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG"); + + ... + + javax.crypto.Cipher.getInstance($PROP, ...); + + ' + - metavariable-comparison: + metavariable: $ALG + comparison: "$ALG in (\n \"AES/ECB/NoPadding\" \"AES/ECB/PKCS5Padding\"\n \"DES/ECB/NoPadding\"\ + \ \"DES/ECB/PKCS5Padding\"\n \"DESede/ECB/NoPadding\" \"DESede/ECB/PKCS5Padding\"\n \"AES/ECB/PKCS7Padding\"\ + \n)\n" + message: "Cryptographic algorithms provide many different modes of operation, only some of which provide\n\ + message integrity. Without message integrity it could be possible for an adversary to attempt\nto tamper\ + \ with the ciphertext which could lead to compromising the encryption key. Newer\nalgorithms\napply\ + \ message integrity to validate ciphertext has not been tampered with.\n\nInstead of using an algorithm\ + \ that requires configuring a cipher mode, an algorithm\nthat has built-in message integrity should\ + \ be used. Consider using `ChaCha20Poly1305` or\n`AES-256-GCM` instead.\n\nFor older applications that\ + \ don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n\ + \ - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values are reused.\n\nExample\ + \ using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n chaChaEncryption(\"Secret\ + \ text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom getSecureRandomDRBG()\ + \ throws NoSuchAlgorithmException {\n // Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\ + \ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\ + \ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\ + \ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\ + \ personalization string (optional, not necessary)\n \"some_personalization_string\"\ + .getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\ + \ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\ + \ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\ + \ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\ + ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\ + \ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \ + \ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\ + \ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\ + \ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\ + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\ + \ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\ + \ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\ + \ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\ + \ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\ + \n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \ + \ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\ + \ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\ + encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\ + \ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\ + \n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\ + \ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\ + \ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\ + \ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n" + severity: ERROR + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-CipherIntegrity + languages: [java] + patterns: + - pattern-either: + - pattern: javax.crypto.Cipher.getInstance("$ALG", ...) + - pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG"); + + ... + + javax.crypto.Cipher.getInstance($PROP, ...); + + ' + - metavariable-comparison: + metavariable: $ALG + comparison: "$ALG in (\n \"AES\"\n \"AES/CBC/NoPadding\" \"AES/CBC/PKCS5Padding\" \"AES/CBC/PKCS7Padding\"\ + \n \"AES/CFB/NoPadding\" \"AES/CFB/PKCS5Padding\" \"AES/CFB/PKCS7Padding\"\n \"AES/CTR/NoPadding\"\ + \n \"AES/ECB/NoPadding\" \"AES/ECB/PKCS5Padding\" \"AES/ECB/PKCS7Padding\"\n \"AES/OFB/NoPadding\"\ + \ \"AES/OFB/PKCS5Padding\" \"AES/OFB/PKCS7Padding\"\n \"ARCFOUR\"\n \"DES\"\n \"DES/CBC/NoPadding\"\ + \ \"DES/CBC/PKCS5Padding\"\n \"DES/ECB/NoPadding\" \"DES/ECB/PKCS5Padding\"\n \"DESede\"\n \"\ + DESede/CBC/NoPadding\" \"DESede/CBC/PKCS5Padding\"\n \"DESede/ECB/NoPadding\" \"DESede/ECB/PKCS5Padding\"\ + \n \"RC4\"\n)\n" + message: "Cryptographic algorithms provide many different modes of operation, only some of which provide\n\ + message integrity. Without message integrity it could be possible for an adversary to attempt\nto tamper\ + \ with the ciphertext which could lead to compromising the encryption key. Newer\nalgorithms\napply\ + \ message integrity to validate ciphertext has not been tampered with.\n\nInstead of using an algorithm\ + \ that requires configuring a cipher mode, an algorithm\nthat has built-in message integrity should\ + \ be used. Consider using `ChaCha20Poly1305` or\n`AES-256-GCM` instead.\n\nFor older applications that\ + \ don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n\ + \ - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values are reused.\n\nExample\ + \ using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n chaChaEncryption(\"Secret\ + \ text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom getSecureRandomDRBG()\ + \ throws NoSuchAlgorithmException {\n// Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\ + \ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\ + \ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\ + \ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\ + \ personalization string (optional, not necessary)\n \"some_personalization_string\"\ + .getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\ + \ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\ + \ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\ + \ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\ + ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\ + \ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \ + \ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\ + \ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\ + \ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\ + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\ + \ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\ + \ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\ + \ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\ + \ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\ + \n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \ + \ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\ + \ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\ + encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\ + \ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\ + \n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\ + \ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\ + \ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\ + \ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n" + severity: ERROR + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-CipherPaddingOracle + languages: [java] + patterns: + - pattern-either: + - pattern: javax.crypto.Cipher.getInstance("$ALG", ...) + - pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG"); + + ... + + javax.crypto.Cipher.getInstance($PROP, ...); + + ' + - metavariable-comparison: + metavariable: $ALG + comparison: "$ALG in (\n \"AES/CBC/PKCS5Padding\" \"DES/CBC/PKCS5Padding\" \"DESede/CBC/PKCS5Padding\"\ + \ \"AES/CBC/PKCS7Padding\"\n)\n" + message: "Cryptographic block ciphers can be configured to pad individual blocks if there is not enough\n\ + input data to match the size of the block. This specific mode of CBC used in combination with\nPKCS5Padding\ + \ is susceptible to padding oracle attacks. An adversary could potentially decrypt\nthe message if the\ + \ system exposed the difference between plaintext with invalid padding or\nvalid padding. The distinction\ + \ between valid and invalid padding is usually revealed through\ndistinct error messages being returned\ + \ for each condition.\n\nConsider switching to a more secure cipher that doesn't require padding and\ + \ builds in message\nauthentication integrity directly into the algorithm.\n\nConsider using `ChaCha20Poly1305`\ + \ or\n`AES-256-GCM` instead.\n\nFor older applications that don't have support for `ChaCha20Poly1305`,\ + \ `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n - Slower than `ChaCha20Poly1305`.\n\ + \ - Catastrophic failure if nonce values are reused.\n\nExample using `ChaCha20Poly1305`:\n```\npublic\ + \ encrypt() throws Exception {\n chaChaEncryption(\"Secret text to encrypt\".getBytes(StandardCharsets.UTF_8));\n\ + }\n\npublic SecureRandom getSecureRandomDRBG() throws NoSuchAlgorithmException {\n // Use DRBG according\ + \ to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n return SecureRandom.getInstance(\"\ + DRBG\",\n // Security strength in bits (default is 128)\n DrbgParameters.instantiation(256,\n\ + \ // Set prediction resistance and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n\ + \ // Set the personalization string (optional, not necessary)\n \"some_personalization_string\"\ + .getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\ + \ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\ + \ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\ + \ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\ + ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\ + \ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \ + \ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\ + \ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\ + \ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\ + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\ + \ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\ + \ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\ + \ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\ + \ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\ + \n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \ + \ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\ + \ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\ + encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\ + \ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\ + \n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\ + \ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\ + \ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\ + \ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on padding oracle attacks see:\nhttps://en.wikipedia.org/wiki/Padding_oracle_attack\n\ + \nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n" + severity: ERROR + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-CustomMessageDigest + languages: [java] + patterns: + - pattern: "class $CLAZZ extends java.security.MessageDigest {\n ...\n}\n" + message: 'The application was found implementing a custom `java.security.MessageDigest`. It is + + strongly recommended that a standard Digest algorithm be chosen instead as implementing + + a digest by hand is error-prone. The National Institute of Standards and + + Technology (NIST) recommends the use of SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, or + + SHA-512/256. + + + Example of creating a SHA-384 hash: + + ``` + + // Create a MessageDigest using the SHA-384 algorithm + + MessageDigest sha384Digest = MessageDigest.getInstance("SHA-384"); + + // Call update with your data + + sha384Digest.update(input); + + // Only call digest once all data has been fed into the update sha384digest instance + + byte[] output = sha384Digest.digest(); + + // output base64 encoded version of the hash + + System.out.println("hash: " + Base64.getEncoder().encodeToString(output)); + + ``` + + ' + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-HazelcastSymmetricEncryption + languages: [java] + patterns: + - pattern: new com.hazelcast.config.SymmetricEncryptionConfig() + message: 'The network communications for Hazelcast is configured to use a deprecated symmetric cipher. + + Consider using TLS/SSL when establishing communications across the Hazelcast cluster. + + + For more information on configuring TLS/SSL for Hazelcast see: + + https://docs.hazelcast.com/imdg/4.2/security/tls-ssl + + ' + severity: WARNING + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-InsufficientKeySizeRsa + languages: [java] + patterns: + - pattern-either: + - patterns: + - pattern-inside: '$GEN = KeyPairGenerator.getInstance($ALG, ...); + + ... + + ' + - pattern-either: + - pattern: $VAR.initialize($SIZE, ...); + - pattern: new java.security.spec.RSAKeyGenParameterSpec($SIZE,...); + - metavariable-comparison: + comparison: $SIZE < 2048 + metavariable: $SIZE + - metavariable-regex: + metavariable: $ALG + regex: '"(RSA|DSA)"' + message: "The application is generating an RSA key that is less than the recommended 2048 bits.\nThe National\ + \ Institute of Standards and Technology (NIST) deprecated signing Digital\nCertificates that contained\ + \ RSA Public Keys of 1024 bits in December 2010. While\n1024-bit RSA keys have not been factored yet,\ + \ advances in compute may make it possible\nin the near future.\n\nConsider upgrading to the newer asymmetric\ + \ algorithm such as `Ed25519` which handles\nthe complexities of generating key pairs and choosing correct\ + \ key sizes for you:\n```\npublic static KeyPair generateEd25519() throws NoSuchAlgorithmException {\n\ + \ // Choose Ed25519 for KeyPairGenerator Instance\n KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(\"\ + Ed25519\");\n // Generate a KeyPair and return\n return keyPairGenerator.generateKeyPair();\n\ + }\n```\n\nOtherwise use a key size greater than 2048 when generating RSA keys:\n```\npublic static KeyPair\ + \ generateRSA() throws NoSuchAlgorithmException {\n // Choose RSA for KeyPairGenerator Instance\n\ + \ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(\"RSA\");\n // Initialize with\ + \ 2048 key size\n keyPairGenerator.initialize(2048);\n // Generate a KeyPair and return\n return\ + \ keyPairGenerator.generateKeyPair();\n}\n```\n\nFor more information on Ed25519 see: http://ed25519.cr.yp.to/\n\ + \nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n" + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + security-severity: Medium + severity: WARNING + - id: gitlab-java_crypto_rule-NullCipher + languages: [java] + pattern: new javax.crypto.NullCipher() + message: "The application was found creating a `NullCipher` instance. `NullCipher` implements the\n`Cipher`\ + \ interface by returning ciphertext identical to the supplied plaintext. This means\nany data passed\ + \ to the `doFinal(...)` or `update(...)` methods will not actually encrypt\nthe input.\n\nRemove the\ + \ NullCipher reference and replace with a legitimate `Cipher` instance such as\n`ChaCha20-Poly1305`\n\ + \nExample using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n chaChaEncryption(\"\ + Secret text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom getSecureRandomDRBG()\ + \ throws NoSuchAlgorithmException {\n // Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\ + \ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\ + \ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\ + \ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\ + \ personalization string (optional, not necessary)\n \"some_personalization_string\"\ + .getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\ + \ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\ + \ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\ + \ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\ + ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\ + \ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \ + \ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\ + \ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\ + \ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\ + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\ + \ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\ + \ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\ + \ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\ + \ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\ + \n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \ + \ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\ + \ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\ + encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\ + \ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\ + \n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\ + \ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\ + \ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\ + \ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n" + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-RsaNoPadding + languages: [java] + patterns: + - pattern-either: + - pattern: javax.crypto.Cipher.getInstance("$ALG", ...) + - pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG"); + + ... + + javax.crypto.Cipher.getInstance($PROP, ...); + + ' + - metavariable-regex: + metavariable: $ALG + regex: (?i)^RSA/.*NoPadding$ + message: "The software uses the RSA algorithm but does not incorporate Optimal Asymmetric\nEncryption\ + \ Padding (OAEP). By not enabling padding, the algorithm maybe vulnerable\nto [chosen plaintext attacks](https://en.wikipedia.org/wiki/Chosen-plaintext_attack).\n\ + \nTo enable OAEP mode, pass `RSA/ECB/OAEPWithSHA-256AndMGF1Padding` to the `Cipher.getInstance`\nmethod.\n\ + \nExample encrypting and decrypting a message using RSA with OAEP:\n```\npublic static void encryptWithRSA()\ + \ throws InvalidKeyException, NoSuchAlgorithmException,\nNoSuchPaddingException, IllegalBlockSizeException,\ + \ BadPaddingException {\n // Generate an RSA Public and Private Key Pair\n KeyPair keyPair = generateRSAKeys();\n\ + \ // Create a Cipher instance using RSA, ECB with OAEP\n Cipher rsaEncryptor = Cipher.getInstance(\"\ + RSA/ECB/OAEPWithSHA-256AndMGF1Padding\");\n // Initialize to ENCRYPT_MODE with the public key\n \ + \ rsaEncryptor.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());\n // Encrypt our secret message\n\ + \ byte[] cipherText = rsaEncryptor.doFinal(\"Some secret\nmessage\".getBytes(StandardCharsets.UTF_8));\n\ + \n // Create a Cipher instance using RSA, ECB with OAEP\n Cipher rsaDecryptor = Cipher.getInstance(\"\ + RSA/ECB/OAEPWithSHA-256AndMGF1Padding\");\n // Initialize to DECRYPT_MODE with the private key\n\ + \ rsaDecryptor.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());\n // Decrypt the secret message\n\ + \ byte[] plainText = rsaDecryptor.doFinal(cipherText);\n // Debug output\n System.out.println(new\ + \ String(plainText));\n}\n```\nMore information on Optimal asymmetric encryption padding:\nhttps://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding\n\ + \nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n" + metadata: + shortDescription: Use of RSA algorithm without OAEP + category: security + cwe: CWE-780 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + security-severity: Medium + severity: WARNING + - id: gitlab-java_crypto_rule-WeakMessageDigest + languages: [java] + patterns: + - pattern-either: + - pattern: java.security.MessageDigest.getInstance("$ALG", ...) + - pattern: java.security.Signature.getInstance("$ALG", ...) + - pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG"); + + ... + + java.security.MessageDigest.getInstance("$ALG", ...); + + ' + - pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG"); + + ... + + java.security.Signature.getInstance("$ALG", ...); + + ' + - metavariable-comparison: + metavariable: $ALG + comparison: "$ALG in (\n \"MD2\" \"MD4\" \"MD5\" \"MD5withRSA\"\n \"SHA-1\" \"SHA1withRSA\" \"SHA1withDSA\"\ + \n)\n" + message: 'The application was found using an insecure or risky digest or signature algorithm. Both MD5 + + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + + that two different values, when hashed, can lead to the same hash value. If the application is + + trying + + to use these hash methods for storing passwords, then it is recommended to switch to a + + password hashing + + algorithm such as Argon2id or PBKDF2. + + strongly recommended that a standard Digest algorithm be chosen instead as implementing + + a digest by hand is error-prone. + + + Example of creating a SHA-384 hash: + + ``` + + // Create a MessageDigest using the SHA-384 algorithm + + MessageDigest sha384Digest = MessageDigest.getInstance("SHA-384"); + + // Call update with your data + + sha384Digest.update(input); + + // Only call digest once all data has been fed into the update sha384digest instance + + byte[] output = sha384Digest.digest(); + + // output base64 encoded version of the hash + + System.out.println("hash: " + Base64.getEncoder().encodeToString(output)); + + ``` + + + For more information on secure password storage see OWASP: + + https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + ' + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm (SHA1/MD5) + category: security + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + technology: + - java + security-severity: Medium + - id: gitlab-java_crypto_rule-WeakTLSProtocol-DefaultHttpClient + languages: [java] + patterns: + - pattern: new org.apache.http.impl.client.DefaultHttpClient(); + message: "The `org.apache.http.impl.client.DefaultHttpClient` does not verify the hostnames upon connection.\n\ + \nThis allows for an adversary who is in between the application and the target host to intercept\n\ + potentially sensitive information or transmit malicious data.\n\nDo not use the `org.apache.http.impl.client.DefaultHttpClient();`\ + \ as it is deprecated. Instead\nuse the new `java.net.http.HttpClient` that was introduced in Java 9.\n\ + \nExample connecting to a host that will automatically do TLS validation:\n```\n// Create a new java.net.http.HttpClient\n\ + HttpClient httpClient = HttpClient.newHttpClient();\n// Create a HttpRequest builder\nHttpRequest request\ + \ = HttpRequest.newBuilder()\n // Create a URI for a website which requires TLS\n .uri(URI.create(\"\ + https://www.example.com/\"))\n // Build the request\n .build();\n\n// Use the httpClient\ + \ to send the request and use an HttpResponse.BodyHandlers String type\nHttpResponse response\ + \ = httpClient.send(request, HttpResponse.BodyHandlers.ofString());\n// Debug print\nSystem.out.println(response);\n\ + ```\n" + metadata: + shortDescription: Improper certificate validation + category: security + cwe: CWE-295 + owasp: + - A3:2017-Sensitive Data Exposure + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + security-severity: Medium + severity: WARNING + - id: gitlab-java_crypto_rule-WeakTLSProtocol-SSLContext + languages: [java] + patterns: + - pattern-either: + - pattern: javax.net.ssl.SSLContext.getInstance("$PROTO", ...) + - pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$PROTO"); + + ... + + javax.net.ssl.SSLContext.getInstance($PROP, ...); + + ' + - metavariable-comparison: + metavariable: $PROTO + comparison: '$PROTO not in ("TLS" "TLSv1.2" "TLSv1.3" "DTLSv1.2" "DTLSv1.3") + + ' + message: "Avoid initializing SSLContext with insecure protocols like `SSL`, `SSLv2`, or `SSLv3`.\nThese\ + \ protocols are outdated and do not validate certificates by default. Additionally,\nthese older `SSL`\ + \ versions have many known security issues.\n\nInstead, use secure protocols like `TLSv1.2` or `TLSv1.3`.\n\ + ```\nSSLContext context = SSLContext.getInstance(\"TLSv1.3\");\n```\nFor more information on see OWASP:\n\ + \ - https://owasp.org/www-project-web-security-testing-guide/v41/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/01-Testing_for_Weak_SSL_TLS_Ciphers_Insufficient_Transport_Layer_Protection\n" + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + security-severity: MEDIUM + severity: WARNING + - id: gitlab-java_crypto_rule-WeakTLSProtocolVersion + languages: [java] + patterns: + - pattern-either: + - pattern-inside: 'import javax.net.ssl.*; + + ... + + ' + - pattern-inside: 'import javax.net.ssl.SSLContext; + + ... + + ' + - pattern-either: + - pattern-inside: 'SSLContext.getInstance("$UNSAFE_VERSION"); + + ' + - pattern-inside: 'SSLContext.getInstance(...); + + ... + + $ENGINE.setEnabledProtocols(new String[]{...,"$UNSAFE_VERSION",...}); + + ' + - pattern-not-inside: '$C = SSLContext.getInstance(...); + + ... + + $ENGINE.setEnabledProtocols(new String[]{...,"TLSv1.2",...}); + + ' + - pattern-not-inside: '$C = SSLContext.getInstance(...); + + ... + + $ENGINE.setEnabledProtocols(new String[]{...,"TLSv1.3",...}); + + ' + - pattern-not-inside: '$C = SSLContext.getInstance(...); + + ... + + $ENGINE.setEnabledProtocols(new String[]{...,"DTLSv1.2",...}); + + ' + - pattern-not-inside: '$C = SSLContext.getInstance(...); + + ... + + $ENGINE.setEnabledProtocols(new String[]{...,"DTLSv1.3",...}); + + ' + - metavariable-regex: + metavariable: $UNSAFE_VERSION + regex: ^(TLS|(D)?TLSv1.(0|1))$ + message: 'The application was found enabling insecure TLS protocol versions. When enabling protocol + + versions for an `SSLContext`, only the following versions should be allowed: + + - TLSv1.2 + + - TLSv1.3 + + - DTLSv1.2 + + - DTLSv1.3 + + + To mitigate potential security risks, it is strongly advised to enforce TLS 1.2 as the minimum + + protocol version and disallow older versions such as TLS 1.0. Do note that newer versions of + + Java do not even support TLS 1.0 and will throw `NoSuchAlgorithmException`. Versions of TLS + + prior to 1.2 could expose the connection to downgrade attacks, where an adversary intercepts + + the + + connection and alters the requested protocol version to be a less secure one. + + + In many scenarios, relying on the default system configuration does not meet compliance + + standards. This is due to the application being deployed across diverse systems with varying + + configurations and Java versions. While the default value may be secure on modern and + + up-to-date systems, it may not hold true for older systems. Consequently, it is highly + + recommended to explicitly define a secure configuration in all cases. + + + Example configuring an SSLContext with TLSv1.2: + + ``` + + // Create an SSLContext with TLSv1.2 explicitly + + SSLContext tlsContext = SSLContext.getInstance("TLSv1.2"); // or TLSv1.3, DTLSv1.2, DTLSv1.3 + + + // Alternatively, set the enabled protocols + + SSLContext serverSslContext = SSLContext.getInstance("TLS"); + + SSLEngine serverEngine = serverSslContext.createSSLEngine(); + + // Calling setEnabledProtocols will override the original context''s configured protocol version + + serverEngine.setEnabledProtocols(new String[]{ "TLSv1.2" }); + + ``` + + + For more information on `SSLContext` see: + + - https://docs.oracle.com/en/java/javase/11/docs/api/java.base/javax/net/ssl/SSLContext.html + + + For more information on MiTM attacks see: + + - https://owasp.org/www-community/attacks/Manipulator-in-the-middle_attack + + ' + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + security-severity: Medium + severity: WARNING + - id: gitlab-java_endpoint_rule-HostnameVerifier + languages: [java] + message: "The `HostnameVerifier` has been set to always return `true`. This effectively \ndisables the\ + \ validation of server or client certificates. This could allow an \nadversary who is in between the\ + \ application and the target host to launch a Man \nin the middle attack (MITM) i.e intercept potentially\ + \ sensitive information or \ninject malicious content into the communication stream.\n\nTo mitigate\ + \ this vulnerability and enhance the security of your application, it is \nstrongly advised to adhere\ + \ to the default HostnameVerifier settings. This ensures \nthat the validation mechanism remains intact,\ + \ providing a crucial layer of security \nagainst unauthorized interception and data manipulation.\n\ + \nImplementing the default HostnameVerifier can be achieved with the following code \nsnippet:\n```\n\ + // Use the default HostnameVerifier\nHttpsURLConnection connection = (HttpsURLConnection) url.openConnection();\n\ + connection.setHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier());\n```\nFor more information\ + \ on TLS security, refer the following OWASP documentation:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html\n" + metadata: + shortDescription: Improper certificate validation + category: security + cwe: CWE-295 + owasp: + - A3:2017-Sensitive Data Exposure + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + security-severity: MEDIUM + patterns: + - pattern-inside: "class $V implements HostnameVerifier {\n ...\n}\n" + - pattern-either: + - pattern: "boolean verify(...) {\n ...\n return true;\n ...\n}\n" + - pattern-not: + patterns: + - pattern: "boolean verify(...) {\n ...\n return $VAR;\n ...\n }\n" + - metavariable-regex: + metavariable: $VAR + regex: ^((?!true).)*$ + - pattern-not: "boolean verify(...) {\n $VAR = true;\n ...\n return $VAR;\n ...\n }\n" + severity: WARNING + - id: gitlab-java_endpoint_rule-UnvalidatedRedirect + languages: [java] + message: "Unvalidated redirects occur when an application redirects a user to a\ndestination URL specified\ + \ by a user supplied parameter that is not validated.\nSuch vulnerabilities can be used to facilitate\ + \ phishing attacks.\n\nTo avoid open redirect vulnerabilities in Java, one effective strategy is to\n\ + only allow redirection to URLs that are pre-defined in a safe list. This safe\nlist can be implemented\ + \ using a collection like a Map, List, or Dictionary,\nwhere you store all the valid URLs or URL patterns.\ + \ When a redirect request is\nmade, you can check if the requested URL is in this safe list before proceeding\ + \ \nwith the redirection. For example:\n\n```\n protected void doGet(HttpServletRequest request, HttpServletResponse\ + \ response) throws ServletException, IOException {\n private List safeUrls = new ArrayList<>();\n\ + \ safeUrls.add(\"/home\");\n safeUrls.add(\"/user/profile\");\n safeUrls.add(\"/dashboard\"\ + );\n \n String redirectUrl = request.getParameter(\"url\");\n\n if (safeUrls.contains(redirectUrl))\ + \ {\n response.sendRedirect(redirectUrl);\n } else {\n response.sendRedirect(\"\ + /errorPage\");\n }\n }\"\n``` \n" + mode: taint + pattern-sources: + - patterns: + - pattern: '$URL = ($X.servlet.http.HttpServletRequest $REQ).$M(...); + + ' + - metavariable-regex: + metavariable: $M + regex: (getParameter|getCookies|getHeader|getHeaders|getHeaderNames|getPathInfo|getPathTranslated|getContextPath|getQueryString|getRemoteUser|getRequestedSessionId|getRequestURI|getRequestURL|getServletPath|getParts|getPart|getReader) + pattern-sinks: + - pattern-either: + - pattern: '($X.servlet.http.HttpServletResponse $RES).sendRedirect($URL) + + ' + - pattern: '($X.servlet.http.HttpServletResponse $RES).addHeader("Location", $URL) + + ' + pattern-sanitizers: + - patterns: + - pattern-inside: "if ($SAFE.contains($URL)){\n ...\n}\n" + - pattern-either: + - pattern: '($X.servlet.http.HttpServletResponse $RES).sendRedirect($URL) + + ' + - pattern: '($X.servlet.http.HttpServletResponse $RES).addHeader("Location", $URL) + + ' + metadata: + category: security + cwe: CWE-601 + owasp: + - A1:2017-Injection + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + shortDescription: URL redirection to untrusted site ('Open Redirect') + security-severity: Info + severity: ERROR + - id: gitlab-java_endpoint_rule-X509TrustManager + languages: [java] + message: "The `X509TrustManager` has been configured to return null. This effectively disables the\nvalidation\ + \ of server or client certificates. This could allow an adversary who is in \nbetween the application\ + \ and the target host to launch a Man in the middle attack (MITM) i.e \nintercept potentially sensitive\ + \ information or inject malicious content into the \ncommunication stream.\n\nConsider using the \n\ + default `TrustManager` instead of implementing a custom one. If you must override\nthe default verification\ + \ process, implement proper TrustManager verification for\n`checkServerTrusted` and `checkClientTrusted`\ + \ by throwing `CertificateException` if \nthe certificate is invalid.\n\nFor most applications, using\ + \ the default TrustManager provided by the Java runtime is \nsufficient and recommended. Following is\ + \ an example using the built in `TrustManagerFactory` \nto manage validating certificate chains:\n```\n\ + // Use the default TrustManagerFactory\nTrustManagerFactory trustManagerFactory =\nTrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n\ + // Use default system KeyStore, alternatively pass in your own keystore.\ntrustManagerFactory.init((KeyStore)\ + \ null);\n// Create SSLContext for TLS connections\nSSLContext tlsContext = SSLContext.getInstance(\"\ + TLS\");\n// Initialize the tlsContext with our trust manager and a SecureRandom number generator.\n\ + tlsContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());\n```\nFor more information\ + \ on TLS security, refer the following OWASP documentation:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html\n" + metadata: + shortDescription: Improper certificate validation + category: security + cwe: CWE-295 + owasp: + - A3:2017-Sensitive Data Exposure + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + security-severity: MEDIUM + patterns: + - pattern-inside: "class $V implements X509TrustManager {\n ...\n}\n" + - pattern-either: + - pattern: public void checkClientTrusted(...) {} + - pattern: public void checkServerTrusted(...) {} + - patterns: + - pattern-either: + - pattern: "X509Certificate[] getAcceptedIssuers() {\n ...\n return null;\n ...\n}\n" + - pattern-not: + patterns: + - pattern: "X509Certificate[] getAcceptedIssuers() {\n ...\n return $VAR;\n ...\n }\n" + - metavariable-regex: + metavariable: $VAR + regex: ^((?!null).)*$ + - pattern-not: "X509Certificate[] getAcceptedIssuers() {\n $VAR = null;\n ...\n return\ + \ $VAR;\n ...\n }\n" + severity: WARNING + - id: gitlab-java_file_rule-FileUploadFileName + languages: [java] + message: "The filename provided by the FileUpload API can be tampered with\nwhich could lead to unauthorized\ + \ access or file inclusion vulnerabilities.\nTo mitigate this risk, it is essential to conduct rigorous\ + \ validation of the\nfilenames provided by clients. This validation should ensure that the filename\n\ + adheres to a predefined structure, is devoid of potentially dangerous characters\n(such as forward slashes\ + \ / and backslashes \\), and corresponds to an authorized\nfile only.\n\nFor example, as a remediation\ + \ strategy, the application could:\n1. Sanitize Filenames: Create a function to sanitize filenames by\ + \ removing\n or replacing unauthorized characters, including path traversal sequences (../ or ..\\\ + ).\n2. Allowlist Validation: Implement a allowlist approach, allowing only filenames\n that match\ + \ a specific pattern or are part of a predefined list.\n3. Use Server-Generated Filenames: Rather than\ + \ relying on client-provided filenames,\n generate unique names server-side for storing files.\n4.\ + \ Verify File Paths: Ensure files are being saved in the correct,\n intended directory, and prevent\ + \ redirection to unauthorized directories.\n\nExample remediation:\n```\n public class FileUploadHandler\ + \ {\n\n protected void doPost(HttpServletRequest request, HttpServletResponse response)\n \ + \ throws ServletException, IOException {\n\n Part filePart = request.getPart(\"file\"\ + );\n String fileName = filePart.getSubmittedFileName();\n\n // removes any path information\ + \ from the filename\n String sanitizedFileName = sanitizeFileName(fileName);\n if\ + \ (!isFileNameAllowed(sanitizedFileName)) {\n throw new SecurityException(\"Invalid file\ + \ name\");\n }\n\n // Generate a unique file name for storage\n String storedFileName\ + \ = UUID.randomUUID().toString() + \".txt\";\n\n Path targetPath = Paths.get(\"uploads\").resolve(storedFileName);\n\ + \ Files.copy(fileContent, targetPath, StandardCopyOption.REPLACE_EXISTING);\n }\n\n \ + \ private String sanitizeFileName(String fileName) {\n return Paths.get(fileName).getFileName().toString();\n\ + \ }\n\n private boolean isFileNameAllowed(String fileName) {\n return fileName.matches(\"\ + [a-zA-Z0-9._-]+\");\n }\n }\n```\n" + pattern-either: + - patterns: + - pattern-inside: "$FILES = (ServletFileUpload $SFU).parseRequest(($X.servlet.http.HttpServletRequest\ + \ $REQ));\n...\nfor(FileItem $ITEM : $FILES) {\n ...\n}\n" + - pattern: $ITEM.getName() + - pattern: ($X.servlet.http.Part $PART).getSubmittedFileName() + metadata: + shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal') + cwe: CWE-22 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + security-severity: Info + category: security + technology: + - java + severity: WARNING + - id: gitlab-java_file_rule-FilenameUtils + languages: [java] + message: "The filename provided by the FileUpload API can be tampered with by the client to reference\n\ + unauthorized files. The provided filename should be properly validated to ensure it's properly\nstructured,\ + \ contains no unauthorized path characters (e.g., / \\), and refers to an authorized\nfile.\n\nThe application\ + \ was found to take a parameter from user input to construct a path name. If an\nunfiltered parameter\ + \ is passed to this file API, files from an arbitrary filesystem location\ncould be read. When data\ + \ from an unstrusted source is untrusted source is used to construct\na file path, an attacker could\ + \ potentially gain access to restrcited files locations outside\nthe relevant context.\n\nFor example,\ + \ if the application tries to access the users profile picture based on their user\nname by concatenating\ + \ the username to the filepath:\n\n\"images/userprofiles/\" + username\n\nThe expected result of this\ + \ would be \"images/userprofiles/alice\", however an attacker could\nuse a malicious input such as \"\ + ../../../etc/passwd\" to gain access to and/or manipulate\nsensitive information\n\nAssume all input\ + \ is malicious. Use an \"accept known good\" input validation strategy.\n\nInputs can be sanitized by\ + \ using the getName() method with concat() method to remove the \npotentially malicious path traversal\ + \ and limit the scope to a restricted directory. Or \ninput can also be sanitized by using resolve()\ + \ method alongwith startsWith() method to \nverify that the base path of the file is safe and expected.\n\ + \nExample of limiting path traversal using getName:\n\n```\nprotected void doPut(HttpServletRequest\ + \ req, HttpServletResponse resp) throws ServletException, IOException {\n\n String input = req.getHeader(\"\ + input\");\n\n input = getName(input);\n \n String safePath = concat(basePath, input);\n\n \ + \ // Read the contents of the file\n File file = new File(safePath);\n}\n```\n" + metadata: + category: security + cwe: CWE-22 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal') + security-severity: Info + technology: + - java + mode: taint + pattern-sanitizers: + - pattern: '$NAME = org.apache.commons.io.FilenameUtils.getName(...); + + ... + + $SAFE = concat($BASE, $NAME); + + ' + - pattern: "$RET $FUN(...){\n ...\n $PATH = $BP.resolve(...);\n ...\n if(!$PATH.startsWith(...)) {\n\ + \ throw new $EXC(...);\n }\n ...\n}\n" + pattern-sources: + - pattern: (HttpServletRequest $REQ) + pattern-sinks: + - pattern: org.apache.commons.io.FilenameUtils.concat(...) + - pattern: org.apache.commons.io.FilenameUtils.getFullPath(...) + - pattern: org.apache.commons.io.FilenameUtils.getFullPathNoEndSeparator(...) + - pattern: org.apache.commons.io.FilenameUtils.getPath(...) + - pattern: org.apache.commons.io.FilenameUtils.getPathNoEndSeparator(...) + - pattern: org.apache.commons.io.FilenameUtils.normalize(...) + - pattern: org.apache.commons.io.FilenameUtils.normalizeNoEndSeparator(...) + - pattern: org.apache.commons.io.FilenameUtils.normalizeNoEndSeparator(...) + - pattern: org.apache.commons.io.FilenameUtils.removeExtension(...) + - pattern: org.apache.commons.io.FilenameUtils.separatorsToSystem(...) + - pattern: org.apache.commons.io.FilenameUtils.separatorsToUnix(...) + - pattern: org.apache.commons.io.FilenameUtils.separatorsToWindows(...) + severity: WARNING + - id: gitlab-java_inject_rule-CommandInjection + languages: [java] + mode: taint + pattern-sources: + - pattern: (javax.servlet.http.HttpServletRequest $R).$METHOD(...) + - pattern: (java.util.Scanner $S).$METHOD(...) + - pattern: (java.util.stream.Stream).$METHOD(...) + - pattern: (java.util.StringJoiner $SJ).toString(...) + - pattern: (java.sql.ResultSet.getString $R).$METHOD(...) + - pattern: (java.lang.System $S).getProperty(...) + - pattern: (java.lang.System $S).getenv(...) + - pattern: (java.lang.StringBuilder $SB).toString(...) + - pattern: (java.io.FileInputStream $F).read(...) + - pattern: (java.io.FileReader $F).read(...) + - pattern: (java.net.Socket $S).getInputStream(...) + - pattern: (java.net.Socket $S).getOutputStream(...) + - pattern: (java.net.DatagramSocket $S).receive(...) + - pattern: (java.net.DatagramSocket $S).getInputStream(...) + - pattern: java.nio.file.Files.readAllBytes(...) + - pattern: java.nio.file.Files.readAllLines(...) + - pattern: java.nio.file.Files.lines(...) + - pattern: java.nio.file.Files.newBufferedReader(...) + - pattern: org.apache.commons.io.IOUtils.toString(...) + - pattern: org.apache.commons.io.IOUtils.readLines(...) + - pattern: org.apache.commons.io.IOUtils.toByteArray(...) + - pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).readValue(...) + - pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).treeToValue(...) + - pattern: $CLASS.$METHOD(..., (javax.servlet.http.HttpServletRequest $R), ...) + - pattern: $FUNC(..., (javax.servlet.http.HttpServletRequest $R), ...) + - patterns: + - pattern-inside: $FUNC(..., String $X, ...) { ... } + - focus-metavariable: $X + pattern-propagators: + - pattern: $LIST.add($X) + from: $X + to: $LIST + - pattern: $MAP.put(..., $X) + from: $X + to: $MAP + - pattern: $STR.concat($X) + from: $X + to: $STR + - pattern: $STR = String.format(..., $X, ...) + from: $X + to: $STR + - pattern: $STR = String.join(..., $X, ...) + from: $X + to: $STR + pattern-sinks: + - pattern: (ProcessBuilder $PB).command(...) + - pattern: new ProcessBuilder(...) + - pattern: (Runtime $R).exec(...) + message: "OS command injection is a critical vulnerability that can lead to a full system\ncompromise\ + \ as it may allow an adversary to pass in arbitrary commands or arguments\nto be executed.\n\nUser input\ + \ should never be used in constructing commands or command arguments\nto functions which execute OS\ + \ commands. This includes filenames supplied by\nuser uploads or downloads.\n\nEnsure your application\ + \ does not:\n\n- Use user-supplied information in the process name to execute.\n- Use user-supplied\ + \ information in an OS command execution function which does\nnot escape shell meta-characters.\n- Use\ + \ user-supplied information in arguments to OS commands.\n\nThe application should have a hardcoded\ + \ set of arguments that are to be passed\nto OS commands. If filenames are being passed to these functions,\ + \ it is\nrecommended that a hash of the filename be used instead, or some other unique\nidentifier.\ + \ It is strongly recommended that a native library that implements\nthe same functionality be used instead\ + \ of using OS system commands, due to the\nrisk of unknown attacks against third party commands.\n\n\ + When specifying the OS command, ensure the application uses the full path\ninformation, otherwise the\ + \ OS may attempt to look up which process to execute\nand could be vulnerable to untrusted search path\ + \ vulnerabilities (CWE-426).\n\nExample of safely executing an OS command:\n```\npublic static void\ + \ executeCommand(String userFileData) throws java.io.IOException {\n // Generate a random filename,\ + \ do not use user input\n String fileName = UUID.randomUUID().toString();\n // Create a Buffered/FileWriter\n\ + \ BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));\n // Write the user content\ + \ to our random file\n writer.write(userFileData);\n // Close the file to flush contents\n \ + \ writer.close();\n // Create the process builder with a hardcoded path to the binary, and our randomly\n\ + generated filename\n ProcessBuilder processBuilder = new ProcessBuilder(\"/opt/app/path\", fileName);\n\ + \ // Start the process\n Process process = processBuilder.start();\n // Handle/redirect output\ + \ of process here\n // ...\n}\n```\n\nFor more information on OS command injection, see OWASP's guide:\n\ + https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html\n" + severity: WARNING + metadata: + shortDescription: Improper neutralization of special elements used in an OS command ('OS Command Injection') + category: security + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + technology: + - java + security-severity: High + - id: gitlab-java_inject_rule-ELInjection + languages: [java] + message: "This rule identifies potential Expression Language (EL) injection vulnerabilities within Java\ + \ applications. \nThe rule targets use of `createValueExpression`, `createMethodExpression`, `ELProcessor.eval`,\ + \ `getValue`, \nand `setValue` methods, particularly when input to these methods is not a hardcoded\ + \ string, indicating dynamic \nevaluation of potentially untrusted input. \n\n`createValueExpression`\ + \ creates a `ValueExpression` object which gets evaluated upon calling methods like \n`getValue()` and\ + \ `setValue()` or a Lambda `invoke()` i.e. it evaluates the expression passed to the \n`createValueExpression`\ + \ method.\n\nSimilarly, `createMethodExpression` creates a `MethodExpression` object which gets evaluated\ + \ upon calling \nmethods like `invoke()` and `getMethodInfo()`.\n`ELProcessor.eval`, `getValue()`, and\ + \ `setValue()` methods all evaluate their expressions which are passed \nas parameters.\n\nCalling these\ + \ method directly with user-supplied input may allow an adversary to execute arbitrary Java \ncode,\ + \ including OS system commands. Never call these methods directly with user-supplied input. Consider\ + \ \nalternate methods such as a lookup table to take user input and resolve hardcoded values.\n\nSecure\ + \ example:\n\n```\nimport javax.el.ELProcessor;\nimport java.util.Set;\n\npublic class SafeELHandling\ + \ {\n private static final Set ALLOWED_VALUES = Set.of(\"value1\", \"value2\", \"value3\"\ + );\n\n public void processInput(String userInput) {\n // Validate user input against the allowlist\n\ + \ if (!ALLOWED_VALUES.contains(userInput)) {\n throw new IllegalArgumentException(\"\ + Invalid input\");\n }\n \n ELProcessor elProcessor = new ELProcessor();\n \ + \ elProcessor.defineBean(\"userInput\", userInput);\n \n // Example EL expression using\ + \ the safe, predefined input\n String result = (String) elProcessor.eval(userInput);\n }\n\ + }\n```\n" + metadata: + category: security + cwe: CWE-917 + shortDescription: Improper neutralization of special elements used in an expression language statement + ('Expression Language Injection') + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + technology: + - java + security-severity: Info + pattern-either: + - patterns: + - pattern: '(ExpressionFactory $EXP).createValueExpression((ELContext $CTX), $EXPR, + + ...) + + ' + - pattern-not: '(ExpressionFactory $EXP).createValueExpression((ELContext $CTX), "...", + + ...) + + ' + - patterns: + - pattern: '(ExpressionFactory $EXP).createMethodExpression((ELContext $CTX), $EXPR, + + ...) + + ' + - pattern-not: '(ExpressionFactory $EXP).createMethodExpression((ELContext $CTX), "...", + + ...) + + ' + - patterns: + - pattern: '($X.el.ELProcessor $P).eval(...) + + ' + - pattern-not: '($X.el.ELProcessor $P).eval("...", ...) + + ' + - patterns: + - pattern: '($X.el.ELProcessor $P).getValue(...) + + ' + - pattern-not: '($X.el.ELProcessor $P).getValue("...", ...) + + ' + - patterns: + - pattern: '($X.el.ELProcessor $P).setValue(...) + + ' + - pattern-not: "($X.el.ELProcessor $P).setValue(\"...\", \"...\") \n" + severity: WARNING + - id: gitlab-java_inject_rule-FileDisclosureRequestDispatcher + languages: [java] + mode: taint + pattern-sources: + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameter(...) + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterNames(); + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterValues(...); + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterMap(); + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getHeader(...); + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getPathInfo(); + pattern-sinks: + - patterns: + - pattern-not-inside: '$VAL = $MAP.getOrDefault(..., "..."); + + ... + + ' + - pattern-inside: '$REQ = $HTTP.getRequestDispatcher(...); + + ... + + ' + - pattern-either: + - pattern: $REQ.include($FST, $SND) + - pattern: $REQ.forward($FST, $SND) + message: 'The `HttpRequest.getRequestDispatcher()`''s `include` and `forward` methods will return + + any file that is resolvable within the web application context. This includes the `web.xml` + + file, any compiled classes, `jsp` files, and additional JAR or WAR libraries that are + + accessible. + + + Never pass user-supplied input directly to any of these methods. Use a lookup table or + + hardcode + + which views or paths the user should be directed to. Another option is to use a simple HTTP + + redirect by returning an empty response body with a 301 status code and a `Location` redirect + + header. In Java servlets, this can be done by using the `response.sendRedirect(...)` method. + + + Example using a redirect instead of a `RequestDispatcher`: + + ``` + + // Create a look up table or pull from a data source + + HashMap lookupTable = new HashMap<>(); + + lookupTable.put("key1", "/Resource1"); + + lookupTable.put("key2", "/Resource2"); + + // Get user input + + String userInput = request.getParameter("key"); + + // Look up resource to redirect to from the user input + + String redirectValue = lookupTable.getOrDefault(userInput, "/Resource1"); + + // Redirect the user + + response.sendRedirect(redirectValue); + + ``` + + ' + metadata: + shortDescription: Files or directories accessible to external parties + category: security + cwe: CWE-552 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + security-severity: HIGH + severity: ERROR + - id: gitlab-java_inject_rule-FileDisclosureSpringFramework + languages: [java] + mode: taint + pattern-sources: + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameter(...) + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterNames(); + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterValues(...); + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterMap(); + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getHeader(...); + - pattern: (javax.servlet.http.HttpServletRequest $VAR).getPathInfo(); + pattern-sinks: + - patterns: + - pattern-not-inside: "$FST = $MAP.getOrDefault(..., \"...\");\n ...\n" + - pattern: new org.springframework.web.servlet.ModelAndView($FST, ...); + - focus-metavariable: $FST + - patterns: + - pattern-not-inside: '$FST = $MAP.getOrDefault(..., "..."); + + ... + + ' + - pattern-inside: '$MVC = new org.springframework.web.servlet.ModelAndView(); + + ... + + ' + - pattern: $MVC.setViewName(...); + message: "The `org.springframework.web.servlet.ModelAndView` class may\npotentially allow access to restricted\ + \ files if called with user-supplied input.\n\nThe ModelAndView class looks up a view by name to resolve\ + \ a `.jsp`\nfile. If this view name comes from user-supplied input, it could be abused to attempt\n\ + to return a JSP view that the user should not have access to.\n\nUse a lookup table or hardcode which\ + \ views or paths the user should be directed to.\n\nExample using a lookup table to resolve a view from\ + \ a Spring MVC application:\n```\n@RequestMapping(value=\"/mvc\", method=RequestMethod.GET)\npublic\ + \ ModelAndView mvc(HttpServletRequest request, HttpServletResponse response, Model model)\n {\n //\ + \ Create a look up table or pull from a data source\n HashMap lookupTable = new HashMap<>();\n\ + \ lookupTable.put(\"key1\", \"view1\");\n lookupTable.put(\"key2\", \"view2\");\n // Get user input\n\ + \ String userInput = request.getParameter(\"key\");\n // Look up view from the user input\n String\ + \ viewValue = lookupTable.getOrDefault(userInput, \"Resource1\");\n // return the new model and view\n\ + \ return new ModelAndView(viewValue);\n}\n```\n\nExample using a redirect instead of a `RequestDispatcher`\ + \ in Spring:\n```\n@RequestMapping(value=\"/mvc\", method=RequestMethod.GET)\npublic void mvc(HttpServletRequest\ + \ request, HttpServletResponse response, Model model)\n {\n // Create a look up table or pull from\ + \ a data source\n HashMap lookupTable = new HashMap<>();\n lookupTable.put(\"key1\"\ + , \"view1\");\n lookupTable.put(\"key2\", \"view2\");\n // Get user input\n String userInput = request.getParameter(\"\ + key\");\n // Look up resource to redirect to from the user input\n String redirectValue = lookupTable.getOrDefault(userInput,\ + \ \"/Resource1\");\n // return the new model and view\n response.sendRedirect(redirectValue);\n}\n\ + ```\n" + metadata: + shortDescription: Files or directories accessible to external parties + category: security + cwe: CWE-552 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + security-severity: HIGH + severity: ERROR + - id: gitlab-java_inject_rule-HttpParameterPollution + languages: [java] + mode: taint + pattern-sources: + - pattern: (HttpServletRequest $REQ).getParameter(...) + pattern-sanitizers: + - pattern: java.net.URLEncoder.encode(...) + - pattern: com.google.common.net.UrlEscapers.urlPathSegmentEscaper().escape(...) + pattern-sinks: + - pattern: new org.apache.http.client.methods.HttpGet(...) + - pattern: new org.apache.commons.httpclient.methods.GetMethod(...) + - pattern: (org.apache.commons.httpclient.methods.GetMethod $GM).setQueryString(...) + message: "The application was found including unvalidated user input into a URL, which could lead to\n\ + HTTP Parameter Pollution (HPP) or worse, Server Side Request Forgery (SSRF). This could\nallow an adversary\ + \ to override the value of a URL or a request parameter. HTTP Parameter\nPollution\n(HPP) attacks consist\ + \ of injecting encoded query string delimiters into other existing\nparameters. If a web\napplication\ + \ does not properly sanitize the user input, an adversary may modify the logic of\nthese\nrequests to\ + \ other applications.\n\nTo remediate this issue, never allow user input directly into creation of a\ + \ URL or URL\nparameter. Consider\nusing a map to look up user-supplied information and return exact\ + \ values to be used in the\ngeneration of\nrequests.\n\nExample using a map to look up a key to be used\ + \ in a HTTP request:\n```\nHashMap lookupTable = new HashMap<>();\nlookupTable.put(\"\ + key1\", \"value1\");\nlookupTable.put(\"key2\", \"value2\");\nString userInput = request.getParameter(\"\ + key\");\n\n// Create a CloseableHttpClient, ideally any requests issued should be done\n// out-of-band\ + \ from the servlet request itself (such as using a separate thread/scheduler\nsystem)\ntry (final CloseableHttpClient\ + \ httpClient = HttpClients.createDefault()) {\n // Lookup the value from our user input from our\ + \ lookupTable\n String value = lookupTable.getOrDefault(userInput, \"value1\");\n // Construct\ + \ the url, with the hardcoded url and only pass in the value from the\nlookupTable,\n // not direct\ + \ user input\n final HttpGet httpget = new HttpGet(\"https://example.com/getId?key=\"+value);\n \ + \ // Execute the request\n CloseableHttpResponse clientResponse = httpClient.execute(httpget);\n\ + \ // Read the response\n byte[] responseData = clientResponse.getEntity().getContent().readAllBytes();\n\ + \ // Handle the response\n // ...\n}\n```\n\nIf using a map is not possible, the user-supplied\ + \ input must be encoded prior to use, and\nnever allow full\nURLs:\n```\n// Get user input\nString userInput\ + \ = request.getParameter(\"key\");\n// Encode the string using java.net.URLEncoder with the UTF-8 character\ + \ set\nString encodedString = java.net.URLEncoder.encode(userInput, StandardCharsets.UTF_8);\n// Create\ + \ a CloseableHttpClient, ideally any requests issued should be done\n// out-of-band from the servlet\ + \ request itself (such as using a separate thread/scheduler\nsystem)\ntry (final CloseableHttpClient\ + \ httpClient = HttpClients.createDefault()) {\n // Construct the url, with the hardcoded url and only\ + \ pass in the encoded value, never a\nfull URL\n final HttpGet httpget = new HttpGet(\"https://example.com/getId?key=\"\ + +encodedString);\n // Execute the request\n CloseableHttpResponse clientResponse = httpClient.execute(httpget);\n\ + \ // Read the response\n byte[] responseData = clientResponse.getEntity().getContent().readAllBytes();\n\ + \ // handle the response\n}\n```\n\nFor more information on SSRF see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html\n\ + \nFor more information on HTTP Parameter Pollution see:\nhttps://en.wikipedia.org/wiki/HTTP_parameter_pollution\n" + severity: ERROR + metadata: + shortDescription: Improper neutralization of argument delimiters in a command ('Argument Injection') + category: security + cwe: CWE-88 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + technology: + - java + security-severity: Medium + - id: gitlab-java_inject_rule-LDAPInjection + languages: [java] + mode: taint + pattern-sinks: + - pattern: javax.naming.ldap.LdapName(...) + - pattern: (javax.naming.directory.Context $C).lookup(...) + - pattern: (javax.naming.Context $C).lookup(...) + - patterns: + - pattern-inside: (com.unboundid.ldap.sdk.LDAPConnection $C).search($QUERY, ...) + - pattern: $QUERY + - patterns: + - pattern-either: + - pattern: $CTX.lookup(...) + - patterns: + - pattern-inside: $CTX.search($QUERY, ...) + - pattern: $QUERY + - patterns: + - pattern-inside: $CTX.search($NAME, $FILTER, ...) + - pattern: $FILTER + - metavariable-pattern: + metavariable: $CTX + pattern-either: + - pattern: (DirContext $C) + - pattern: (InitialDirContext $IDC) + - pattern: (LdapContext $LC) + - pattern: (EventDirContext $EDC) + - pattern: (LdapCtx $LC) + - pattern: (javax.naming.directory.DirContext $C) + - pattern: (javax.naming.directory.InitialDirContext $IDC) + - pattern: (javax.naming.ldap.LdapContext $LC) + - pattern: (javax.naming.event.EventDirContext $EDC) + - pattern: (com.sun.jndi.ldap.LdapCtx $LC) + - patterns: + - pattern-either: + - patterns: + - pattern-inside: $CTX.list($QUERY, ...) + - pattern: $QUERY + - patterns: + - pattern-inside: $CTX.lookup($QUERY, ...) + - pattern: $QUERY + - patterns: + - pattern-inside: $CTX.search($QUERY, ...) + - pattern: $QUERY + - patterns: + - pattern-inside: $CTX.search($NAME, $FILTER, ...) + - pattern: $FILTER + - metavariable-pattern: + metavariable: $CTX + pattern-either: + - pattern: (LdapTemplate $LT) + - pattern: (LdapOperations $LO) + - pattern: (org.springframework.ldap.core.LdapTemplate $LT) + - pattern: (org.springframework.ldap.core.LdapOperations $LO) + pattern-sources: + - patterns: + - pattern-inside: "$FUNC(..., $T $VAR, ...) {\n ...\n}\n" + - pattern: $VAR + - patterns: + - pattern-inside: "$FUNC(..., $T $X, ...) {\n ...\n $VAR = ... + $X;\n ...\n}\n" + - pattern: $VAR + message: "LDAP injection attacks exploit LDAP queries to influence how data is returned by\nthe LDAP server.\n\ + \nLater versions of Java's `InitialDirContext.search` introduced a four argument method, one of\nwhich\ + \ is the `filterArg` parameter. The `filterArg` will be automatically encoded when\nquerying\nthe LDAP\ + \ server. If this method signature is not available, the application must encode the\nLDAP strings manually.\n\ + \nMore details on the four argument `search` method can be found here:\nhttps://docs.oracle.com/en/java/javase/20/docs/api/java.naming/javax/naming/directory/InitialDirContext.html#search(javax.naming.Name,java.lang.String,java.lang.Object[],javax.naming.directory.SearchControls)\n\ + \nTo encode the string manually, it is recommended that all input passed to LDAP querying\nsystems\n\ + encode the following values:\n\n- Any occurrence of the null character must be escaped as “\\00”.\n\ + - Any occurrence of the open parenthesis character must be escaped as “\\28”.\n- Any occurrence of the\ + \ close parenthesis character must be escaped as “\\29”.\n- Any occurrence of the asterisk character\ + \ must be escaped as “\\2a”.\n- Any occurrence of the backslash character must be escaped as “\\5c”.\n\ + \nExample function that safely encodes user-supplied input to be used in an LDAP query.\n```\npublic\ + \ static String encodeLDAPString(String input) {\n // Note the \\ character is replaced first\n CharSequence[]\ + \ chars = new CharSequence[] { \"\\\\\", \"\\0\", \"(\", \")\", \"*\" };\n CharSequence[] encoded =\ + \ new CharSequence[] { \"\\\\5c\", \"\\\\00\", \"\\\\28\", \"\\\\29\", \"\\\\2a\" };\n // Iterate over\ + \ each character sequence, replacing the raw value with an encoded version of\nit\n for (int i = 0;\ + \ i < chars.length; i++)\n {\n // re-assign to input\n input = input.replace(chars[i], encoded[i]);\n\ + \ }\n // return our modified input string\n return input;\n}\n```\n\nExample code that using the\ + \ `filterArgs` parameter which automatically encodes for us:\n```\n// Create a properties to hold the\ + \ ldap connection details\nProperties props = new Properties();\n// Use the com.sun.jndi.ldap.LdapCtxFactory\ + \ factory provider\nprops.put(Context.INITIAL_CONTEXT_FACTORY, \"com.sun.jndi.ldap.LdapCtxFactory\"\ + );\n// The LDAP server URL\nprops.put(Context.PROVIDER_URL, \"ldap://ldap.example.org:3889\");\n// User\ + \ details for the connection\nprops.put(Context.SECURITY_PRINCIPAL, \"cn=admin,dc=example,dc=org\");\n\ + // LDAP account password\nString ldapAccountPassword = getAccountPasswordFromSecureStoreOrKMS();\n//\ + \ Pass in the LDAP password\nprops.put(Context.SECURITY_CREDENTIALS, ldapAccountPassword);\n\n// Create\ + \ the LDAPContext\nInitialDirContext ldapContext = new InitialDirContext(props);\n// Example using SUBTREE_SCOPE\ + \ SearchControls\nSearchControls searchControls = new SearchControls();\nsearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);\n\ + \n// Get user input for query\nString userQuery = someUserInput;\n// Use searchArguments to hold the\ + \ user-supplied input\nObject[] searchArguments = new Object[]{userQuery};\n// Hardcode the BaseDN,\ + \ use the {0} format specifier to use the searchArguments array value,\nand pass in the search controls.\n\ + // searchArguments automatically encode\nNamingEnumeration answer = ldapContext.search(\"dc=example,dc=org\"\ + , \"(cn={0})\",\nsearchArguments, searchControls);\n// Process the response answer\nwhile (answer.hasMoreElements())\ + \ {\n ...\n}\n```\n\nFor more information on LDAP Injection see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html\n" + severity: WARNING + metadata: + shortDescription: Improper neutralization of special elements used in an LDAP query ('LDAP Injection') + category: security + cwe: CWE-90 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + technology: + - java + security-severity: Medium + - id: gitlab-java_inject_rule-OgnlInjection + languages: [java] + mode: taint + pattern-sources: + - patterns: + - pattern-inside: "$FUNC(..., $T $VAR, ...) {\n ...\n}\n" + - metavariable-pattern: + metavariable: $VAR + pattern-either: + - pattern: (String $S) + - pattern: (Map $M) + - pattern: (Map $M) + - pattern: (Map $M) + - pattern: $VAR + pattern-sinks: + - patterns: + - pattern-inside: com.opensymphony.xwork2.util.TextParseUtil.translateVariables($VAL, ...) + - pattern: $VAL + - patterns: + - pattern-inside: com.opensymphony.xwork2.util.TextParseUtil.translateVariablesCollection($VAL, ...) + - pattern: $VAL + - pattern: com.opensymphony.xwork2.util.TextParseUtil.shallBeIncluded(...) + - pattern: com.opensymphony.xwork2.util.TextParseUtil.commaDelimitedStringToSet(...) + - patterns: + - pattern-inside: (com.opensymphony.xwork2.util.TextParser $P).evaluate($VAR, $VAL, ...) + - pattern: $VAL + - patterns: + - pattern-inside: (com.opensymphony.xwork2.util.OgnlTextParser $P).evaluate($VAR, $VAL, ...) + - pattern: $VAL + - pattern: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).getGetMethod($CLZ, ...) + - pattern: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).getSetMethod($CLZ, ...) + - pattern: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).getField($CLZ, ...) + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).setProperties($MAP, ...) + - pattern: $MAP + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).setProperty($VAL, ...) + - pattern: $VAL + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).getValue($VAL, ...) + - pattern: $VAL + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).setValue($VAL, ...) + - pattern: $VAL + - pattern: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).getGetMethod($CLZ, ...) + - pattern: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).getSetMethod($CLZ, ...) + - pattern: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).getField($CLZ, ...) + - patterns: + - pattern-inside: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).setProperties($MAP, + ...) + - pattern: $MAP + - patterns: + - pattern-inside: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).setProperty($VAR, + ...) + - pattern: $VAR + - patterns: + - pattern-inside: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).getValue($VAR, ...) + - pattern: $VAR + - patterns: + - pattern-inside: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).setValue($VAR, ...) + - pattern: $VAR + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).setProperties($MAP, ...) + - pattern: $MAP + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).setProperty($VAR, ...) + - pattern: $VAR + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).getValue($VAR, ...) + - pattern: $VAR + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).setValue($VAR, ...) + - pattern: $VAR + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).callMethod($VAR, ...) + - pattern: $VAR + - patterns: + - pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).compile($VAR, ...) + - pattern: $VAR + - pattern: (org.apache.struts2.util.VelocityStrutsUtil $P).evaluate(...) + - pattern: org.apache.struts2.util.StrutsUtil.findString(...) + - pattern: org.apache.struts2.util.StrutsUtil.findValue(..., $VAL) + - pattern: org.apache.struts2.util.StrutsUtil.getText(...) + - pattern: org.apache.struts2.util.StrutsUtil.translateVariables(...) + - patterns: + - pattern-inside: org.apache.struts2.util.StrutsUtil.makeSelectList($VAR, ...) + - pattern: $VAR + - patterns: + - pattern-inside: (org.apache.struts2.views.jsp.ui.OgnlTool $T).findValue($VAR, ...) + - pattern: $VAR + - pattern: (com.opensymphony.xwork2.util.ValueStack $V).findString(...) + - patterns: + - pattern-inside: (com.opensymphony.xwork2.util.ValueStack $V).findValue($VAR, ...) + - pattern: $VAR + - patterns: + - pattern-inside: (com.opensymphony.xwork2.util.ValueStack $V).setValue($VAR, ...) + - pattern: $VAR + - patterns: + - pattern-inside: (com.opensymphony.xwork2.util.ValueStack $V).setParameter($VAR, ...) + - pattern: $VAR + message: 'The Object Graph Navigation Language (OGNL) is an expression language that allows access to + + Java objects and properties stored in an ActionContext. Usage of these low-level + + functions is discouraged because they can effectively execute strings as code, leading to + + remote code execution vulnerabilities. Consider using struts tags when processing + + user-supplied input and templates. + + + Much like the Struts security guide recommending to not use raw `${}` EL expressions, + + do not call or use the following OGNL packages with user-supplied input: + + + - `com.opensymphony.xwork2.ognl` + + - `com.opensymphony.xwork2.util` + + - `com.opensymphony.xwork2.util.reflection` + + - `org.apache.struts2.util.StrutsUtil` + + + For more information on Struts2 security see: + + https://struts.apache.org/security/#do-not-use-incoming-untrusted-user-input-in-forced-expression-evaluation + + ' + severity: WARNING + metadata: + shortDescription: Expression injection (OGNL) + category: security + cwe: CWE-917 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + technology: + - java + security-severity: High + - id: gitlab-java_inject_rule-SpotbugsPathTraversalAbsolute + languages: [java] + mode: taint + pattern-sources: + - pattern: (javax.servlet.http.HttpServletRequest $R).$METHOD(...) + - pattern: (java.util.Scanner $S).$METHOD(...) + - pattern: (java.util.stream.Stream).$METHOD(...) + - pattern: (java.util.StringJoiner $SJ).toString(...) + - pattern: (java.sql.ResultSet.getString $R).$METHOD(...) + - pattern: (java.lang.System $S).getProperty(...) + - pattern: (java.lang.System $S).getenv(...) + - pattern: (java.lang.StringBuilder $SB).toString(...) + - pattern: (java.io.FileInputStream $F).read(...) + - pattern: (java.io.FileReader $F).read(...) + - pattern: (java.net.Socket $S).getInputStream(...) + - pattern: (java.net.Socket $S).getOutputStream(...) + - pattern: (java.net.DatagramSocket $S).receive(...) + - pattern: (java.net.DatagramSocket $S).getInputStream(...) + - pattern: java.nio.file.Files.readAllBytes(...) + - pattern: java.nio.file.Files.readAllLines(...) + - pattern: java.nio.file.Files.lines(...) + - pattern: java.nio.file.Files.newBufferedReader(...) + - pattern: org.apache.commons.io.IOUtils.toString(...) + - pattern: org.apache.commons.io.IOUtils.readLines(...) + - pattern: org.apache.commons.io.IOUtils.toByteArray(...) + - pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).readValue(...) + - pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).treeToValue(...) + - pattern: $CLASS.$METHOD(..., (javax.servlet.http.HttpServletRequest $R), ...) + - pattern: $FUNC(..., (javax.servlet.http.HttpServletRequest $R), ...) + - patterns: + - pattern-inside: $FUNC(..., @RequestParam String $X, ...) { ... } + - focus-metavariable: $X + pattern-propagators: + - pattern: $LIST.add($X) + from: $X + to: $LIST + - pattern: $MAP.put(..., $X) + from: $X + to: $MAP + - pattern: $STR.concat($X) + from: $X + to: $STR + - pattern: $STR = String.format(..., $X, ...) + from: $X + to: $STR + - pattern: $STR = String.join(..., $X, ...) + from: $X + to: $STR + pattern-sanitizers: + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + pattern-sinks: + - patterns: + - pattern-inside: '$U = new java.net.URI($VAR) + + ' + - pattern-either: + - pattern-inside: new java.io.File($U) + - pattern-inside: java.nio.file.Paths.get($U) + - pattern: $VAR + - patterns: + - pattern-inside: new java.io.RandomAccessFile($INPUT,...) + - pattern: $INPUT + - pattern: new java.io.FileReader(...) + - pattern: new javax.activation.FileDataSource(...) + - pattern: new java.io.FileInputStream(...) + - pattern: new java.io.FileOutputStream(...) + - pattern: new java.io.File(...) + - pattern: java.nio.file.Paths.get(...) + - pattern: java.io.File.createTempFile(...) + - pattern: java.io.File.createTempDirectory(...) + - pattern: java.nio.file.Files.createTempFile(...) + - pattern: java.nio.file.Files.createTempDirectory(...) + - patterns: + - pattern: $SRC.$METHOD(...) + - metavariable-pattern: + metavariable: $SRC + pattern-either: + - pattern: getClass() + - pattern: getClass().getClassLoader() + - pattern: (ClassLoader $C) + - pattern: (Class $C) + - pattern: $CLZ.getClassLoader() + - metavariable-pattern: + metavariable: $METHOD + pattern-either: + - pattern: getResourceAsStream + - pattern: getResource + - patterns: + - pattern-inside: new java.io.FileWriter($PATH, ...) + - pattern: $PATH + - patterns: + - pattern-inside: new java.io.FileOutputStream($PATH, ...) + - pattern: $PATH + message: "The application dynamically constructs file or path information. If the path\ninformation comes\ + \ from user input, it could be abused to read sensitive files,\naccess other users' data, or aid in\ + \ exploitation to gain further system access.\n\nUser input should never be used in constructing paths\ + \ or files for interacting\nwith the filesystem. This includes filenames supplied by user uploads or\ + \ downloads.\nIf possible, consider hashing user input or replacing it with unique values and\nuse `Path.resolve`\ + \ to resolve and validate the path information\nprior to processing any file functionality.\n\nExample\ + \ using `Path.resolve` and not allowing direct user input:\n```\n// Class to store our user data along\ + \ with a randomly generated file name\npublic static class UserData {\n private String userFileNameUnsafe;\n\ + \ private String fileName;\n public UserData(String userFileName) {\n this.userFileNameUnsafe\ + \ = userFileName;\n // Generate a random ID for the filename\n this.fileName = UUID.randomUUID().toString();\n\ + \ }\n public String getUserFileNameUnsafe() { return userFileNameUnsafe; };\n public String\ + \ getFileName() { return fileName; };\n}\n\npublic static void main(String[] args) throws Exception\ + \ {\n // User input, saved only as a reference\n UserData userData = new UserData(\"..\\\\test.txt\"\ + );\n // Restrict all file processing to this directory only\n String base = \"/var/app/restricted\"\ + ;\n Path basePath = Paths.get(base);\n // Resolve the full path, but only use our random generated\ + \ filename\n Path fullPath = basePath.resolve(userData.getFileName());\n // verify the path is\ + \ contained within our basePath\n if (!fullPath.startsWith(base)) {\n throw new Exception(\"\ + Invalid path specified!\");\n }\n // process / work with file\n}\n```\n\nFor more information\ + \ on path traversal issues see OWASP:\nhttps://owasp.org/www-community/attacks/Path_Traversal\n" + metadata: + shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal') + cwe: CWE-22 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + security-severity: Medium + technology: + - java + category: security + severity: WARNING + - id: gitlab-java_ldap_rule-AnonymousLDAP + languages: [java] + patterns: + - pattern-inside: 'import javax.naming.Context; + + ... + + ' + - pattern: $ENV.put(Context.SECURITY_AUTHENTICATION, "none"); + message: "The application does not provide authentication when communicating an LDAP\nserver. It is strongly\ + \ recommended that the LDAP server be configured with\nauthentication and restrict what queries users\ + \ can execute.\n\nExample code that authenticates with a remote LDAP server and encodes any\nuser-supplied\ + \ input:\n```\n// Create a properties to hold the ldap connection details\nProperties props = new Properties();\n\ + // Use the com.sun.jndi.ldap.LdapCtxFactory factory provider\nprops.put(Context.INITIAL_CONTEXT_FACTORY,\ + \ \"com.sun.jndi.ldap.LdapCtxFactory\");\n// The LDAP server URL\nprops.put(Context.PROVIDER_URL, \"\ + ldap://ldap.example.org:3889\");\n// User details for the connection\nprops.put(Context.SECURITY_PRINCIPAL,\ + \ \"cn=admin,dc=example,dc=org\");\n// LDAP account password\nString ldapAccountPassword = getAccountPasswordFromSecureStoreOrKMS();\n\ + // Pass in the LDAP password\nprops.put(Context.SECURITY_CREDENTIALS, ldapAccountPassword);\n\n// Create\ + \ the LDAPContext\nInitialDirContext ldapContext = new InitialDirContext(props);\n// Example using SUBTREE_SCOPE\ + \ SearchControls\nSearchControls searchControls = new SearchControls();\nsearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);\n\ + \n// Get user input for query\nString userQuery = someUserInput;\n// Use searchArguments to hold the\ + \ user-supplied input\nObject[] searchArguments = new Object[]{userQuery};\n// Hardcode the BaseDN,\ + \ use the {0} format specifier to use the searchArguments array value,\nand pass in the search controls.\n\ + // searchArguments automatically encode\nNamingEnumeration answer = ldapContext.search(\"dc=example,dc=org\"\ + , \"(cn={0})\",\nsearchArguments, searchControls);\n// Process the response answer\nwhile (answer.hasMoreElements())\ + \ {\n ...\n}\n```\n\nFor information on enabling authentication, please see your LDAP server's\ndocumentation.\n\ + \nFor more information on LDAP Injection see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html\n" + metadata: + shortDescription: Missing authentication for critical function (LDAP) + category: security + cwe: CWE-306 + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + security-severity: High + severity: WARNING + - id: gitlab-java_password_rule-ConstantDBPassword + languages: [java] + patterns: + - pattern: java.sql.DriverManager.getConnection($URI, $USR, "..."); + - pattern-not: java.sql.DriverManager.getConnection($URI, $USR, ""); + message: 'A potential hard-coded password was identified in a database connection string. + + Passwords should not be stored directly in code + + but loaded from secure locations such as a Key Management System (KMS). + + + The purpose of using a Key Management System is so access can be audited and keys easily + + rotated + + in the event of a breach. By hardcoding passwords, it will be extremely difficult to determine + + when or if, a key is compromised. + + + The recommendation on which KMS to use depends on the environment the application is running + + in: + + + - For Google Cloud Platform consider [Cloud Key Management](https://cloud.google.com/kms/docs) + + - For Amazon Web Services consider [AWS Key Management](https://aws.amazon.com/kms/) + + - For on premise or other alternatives to cloud providers, consider [Hashicorp''s + + Vault](https://www.vaultproject.io/) + + - For other cloud providers, please see their documentation + + ' + severity: ERROR + metadata: + shortDescription: Use of hard-coded password + category: security + cwe: CWE-259 + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + technology: + - java + security-severity: Critical + - id: gitlab-java_password_rule-EmptyDBPassword + languages: [java] + patterns: + - pattern: java.sql.DriverManager.getConnection($URI, $USR, ""); + message: 'The application does not provide authentication when communicating a database + + server. It is strongly recommended that the database server be configured with + + authentication and restrict what queries users can execute. + + + Please see your database server''s documentation on how to configure a password. + + + Additionally, passwords should not be stored directly in code + + but loaded from secure locations such as a Key Management System (KMS). + + + The purpose of using a Key Management System is so access can be audited and keys easily + + rotated + + in the event of a breach. By hardcoding passwords, it will be extremely difficult to determine + + when or if, a key is compromised. + + + The recommendation on which KMS to use depends on the environment the application is running + + in: + + + - For Google Cloud Platform consider [Cloud Key Management](https://cloud.google.com/kms/docs) + + - For Amazon Web Services consider [AWS Key Management](https://aws.amazon.com/kms/) + + - For on premise or other alternatives to cloud providers, consider [Hashicorp''s + + Vault](https://www.vaultproject.io/) + + - For other cloud providers, please see their documentation + + ' + severity: ERROR + metadata: + shortDescription: Missing authentication for critical function (database) + category: security + cwe: CWE-306 + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + technology: + - java + security-severity: Critical + - id: gitlab-java_password_rule-HardcodePassword + languages: [java] + pattern-either: + - pattern: new java.security.KeyStore.PasswordProtection("...".toCharArray()) + - pattern: java.security.KeyStore.getInstance(...).load(..., "...".toCharArray()) + - pattern: (java.security.KeyStore $KS).load(..., "...".toCharArray()) + - pattern: KeyManagerFactory.getInstance(...).init(..., "...".toCharArray()) + - pattern: (KeyManagerFactory $KMF).init(..., "...".toCharArray()) + - pattern: PBEKeySpec("...", ...) + - pattern: PasswordAuthentication("...", "...") + - pattern: (PasswordCallback $CB).setPassword("...") + - pattern: KerberosKey(...,"...",...) + - pattern: java.sql.DriverManager.getConnection(..., "...") + - pattern: io.vertx.ext.web.handler.CSRFHandler.create(..., "...") + - pattern: $S.setPassword("...") + message: 'A potential hard-coded password was identified in a hard-coded string. + + Passwords should not be stored directly in code + + but loaded from secure locations such as a Key Management System (KMS). + + + The purpose of using a Key Management System is so access can be audited and keys easily + + rotated + + in the event of a breach. By hardcoding passwords, it will be extremely difficult to determine + + when or if, a key is compromised. + + + The recommendation on which KMS to use depends on the environment the application is running + + in: + + + - For Google Cloud Platform consider [Cloud Key Management](https://cloud.google.com/kms/docs) + + - For Amazon Web Services consider [AWS Key Management](https://aws.amazon.com/kms/) + + - For on premise or other alternatives to cloud providers, consider [Hashicorp''s + + Vault](https://www.vaultproject.io/) + + - For other cloud providers, please see their documentation + + ' + severity: ERROR + metadata: + shortDescription: Use of hard-coded password + category: security + cwe: CWE-259 + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + technology: + - java + security-severity: High + - id: gitlab-java_perm_rule-DangerousPermissions + languages: [java] + pattern-either: + - pattern: '$RUNVAR = new RuntimePermission("createClassLoader"); + + ... + + (PermissionCollection $PC).add($RUNVAR); + + ' + - pattern: '$REFVAR = new ReflectPermission("suppressAccessChecks"); + + ... + + (PermissionCollection $PC).add($REFVAR); + + ' + - pattern: (PermissionCollection $PC).add(new ReflectPermission("suppressAccessChecks")) + - pattern: (PermissionCollection $PC).add(new RuntimePermission("createClassLoader")) + message: 'The application was found to permit the `RuntimePermission` of `createClassLoader`, + + `ReflectPermission` of `suppressAccessChecks`, or both. + + + By granting the `RuntimePermission` of `createClassLoader`, a compromised application + + could instantiate their own class loaders and load arbitrary classes. + + + By granting the `ReflectPermission` of `suppressAccessChecks` an application will no longer + + check Java language access checks on fields and methods of a class. This will effectively + + grant access to protected and private members. + + + For more information on `RuntimePermission` see: + + https://docs.oracle.com/javase/8/docs/api/java/lang/RuntimePermission.html + + + For more information on `ReflectPermission` see: + + https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/ReflectPermission.html + + ' + metadata: + shortDescription: Incorrect permission assignment for critical resource + category: security + cwe: CWE-732 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + confidence: HIGH + security-severity: Medium + severity: WARNING + - id: gitlab-java_perm_rule-OverlyPermissiveFilePermissionInline + languages: [java] + patterns: + - pattern-either: + - pattern: java.nio.file.Files.setPosixFilePermissions(..., java.nio.file.attribute.PosixFilePermissions.fromString("$PERM_STRING")); + - pattern: '$PERMISSIONS = java.nio.file.attribute.PosixFilePermissions.fromString("$PERM_STRING"); + + ... + + java.nio.file.Files.setPosixFilePermissions(..., $PERMISSIONS); + + ' + - metavariable-regex: + metavariable: $PERM_STRING + regex: '[rwx-]{6}[rwx]{1,}' + message: 'The application was found setting file permissions to overly permissive values. Consider + + using the following values if the application user is the only process to access + + the file: + + + - `r--` - read only access to the file + + - `w--` - write only access to the file + + - `rw-` - read/write access to the file + + + Example setting read/write permissions for only the owner of a `Path`: + + ``` + + // Get a reference to the path + + Path path = Paths.get("/tmp/somefile"); + + // Create a PosixFilePermission set from java.nio.file.attribute + + Set permissions = + + java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"); + + // Set the permissions + + java.nio.file.Files.setPosixFilePermissions(path, permissions); + + ``` + + + For all other values please see: + + https://en.wikipedia.org/wiki/File-system_permissions#Symbolic_notation + + ' + metadata: + shortDescription: Incorrect permission assignment for critical resource + cwe: CWE-732 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + category: security + confidence: HIGH + security-severity: Medium + severity: WARNING + - id: gitlab-java_script_rule-ScriptInjection + languages: [java] + mode: taint + pattern-sinks: + - patterns: + - pattern: (javax.script.ScriptEngine $ENGINE).eval($ARG, ...); + - pattern-not: (javax.script.ScriptEngine $ENGINE).eval("..."); + - pattern-not: (javax.script.ScriptEngine $ENGINE).eval("...", (javax.script.Bindings $BINDING)); + - patterns: + - pattern-either: + - pattern: (javax.script.Invocable $INVC).invokeFunction(..., $ARG) + - pattern: (javax.script.Invocable $INVC).invokeMethod(..., $ARG) + pattern-sources: + - patterns: + - pattern-inside: $FUNC(..., $T $VAR, ...) { ... } + - pattern: $VAR + message: "The application executes an argument using a `ScriptEngine`'s `eval` method. This\nmay allow\ + \ for direct OS commands to be executed as it's possible to pass in strings\nsuch as `java.lang.Runtime.getRuntime().exec('/bin/sh\ + \ ...');`.\n\nNever pass user-supplied input directly to the `eval` function. If possible hardcode all\n\ + JavasScript code or use a lookup table to resolve user input to known values. If none of these\ntechniques\ + \ are possible, use `javax.script.Bindings` to pass input to the script engine.\n\nExample using `Binding`\ + \ to safely pass in string values:\n```\n// Get ECMAScript engine\nScriptEngine engine = new ScriptEngineManager().getEngineByName(\"\ + ECMAScript\");\n\n// User input, consisting of first and last name\nString userFirstName = \"John\"\ + ;\nString userLastName = \"Snow\";\n\n// Create bindings to pass into our script, forcing the values\ + \ to be String.\nBindings bindings = engine.createBindings();\nbindings.put(\"fname\", new String(userFirstName));\n\ + bindings.put(\"lname\", new String(userLastName));\n\n// Example script that concatenates a greeting\ + \ with the user-supplied input first/last name\nString script = \"var greeting='Hello ';\" +\n// fname\ + \ and lname variables will be resolved by our bindings defined above\n\"greeting += fname + ' ' + lname;\"\ + \ +\n// prints greeting\n\"greeting\";\n\ntry {\n // Execute the script, passing in the bindings\n\ + \ Object bindingsResult = engine.eval(script, bindings);\n // Work with result\n // ...\n} catch\ + \ (ScriptException e) {\n // Handle exception\n e.printStackTrace();\n}\n```\n" + severity: ERROR + metadata: + shortDescription: Improper control of generation of code ('Code Injection') + category: security + cwe: CWE-94 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + security-severity: High + - id: gitlab-java_script_rule-SpringSpelExpressionParser + languages: [java] + patterns: + - pattern: ($PARSER $P).$METHOD($ARG); + - pattern-not: ($PARSER $P).$METHOD("..."); + - metavariable-pattern: + metavariable: $PARSER + pattern-either: + - pattern: org.springframework.expression.spel.standard.SpelExpressionParser + - pattern: org.springframework.expression.ExpressionParser + - metavariable-regex: + metavariable: $METHOD + regex: (parseExpression|parseRaw) + message: "The application was found calling SpringFramework's `SpelExpressionParser.parseExpression`.\n\ + Calling this method directly with user-supplied input may allow an adversary to\nexecute arbitrary Java\ + \ code including OS system commands.\n\nNever call `parseExpression` or `parseRaw` directly with user-supplied\ + \ input. Consider\nalternate\nmethods such as a lookup table to take user input and resolve hardcoded\ + \ values.\n\nLater versions of SpringFramework introduced a `SimpleEvaluationContext` which can be\n\ + used to access bound data when calling the `getValue` result of `parseExpression`. This\n`SimpleEvaluationContext`\ + \ has a reduced set of functionality and can restrict data binding\nto read-only or read-write contexts.\ + \ An adversary could still access public properties\nor fields on custom types that have been provided\ + \ to the evaluation context. Use with caution.\n\nExample using `SimpleEvaluationContext` with a read-write\ + \ data binding context:\n```\n@RequestMapping(value=\"/spel\", method=RequestMethod.POST)\npublic String\ + \ spel(@Validated User user, Model model) {\n // Create the Expression Parser\n SpelExpressionParser\ + \ parser = new SpelExpressionParser();\n // Parse the expression\n Expression parsedExpression = parser.parseExpression(model.getPossiblyUnsafeData());\n\ + \ // Create the read-write data binding context\n SimpleEvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();\n\ + \ // Execute the expression, passing in the read-write context\n Object result = parsedExpression.getValue(context);\n\ + \ // work with the result\n // ...\n return \"user\";\n}\n```\n\nFor more information on SimpleEvaluationContext\ + \ see:\nhttps://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/expression/spel/support/SimpleEvaluationContext.html\n" + severity: ERROR + metadata: + shortDescription: Improper neutralization of special elements used in an expression language statement + ('Expression Language Injection') + category: security + cwe: CWE-917 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + security-severity: High + - id: gitlab-java_smtp_rule-InsecureSmtp + languages: [java] + patterns: + - pattern-either: + - pattern-inside: '$E = new org.apache.commons.mail.SimpleEmail(...); + + ... + + ' + - pattern-inside: '$E = new org.apache.commons.mail.Email(...); + + ... + + ' + - pattern-inside: '$E = new org.apache.commons.mail.MultiPartEmail(...); + + ... + + ' + - pattern-inside: '$E = new org.apache.commons.mail.HtmlEmail(...); + + ... + + ' + - pattern-inside: '$E = new org.apache.commons.mail.ImageHtmlEmail(...); + + ... + + ' + - pattern-not-inside: '... + + $E.setSSLOnConnect(true); + + ... + + $E.setSSLCheckServerIdentity(true); + + ' + - pattern-not-inside: '... + + $E.setSSLCheckServerIdentity(true); + + ... + + $E.setSSLOnConnect(true); + + ' + message: 'The Apache commons mail client by default does not enable TLS server identity. + + This allows for an adversary who is in between the application and the target host to intercept + + potentially sensitive information or transmit malicious data. + + + Enable checking server identity by calling `Email.setSSLCheckServerIdentity(true)` + + + Example email client that enables TLS and server identity: + + ``` + + // Create an email client + + Email email = new SimpleEmail(); + + // Configure the email hostname + + email.setHostName("smtp.mail.example.com"); + + // Set the port + + email.setSmtpPort(465); + + // Securely retrieve username and password values + + String username = getUserNameFromKMSorSecretStore(); + + String password = getPasswordFromKMSorSecretStore(); + + // Configure the Authenticator + + DefaultAuthenticator auth = new DefaultAuthenticator(username, password); + + // Set the authenticator + + email.setAuthenticator(auth); + + // Ensure we use SSL on connect + + email.setSSLOnConnect(true); + + // Ensure we validate server identity + + email.setSSLCheckServerIdentity(true); + + // configure the rest of the email + + email.setFrom("x@example.com"); + + email.setSubject("TestMail"); + + email.setMsg("This is a test mail ... :-)"); + + email.addTo("y@example.com"); + + email.send(); + + ``` + + ' + metadata: + shortDescription: Improper validation of certificate with host mismatch + category: security + cwe: CWE-297 + owasp: + - A3:2017-Sensitive Data Exposure + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + security-severity: Medium + severity: ERROR + - id: gitlab-java_smtp_rule-SmtpClient + languages: [java] + message: 'The application was found calling `MimeMessage` methods without encoding + + new line characters. Much like HTTP, Simple Mail Transfer Protocol (SMTP) is a + + text based protocol that uses headers to convey additional directives for how + + email messages should be treated. An adversary could potentially cause email + + messages to be sent to unintended recipients by abusing the CC or BCC headers + + if they were able to inject them. + + + To mitigate this issue, `\r\n` (CRLF) character sequences must be escaped + + or encoded prior to being used in any of the `MimeMessage` methods. + + + Example that escapes values that come from user input with + + [Apache Commons Text](https://commons.apache.org/proper/commons-text/): + + ``` + + // Create a MimeMessage with a javax.mail.Session + + Message message = new MimeMessage(session); + + // Set the from address + + message.setFrom(new InternetAddress("source@example.com")); + + // Set the to address + + message.setRecipients(Message.RecipientType.TO,new InternetAddress[] {new + + InternetAddress("destination@example.com")}); + + // Example user input + + String subject = "potentially malicious data"; + + String headerValue = "potentially malicious data"; + + // Use Apache Commons Text StringEscapeUtils.escapeJava to encode \r\n to \\r\\n. + + message.setSubject(StringEscapeUtils.escapeJava(subject)); + + // Use Apache Commons Text StringEscapeUtils.escapeJava to encode \r\n to \\r\\n. + + message.addHeader("HeaderName", StringEscapeUtils.escapeJava(header)); + + // Use Apache Commons Text StringEscapeUtils.escapeJava to encode \r\n to \\r\\n. + + message.setDescription(StringEscapeUtils.escapeJava("some description")); + + // Use Apache Commons Text StringEscapeUtils.escapeJava to encode \r\n to \\r\\n. + + message.setDisposition(StringEscapeUtils.escapeJava("some disposition")); + + // Set the mail body text + + message.setText("Some email content."); + + // Send the message + + ``` + + ' + patterns: + - pattern-inside: '$M = new MimeMessage(...); + + ... + + ' + - pattern-either: + - patterns: + - pattern-either: + - pattern: $M.setSubject($VAR) + - pattern: $M.addHeader($ARG, $VAR) + - pattern: $M.addHeader($VAR, $ARG) + - pattern: $M.setDescription($VAR) + - pattern: $M.setDisposition($VAR) + - metavariable-regex: + metavariable: $VAR + regex: ^[a-zA-Z_$][a-zA-Z0-9_$]*$ + - patterns: + - pattern-either: + - pattern: $M.setSubject($OBJ.$GETTER(...)) + - pattern: $M.setSubject($OBJ.$GETTER(...) + ...) + - pattern: $M.setSubject(... + $OBJ.$GETTER(...)) + - pattern: $M.setSubject(... + $OBJ.$GETTER(...) + ...) + - pattern: $M.addHeader($ARG, $OBJ.$GETTER(...)) + - pattern: $M.addHeader($ARG, $OBJ.$GETTER(...) + ...) + - pattern: $M.addHeader($ARG, ... + $OBJ.$GETTER(...)) + - pattern: $M.addHeader($ARG, ... + $OBJ.$GETTER(...) + ...) + - pattern: $M.addHeader($OBJ.$GETTER(...), $ARG) + - pattern: $M.addHeader($OBJ.$GETTER(...) + ..., $ARG) + - pattern: $M.addHeader(... + $OBJ.$GETTER(...), $ARG) + - pattern: $M.addHeader(... + $OBJ.$GETTER(...) + ..., $ARG) + - pattern: $M.setDescription($OBJ.$GETTER(...)) + - pattern: $M.setDisposition($OBJ.$GETTER(...) + ...) + - pattern: $M.setDisposition(... + $OBJ.$GETTER(...)) + - pattern: $M.setDisposition(... + $OBJ.$GETTER(...) + ...) + - metavariable-regex: + metavariable: $GETTER + regex: ^get + metadata: + shortDescription: Improper neutralization of special elements used in a command + category: security + cwe: CWE-77 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + security-severity: Low + severity: ERROR + - id: gitlab-java_ssrf_rule-SSRF + languages: [java] + message: "Server-Side-Request-Forgery (SSRF) exploits backend systems that initiate requests to third\n\ + parties.\nIf user input is used in constructing or sending these requests, an attacker could supply\n\ + malicious\ndata to force the request to other systems or modify request data to cause unwanted actions.\n\ + \nEnsure user input is not used directly in constructing URLs or URIs when initiating requests\nto third\ + \ party\nsystems from back end systems. Care must also be taken when constructing payloads using user\n\ + input. Where\npossible restrict to known URIs or payloads. Consider using a server-side map where keys\ + \ are\nused to return\nURLs such as `https://site/goto?key=1` where `{key: 1, url: 'http://some.url/',\ + \ key: 2, url:\n'http://...'}`.\n\nIf you must use user-supplied input for requesting URLs, it is strongly\ + \ recommended that the\nHTTP client\nchosen allows you to customize and block certain IP ranges at the\ + \ network level. By blocking\nRFC 1918\naddresses or other network address ranges, you can limit the\ + \ severity of a successful SSRF\nattack. Care must\nalso be taken to block certain protocol or address\ + \ formatting such as IPv6.\n\nIf you cannot block address ranges at the client level, you may want to\ + \ run the HTTP client\nas a protected\nuser, or in a protected network where you can apply IP Table\ + \ or firewall rules to block access\nto dangerous\naddresses. Finally, if none of the above protections\ + \ are available, you could also run a\ncustom HTTP proxy\nand force all requests through it to handle\ + \ blocking dangerous addresses.\n\nExample using a map to look up a key to be used in a HTTP request:\n\ + ```\nHashMap lookupTable = new HashMap<>();\nlookupTable.put(\"key1\", \"https://example.com/\"\ + );\nlookupTable.put(\"key2\", \"https://safeurl.com/\");\nString userInput = request.getParameter(\"\ + key\");\n\n// Create a CloseableHttpClient, ideally any requests issued should be done\n// out-of-band\ + \ from the servlet request itself (such as using a separate thread/scheduler\nsystem)\ntry (final CloseableHttpClient\ + \ httpClient = HttpClients.createDefault()) {\n // Lookup the value from our user input from our\ + \ lookupTable\n String value = lookupTable.getOrDefault(userInput, \"https://example.com/\");\n \ + \ // Construct the url, with the hardcoded url and only pass in the value from the\nlookupTable,\n\ + \ // not direct user input\n final HttpGet httpget = new HttpGet(value);\n // Execute the request\n\ + \ CloseableHttpResponse clientResponse = httpClient.execute(httpget);\n // Read the response\n\ + \ byte[] responseData = clientResponse.getEntity().getContent().readAllBytes();\n // Handle the\ + \ response\n // ...\n}\n```\n\nIf using a map is not possible, the user-supplied input must be encoded\ + \ prior to use, and\nnever allow full\nURLs:\n```\n// Get user input\nString userInput = request.getParameter(\"\ + key\");\n// Encode the string using java.net.URLEncoder with the UTF-8 character set\nString encodedString\ + \ = java.net.URLEncoder.encode(userInput, StandardCharsets.UTF_8);\n// Create a CloseableHttpClient,\ + \ ideally any requests issued should be done\n// out-of-band from the servlet request itself (such as\ + \ using a separate thread/scheduler\nsystem)\ntry (final CloseableHttpClient httpClient = HttpClients.createDefault())\ + \ {\n // Construct the url, with the hardcoded url and only pass in the encoded value, never a\nfull\ + \ URL\n final HttpGet httpget = new HttpGet(\"https://example.com/getId?key=\"+encodedString);\n //\ + \ Execute the request\n CloseableHttpResponse clientResponse = httpClient.execute(httpget);\n // Read\ + \ the response\n byte[] responseData = clientResponse.getEntity().getContent().readAllBytes();\n //\ + \ handle the response\n}\n```\n\nFor more information on SSRF see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html\n" + pattern-either: + - patterns: + - pattern-either: + - pattern-inside: 'import java.net.*; + + ... + + ' + - pattern-inside: 'import java.net.URL; + + ... + + ' + - pattern-inside: 'import java.net.URI; + + ... + + ' + - pattern: new $TYPE(...). ... .$FUNC + - pattern-not: new $TYPE("..."). ... .$FUNC + - metavariable-pattern: + metavariable: $FUNC + pattern-either: + - pattern: connect + - pattern: GetContent + - pattern: openConnection + - pattern: openStream + - pattern: getContent + - metavariable-pattern: + metavariable: $TYPE + pattern-either: + - pattern: URL + - pattern: java.net.URL + - pattern: URI + - pattern: java.net.URI + - patterns: + - pattern-either: + - pattern-inside: 'import java.net.*; + + ... + + ' + - pattern-inside: 'import java.net.InetSocketAddress; + + ... + + ' + - pattern: 'new InetSocketAddress(..., $PORT) + + ' + - pattern-not: 'new InetSocketAddress("...", $PORT) + + ' + metadata: + shortDescription: Server-Side Request Forgery (SSRF) + category: security + cwe: CWE-918 + owasp: + - A1:2017-Injection + - A10:2021-Server-Side Request Forgery + - A01:2025-Broken Access Control + security-severity: Medium + severity: ERROR + - id: gitlab-java_strings_rule-BadHexConversion + languages: [java] + message: 'The application is using `Integer.toHexString` on a digest array buffer which + + may lead to an incorrect version of values. + + + Consider using the `java.util.HexFormat` object introduced in Java 17. For older Java applications + + consider using the `javax.xml.bind.DatatypeConverter`. + + + Example using `HexFormat` to create a human-readable string: + + ``` + + // Create a MessageDigest using the SHA-384 algorithm + + MessageDigest sha384Digest = MessageDigest.getInstance("SHA-384"); + + // Call update with your data + + sha384Digest.update("some input".getBytes(StandardCharsets.UTF_8)); + + // Only call digest once all data has been fed into the update sha384digest instance + + byte[] output = sha384Digest.digest(); + + // Create a JDK 17 HexFormat object + + HexFormat hex = HexFormat.of(); + + // Use formatHex on the byte array to create a string (note that alphabet characters are + + lowercase) + + String hexString = hex.formatHex(output); + + ``` + + + For more information on DatatypeConverter see: + + https://docs.oracle.com/javase/9/docs/api/javax/xml/bind/DatatypeConverter.html#printHexBinary-byte:A- + + ' + patterns: + - pattern-inside: '$B_ARR = (java.security.MessageDigest $MD).digest(...); + + ... + + ' + - pattern-either: + - pattern: "for(...) {\n ...\n $B = $B_ARR[...];\n ...\n Integer.toHexString($B);\n}\n" + - pattern: "for(...) {\n ...\n Integer.toHexString($B_ARR[...]);\n}\n" + - pattern: "for(byte $B :$B_ARR) {\n ...\n Integer.toHexString($B);\n}\n" + - pattern: "while(...) {\n ...\n Integer.toHexString($B_ARR[...])\n}\n" + - pattern: "do {\n ...\n Integer.toHexString($B_ARR[...])\n} while(...)\n" + - pattern: "while(...) {\n ...\n $B = $B_ARR[...];\n ...\n Integer.toHexString($B);\n}\n" + - pattern: "do {\n ...\n $B = $B_ARR[...];\n ...\n Integer.toHexString($B);\n} while(...)\n" + metadata: + shortDescription: Incorrect type conversion or cast + cwe: CWE-704 + category: security + confidence: HIGH + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + security-severity: Info + severity: WARNING + - id: gitlab-java_strings_rule-FormatStringManipulation + languages: [java] + patterns: + - pattern-either: + - patterns: + - pattern-inside: 'String $INPUT = (HttpServletRequest $REQ).getParameter(...); + + ... + + ' + - pattern-inside: 'String $FORMAT_STR = ... + $INPUT; + + ... + + ' + - patterns: + - pattern-inside: 'String $INPUT = (HttpServletRequest $REQ).getParameter(...); + + ... + + ' + - pattern-inside: 'String $FORMAT_STR = ... + $INPUT + ...; + + ... + + ' + - pattern-inside: 'String $FORMAT_STR = ... + (HttpServletRequest $REQ).getParameter(...) + ...; + + ... + + ' + - pattern-inside: 'String $FORMAT_STR = ... + (HttpServletRequest $REQ).getParameter(...); + + ... + + ' + - pattern-either: + - pattern: String.format($FORMAT_STR, ...); + - pattern: String.format(java.util.Locale.$LOCALE, $FORMAT_STR, ...); + - pattern: (java.util.Formatter $F).format($FORMAT_STR, ...); + - pattern: (java.util.Formatter $F).format(java.util.Locale.$LOCALE, $FORMAT_STR, ...); + - pattern: (java.io.PrintStream $F).printf($FORMAT_STR, ...); + - pattern: (java.io.PrintStream $F).printf(java.util.Locale.$LOCALE, $FORMAT_STR, ...); + - pattern: (java.io.PrintStream $F).format($FORMAT_STR, ...); + - pattern: (java.io.PrintStream $F).format(java.util.Locale.$LOCALE, $FORMAT_STR, ...); + - pattern: System.out.printf($FORMAT_STR, ...); + - pattern: System.out.printf(java.util.Locale.$LOCALE, $FORMAT_STR, ...); + - pattern: System.out.format($FORMAT_STR, ...); + - pattern: System.out.format(java.util.Locale.$LOCALE, $FORMAT_STR, ...); + message: 'The application allows user input to control format string parameters. By passing invalid + + format + + string specifiers an adversary could cause the application to throw exceptions or possibly + + leak + + internal information depending on application logic. + + + Never allow user-supplied input to be used to create a format string. Replace all format + + string + + arguments with hardcoded format strings containing the necessary specifiers. + + + Example of using `String.format` safely: + + ``` + + // Get untrusted user input + + String userInput = request.getParameter("someInput"); + + // Ensure that user input is not included in the first argument to String.format + + String.format("Hardcoded string expecting a string: %s", userInput); + + // ... + + ``` + + ' + metadata: + shortDescription: Use of externally-controlled format string + cwe: CWE-134 + category: security + confidence: HIGH + owasp: + - A1:2017-Injection + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + security-severity: Medium + severity: ERROR + - id: gitlab-java_strings_rule-ModifyAfterValidation + languages: [java] + patterns: + - pattern: '(java.util.regex.Pattern $Y).matcher($VAR); + + ... + + $VAR.$METHOD(...); + + ' + - metavariable-regex: + metavariable: $METHOD + regex: (replace|replaceAll|replaceFirst|concat) + message: "The application was found matching a variable during a regular expression\npattern match, and\ + \ then calling string modification functions after validation has occurred.\nThis is usually indicative\ + \ of a poor input validation strategy as an adversary may attempt to\nexploit the removal of characters.\n\ + \nFor example a common mistake in attempting to remove path characters to protect against path\ntraversal\ + \ is to match '../' and then remove any matches. However, if an adversary were to\ninclude in their\ + \ input: '....//' then the `replace` method would replace the first `../` but\ncause the leading `..`\ + \ and trailing `/` to join into the final string of `../`, effectively\nbypassing the check.\n\nTo remediate\ + \ this issue always perform string modifications before any validation of a string.\nIt is strongly\ + \ recommended that strings be encoded instead of replaced or removed prior to\nvalidation.\n\n\nExample\ + \ replaces `..` before validation. Do note this is still not a recommended method for\nprotecting against\ + \ directory traversal, always use randomly generated IDs or filenames instead:\n```\n// This is ONLY\ + \ for demonstration purpose, never use untrusted input\n// in paths, always use randomly generated filenames\ + \ or IDs.\nString input = \"test../....//dir\";\n// Use replaceAll _not_ replace\ninput = input.replaceAll(\"\ + \\\\.\\\\.\", \"\");\n// Input would be test///dir at this point\n// Create a pattern to match on\n\ + Pattern pattern = Pattern.compile(\"\\\\.\\\\.\");\n// Create a matcher\nMatcher match = pattern.matcher(input);\n\ + // Call find to see if .. is still in our string\nif (match.find()) {\n throw new Exception(\"..\ + \ detected\");\n}\n// Use the input (but do not modify the string)\nSystem.out.println(input + \" safe\"\ + );\n```\n\nFor more information see Carnegie Mellon University's Secure Coding Guide:\nhttps://wiki.sei.cmu.edu/confluence/display/java/IDS11-J.+Perform+any+string+modifications+before+validation\n\ + \n" + metadata: + shortDescription: Collapse of data into unsafe value + category: security + cwe: CWE-182 + confidence: HIGH + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: Info + severity: WARNING + - id: gitlab-java_strings_rule-NormalizeAfterValidation + languages: [java] + patterns: + - pattern: '$Y = java.util.regex.Pattern.compile("[<>]"); + + ... + + $Y.matcher($VAR); + + ... + + java.text.Normalizer.normalize($VAR, ...); + + ' + message: "The application was found matching a variable during a regular expression\npattern match, and\ + \ then calling a Unicode normalize function after validation has occurred.\nThis is usually indicative\ + \ of a poor input validation strategy as an adversary may attempt to\nexploit the normalization process.\n\ + \nTo remediate this issue, always perform Unicode normalization before any validation of a\nstring.\n\ + \nExample of normalizing a string before validation:\n```\n// User input possibly containing malicious\ + \ unicode\nString userInput = \"\\uFE64\" + \"tag\" + \"\\uFE65\";\n// Normalize the input\nuserInput\ + \ = Normalizer.normalize(userInput, Normalizer.Form.NFKC);\n// Compile our regex pattern looking for\ + \ < or > characters\nPattern pattern = Pattern.compile(\"[<>]\");\n// Create a matcher from the userInput\n\ + Matcher matcher = pattern.matcher(userInput);\n// See if the matcher matches\nif (matcher.find()) {\n\ + \ // It did so throw an error\n throw new Exception(\"found banned characters in input\");\n}\n\ + ```\n\nFor more information see Carnegie Mellon University's Secure Coding Guide:\nhttps://wiki.sei.cmu.edu/confluence/display/java/IDS01-J.+Normalize+strings+before+validating+them\n" + metadata: + shortDescription: 'Incorrect behavior order: validate before canonicalize' + category: security + cwe: CWE-180 + confidence: HIGH + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + security-severity: Info + severity: WARNING + - id: gitlab-java_templateinjection_rule-TemplateInjection + languages: [java] + message: 'The application may allow control over a template string. Providing user input directly in the + + template by + + dynamically creating template strings may allow an adversary to execute arbitrary Java code, + + including + + OS system commands. + + + For Velocity, never call `evaluate` with user-supplied input in the template string. Use a + + `VelocityContext` + + object instead to data-bind user-supplied information as it will be treated as an underlying + + data type and not + + template code. + + + Example using Apache Velocity''s `VelocityContext` and escape tools to pass in user-supplied + + data to a template: + + ``` + + // Create a tool manager + + ToolManager manager = new ToolManager(true); + + // Create a context from the tool manager + + Context context = manager.createContext(); + + // For demonstration purposes, alternatively configure from a properties file + + context.put("esc", new EscapeTool()); + + // For demonstration purposes, create an output buffer + + StringWriter stringWriter = new StringWriter(); + + // Get userInput + + String userInput = "potentially malicious data"; + + // Use the context to pass in the userInput value + + context.put("userInput", userInput); + + // Pass in the context, the output buffer, a logtag (demo), and the template with userInput + + // making sure to escape it if in the context of HTML. + + Velocity.evaluate(context, stringWriter, "demo", "Hello $esc.html($userInput)"); + + // Work with the output buffer + + // ... + + ``` + + + For other templating engines, please see your framework''s documentation. + + ' + pattern-either: + - patterns: + - pattern: org.apache.velocity.app.Velocity.evaluate(..., $VAR) + - pattern-not: org.apache.velocity.app.Velocity.evaluate(..., "...") + - patterns: + - pattern-not-inside: '$C = (freemarker.template.Configuration $CFG).getTemplate("..."); + + ... + + ' + - pattern-inside: '$C = (freemarker.template.Configuration $CFG).getTemplate($IN); + + ... + + ' + - pattern: $C.process(...) + - patterns: + - pattern-inside: 'import com.mitchellbosecke.pebble.PebbleEngine; + + ... + + ' + - pattern-inside: '$C = $T.getTemplate($IN); + + ... + + ' + - pattern-not-inside: '$C = $T.getTemplate("..."); + + ... + + ' + - pattern: $C.evaluate(...) + metadata: + shortDescription: Improper control of generation of code ('Code Injection') + category: security + cwe: CWE-94 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + security-severity: High + severity: ERROR + - id: gitlab-java_unsafe_rule-ExternalConfigControl + languages: [java] + patterns: + - pattern: '$TAINTED = (HttpServletRequest $REQ).getParameter(...); + + ... + + (java.sql.Connection $CONN).setCatalog($TAINTED); + + ' + message: 'The application was found using user-supplied input in a `java.sql.Connection`''s + + `setCatalog` call. This could allow an adversary to supply a different database for the + + lifetime of the connection. Allowing external control of system settings can disrupt service + + or cause an application to behave in unexpected, and potentially malicious ways. Most likely + + this would only cause an error by providing a nonexistent catalog name. + + + It is recommended to not use user-supplied input when selecting the database for an + + applications + + database connection. + + ' + severity: WARNING + metadata: + shortDescription: External control of system or configuration setting + category: security + cwe: CWE-15 + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + technology: + - java + security-severity: Low + - id: gitlab-java_xml_rule-SAMLIgnoreComments + languages: [java] + message: "SAML parses attestations as an XML document. By processing XML comments, comment\nfields can\ + \ end up modifying the interpretation of input fields. This could allow\nan adversary to insert an XML\ + \ comment to break up the attestation's username\nor other fields, allowing an attacker to bypass authorization\ + \ or authentication checks.\n\nTo remediate this issue, when using `org.opensaml.xml.parse.BasicParserPool`\ + \ ensure\n`setIgnoreComments(false)` is not called.\n\nThe default value of `ignoreComments` is true,\ + \ which is safe. \n\nRef:\n- https://javadoc.io/doc/org.opensaml/xmltooling/latest/org/opensaml/xml/parse/BasicParserPool.html#ignoreComments\n\ + \nFor more information on how this issue can be exploited see:\nhttps://developer.okta.com/blog/2018/02/27/a-breakdown-of-the-new-saml-authentication-bypass-vulnerability\n\ + \nFor more information on SAML security see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/SAML_Security_Cheat_Sheet.html\n" + metadata: + shortDescription: Weak authentication + cwe: CWE-1390 + category: security + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + security-severity: Medium + pattern: (org.opensaml.xml.parse.BasicParserPool $POOL).setIgnoreComments(false); + severity: WARNING + - id: gitlab-java_xml_rule-XmlDecoder + languages: [java] + message: "Deserialization attacks exploit the process of reading serialized data and turning it back\n\ + into an object. By constructing malicious objects and serializing them, an adversary may\nattempt to:\n\ + \n- Inject code that is executed upon object construction, which occurs during the\ndeserialization\ + \ process.\n- Exploit mass assignment by including fields that are not normally a part of the serialized\n\ + data but are read in during deserialization.\n\nConsider safer alternatives such as serializing data\ + \ in the JSON format. Ensure any format\nchosen allows\nthe application to specify exactly which object\ + \ types are allowed to be deserialized.\nAdditionally, when\ndeserializing, never deserialize to base\ + \ object types like `Object` and only cast to the exact\nobject\ntype that is expected.\n\nTo protect\ + \ against mass assignment, only allow deserialization of the specific fields that are\nrequired. If\ + \ this is not easily done, consider creating an intermediary type that\ncan be serialized with only\ + \ the necessary fields exposed.\n\nDo note that `XMLEncoder` and `XMLDecoder` are not recommended. If\ + \ the application must\nuse this serialization method, use a custom ClassLoader to prevent loading of\ + \ arbitrary\nclasses:\n```\nXMLDecoder decoder = new XMLDecoder(inputStream, null, null, new ClassLoader()\ + \ {\n @Override\n protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException\ + \ {\n if (!name.equals(NameOfBeanHere.class.getName()) &&\n!name.equals(XMLDecoder.class.getName()))\ + \ {\n throw new RuntimeException(\"Unauthorized deserialization attempt: \" + name);\n \ + \ }\n\n return super.loadClass(name, resolve);\n }\n});\n```\n\nFor more information\ + \ on XML security see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java\n\ + \nFor more details on deserialization attacks in general, see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n\ + \nIt should be noted that [tools exist](https://github.com/frohoff/ysoserial) to\nautomatically create\n\ + exploit code for these vulnerabilities.\n" + metadata: + shortDescription: Deserialization of untrusted data + category: security + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + - A08:2025-Software or Data Integrity Failures + security-severity: High + patterns: + - pattern: '(java.beans.XMLDecoder $D).readObject(); + + ' + - pattern-not: + pattern-either: + - patterns: + - pattern-inside: 'java.beans.XMLDecoder $DEC = new java.beans.XMLDecoder(..., $CL); + + ... + + ' + - pattern: $DEC.readObject(); + - metavariable-pattern: + metavariable: $CL + patterns: + - pattern: "new ClassLoader(){\n ...\n $RET loadClass(String name, boolean resolve){\n \ + \ if($X){\n throw ...\n }\n ...\n }\n ...\n}\n" + - metavariable-pattern: + metavariable: $X + pattern-either: + - pattern: '!name.equals(...) + + ' + - pattern: '!$LIST.contains(name) + + ' + - patterns: + - pattern-inside: 'ClassLoader $CLASS_LOADER = $CL; + + ... + + java.beans.XMLDecoder $DEC = new java.beans.XMLDecoder(..., $CLASS_LOADER); + + ... + + ' + - pattern: $DEC.readObject(); + - metavariable-pattern: + metavariable: $CL + patterns: + - pattern: "new ClassLoader(){\n ...\n $RET loadClass(String name, boolean resolve){\n \ + \ if($X){\n throw ...\n }\n ...\n }\n ...\n}\n" + - metavariable-pattern: + metavariable: $X + pattern-either: + - pattern: '!name.equals(...) + + ' + - pattern: '!$LIST.contains(name) + + ' + severity: WARNING + - id: gitlab-java_xml_rule-XsltTransform + languages: [java] + mode: taint + pattern-sources: + - patterns: + - pattern-either: + - patterns: + - pattern-inside: "$FUNC(...,String $VAR, ...) {\n ...\n}\n" + - pattern-either: + - pattern: new FileInputStream(<... $VAR ...>); + - pattern: getClass().getResourceAsStream(<... $VAR ...>) + - patterns: + - pattern-inside: "class $CLZ {\n String $X = \"...\";\n ...\n}\n" + - pattern-inside: "$FUNC(...,String $Y, ...) {\n ...\n}\n" + - pattern-either: + - pattern: new FileInputStream($X + $Y); + - pattern: getClass().getResourceAsStream($X + $Y) + pattern-sinks: + - patterns: + - pattern-either: + - pattern-inside: (javax.xml.transform.TransformerFactory $T).newTransformer($SRC, ...) + - pattern-inside: (javax.xml.transform.Transformer $T).transform($SRC, ...) + - pattern: $SRC + message: 'The application performs XSLT translation with potentially malicious input. An adversary who + + is able to influence the + + loaded + + XSL document could call XSL functions or exploit External XML Entity (XXE) attacks that allow + + file + + retrieval or force the parser to connect to arbitrary servers to exfiltrate files. It is + + strongly + + recommended that an alternative approach is used to work with XML data. + + + For increased security, never process user-supplied XSL style sheets. If XSLT processing is + + absolutely + + necessary, ensure that `FEATURE_SECURE_PROCESSING` is enabled prior to processing the XSLT + + file: + + ``` + + // Create a new TransformerFactory instance + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + + // Enable the FEATURE_SECURE_PROCESSING feature + + transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + + // Read in the XML Source + + Source xmlSource = new StreamSource(new FileInputStream("hardcoded.xml")); + + // Read in the XSL template file + + Source xslSource = new StreamSource(new FileInputStream("hardcoded.xsl")); + + /// Create the transformer object to do the transformation + + Transformer transformer = transformerFactory.newTransformer(xslSource); + + // Create a Result object for output + + Result result = new StreamResult(System.out); + + // Execute the transformation process + + transformer.transform(xmlSource, result); + + ``` + + + For more information on XML security see OWASP''s guide: + + https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java + + + For more information on the secure processing feature see: + + - https://xml.apache.org/xalan-j/features.html#secureprocessing + + ' + metadata: + shortDescription: XML injection (aka Blind XPath injection) + category: security + cwe: CWE-91 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + security-severity: Medium + severity: WARNING + - id: gitlab-java_xss_rule-WicketXSS + languages: [java] + patterns: + - pattern-inside: 'import org.apache.wicket.$A; + + ... + + ' + - pattern: '$OBJ.setEscapeModelStrings(false); + + ' + message: "The application is disabling Wicket's string escaping functionality by calling\n`setEscapeModelStrings(false)`.\n\ + This could lead to Cross Site Scripting (XSS) if used with user-supplied input. XSS is an\nattack which\ + \ exploits\n a web application or system to treat user input\nas markup or script code. It is important\ + \ to encode the data depending on the specific context\nit\nis used in. There are at least six context\ + \ types:\n\n- Inside HTML tags `
context 1
`\n- Inside attributes: `
`\n- Inside event attributes ``\n- Inside script\ + \ blocks: ``\n- Unsafe element HTML assignment: `element.innerHTML\ + \ = \"context 5\"`\n- Inside URLs: `link`\n\ + \nScript blocks alone have multiple ways they need to be encoded. Extra care must be taken if\nuser\ + \ input\nis ever output inside of script tags.\n\nUser input that is displayed within the application\ + \ must be encoded, sanitized or validated\nto ensure it cannot be treated as HTML or executed as JavaScript\ + \ code. Care must also be\ntaken\nto not mix server-side templating with client-side templating, as\ + \ the server-side templating\nwill\nnot encode things like {{ 7*7 }} which may execute client-side templating\ + \ features.\n\nIt is _NOT_ advised to encode user input prior to inserting into a data store. The data\ + \ will\nneed to be\nencoded depending on context of where it is output. It is much safer to force the\ + \ displaying\nsystem to\nhandle the encoding and not attempt to guess how it should be encoded.\n\n\ + Use Wicket's built in escaping feature by calling `Component.setEscapeModelStrings(true);`\n\nFor more\ + \ information on Wicket components see:\n- https://nightlies.apache.org/wicket/apidocs/9.x/org/apache/wicket/Component.html\n\ + \nFor more information on XSS see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\n" + metadata: + shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting') + category: security + cwe: CWE-79 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + - A05:2025-Injection + security-severity: Medium + severity: WARNING + - id: gitlab-java_xss_rule-XSSReqParamToServletWriter + languages: [java] + mode: taint + pattern-sources: + - pattern: (javax.servlet.http.HttpServletRequest $R).$METHOD(...) + - pattern: (java.util.Scanner $S).$METHOD(...) + - pattern: (java.util.stream.Stream).$METHOD(...) + - pattern: (java.util.StringJoiner $SJ).toString(...) + - pattern: (java.sql.ResultSet.getString $R).$METHOD(...) + - pattern: (java.lang.System $S).getProperty(...) + - pattern: (java.lang.System $S).getenv(...) + - pattern: (java.lang.StringBuilder $SB).toString(...) + - pattern: (java.io.FileInputStream $F).read(...) + - pattern: (java.io.FileReader $F).read(...) + - pattern: (java.net.Socket $S).getInputStream(...) + - pattern: (java.net.Socket $S).getOutputStream(...) + - pattern: (java.net.DatagramSocket $S).receive(...) + - pattern: (java.net.DatagramSocket $S).getInputStream(...) + - pattern: java.nio.file.Files.readAllBytes(...) + - pattern: java.nio.file.Files.readAllLines(...) + - pattern: java.nio.file.Files.lines(...) + - pattern: java.nio.file.Files.newBufferedReader(...) + - pattern: org.apache.commons.io.IOUtils.toString(...) + - pattern: org.apache.commons.io.IOUtils.readLines(...) + - pattern: org.apache.commons.io.IOUtils.toByteArray(...) + - pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).readValue(...) + - pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).treeToValue(...) + - pattern: $CLASS.$METHOD(..., (javax.servlet.http.HttpServletRequest $R), ...) + - pattern: $FUNC(..., (javax.servlet.http.HttpServletRequest $R), ...) + - patterns: + - pattern-inside: $FUNC(..., String $X, ...) { ... } + - focus-metavariable: $X + pattern-propagators: + - pattern: $LIST.add($X) + from: $X + to: $LIST + - pattern: $MAP.put(..., $X) + from: $X + to: $MAP + - pattern: $STR.concat($X) + from: $X + to: $STR + - pattern: $STR = String.format(..., $X, ...) + from: $X + to: $STR + - pattern: $STR = String.join(..., $X, ...) + from: $X + to: $STR + pattern-sanitizers: + - pattern: org.owasp.encoder.Encode.forHtml(...) + - pattern: org.owasp.esapi.ESAPI.encoder().encodeForHTML(...) + - pattern: org.apache.commons.text.StringEscapeUtils.escapeHtml3(...) + - pattern: org.apache.commons.text.StringEscapeUtils.escapeHtml4(...) + - pattern: org.owasp.benchmark.helpers.Utils.encodeForHTML(...) + pattern-sinks: + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().print(...) + - patterns: + - pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + + ... + + ' + - pattern: $W.print(...); + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().println(...) + - patterns: + - pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + + ... + + ' + - pattern: $W.println(...); + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().format(...) + - patterns: + - pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + + ... + + ' + - pattern: $W.format(...); + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().append(...) + - patterns: + - pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + + ... + + ' + - pattern: $W.append(...); + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().write(...) + - patterns: + - pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + + ... + + ' + - pattern: $W.write(...); + message: 'The application is returning user-supplied data from an HTTP request directly into an HTTP + + response output + + writer. This could lead to Cross Site Scripting (XSS) if the input were malicious + + script code and the application server is not properly validating the output. + + + XSS is an attack which exploits a web application or system to treat user input + + as markup or script code. It is important to encode the data depending on the specific context + + it is used in. There are at least six context types: + + + - Inside HTML tags `
context 1
` + + - Inside attributes: `
` + + - Inside event attributes `` + + - Inside script blocks: `` + + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + + - Inside URLs: `link` + + + Script blocks alone have multiple ways they need to be encoded. Extra care must be taken if + + user input + + is ever output inside of script tags. + + + User input that is displayed within the application must be encoded, sanitized or validated + + to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be + + taken + + to not mix server-side templating with client-side templating, as the server-side templating + + will + + not encode things like {{ 7*7 }} which may execute client-side templating features. + + + It is _NOT_ advised to encode user input prior to inserting into a data store. The data will + + need to be + + encoded depending on context of where it is output. It is much safer to force the displaying + + system to + + handle the encoding and not attempt to guess how it should be encoded. + + + If possible do not use user input directly in the output to the response writer. + + + If the application must output user-supplied input, it will need to encode the data depending + + on + + the output context. + + + Consider using [Apache Commons Text](https://commons.apache.org/proper/commons-text/) + + `StringEscapeUtils` methods for various context. Please note there is no way to safely + + output script code in most circumstances, regardless of encoding. If calling the HTTP + + response writer directly, ensure that the `Content-Type` is set to `text/plain` so it will + + not be accidentally interpreted by HTML by modern browsers. + + ``` + + // Get user input + + String htmlInput = request.getParameter("userInput"); + + // Encode the input using the Html4 encoder + + String htmlEncoded = StringEscapeUtils.escapeHtml4(htmlInput); + + // Force the HTTP response to be content type of text/plain so it is not interpreted as HTML + + response.setContentType("text/plain"); + + // Ensure UTF-8 + + response.setCharacterEncoding("UTF-8"); + + // Write response + + response.getWriter().write(htmlEncoded); + + ``` + + + For more information on XSS see OWASP: + + - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html + + ' + severity: WARNING + metadata: + shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting') + category: security + cwe: CWE-79 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + - A05:2025-Injection + technology: + - java + security-severity: Medium + - id: gitlab-java_xxe_rule-XMLRdr + languages: [java] + message: 'External XML entities are a feature of XML parsers that allow documents to contain references + + to + + other documents or data. This feature can be abused to read files, communicate with external + + hosts, + + exfiltrate data, or cause a Denial of Service (DoS). + + + The XMLReaderFactory has been deprecated. It is recommended that + + [SAXParserFactory](https://docs.oracle.com/javase/9/docs/api/javax/xml/parsers/SAXParserFactory.html) + + be used + + instead. Additionally when using the SAXParser it must be configured to disallow doctypes, + + which will + + protect against the majority of XXE attacks. + + + Example creating a SAXParser with disallowing the doctypes feature enabled: + + ``` + + // Create a SAXParserFactory + + SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); + + // Enable the feature which disallows + + ' + - pattern: '{dangerouslySetInnerHTML: ...} + + ' + severity: WARNING + message: 'The application was found calling `dangerouslySetInnerHTML` which may lead to Cross Site + + Scripting (XSS). By default, React components will encode the data properly before rendering. + + Calling `dangerouslySetInnerHTML` disables this encoding and allows raw markup + + and JavaScript to be executed. + + + XSS is an attack which exploits a web application or system to treat + + user input as markup or script code. It is important to encode the data, depending on the + + specific context it is used in. There are at least six context types: + + + - Inside HTML tags `
context 1
` + + - Inside attributes: `
` + + - Inside event attributes `` + + - Inside script blocks: `` + + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + + - Inside URLs: `link` + + + Script blocks alone have multiple ways they need to be encoded. Extra care must be taken if + + user input + + is ever output inside of script tags. + + + User input that is displayed within the application must be encoded, sanitized or validated + + to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be + + taken + + to not mix server-side templating with client-side templating, as the server-side templating + + will + + not encode things like {{ 7*7 }} which may execute client-side templating features. + + + It is _NOT_ advised to encode user input prior to inserting into a data store. The data will + + need to be + + encoded depending on context of where it is output. It is much safer to force the displaying + + system to + + handle the encoding and not attempt to guess how it should be encoded. + + + Remove the call to `dangerouslySetInnerHTML` or ensure that the data used in this call does + + not come from user-supplied input. + + + For more information on dangerously setting inner HTML see: + + - https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html + + ' + metadata: + cwe: CWE-79 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + - A05:2025-Injection + shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting') + category: security + security-severity: Medium + - id: gitlab-javascript_require_rule-non-literal-require + languages: [javascript, typescript] + patterns: + - pattern: require($OBJ) + - pattern-not: require('...') + severity: WARNING + message: 'The application was found to dynamically import a module by calling `require` using a + + non-literal string. An adversary might be able to read the first line of + + arbitrary files. If they had write access to the file system, they may also be able to + + execute arbitrary code. + + + To remediate this issue, use a hardcoded string literal when calling `require`. Never call it + + it with dynamically created variables or user-supplied data. + + ' + metadata: + cwe: CWE-95 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + shortDescription: Improper neutralization of directives in dynamically evaluated code ('Eval Injection') + category: security + source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-non-literal-require.js + security-severity: Low + - id: gitlab-javascript_timing_rule-possible-timing-attacks + languages: [javascript] + patterns: + - pattern-not: if ($Z == null) { ... }; + - pattern-not: if ($Z === null) { ... }; + - pattern-not: if ($Z != null) { ... }; + - pattern-not: if ($Z !== null) { ... }; + - pattern-not: if ($Q != undefined) { ... }; + - pattern-not: if ($Q !== undefined) { ... }; + - pattern-not: if ($Q == undefined) { ... }; + - pattern-not: if ($Q === undefined) { ... }; + - pattern-not: return $Y == null; + - pattern-not: return $Y === null; + - pattern-not: return $Y != null; + - pattern-not: return $Y !== null; + - pattern-not: return $Y == undefined; + - pattern-not: return $Y === undefined; + - pattern-not: return $Y != undefined; + - pattern-not: return $Y !== undefined; + - pattern-either: + - pattern: "if (password == $X) {\n ...\n}\n" + - pattern: "if ($X == password) {\n ...\n}\n" + - pattern: "if (password === $X) {\n ...\n}\n" + - pattern: "if ($X === password) {\n ...\n}\n" + - pattern: "if (pass == $X) {\n ...\n}\n" + - pattern: "if ($X == pass) {\n ...\n}\n" + - pattern: "if (pass === $X) {\n ...\n}\n" + - pattern: "if ($X === pass) {\n ...\n}\n" + - pattern: "if (secret == $X) {\n ...\n}\n" + - pattern: "if ($X == secret) {\n ...\n}\n" + - pattern: "if (secret === $X) {\n ...\n}\n" + - pattern: "if ($X === secret) {\n ...\n}\n" + - pattern: "if (api == $X) {\n ...\n}\n" + - pattern: "if ($X == api) {\n ...\n}\n" + - pattern: "if (api === $X) {\n ...\n}\n" + - pattern: "if ($X === api) {\n ...\n}\n" + - pattern: "if (apiKey == $X) {\n ...\n}\n" + - pattern: "if ($X == apiKey) {\n ...\n}\n" + - pattern: "if (apiKey === $X) {\n ...\n}\n" + - pattern: "if ($X === apiKey) {\n ...\n}\n" + - pattern: "if (apiSecret == $X) {\n ...\n}\n" + - pattern: "if ($X == apiSecret) {\n ...\n}\n" + - pattern: "if (apiSecret === $X) {\n ...\n}\n" + - pattern: "if ($X === apiSecret) {\n ...\n}\n" + - pattern: "if (token == $X) {\n ...\n}\n" + - pattern: "if ($X == token) {\n ...\n}\n" + - pattern: "if (token === $X) {\n ...\n}\n" + - pattern: "if ($X === token) {\n ...\n}\n" + - pattern: "if (hash == $X) {\n ...\n}\n" + - pattern: "if ($X == hash) {\n ...\n}\n" + - pattern: "if (hash === $X) {\n ...\n}\n" + - pattern: "if ($X === hash) {\n ...\n}\n" + - pattern: "if (auth_token == $X) {\n ...\n}\n" + - pattern: "if ($X == auth_token) {\n ...\n}\n" + - pattern: "if (auth_token === $X) {\n ...\n}\n" + - pattern: "if ($X === auth_token) {\n ...\n}\n" + - pattern: "if (password != $X) {\n ...\n}\n" + - pattern: "if ($X != password) {\n ...\n}\n" + - pattern: "if (password !== $X) {\n ...\n}\n" + - pattern: "if ($X !== password) {\n ...\n}\n" + - pattern: "if (pass != $X) {\n ...\n}\n" + - pattern: "if ($X != pass) {\n ...\n}\n" + - pattern: "if (pass !== $X) {\n ...\n}\n" + - pattern: "if ($X !== pass) {\n ...\n}\n" + - pattern: "if (secret != $X) {\n ...\n}\n" + - pattern: "if ($X != secret) {\n ...\n}\n" + - pattern: "if (secret !== $X) {\n ...\n}\n" + - pattern: "if ($X !== secret) {\n ...\n}\n" + - pattern: "if (api != $X) {\n ...\n}\n" + - pattern: "if ($X != api) {\n ...\n}\n" + - pattern: "if (api !== $X) {\n ...\n}\n" + - pattern: "if ($X !== api) {\n ...\n}\n" + - pattern: "if (apiKey != $X) {\n ...\n}\n" + - pattern: "if ($X != apiKey) {\n ...\n}\n" + - pattern: "if (apiKey !== $X) {\n ...\n}\n" + - pattern: "if ($X !== apiKey) {\n ...\n}\n" + - pattern: "if (apiSecret != $X) {\n ...\n}\n" + - pattern: "if ($X != apiSecret) {\n ...\n}\n" + - pattern: "if (apiSecret !== $X) {\n ...\n}\n" + - pattern: "if ($X !== apiSecret) {\n ...\n}\n" + - pattern: "if (token != $X) {\n ...\n}\n" + - pattern: "if ($X != token) {\n ...\n}\n" + - pattern: "if (token !== $X) {\n ...\n}\n" + - pattern: "if ($X !== token) {\n ...\n}\n" + - pattern: "if (hash != $X) {\n ...\n}\n" + - pattern: "if ($X != hash) {\n ...\n}\n" + - pattern: "if (hash !== $X) {\n ...\n}\n" + - pattern: "if ($X !== hash) {\n ...\n}\n" + - pattern: "if (auth_token != $X) {\n ...\n}\n" + - pattern: "if ($X != auth_token) {\n ...\n}\n" + - pattern: "if (auth_token !== $X) {\n ...\n}\n" + - pattern: "if ($X !== auth_token) {\n ...\n}\n" + - pattern: 'return $X === auth_token; + + ' + - pattern: 'return auth_token === $X; + + ' + - pattern: 'return $X === token; + + ' + - pattern: 'return token === $X; + + ' + - pattern: 'return $X === hash; + + ' + - pattern: 'return hash === $X; + + ' + - pattern: 'return $X === password; + + ' + - pattern: 'return password === $X; + + ' + - pattern: 'return $X === pass; + + ' + - pattern: 'return pass === $X; + + ' + - pattern: 'return $X === apiKey; + + ' + - pattern: 'return apiKey === $X; + + ' + - pattern: 'return $X === apiSecret; + + ' + - pattern: 'return apiSecret === $X; + + ' + - pattern: 'return $X === api_key; + + ' + - pattern: 'return api_key === $X; + + ' + - pattern: 'return $X === api_secret; + + ' + - pattern: 'return api_secret === $X; + + ' + - pattern: 'return $X === secret; + + ' + - pattern: 'return secret === $X; + + ' + - pattern: 'return $X === api; + + ' + - pattern: 'return api === $X; + + ' + - pattern: 'return $X == auth_token; + + ' + - pattern: 'return auth_token == $X; + + ' + - pattern: 'return $X == token; + + ' + - pattern: 'return token == $X; + + ' + - pattern: 'return $X == hash; + + ' + - pattern: 'return hash == $X; + + ' + - pattern: 'return $X == password; + + ' + - pattern: 'return password == $X; + + ' + - pattern: 'return $X == pass; + + ' + - pattern: 'return pass == $X; + + ' + - pattern: 'return $X == apiKey; + + ' + - pattern: 'return apiKey == $X; + + ' + - pattern: 'return $X == apiSecret; + + ' + - pattern: 'return apiSecret == $X; + + ' + - pattern: 'return $X == api_key; + + ' + - pattern: 'return api_key == $X; + + ' + - pattern: 'return $X == api_secret; + + ' + - pattern: 'return api_secret == $X; + + ' + - pattern: 'return $X == secret; + + ' + - pattern: 'return secret == $X; + + ' + - pattern: 'return $X == api; + + ' + - pattern: 'return api == $X; + + ' + - pattern: 'return $X !== auth_token; + + ' + - pattern: 'return auth_token !== $X; + + ' + - pattern: 'return $X !== token; + + ' + - pattern: 'return token !== $X; + + ' + - pattern: 'return $X !== hash; + + ' + - pattern: 'return hash !== $X; + + ' + - pattern: 'return $X !== password; + + ' + - pattern: 'return password !== $X; + + ' + - pattern: 'return $X !== pass; + + ' + - pattern: 'return pass !== $X; + + ' + - pattern: 'return $X !== apiKey; + + ' + - pattern: 'return apiKey !== $X; + + ' + - pattern: 'return $X !== apiSecret; + + ' + - pattern: 'return apiSecret !== $X; + + ' + - pattern: 'return $X !== api_key; + + ' + - pattern: 'return api_key !== $X; + + ' + - pattern: 'return $X !== api_secret; + + ' + - pattern: 'return api_secret !== $X; + + ' + - pattern: 'return $X !== secret; + + ' + - pattern: 'return secret !== $X; + + ' + - pattern: 'return $X !== api; + + ' + - pattern: 'return api !== $X; + + ' + - pattern: 'return $X != auth_token; + + ' + - pattern: 'return auth_token != $X; + + ' + - pattern: 'return $X != token; + + ' + - pattern: 'return token != $X; + + ' + - pattern: 'return $X != hash; + + ' + - pattern: 'return hash != $X; + + ' + - pattern: 'return $X != password; + + ' + - pattern: 'return password != $X; + + ' + - pattern: 'return $X != pass; + + ' + - pattern: 'return pass != $X; + + ' + - pattern: 'return $X != apiKey; + + ' + - pattern: 'return apiKey != $X; + + ' + - pattern: 'return $X != apiSecret; + + ' + - pattern: 'return apiSecret != $X; + + ' + - pattern: 'return $X != api_key; + + ' + - pattern: 'return api_key != $X; + + ' + - pattern: 'return $X != api_secret; + + ' + - pattern: 'return api_secret != $X; + + ' + - pattern: 'return $X != secret; + + ' + - pattern: 'return secret != $X; + + ' + - pattern: 'return $X != api; + + ' + - pattern: 'return api != $X; + + ' + severity: WARNING + message: "The application was found executing string comparisons using one of `===`, `!==`, `==` or `!=`\n\ + against security sensitive values. String comparisons like this are not constant time, meaning\nthe\n\ + first character found not to match in the two strings will immediately exit the conditional\nstatement.\n\ + This allows an adversary to calculate or observe small timing differences depending on the\nstrings\n\ + passed to this comparison. This potentially allows an adversary the ability to brute force a\nstring\n\ + that will match the expected value by monitoring different character values.\n\nTo remediate this issue,\ + \ use the `crypto.timingSafeEqual` method when comparing strings.\n\nExample using `crypto.timingSafeEqual`\ + \ to safely compare strings:\n```\nfunction constantTimeIsPasswordEqual(userInput) {\n // Retrieve\ + \ the password from a secure data store such as a KMS or Hashicorp's vault.\n const password = getPasswordFromSecureDataStore();\n\ + \ // Use crypto timingSafeEqual to ensure the comparison is done in constant time.\n return crypto.timingSafeEqual(Buffer.from(userInput,\ + \ 'utf-8'), Buffer.from(password,\n'utf-8'));\n}\n```\n\nFor more information on constant time comparison\ + \ see:\n- https://nodejs.org/api/crypto.html#crypto_crypto_timingsafeequal_a_b\n" + metadata: + cwe: CWE-208 + shortDescription: Observable timing discrepancy + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + security-severity: Medium + - id: gitlab-python_bind-all-interfaces_rule-general-bindall-interfaces + languages: [python] + message: 'Binding to all network interfaces can potentially open up a service to + + traffic on unintended interfaces, that may not be properly documented or + + secured. By passing "0.0.0.0", "::" or an empty string as the address to the `socket.bind` + + function, + + the application will bind to all interfaces. + + + Consider passing in the interface ip address through an environment variable, + + configuration file, or by determining the primary interface(s) IP address. + + + Example getting the IP address from an environment variable `IP_ADDRESS`: + + ``` + + # Get the IP_ADDRESS env variable, or bind to + + # 127.0.0.1 if it is not set + + address = os.getenv("IP_ADDRESS", "127.0.0.1") + + # Create an internet socket + + sock = socket.socket(socket.AF_INET) + + # Set the port to listen on + + port = 9777 + + # Bind to the address and port combination + + sock.bind((address, port)) + + # Listen for connections + + sock.listen() + + # Handle the connection + + ``` + + ' + patterns: + - pattern-either: + - pattern: '$S = socket.socket(...) + + ... + + $S.bind(("0.0.0.0", ...)) + + ' + - pattern: '$S = socket.socket(...) + + ... + + $S.bind(("::", ...)) + + ' + - pattern: '$S = socket.socket(...) + + ... + + $S.bind(("", ...)) + + ' + metadata: + category: security + owasp: + - A6:2017-Security Misconfiguration + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + shortDescription: Binding to an unrestricted IP address + cwe: CWE-1327 + security-severity: Low + severity: INFO + - id: gitlab-python_crypto_rule-cipher-modes + languages: [python] + message: "Cryptographic algorithms provide many different modes of operation, only some of which provide\n\ + message integrity. Without message integrity it could be possible for an adversary to attempt\nto tamper\ + \ with the ciphertext which could lead to compromising the encryption key. Newer\nalgorithms\napply\ + \ message integrity to validate ciphertext has not been tampered with.\n\nInstead of using an algorithm\ + \ that requires configuring a cipher mode, an algorithm\nthat has built-in message integrity should\ + \ be used. Consider using `ChaCha20Poly1305` or\n`AES-256-GCM` instead.\n\nFor older applications that\ + \ don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n\ + \ - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values are reused.\n\nExample\ + \ using `ChaCha20Poly1305`:\n```\nimport os\n# Import ChaCha20Poly1305 from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\ + \ import ChaCha20Poly1305\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We\ + \ do not require authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure\ + \ key\nkey = ChaCha20Poly1305.generate_key()\n# Create a new ChaCha20Poly1305 instance with our secure\ + \ key\nchacha = ChaCha20Poly1305(key)\n# Note: nonce values _must_ be regenerated every time they are\ + \ used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text = chacha.encrypt(nonce, plain_text,\ + \ aad)\n# Decrypt the plain text using the nonce and cipher_text\nchacha.decrypt(nonce, cipher_text,\ + \ aad)\n```\n\nExample using `AESGCM`:\n```\nimport os\n# Import AESGCM from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\ + \ import AESGCM\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We do not require\ + \ authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure key\nkey = AESGCM.generate_key(bit_length=128)\n\ + # Create a new AESGCM instance with our secure key\naesgcm = AESGCM(key)\n# Note: nonce values _must_\ + \ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text\ + \ = aesgcm.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\ + aesgcm.decrypt(nonce, cipher_text, aad)\n```\n\nFor more information on the cryptography module see:\n\ + - https://cryptography.io/en/latest/\n" + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + pattern: cryptography.hazmat.primitives.ciphers.modes.ECB(...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-cipher-blowfish + languages: [python] + message: "The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created\ + \ in\n1993. Smaller key sizes may make the ciphertext vulnerable to [birthday\nattacks](https://en.wikipedia.org/wiki/Birthday_attack).\ + \ While no known attacks against\nBlowfish\nexist, it should never be used to encrypt files over 4GB\ + \ in size. If possible consider\nusing ChaCha20Poly1305 or AES-GCM instead of Blowfish.\n\nFor older\ + \ applications that don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however\ + \ it has many drawbacks:\n - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values\ + \ are reused.\n\nNote that the `Crypto` and `Cryptodome` Python packages are no longer recommended for\n\ + new applications, instead consider using the [cryptography](https://cryptography.io/) package.\n\nExample\ + \ using `ChaCha20Poly1305`:\n```\nimport os\n# Import ChaCha20Poly1305 from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\ + \ import ChaCha20Poly1305\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We\ + \ do not require authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure\ + \ key\nkey = ChaCha20Poly1305.generate_key()\n# Create a new ChaCha20Poly1305 instance with our secure\ + \ key\nchacha = ChaCha20Poly1305(key)\n# Note: nonce values _must_ be regenerated every time they are\ + \ used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text = chacha.encrypt(nonce, plain_text,\ + \ aad)\n# Decrypt the plain text using the nonce and cipher_text\nchacha.decrypt(nonce, cipher_text,\ + \ aad)\n```\n\nExample using `AESGCM`:\n```\nimport os\n# Import AESGCM from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\ + \ import AESGCM\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We do not require\ + \ authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure key\nkey = AESGCM.generate_key(bit_length=128)\n\ + # Create a new AESGCM instance with our secure key\naesgcm = AESGCM(key)\n# Note: nonce values _must_\ + \ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text\ + \ = aesgcm.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\ + aesgcm.decrypt(nonce, cipher_text, aad)\n```\n\nFor more information on the cryptography module see:\n\ + - https://cryptography.io/en/latest/\n" + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.Blowfish.new(...) + - pattern: Crypto.Cipher.Blowfish.new(...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-cipher-des + languages: [python] + message: 'DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms. + + Newer algorithms apply message integrity to validate ciphertext has not been tampered + + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + + alternatives such as `AES-256-GCM`. + + + For older applications that don''t have support for `ChaCha20Poly1305`, + + `AES-256-GCM` is recommended, however it has many drawbacks: + + - Slower than `ChaCha20Poly1305`. + + - Catastrophic failure if nonce values are reused. + + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + + Example using `ChaCha20Poly1305`: + + ``` + + import os + + # Import ChaCha20Poly1305 from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = ChaCha20Poly1305.generate_key() + + # Create a new ChaCha20Poly1305 instance with our secure key + + chacha = ChaCha20Poly1305(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = chacha.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + chacha.decrypt(nonce, cipher_text, aad) + + ``` + + + Example using `AESGCM`: + + ``` + + import os + + # Import AESGCM from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = AESGCM.generate_key(bit_length=128) + + # Create a new AESGCM instance with our secure key + + aesgcm = AESGCM(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + aesgcm.decrypt(nonce, cipher_text, aad) + + ``` + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.DES.new(...) + - pattern: Crypto.Cipher.DES.new(...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-cipher-rc2 + languages: [python] + message: 'DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms. + + Newer algorithms apply message integrity to validate ciphertext has not been tampered + + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + + alternatives such as `AES-256-GCM`. + + + For older applications that don''t have support for `ChaCha20Poly1305`, + + `AES-256-GCM` is recommended, however it has many drawbacks: + + - Slower than `ChaCha20Poly1305`. + + - Catastrophic failure if nonce values are reused. + + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + + Example using `ChaCha20Poly1305`: + + ``` + + import os + + # Import ChaCha20Poly1305 from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = ChaCha20Poly1305.generate_key() + + # Create a new ChaCha20Poly1305 instance with our secure key + + chacha = ChaCha20Poly1305(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = chacha.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + chacha.decrypt(nonce, cipher_text, aad) + + ``` + + + Example using `AESGCM`: + + ``` + + import os + + # Import AESGCM from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = AESGCM.generate_key(bit_length=128) + + # Create a new AESGCM instance with our secure key + + aesgcm = AESGCM(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + aesgcm.decrypt(nonce, cipher_text, aad) + + ``` + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.ARC2.new(...) + - pattern: Crypto.Cipher.ARC2.new + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-cipher-rc4 + languages: [python] + message: 'DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms. + + Newer algorithms apply message integrity to validate ciphertext has not been tampered + + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + + alternatives such as `AES-256-GCM`. + + + For older applications that don''t have support for `ChaCha20Poly1305`, + + `AES-256-GCM` is recommended, however it has many drawbacks: + + - Slower than `ChaCha20Poly1305`. + + - Catastrophic failure if nonce values are reused. + + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + + Example using `ChaCha20Poly1305`: + + ``` + + import os + + # Import ChaCha20Poly1305 from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = ChaCha20Poly1305.generate_key() + + # Create a new ChaCha20Poly1305 instance with our secure key + + chacha = ChaCha20Poly1305(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = chacha.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + chacha.decrypt(nonce, cipher_text, aad) + + ``` + + + Example using `AESGCM`: + + ``` + + import os + + # Import AESGCM from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = AESGCM.generate_key(bit_length=128) + + # Create a new AESGCM instance with our secure key + + aesgcm = AESGCM(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + aesgcm.decrypt(nonce, cipher_text, aad) + + ``` + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.ARC4.new(...) + - pattern: Crypto.Cipher.ARC4.new(...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-cipher-xor + languages: [python] + message: 'The application was found using the `xor` algorithm, which can be trivially decoded. + + Newer algorithms apply message integrity to validate ciphertext has not been tampered + + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + + alternatives such as `AES-256-GCM`. + + + For older applications that don''t have support for `ChaCha20Poly1305`, + + `AES-256-GCM` is recommended, however it has many drawbacks: + + - Slower than `ChaCha20Poly1305`. + + - Catastrophic failure if nonce values are reused. + + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + + Example using `ChaCha20Poly1305`: + + ``` + + import os + + # Import ChaCha20Poly1305 from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = ChaCha20Poly1305.generate_key() + + # Create a new ChaCha20Poly1305 instance with our secure key + + chacha = ChaCha20Poly1305(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = chacha.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + chacha.decrypt(nonce, cipher_text, aad) + + ``` + + + Example using `AESGCM`: + + ``` + + import os + + # Import AESGCM from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = AESGCM.generate_key(bit_length=128) + + # Create a new AESGCM instance with our secure key + + aesgcm = AESGCM(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + aesgcm.decrypt(nonce, cipher_text, aad) + + ``` + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.XOR.new(...) + - pattern: Crypto.Cipher.XOR.new(...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-encrypt-dsa-rsa + languages: [python] + message: "The application is generating an RSA key that is less than the recommended 2048 bits.\nThe National\ + \ Institute of Standards and Technology (NIST) deprecated signing Digital\nCertificates that contained\ + \ RSA Public Keys of 1024 bits in December 2010. While\n1024-bit RSA keys have not been factored yet,\ + \ advances in compute may make it possible\nin the near future.\n\nConsider upgrading to the newer asymmetric\ + \ algorithm such as `X25519` which handles\nthe complexities of generating key pairs and choosing correct\ + \ key sizes for you:\n```\nfrom cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey\n\ + \n# Generate a private key for use in the exchange.\nprivate_key = X25519PrivateKey.generate()\n# Work\ + \ with private key/exchange with a peer's\n# public key to created a shared and derived key\n# ...\n\ + ```\n\nOtherwise use a key size greater than 2048 when generating RSA keys:\n```\nfrom cryptography.hazmat.primitives.asymmetric\ + \ import rsa\n# Generate a private key of 4096 bits\nprivate_key = rsa.generate_private_key(\n #\ + \ do not change the exponent value from 65537\n public_exponent=65537,\n key_size=4096,\n)\n#\ + \ Work with the private key to sign/encrypt data\n# ...\n```\n\nFor more information on using the cryptography\ + \ module see:\n- https://cryptography.io/en/latest\n" + metadata: + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Inadequate encryption strength + security-severity: Medium + patterns: + - pattern-either: + - pattern: 'cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(...,key_size=$SIZE,...) + + ' + - pattern: 'cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key($EXP, $SIZE,...) + + ' + - pattern: 'cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key($SIZE, ...) + + ' + - pattern: 'cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key(...,key_size=$SIZE,...) + + ' + - pattern: 'cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key($EXP, $SIZE, ...) + + ' + - pattern: cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key($SIZE,...) + - pattern: Crypto.PublicKey.RSA.generate($SIZE, ...) + - pattern: Crypto.PublicKey.DSA.generate($SIZE, ...) + - pattern: Cryptodome.PublicKey.DSA.generate($SIZE, ...) + - pattern: Cryptodome.PublicKey.RSA.generate($SIZE, ...) + - pattern: Crypto.PublicKey.DSA.generate(bits=$SIZE, ...) + - pattern: Cryptodome.PublicKey.DSA.generate(bits=$SIZE, ...) + - pattern: pycrypto_rsa.generate(bits=$SIZE, ...) + - pattern: pycrypto_dsa.generate(bits=$SIZE, ...) + - pattern: pycryptodomex_rsa.generate(bits=$SIZE, ...) + - pattern: pycryptodomex_rsa.generate($SIZE, ...) + - pattern: pycryptodomex_dsa.generate(bits=$SIZE, ...) + - pattern: pycryptodomex_dsa.generate($SIZE, ...) + - metavariable-comparison: + comparison: $SIZE < 2048 + metavariable: $SIZE + severity: ERROR + - id: gitlab-python_crypto_rule-crypto-hash-md5 + languages: [python] + message: 'The application was found using an insecure or risky digest or signature algorithm. MD5 + + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + + This means + + that two different values, when hashed, can lead to the same hash value. If the application is + + trying + + to use these hash methods for storing passwords, then it is recommended to switch to a + + password hashing + + algorithm such as Argon2id or PBKDF2. + + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + + a custom algorithm is prone to errors. + + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + + Example of creating a SHA-384 hash using the `cryptography` package: + + ``` + + from cryptography.hazmat.primitives import hashes + + # Create a SHA384 digest + + digest = hashes.Hash(hashes.SHA384()) + + # Update the digest with some initial data + + digest.update(b"some data to hash") + + # Add more data to the digest + + digest.update(b"some more data") + + # Finalize the digest as bytes + + result = digest.finalize() + + ``` + + + For more information on secure password storage see OWASP: + + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: Crypto.Hash.MD5.new(...) + - pattern: Cryptodome.Hash.MD5.new (...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-hash-sha1 + languages: [python] + message: 'The application was found using an insecure or risky digest or signature algorithm. MD5 + + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + + This means + + that two different values, when hashed, can lead to the same hash value. If the application is + + trying + + to use these hash methods for storing passwords, then it is recommended to switch to a + + password hashing + + algorithm such as Argon2id or PBKDF2. + + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + + a custom algorithm is prone to errors. + + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + + Example of creating a SHA-384 hash using the `cryptography` package: + + ``` + + from cryptography.hazmat.primitives import hashes + + # Create a SHA384 digest + + digest = hashes.Hash(hashes.SHA384()) + + # Update the digest with some initial data + + digest.update(b"some data to hash") + + # Add more data to the digest + + digest.update(b"some more data") + + # Finalize the digest as bytes + + result = digest.finalize() + + ``` + + + For more information on secure password storage see OWASP: + + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: Crypto.Hash.SHA.new(...) + - pattern: Cryptodome.Hash.SHA.new (...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-hazmat-cipher-arc4 + languages: [python] + message: 'DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms. + + Newer algorithms apply message integrity to validate ciphertext has not been tampered + + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + + alternatives such as `AES-256-GCM`. + + + For older applications that don''t have support for `ChaCha20Poly1305`, + + `AES-256-GCM` is recommended, however it has many drawbacks: + + - Slower than `ChaCha20Poly1305`. + + - Catastrophic failure if nonce values are reused. + + + Example using `ChaCha20Poly1305`: + + ``` + + import os + + # Import ChaCha20Poly1305 from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = ChaCha20Poly1305.generate_key() + + # Create a new ChaCha20Poly1305 instance with our secure key + + chacha = ChaCha20Poly1305(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = chacha.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + chacha.decrypt(nonce, cipher_text, aad) + + ``` + + + Example using `AESGCM`: + + ``` + + import os + + # Import AESGCM from cryptography + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + # Our plaintext to encrypt + + plain_text = b"Secret text to encrypt" + + # We do not require authenticated but unencrypted data, so set to None + + aad = None + + # Generate a secure key + + key = AESGCM.generate_key(bit_length=128) + + # Create a new AESGCM instance with our secure key + + aesgcm = AESGCM(key) + + # Note: nonce values _must_ be regenerated every time they are used. + + nonce = os.urandom(12) + + # Encrypt our plaintext + + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + + # Decrypt the plain text using the nonce and cipher_text + + aesgcm.decrypt(nonce, cipher_text, aad) + + ``` + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + pattern: cryptography.hazmat.primitives.ciphers.algorithms.ARC4(...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-hazmat-cipher-blowfish + languages: [python] + message: "The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created\ + \ in\n1993. Smaller key sizes may make the ciphertext vulnerable to [birthday\nattacks](https://en.wikipedia.org/wiki/Birthday_attack).\ + \ While no known attacks against\nBlowfish\nexist, it should never be used to encrypt files over 4GB\ + \ in size. If possible consider\nusing ChaCha20Poly1305 or AES-GCM instead of Blowfish.\n\nFor older\ + \ applications that don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however\ + \ it has many drawbacks:\n - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values\ + \ are reused.\n\nExample using `ChaCha20Poly1305`:\n```\nimport os\n# Import ChaCha20Poly1305 from cryptography\n\ + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305\n# Our plaintext to encrypt\n\ + plain_text = b\"Secret text to encrypt\"\n# We do not require authenticated but unencrypted data, so\ + \ set to None\naad = None\n# Generate a secure key\nkey = ChaCha20Poly1305.generate_key()\n# Create\ + \ a new ChaCha20Poly1305 instance with our secure key\nchacha = ChaCha20Poly1305(key)\n# Note: nonce\ + \ values _must_ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\n\ + cipher_text = chacha.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\ + chacha.decrypt(nonce, cipher_text, aad)\n```\n\nExample using `AESGCM`:\n```\nimport os\n# Import AESGCM\ + \ from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM\n# Our plaintext\ + \ to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We do not require authenticated but unencrypted\ + \ data, so set to None\naad = None\n# Generate a secure key\nkey = AESGCM.generate_key(bit_length=128)\n\ + # Create a new AESGCM instance with our secure key\naesgcm = AESGCM(key)\n# Note: nonce values _must_\ + \ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text\ + \ = aesgcm.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\ + aesgcm.decrypt(nonce, cipher_text, aad)\n```\n\nFor more information on the cryptography module see:\n\ + - https://cryptography.io/en/latest/\n" + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + pattern: cryptography.hazmat.primitives.ciphers.algorithms.Blowfish(...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-hazmat-cipher-idea + languages: [python] + message: "The IDEA encryption algorithm was meant as a drop-in replacement for DES and was created in\n\ + 1991. A number of [vulnerabilities and\nexploits](https://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm#Security)\ + \ have\nbeen identified to work against IDEA and\nit is no longer recommended. If possible consider\n\ + using ChaCha20Poly1305 or AES-GCM instead of Blowfish.\n\nFor older applications that don't have support\ + \ for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n - Slower\ + \ than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values are reused.\n\nExample using `ChaCha20Poly1305`:\n\ + ```\nimport os\n# Import ChaCha20Poly1305 from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\ + \ import ChaCha20Poly1305\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We\ + \ do not require authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure\ + \ key\nkey = ChaCha20Poly1305.generate_key()\n# Create a new ChaCha20Poly1305 instance with our secure\ + \ key\nchacha = ChaCha20Poly1305(key)\n# Note: nonce values _must_ be regenerated every time they are\ + \ used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text = chacha.encrypt(nonce, plain_text,\ + \ aad)\n# Decrypt the plain text using the nonce and cipher_text\nchacha.decrypt(nonce, cipher_text,\ + \ aad)\n```\n\nExample using `AESGCM`:\n```\nimport os\n# Import AESGCM from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\ + \ import AESGCM\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We do not require\ + \ authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure key\nkey = AESGCM.generate_key(bit_length=128)\n\ + # Create a new AESGCM instance with our secure key\naesgcm = AESGCM(key)\n# Note: nonce values _must_\ + \ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text\ + \ = aesgcm.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\ + aesgcm.decrypt(nonce, cipher_text, aad)\n```\n\nFor more information on the cryptography module see:\n\ + - https://cryptography.io/en/latest/\n" + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + shortDescription: Use of a Broken or Risky Cryptographic Algorithm + security-severity: Medium + category: security + pattern: cryptography.hazmat.primitives.ciphers.algorithms.IDEA(...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-hazmat-hash-md5 + languages: [python] + message: 'The application was found using an insecure or risky digest or signature algorithm. MD2, MD5 + + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + + This means + + that two different values, when hashed, can lead to the same hash value. If the application is + + trying + + to use these hash methods for storing passwords, then it is recommended to switch to a + + password hashing + + algorithm such as Argon2id or PBKDF2. + + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + + a custom algorithm is prone to errors. + + + Example of creating a SHA-384 hash using the `cryptography` package: + + ``` + + from cryptography.hazmat.primitives import hashes + + # Create a SHA384 digest + + digest = hashes.Hash(hashes.SHA384()) + + # Update the digest with some initial data + + digest.update(b"some data to hash") + + # Add more data to the digest + + digest.update(b"some more data") + + # Finalize the digest as bytes + + result = digest.finalize() + + ``` + + + For more information on secure password storage see OWASP: + + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + category: security + pattern: cryptography.hazmat.primitives.hashes.MD5(...) + severity: WARNING + - id: gitlab-python_crypto_rule-crypto-hazmat-hash-sha1 + languages: [python] + message: 'The application was found using an insecure or risky digest or signature algorithm. MD2, MD5 + + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + + This means + + that two different values, when hashed, can lead to the same hash value. If the application is + + trying + + to use these hash methods for storing passwords, then it is recommended to switch to a + + password hashing + + algorithm such as Argon2id or PBKDF2. + + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + + a custom algorithm is prone to error. + + + Example of creating a SHA-384 hash using the `cryptography` package: + + ``` + + from cryptography.hazmat.primitives import hashes + + # Create a SHA384 digest + + digest = hashes.Hash(hashes.SHA384()) + + # Update the digest with some initial data + + digest.update(b"some data to hash") + + # Add more data to the digest + + digest.update(b"some more data") + + # Finalize the digest as bytes + + result = digest.finalize() + + ``` + + + For more information on secure password storage see OWASP: + + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + pattern: cryptography.hazmat.primitives.hashes.SHA1(...) + severity: WARNING + - id: gitlab-python_crypto_rule-hash-md2 + languages: [python] + message: 'The application was found using an insecure or risky digest or signature algorithm. MD2, MD5 + + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + + This means + + that two different values, when hashed, can lead to the same hash value. If the application is + + trying + + to use these hash methods for storing passwords, then it is recommended to switch to a + + password hashing + + algorithm such as Argon2id or PBKDF2. + + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + + Example of creating a SHA-384 hash using the `cryptography` package: + + ``` + + from cryptography.hazmat.primitives import hashes + + # Create a SHA384 digest + + digest = hashes.Hash(hashes.SHA384()) + + # Update the digest with some initial data + + digest.update(b"some data to hash") + + # Add more data to the digest + + digest.update(b"some more data") + + # Finalize the digest as bytes + + result = digest.finalize() + + ``` + + + For more information on secure password storage see OWASP: + + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + + For more information on the cryptography module see: + + - https://cryptography.io/en/latest/ + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: Crypto.Hash.MD2.new(...) + - pattern: Cryptodome.Hash.MD2.new (...) + severity: WARNING + - id: gitlab-python_crypto_rule-hash-md4 + languages: [python] + message: "The application was found using an insecure or risky digest or signature algorithm. MD2, MD4,\n\ + \ MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions.\n\nThis means\n\ + that two different values, when hashed, can lead to the same hash value. If the application is\ntrying\n\ + to use these hash methods for storing passwords, then it is recommended to switch to a\npassword hashing\n\ + algorithm such as Argon2id or PBKDF2.\n\nNote that the `Crypto` and `Cryptodome` Python packages are\ + \ no longer recommended for\nnew applications, instead consider using the [cryptography](https://cryptography.io/)\ + \ package.\n\nExample of creating a SHA-384 hash using the `cryptography` package:\n```\nfrom cryptography.hazmat.primitives\ + \ import hashes\n# Create a SHA384 digest\ndigest = hashes.Hash(hashes.SHA384())\n# Update the digest\ + \ with some initial data\ndigest.update(b\"some data to hash\")\n# Add more data to the digest\ndigest.update(b\"\ + some more data\")\n# Finalize the digest as bytes\nresult = digest.finalize()\n```\n\nFor more information\ + \ on secure password storage see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html\n\ + \nFor more information on the cryptography module see:\n- https://cryptography.io/en/latest/\n" + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: Crypto.Hash.MD4.new(...) + - pattern: Cryptodome.Hash.MD4.new (...) + severity: WARNING + - id: gitlab-python_crypto_rule-hash-md5 + languages: [python] + message: "The application was found using an insecure or risky digest or signature algorithm. MD2, MD4,\n\ + \ MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions.\n\nThis means\n\ + that two different values, when hashed, can lead to the same hash value. If the application is\ntrying\n\ + to use these hash methods for storing passwords, then it is recommended to switch to a\npassword hashing\n\ + algorithm such as Argon2id or PBKDF2.\n\nNote that the `Crypto` and `Cryptodome` Python packages are\ + \ no longer recommended for\nnew applications, instead consider using the [cryptography](https://cryptography.io/)\ + \ package.\n\nExample of creating a SHA-384 hash using the `cryptography` package:\n```\nfrom cryptography.hazmat.primitives\ + \ import hashes\n# Create a SHA384 digest\ndigest = hashes.Hash(hashes.SHA384())\n# Update the digest\ + \ with some initial data\ndigest.update(b\"some data to hash\")\n# Add more data to the digest\ndigest.update(b\"\ + some more data\")\n# Finalize the digest as bytes\nresult = digest.finalize()\n```\n\nFor more information\ + \ on secure password storage see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html\n\ + \nFor more information on the cryptography module see:\n- https://cryptography.io/en/latest/\n" + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + pattern: hashlib.md5(...) + severity: WARNING + - id: gitlab-python_crypto_rule-hash-sha1 + languages: [python] + message: "The application was found using an insecure or risky digest or signature algorithm. MD2, MD4,\n\ + \ MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions.\n\nThis means\n\ + that two different values, when hashed, can lead to the same hash value. If the application is\ntrying\n\ + to use these hash methods for storing passwords, then it is recommended to switch to a\npassword hashing\n\ + algorithm such as Argon2id or PBKDF2.\n\nNote that the `Crypto` and `Cryptodome` Python packages are\ + \ no longer recommended for\nnew applications, instead consider using the [cryptography](https://cryptography.io/)\ + \ package.\n\nExample of creating a SHA-384 hash using the `cryptography` package:\n```\nfrom cryptography.hazmat.primitives\ + \ import hashes\n# Create a SHA384 digest\ndigest = hashes.Hash(hashes.SHA384())\n# Update the digest\ + \ with some initial data\ndigest.update(b\"some data to hash\")\n# Add more data to the digest\ndigest.update(b\"\ + some more data\")\n# Finalize the digest as bytes\nresult = digest.finalize()\n```\n\nFor more information\ + \ on secure password storage see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html\n\ + \nFor more information on the cryptography module see:\n- https://cryptography.io/en/latest/\n" + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + pattern: hashlib.sha1(...) + severity: WARNING + - id: gitlab-python_crypto_rule-hashlib-new-insecure-functions + languages: [python] + message: 'The application was found using an insecure or risky digest or signature algorithm. MD2, MD4, + + MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + + This means + + that two different values, when hashed, can lead to the same hash value. If the application is + + trying + + to use these hash methods for storing passwords, then it is recommended to switch to a + + password hashing + + algorithm such as Argon2id or PBKDF2. + + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + + a custom algorithm is prone to errors. + + + Example using `hashlib.sha384()` to create a SHA384 hash: + + ``` + + import hashlib + + # Create a SHA384 digest + + digest = hashlib.sha384() + + # Update the digest with some initial data + + digest.update(b"some data to hash") + + # Add more data to the digest + + digest.update(b"some more data") + + # Finalize the digest as bytes + + digest.digest() + + ``` + + ' + metadata: + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + patterns: + - pattern-either: + - pattern: hashlib.new("=~/[M|m][D|d][4|5]/", ...) + - pattern: hashlib.new(..., name="=~/[M|m][D|d][4|5]/", ...) + - pattern: hashlib.new('sha1') + - pattern: hashlib.new(..., name='SHA1') + - pattern: hashlib.new('sha', string='test') + - pattern: hashlib.new(name='SHA', string='test') + severity: WARNING + - id: gitlab-python_crypto_rule-import-pycrypto + languages: [python] + message: 'The application was detected importing `pycrypto`. This package has been deprecated as it + + contains + + security vulnerabilities. + + + To remediate this issue, consider using the [cryptography](https://cryptography.io/) + + package instead. + + ' + metadata: + cwe: CWE-1104 + owasp: + - A9:2017-Using Components with Known Vulnerabilities + - A06:2021-Vulnerable and Outdated Components + - A03:2025-Software Supply Chain Failures + category: security + shortDescription: Use of unmaintained third party components + security-severity: Medium + pattern-either: + - pattern: import pycryto + - pattern: import Crypto.Cipher + - pattern: import Crypto.Hash + - pattern: import Crypto.IO + - pattern: import Crypto.Protocol + - pattern: import Crypto.PublicKey + - pattern: import Crypto.Random + - pattern: import Crypto.Signature + - pattern: import Crypto.Util + severity: ERROR + - id: gitlab-python_deserialization_rule-cpickle + languages: [python] + message: "The application was found using `cPickle` which is vulnerable to deserialization attacks.\n\ + Deserialization attacks exploit the process of reading serialized data and turning it back\ninto an\ + \ object. By constructing malicious objects and serializing them, an adversary may\nattempt to:\n\n\ + - Inject code that is executed upon object construction, which occurs during the\ndeserialization process.\n\ + - Exploit mass assignment by including fields that are not normally a part of the serialized\ndata but\ + \ are read in during deserialization.\n\nConsider safer alternatives such as serializing data in the\ + \ JSON format. Ensure any format\nchosen allows\nthe application to specify exactly which object types\ + \ are allowed to be deserialized.\n\nTo protect against mass assignment, only allow deserialization\ + \ of the specific fields that are\nrequired. If this is not easily done, consider creating an intermediary\ + \ type that\ncan be serialized with only the necessary fields exposed.\n\nExample JSON deserializer\ + \ using an intermediary type that is validated against a schema to\nensure\nit is safe from mass assignment:\n\ + ```\nimport jsonschema\n\n# Create a schema to validate our user-supplied input against\n# an intermediary\ + \ object\nintermediary_schema = {\n \"type\" : \"object\",\n \"properties\" : {\n \"name\"\ + : {\"type\" : \"string\"}\n },\n \"required\": [\"name\"],\n # Protect against random properties\ + \ being added to the object\n \"additionalProperties\": False,\n}\n# If a user attempted to add \"\ + 'is_admin': True\" it would cause a validation error\nintermediary_object = {'name': 'test user'}\n\n\ + try:\n # Validate the user supplied intermediary object against our schema\n jsonschema.validate(instance=intermediary_object,\ + \ schema=intermediary_schema)\n user_object = {'user':\n {\n # Assign the deserialized\ + \ data from intermediary object\n 'name': intermediary_object['name'],\n # Add\ + \ in protected data in object definition (or set it from a class constructor)\n 'is_admin':\ + \ False,\n }\n }\n # Work with the user_object\nexcept jsonschema.exceptions.ValidationError\ + \ as ex:\n # Gracefully handle validation errors\n # ...\n```\n\nFor more details on deserialization\ + \ attacks in general, see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n" + metadata: + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + - A08:2025-Software or Data Integrity Failures + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + pattern: cPickle.$FUNC(...) + severity: WARNING + - id: gitlab-python_deserialization_rule-pickle + languages: [python] + message: "The application was found using `pickle` which is vulnerable to deserialization attacks.\nDeserialization\ + \ attacks exploit the process of reading serialized data and turning it back\ninto an object. By constructing\ + \ malicious objects and serializing them, an adversary may\nattempt to:\n\n- Inject code that is executed\ + \ upon object construction, which occurs during the\ndeserialization process.\n- Exploit mass assignment\ + \ by including fields that are not normally a part of the serialized\ndata but are read in during deserialization.\n\ + \nConsider safer alternatives such as serializing data in the JSON format. Ensure any format\nchosen\ + \ allows the application to specify exactly which object types are allowed to be deserialized.\n\nTo\ + \ protect against mass assignment, only allow deserialization of the specific fields that are\nrequired.\ + \ If this is not easily done, consider creating an intermediary type that\ncan be serialized with only\ + \ the necessary fields exposed.\n\nExample JSON deserializer using an intermediary type that is validated\ + \ against a schema to ensure\nit is safe from mass assignment:\n```\nimport jsonschema\n\n# Create a\ + \ schema to validate our user-supplied input against\n# an intermediary object\nintermediary_schema\ + \ = {\n \"type\" : \"object\",\n \"properties\" : {\n \"name\": {\"type\" : \"string\"\ + }\n },\n \"required\": [\"name\"],\n # Protect against random properties being added to the\ + \ object\n \"additionalProperties\": False,\n}\n# If a user attempted to add \"'is_admin': True\"\ + \ it would cause a validation error\nintermediary_object = {'name': 'test user'}\n\ntry:\n # Validate\ + \ the user supplied intermediary object against our schema\n jsonschema.validate(instance=intermediary_object,\ + \ schema=intermediary_schema)\n user_object = {'user':\n {\n # Assign the deserialized\ + \ data from intermediary object\n 'name': intermediary_object['name'],\n # Add\ + \ in protected data in object definition (or set it from a class constructor)\n 'is_admin':\ + \ False,\n }\n }\n # Work with the user_object\nexcept jsonschema.exceptions.ValidationError\ + \ as ex:\n # Gracefully handle validation errors\n # ...\n```\n\nFor more details on deserialization\ + \ attacks in general, see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n" + metadata: + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + - A08:2025-Software or Data Integrity Failures + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + patterns: + - pattern-either: + - patterns: + - pattern: pickle.$METHOD(...) + - pattern-not: pickle.$METHOD("...") + - patterns: + - pattern: _pickle.$METHOD(...) + - pattern-not: _pickle.$METHOD("...") + - metavariable-regex: + metavariable: $METHOD + regex: (load|loads|Unpickler) + severity: WARNING + - id: gitlab-python_deserialization_rule-shelve + languages: [python] + message: "The application was found using `shelve` which is vulnerable to deserialization attacks as\n\ + it calls `pickle` internally.\nDeserialization attacks exploit the process of reading serialized data\ + \ and turning it back\ninto an object. By constructing malicious objects and serializing them, an adversary\ + \ may\nattempt to:\n\n- Inject code that is executed upon object construction, which occurs during the\n\ + deserialization process.\n- Exploit mass assignment by including fields that are not normally a part\ + \ of the serialized\ndata but are read in during deserialization.\n\nConsider safer alternatives such\ + \ as serializing data in the JSON format. Ensure any format\nchosen allows\nthe application to specify\ + \ exactly which object types are allowed to be deserialized.\n\nTo protect against mass assignment,\ + \ only allow deserialization of the specific fields that are\nrequired. If this is not easily done,\ + \ consider creating an intermediary type that\ncan be serialized with only the necessary fields exposed.\n\ + \nExample JSON deserializer using an intermediary type that is validated against a schema to\nensure\n\ + it is safe from mass assignment:\n```\nimport jsonschema\n\n# Create a schema to validate our user-supplied\ + \ input against\n# an intermediary object\nintermediary_schema = {\n \"type\" : \"object\",\n \ + \ \"properties\" : {\n \"name\": {\"type\" : \"string\"}\n },\n \"required\": [\"name\"\ + ],\n # Protect against random properties being added to the object\n \"additionalProperties\"\ + : False,\n}\n# If a user attempted to add \"'is_admin': True\" it would cause a validation error\nintermediary_object\ + \ = {'name': 'test user'}\n\ntry:\n # Validate the user supplied intermediary object against our\ + \ schema\n jsonschema.validate(instance=intermediary_object, schema=intermediary_schema)\n user_object\ + \ = {'user':\n {\n # Assign the deserialized data from intermediary object\n \ + \ 'name': intermediary_object['name'],\n # Add in protected data in object definition\ + \ (or set it from a class constructor)\n 'is_admin': False,\n }\n }\n # Work\ + \ with the user_object\nexcept jsonschema.exceptions.ValidationError as ex:\n # Gracefully handle\ + \ validation errors\n # ...\n```\n\nFor more details on deserialization attacks in general, see OWASP's\ + \ guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n" + metadata: + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + - A08:2025-Software or Data Integrity Failures + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + pattern-either: + - pattern: shelve.$FUNC(...) + severity: WARNING + - id: gitlab-python_deserialization_rule-yaml-load + languages: [python] + message: "The application was found using an unsafe version of `yaml` load which is vulnerable to\ndeserialization\ + \ attacks. Deserialization attacks exploit the process of reading serialized\ndata and turning it back\n\ + into an object. By constructing malicious objects and serializing them, an adversary may\nattempt to:\n\ + \n- Inject code that is executed upon object construction, which occurs during the\ndeserialization\ + \ process.\n- Exploit mass assignment by including fields that are not normally a part of the serialized\n\ + data but are read in during deserialization.\n\nTo remediate this issue, use `safe_load()` or call `yaml.load()`\ + \ with the `Loader` argument\nset to\n`yaml.SafeLoader`.\n\nExample loading YAML using `safe_load`:\n\ + ```\nimport yaml\n\n# Use safe_load to load data into an intermediary object\nintermediary_object =\ + \ yaml.safe_load(\"\"\"user:\n name: 'test user'\"\"\"\n)\n# Create our real object, copying over\ + \ only the necessary fields\nuser_object = {'user': {\n # Assign the deserialized data from intermediary\ + \ object\n 'name': intermediary_object['user']['name'],\n # Add in protected data in object\ + \ definition (or set it from a class constructor)\n 'is_admin': False,\n }\n}\n# Work with\ + \ user_object\n# ...\n```\n\nFor more details on deserialization attacks in general, see OWASP's guide:\n\ + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n" + patterns: + - pattern-inside: 'import yaml + + ... + + ' + - pattern-not-inside: 'from ruamel.yaml import YAML + + ... + + ' + - pattern-either: + - pattern: yaml.unsafe_load(...) + - pattern: yaml.$LD(..., Loader=yaml.$LOADER, ...) + - pattern: yaml.$LD($DATA) + - metavariable-regex: + metavariable: $LOADER + regex: (Loader|UnsafeLoader|CLoader|FullLoader) + - metavariable-regex: + metavariable: $LD + regex: (load|load_all) + metadata: + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + - A08:2025-Software or Data Integrity Failures + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + severity: ERROR + - id: gitlab-python_django_rule-django-extra-used + languages: [python] + message: "SQL Injection is a critical vulnerability that can lead to data or system compromise. By\ndynamically\ + \ generating SQL query strings, user input may be able to influence the logic of\nthe SQL statement.\ + \ This could lead to an adversary accessing information they should\nnot have access to, or in some\ + \ circumstances, being able to execute OS functionality or code.\n\nReplace all dynamically generated\ + \ SQL queries with parameterized queries. In situations where\ndynamic queries must be created, never\ + \ use direct user input, but instead use a map or\ndictionary of valid values and resolve them using\ + \ a user supplied key.\n\nFor example, some database drivers do not allow parameterized queries for\ + \ `>` or `<` comparison\noperators. In these cases, do not use a user supplied `>` or `<` value, but\ + \ rather have the\nuser\nsupply a `gt` or `lt` value. The alphabetical values are then used to look\ + \ up the `>` and `<`\nvalues to be used in the construction of the dynamic query. The same goes for\ + \ other queries\nwhere\ncolumn or table names are required but cannot be parameterized.\n\nThe `QuerySet.extra`\ + \ API method will be deprecated as it a source of SQL Injection\nvulnerabilities and other problems.\ + \ This method is especially risky as callers\nwill need to do their own escaping of any parameters that\ + \ come from user-supplied\ninformation.\n\nTo remediate this issue, do not use `extra` but use other\ + \ `QuerySet` methods to achieve\nthe same goals. If for some reason this is not feasible, consider using\ + \ the `RawSQL` method\nand making sure that all arguments, including user-supplied ones, are only used\ + \ in\n`params`\n\n\nWhile not recommended due to [potential SQL\nInjection](https://docs.djangoproject.com/en/4.2/ref/models/expressions/#raw-sql-expressions),\n\ + below is an example using `RawSQL`,\npassing in user-supplied data as a `param` which will escape the\ + \ input:\n```\n# If dealing with integer based user input, restrict the values to integers only using\ + \ the\n# path configuration: path('/someview/', views.some_view,\nname='someview'),\n\ + \n# views.py\ndef some_view(request, user_supplied_id):\n # Never use string interpolation in the `sql`\ + \ parameter.\n # Never quote the `%s` string format such as `... where id='%s'` as this could lead\ + \ to SQL\nInjection.\n # Pass the user supplied data only in the `params` parameter.\n for obj in\ + \ DBObject.objects.all().annotate(\n val=RawSQL(sql=\"select id from some_secondary_table where\ + \ id=%s\",\nparams=[user_supplied_id])):\n # Work with the results from the query\n # ...\n```\n\ + \nFor more information on QuerySet see:\n- https://docs.djangoproject.com/en/4.2/ref/models/querysets/#queryset-api\n\ + \nFor more information on SQL Injection see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\n" + patterns: + - pattern: $X.objects. ... .extra(..., $K = $V, ...) + - pattern-not-inside: '$V = [''...''] + + ... + + ' + - metavariable-pattern: + metavariable: $V + patterns: + - pattern: $V + - pattern-not: '[..., ''...'', ...]' + - pattern-not: '{..., ''...'': ''...'', ...}' + - pattern-not: '"..."' + - pattern-not: '[..., "..." % "...", ...]' + - pattern-not: '{..., $L: "..." % "...", ...}' + - pattern-not: '{..., $L: "...".format("..."), ...}' + - pattern-not: '[..., "...".format("..."), ...]' + metadata: + cwe: CWE-89 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + category: security + shortDescription: Improper neutralization of special elements used in an SQL Command ('SQL Injection') + security-severity: High + severity: WARNING + - id: gitlab-python_escaping_rule-jinja2-autoescape-false + languages: [python] + message: "The application was found using Jinja2 `Environment` without autoescaping enabled. If using\ + \ in\nthe context of HTML this could lead to Cross-Site Scripting (XSS) attacks when rendering with\n\ + user-supplied input.\n\nUnfortunately, Jinja2 does not support context-aware escaping, meaning it is\ + \ insufficient to\nprotect against\nXSS for the various web contexts. It is important to encode the\ + \ data depending on the specific\ncontext\nit\nis used in. There are at least six context types:\n\n\ + - Inside HTML tags `
context 1
`\n- Inside attributes: `
`\n\ + - Inside event attributes ``\n- Inside script blocks: ``\n- Unsafe element HTML assignment: `element.innerHTML = \"context 5\"\ + `\n- Inside URLs: `link`\n\nScript blocks\ + \ alone have multiple ways they need to be encoded. Extra care must be taken if\nuser input\nis ever\ + \ output inside of script tags.\n\nUser input that is displayed within the application must be encoded,\ + \ sanitized or validated\nto ensure it cannot be treated as HTML or executed as Javascript code. Care\ + \ must also be\ntaken\nto not mix server-side templating with client-side templating, as the server-side\ + \ templating\nwill\nnot encode things like {{ 7*7 }} which may execute client-side templating features.\n\ + \nIt is _NOT_ advised to encode user input prior to inserting into a data store. The data will\nneed\ + \ to be\nencoded depending on context of where it is output. It is much safer to force the displaying\n\ + system to\nhandle the encoding and not attempt to guess how it should be encoded.\n\nTo handle different\ + \ contexts, one approach would be to write custom Jinja2 filters. Below is\nan example\nthat escapes\ + \ or encodes links and potentially malicious script, note this does not include\nother contexts\nsuch\ + \ as CSS or attributes:\n```\nfrom jinja2 import Environment, select_autoescape, FileSystemLoader\n\ + from jinja2 import pass_eval_context\nfrom markupsafe import Markup, escape\n\n@pass_eval_context\n\ + def escape_link(eval_ctx, value):\n bad_link = \"#JinjatmplZ\"\n # Block any values that start\ + \ with // as that could be used to inject\n # links to third party pages see:\nhttps://en.wikipedia.org/wiki/Wikipedia:Protocol-relative_URL\n\ + \ if value.startswith('//'):\n return bad_link\n\n # Only allow relative links\n # if\ + \ you want to allow links that start with http or ws replace with below:\n # if not value.startswith('/'):\ + \ and not value.startswith('http') and not\nvalue.startswith('ws')\n if not value.startswith('/'):\n\ + \ return bad_link\n\n # Alternatively, you could only call escape if autoescape is true\n\ + \ # if eval_ctx.autoescape:\n # return escape(value)\n # else\n # return value\n\n\ + \ return escape(value)\n\n# Create a replacement table\njs_replacement = str.maketrans({\n \ + \ '\"': \"\\\\u0022\",\n '`': \"\\\\u0060\",\n '&': \"\\\\u0026\",\n '\\'':\ + \ \"\\\\u0027\",\n '+': \"\\\\u002b\",\n '/': \"\\\\/\",\n '<': \"\\\\u003c\"\ + ,\n '>': \"\\\\u003e\",\n '\\\\': \"\\\\\\\\\",\n '(': \"\\\\u0028\",\n \ + \ ')': \"\\\\u0029\",\n })\n\n@pass_eval_context\ndef escape_js(eval_ctx, value):\n \"\"\"\n\ + \ Escape the input for use in \",\n script_context=\"alert(1);alert`1`\",)\n)\n\n#\ + \ Sample template:\n\"\"\"\n\n\n\n My Webpage\n\ + \n\n

My Webpage

\n {{ html_context }}\n link\n \n\n\n\"\"\"\n```\n\ + \nFor more information on autoescape see:\n- https://jinja.palletsprojects.com/en/3.1.x/api/#autoescaping\n\ + \nFor more information on XSS see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\n" + metadata: + cwe: CWE-116 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + - A05:2025-Injection + category: security + shortDescription: Improper encoding or escaping of output + security-severity: Medium + patterns: + - pattern-inside: 'import jinja2 + + ... + + ' + - pattern-not: jinja2.Environment(..., autoescape=True, ...) + - pattern-not: jinja2.Environment(..., autoescape=jinja2.select_autoescape(...),...) + - pattern-not: jinja2.Environment(..., autoescape=select_autoescape(...), ...) + - pattern: jinja2.Environment(...) + severity: WARNING + - id: gitlab-python_escaping_rule-use-of-mako-templates + languages: [python] + message: "The application was found using mako templates without `default_filters`\nbeing passed to the\ + \ `Template` or `TemplateLookup` constructors. If using \nin the context of HTML, this could lead to\ + \ Cross-Site Scripting (XSS) attacks \nwhen rendering with user-supplied input.\n\nUnfortunately, Jinja2\ + \ does not support context-aware escaping, meaning it\nis insufficient to protect against XSS for the\ + \ various web contexts. It is \nimportant to encode the data depending on the specific context it is\ + \ used in. \nThere are at least six context types:\n\n- Inside HTML tags `
context 1
`\n- Inside\ + \ attributes: `
`\n- Inside event attributes ``\n- Inside script blocks: ``\n- Unsafe element\ + \ HTML assignment: `element.innerHTML = \"context 5\"`\n- Inside URLs: \n`link`\n\nScript blocks alone have multiple ways they need to be\ + \ encoded. Extra care\nmust be taken if user input is ever output inside of script tags.\n\nUser input\ + \ that is displayed within the application must be encoded,\nsanitized or validated to ensure it cannot\ + \ be treated as HTML or executed \nas Javascript code. Care must also be taken to not mix server-side\ + \ templating \nwith client-side templating, as the server-side templating will not encode things \n\ + like {{ 7*7 }} which may execute client-side templating features.\n\nIt is _NOT_ advised to encode user\ + \ input prior to inserting into a data\nstore. The data will need to be encoded depending on context\ + \ of where it is output. \nIt is much safer to force the displaying system to handle the encoding and\ + \ \nnot attempt to guess how it should be encoded.\n\nTo handle different contexts, one approach would\ + \ be to write custom mako\nfilters. Below is an example that escapes or encodes links and \npotentially\ + \ malicious script, note this does not include other contexts \nsuch as CSS or attributes:\n```\n# filters.py\ + \ module:\n\ndef escape_link(value):\n bad_link = \"#JinjatmplZ\"\n # Block any values that start\ + \ with // as that could be used to inject\n # links to third party pages see:\nhttps://en.wikipedia.org/wiki/Wikipedia:Protocol-relative_URL\n\ + \ if value.startswith('//'):\n return bad_link\n\n # Only allow relative links\n # if\ + \ you want to allow links that start with http or ws replace with below:\n # if not value.startswith('/'):\ + \ and not value.startswith('http') and not\nvalue.startswith('ws')\n if not value.startswith('/'):\n\ + \ return bad_link\n\n return value\n\n# Create a replacement table\njs_replacement = str.maketrans({\n\ + \ '\\0': \"\\\\u0000\",\n '\\t': \"\\\\t\",\n '\\n': \"\\\\n\",\n '\\v': \"\\\\u000b\",\n\ + \ '\\f': \"\\\\f`\",\n '\\r': \"\\\\r\",\n '\"': \"\\\\u0022\",\n '`': \"\\\\u0060\",\n\ + \ '&': \"\\\\u0026\",\n '\\'': \"\\\\u0027\",\n '+': \"\\\\u002b\",\n '/': \"\\\\/\"\ + ,\n '<': \"\\\\u003c\",\n '>': \"\\\\u003e\",\n '\\\\': \"\\\\\\\\\",\n '(': \"\\\\u0028\"\ + ,\n ')': \"\\\\u0029\",\n})\n\ndef escape_js(value):\n # Escape the input for use in \n\n\n\"\"\"\n\n# Load our\ + \ template with default filters and our imported filters for\n# usage in template files\nt = Template(template_text,\n\ + \ # By default enable the html filter with 'h'\n default_filters=['h'],\n \ + \ # Import our custom filters\n imports=[\"from filters import escape_link, escape_js\"\ + ])\n\n# Render our template\nprint(t.render(html_context=\"\",\n link_context=\"\ + /# onclick=alert(1)\",\n script_context=\"alert(1)\"\ + ,)\n)\n```\n" + metadata: + cwe: CWE-79 + category: security + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + - A05:2025-Injection + shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting') + security-severity: Medium + patterns: + - pattern-either: + - pattern: mako.template.Template(...) + - pattern: mako.lookup.TemplateLookup(...) + - pattern-not: mako.lookup.TemplateLookup(..., default_filters=["..."]) + - pattern-not: mako.template.Template(..., default_filters=["..."]) + severity: WARNING + - id: gitlab-python_eval_rule-eval + languages: [python] + message: "The application was found calling the `eval` function with non-literal data. If the variable\ + \ contains \nuser-controlled data, either partially or fully, an adversary could compromise the entire\ + \ system by \nexecuting arbitrary Python code.\n\nTo remediate this issue, remove all calls to `eval`\ + \ and consider alternative methods for executing \nthe necessary business logic. There is almost no\ + \ safe method of calling `eval` with user-supplied input.\n\nIf the application only needs to convert\ + \ strings into objects, consider using `json.loads`. In \nsome cases `ast.literal_eval` is recommended,\ + \ but this should be avoided as it can still suffer \nfrom other issues such as the ability for malicious\ + \ code to crash the python interpreter or application.\n\nExample using `json.loads`` to load in arbitrary\ + \ data to create data structures:\n```\n# User supplied data as a blob of JSON\nuser_supplied_data =\ + \ \"\"\"{\"user\": \"test\", \"metadata\": [1,2,3]}\"\"\"\n# Load the JSON\nuser_object = json.loads(user_supplied_data)\n\ + # Manually add protected properties _after_ loading, never before\nuser_object[\"is_admin\"] = False\n\ + # Work with the object\n```\n" + patterns: + - pattern: eval($X,...) + - pattern-not: 'eval("...") + + ' + - pattern-not: 'eval("..." % <... "..." ...>) + + ' + - pattern-not: 'eval(<... "...".format( "..." ) ...>) + + ' + - pattern-not-inside: "def eval(...):\n ...\n...\n" + metadata: + cwe: CWE-95 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + category: security + shortDescription: Improper neutralization of directives in dynamically evaluated code ('Eval Injection') + security-severity: High + severity: WARNING + - id: gitlab-python_exec_rule-exec-used + languages: [python] + message: "The application was found calling the `exec` function with a non-literal variable. If the\n\ + variable comes from user-supplied input, an adversary could compromise the entire system by\nexecuting\ + \ arbitrary python code.\n\nTo remediate this issue, remove all calls to `exec` and consider alternative\ + \ methods for\nexecuting the necessary business logic. There is almost no safe method of calling `eval`\ + \ \nwith user-supplied input.\n\nIf the application only needs to convert strings into objects, consider\ + \ using `json.loads`.\nIn some cases `ast.literal_eval` is recommended, but this should be avoided as\ + \ it can still\nsuffer from other issues such as the ability for malicious code to crash the python\n\ + interpreter or application.\n\nExample using `json.loads`` to load in arbitrary data to create data\ + \ structures:\n```\n# User supplied data as a blob of JSON\nuser_supplied_data = \"\"\"{\"user\": \"\ + test\", \"metadata\": [1,2,3]}\"\"\"\n# Load the JSON\nuser_object = json.loads(user_supplied_data)\n\ + # Manually add protected properties _after_ loading, never before\nuser_object[\"is_admin\"] = False\n\ + # Work with the object\n```\n" + metadata: + cwe: CWE-95 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + category: security + shortDescription: Improper neutralization of directives in dynamically evaluated code ('Eval Injection') + security-severity: High + patterns: + - pattern: exec(...) + - pattern-not: exec("...") + severity: WARNING + - id: gitlab-python_exec_rule-linux-command-wildcard-injection + languages: [python] + message: "Detected use of the wildcard character in a system call that spawns a shell. This subjects the\n\ + wildcard to normal shell expansion, which can have unintended consequences if there exist any\nnon-standard\ + \ file names. For instance, a file named `-e sh script.sh` could cause issues when \nexpanded by the\ + \ shell and executed as a command. Consider using a different method to achieve \nthe same result, such\ + \ as using the `glob` module to expand the wildcard before passing it to the\nsystem call. Or if the\ + \ command is static, consider hardcoding the command instead of using a\nwildcard.\n\nFor example, the\ + \ below code uses the glob module to expand the wildcard and get a list of all \nCSV files in the current\ + \ directory. This list is then used in the subprocess.run call, instead of a \nwildcard. This avoids\ + \ the potential issues that can arise from using a wildcard in a system call.\n```\nimport glob\nimport\ + \ subprocess\n\n# Secure way to process all CSV files\nfiles = glob.glob('*.csv')\nfor file in files:\n\ + \ subprocess.run(['process_data', file])\n```\n" + metadata: + category: security + cwe: CWE-155 + owasp: + - A1:2017-Injection + - A03:2021-Injection + shortDescription: Improper neutralization of wildcards or matching symbols + security-severity: High + patterns: + - pattern-either: + - pattern: os.$X("$CMD", ...) + - pattern: subprocess.Popen("$CMD", shell=True, ...) + - metavariable-regex: + metavariable: $CMD + regex: (.*?)(\*|\?) + - pattern-not-inside: os.spawnvp(...) + metavariable-regex: + X: (system|popen|popen2|popen3|popen4) + severity: WARNING + - id: gitlab-python_exec_rule-os-path + languages: [python] + message: 'Starting a process with a shell; seems safe, but may be changed in the future, consider + + rewriting without shell + + ' + pattern-either: + - pattern: os.system("...", ...) + - pattern: $OS.popen("...", ...) + - pattern: $OS.popen2("...", ...) + - pattern: $OS.popen3("...", ...) + - pattern: $OS.popen4("...", ...) + - pattern: commands.getoutput("...", ...) + - pattern: commands.getstatusoutput("...", ...) + metadata: + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + shortDescription: Improper neutralization of special elements used in an OS Command ('OS Command Injection') + security-severity: High + category: security + severity: INFO + - id: gitlab-python_exec_rule-os-popen2 + languages: [python] + message: 'Starting a process with a shell; seems safe, but may be changed in the future, consider + + rewriting without shell + + ' + patterns: + - pattern-either: + - pattern: os.system(...) + - pattern: os.popen(...) + - pattern: os.popen2(...) + - pattern: os.popen3(...) + - pattern: os.popen4(...) + - pattern: popen2.popen2(...) + - pattern: popen2.popen3(...) + - pattern: popen2.popen4(...) + - pattern: popen2.Popen3(...) + - pattern: popen2.Popen4(...) + - pattern: commands.getoutput(...) + - pattern: commands.getstatusoutput("") + metadata: + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + shortDescription: Improper neutralization of special elements used in an OS Command ('OS Command Injection') + security-severity: High + category: security + severity: INFO + - id: gitlab-python_exec_rule-subprocess-call + languages: [python] + message: 'Python possesses many mechanisms to invoke an external executable. However, + + doing so may present a security issue if appropriate care is not taken to + + sanitize any user provided or variable input. This plugin test is part of a + + family of tests built to check for process spawning and warn appropriately. + + Specifically, this test looks for the spawning of a subprocess without the + + use of a command shell. This type of subprocess invocation is not + + vulnerable to shell injection attacks, but care should still be taken to + + ensure validity of input. + + ' + patterns: + - pattern-not: subprocess.$FUNC($ARG, shell=<... True ...>) + - pattern-not: subprocess.$FUNC($ARG, shell=<... 'True' ...>) + - pattern-not: subprocess.$FUNC($ARG, shell=<... "True" ...>) + - pattern-either: + - pattern: 'subprocess.$FUNC($ARG, shell=False) + + ' + - pattern: 'subprocess.$FUNC($ARG, shell=0) + + ' + - pattern: 'subprocess.$FUNC($ARG, shell={...}) + + ' + - pattern: 'subprocess.$FUNC($ARG, shell=[...]) + + ' + - pattern: 'subprocess.$FUNC($ARG) + + ' + metadata: + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + shortDescription: Improper neutralization of special elements used in an OS Command ('OS Command Injection') + security-severity: High + category: security + severity: WARNING + - id: gitlab-python_exec_rule-subprocess-shell-TRUE + languages: [python] + message: 'subprocess call - check for execution of untrusted input + + ' + patterns: + - pattern-not: subprocess.$FUNC(..., shell=True, ...) + - pattern: $FOO(..., shell=True, ...) + metadata: + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + shortDescription: Improper neutralization of special elements used in an OS Command ('OS Command Injection') + security-severity: High + category: security + severity: WARNING + - id: gitlab-python_file-permissions_rule-general-bad-permission + languages: [python] + message: 'The application was found setting file permissions to overly permissive values. Consider + + using the following values if the application user is the only process to access + + the file: + + + - 0400 - read only access to the file + + - 0200 - write only access to the file + + - 0600 - read/write access to the file + + + Example creating a file with read/write permissions for the application user: + + ``` + + # Use octal values to set 0o600 (read/write access to the file) for the current + + # user + + os.chmod(''somefile.txt'', 0o600) + + ``` + + + For all other values please see: + + https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation + + ' + metadata: + shortDescription: Incorrect permission assignment for critical resource + cwe: CWE-732 + category: security + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + security-severity: Medium + patterns: + - pattern: os.chmod(...,$MASK) + - metavariable-regex: + metavariable: $MASK + regex: (0x..f|0o..[2,3,7]|stat.S_IXGRP|stat.S_IWOTH) + severity: WARNING + - id: gitlab-python_files_rule-tarfile-unsafe-members + languages: [python] + message: "The application may be vulnerable to a path traversal if it extracts untrusted archive files.\n\ + This vulnerability is colloquially known as 'Zip Slip'. Archive files may contain folders\nwhich,\n\ + when extracted, may write outside of the intended directory. This is exploited by including\npath traversal\ + \ characters such as `../../other/directory` to overwrite or place files in system\nor application directories.\n\ + \nExtra care must be taken when extracting archive files as there are numerous concerns:\n\n- If possible,\ + \ generate unique filenames instead of using the archives file names, as it may be\npossible for users\ + \ to overwrite files if the filenames are the same.\n- Validate file paths are written with a prefixed,\ + \ known trusted directory.\n- Only process regular files and not symbolic links, as some applications\ + \ may attempt to\nread/follow\nthe symbolic link, leading to arbitrary file read / write vulnerabilities.\n\ + \nExample of securely processing an archive file:\n```\nimport tarfile\nimport uuid\n# import os\n\n\ + tar = tarfile.open('some.tar')\n\n# Max number of allowed files in our archive\nmax_files = 10\n# Max\ + \ size for all files in archive\nmax_size = 1024 * 1024 * 10 # 10MB\n# Max size per file in archive\n\ + max_file_size = 1024 * 1024 # 1MB\n\n# Validate number of files in archive\nif len(tar.getmembers())\ + \ > max_files:\n raise Exception(\"Too many files in archive\")\n\ntotal_size = 0\n# Loop over all\ + \ files to see if we exceed max size\n# if so, do not process any of them.\nfor f in tar.getmembers():\n\ + \ total_size += f.size\n if total_size >= max_size:\n raise Exception(\"Archive files exceeded\ + \ max file size\")\n\n# Iterate over files now that we know the total size is within limits\nfor f in\ + \ tar.getmembers():\n # Internally this calls TarInfo.isreg() which ensures\n # the file is a\ + \ regular file and not a sym link or directory\n if not f.isfile():\n continue\n\n # Optional,\ + \ set a limit on each file size\n if f.size > max_file_size:\n raise Exception(f\"File {f.name}\ + \ too large: {f.size}\")\n\n # If original names are required, ensure that only the\n # filename\ + \ is used:\n # filename = os.path.basename(f.name)\n\n # More secure, generate a UUID4 value instead\n\ + \ filename = uuid.uuid4().hex\n\n # Reset the archive filename to the basename\n # Newer versions\ + \ of python (3.11.4+) should use:\n # new_tar = old_tar.replace(name=...new name...)\n f.name\ + \ = filename\n\n # Extract the file into a restricted directory, with our\n # own user's attributes,\ + \ not the file from the archive\n tar.extract(f, '/opt/app/restricted/', set_attrs=False)\n```\n\n\ + For more information on tarfile see:\n- https://docs.python.org/3/library/tarfile.html\n" + metadata: + cwe: CWE-22 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal') + security-severity: Medium + category: security + patterns: + - pattern-inside: 'import tarfile + + ... + + ' + - pattern-either: + - patterns: + - pattern-inside: '$TAR = tarfile.open(...) + + ... + + ' + - pattern-either: + - pattern: $TAR.extractall(...) + - pattern: tarfile.extractall(..., members=$TAR) + - pattern: $TAR.extractall(..., members=[]) + - patterns: + - pattern: tarfile.extractall(...) + - pattern: tarfile.extractall(..., members=[]) + severity: WARNING + - id: gitlab-python_ftp_rule-ftplib + languages: [python] + message: "The application was found using an FTP library. As FTP does not provide encryption, it is\n\ + strongly recommended that any file transfers be done over a more secure transport such as\nSSH.\n\n\ + The [paramiko](https://www.paramiko.org/) library can be used with an SCP module to allow\nsecure file\ + \ transfers.\n\nExample using `paramiko` SSH client and the `scp` module:\n```\nimport paramiko\nimport\ + \ scp\n\n# Create an SSH client\nwith paramiko.SSHClient() as ssh:\n # Load the system host keys\ + \ so we can confirm the\n # host we are connecting to is legitimate\n ssh.load_system_host_keys('/home/appuser/.ssh/known_hosts')\n\ + \n # Connect to the remote host using our SSH private key\n ssh.connect(hostname='example.org',\n\ + \ port=22,\n username='appuser',\n key_filename='/home/appuser/.ssh/private_key')\n\ + \n # Create an SCP client with the ssh transport and copy files\n with scp.SCPClient(ssh.get_transport())\ + \ as secure_copy:\n secure_copy.get('remote/test.file', 'local/test.file')\n secure_copy.put('local/some.file',\ + \ 'remote/some.file')\n```\n\nFor more information on the paramiko module see:\n- https://www.paramiko.org/\n\ + \nFor more information on the scp module see:\n- https://github.com/jbardin/scp.py\n" + metadata: + cwe: CWE-319 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Cleartext transmission of sensitive information + security-severity: Medium + pattern: ftplib.$ANYTHING(...) + severity: WARNING + - id: gitlab-python_log_rule-logging-config-insecure-listen + languages: [python] + message: 'The application was found calling the `logging.config.listen`` function, which provides the + + ability to listen for + + external configuration files over a socket server. This listen socket parses part of the + + configuration and calls + + `eval` on the supplied configuration file. A local user, or an adversary who is able to + + exploit + + a Server Side Request Forgery (SSRF) attack to communicate over localhost, would be able to + + execute arbitrary + + code by passing in a logging config that contains python code. + + + To remediate the issue, remove the call to `logging.config.listen` method. + + + For more information on the listen functionality see: + + - https://docs.python.org/3/library/logging.config.html#logging.config.listen + + ' + metadata: + cwe: CWE-94 + shortDescription: Improper control of generation of code ('Code Injection') + category: security + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + security-severity: High + patterns: + - pattern: logging.config.listen(...) + severity: WARNING + - id: gitlab-python_random_rule-random + languages: [python] + message: 'Depending on the context, generating weak random numbers may expose cryptographic functions, + + which rely on these numbers, to be exploitable. When generating numbers for sensitive values + + such as tokens, nonces, and cryptographic keys, it is recommended that the `secrets` module + + be used instead. + + + Example using the secrets module: + + ``` + + import secrets + + + # Generate a secure random 64 byte array + + random_bytes = secrets.token_bytes(64) + + print(random_bytes) + + + # Generate a secure random 64 byte array as a hex string + + random_bytes_hex = secrets.token_hex(64) + + + # Generate a secure random 64 byte array base64 encoded for use in URLs + + random_string = secrets.token_urlsafe(64) + + ``` + + + For more information on the `secrets` module see: + + - https://docs.python.org/3/library/secrets.html + + ' + metadata: + cwe: CWE-338 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + category: security + shortDescription: Use of cryptographically weak pseudo-random number generator (PRNG) + security-severity: Low + pattern-either: + - pattern: random.random(...) + - pattern: random.randrange(...) + - pattern: random.randint(...) + - pattern: random.choice(...) + - pattern: random.uniform(...) + - pattern: random.triangular(...) + severity: WARNING + - id: gitlab-python_requests_rule-request-without-timeout + languages: [python] + message: 'The application was found using the `requests` module without configuring a timeout value for + + connections. This could lead to uncontrolled resource consumption where the application could + + run out of + + socket descriptors, effectively causing a Denial of Service (DoS). + + + To remediate this issue, pass in a `timeout=` argument to each `requests` call. + + + Example using a timeout for an HTTP GET request: + + ``` + + # Issue a GET request to https://example.com with a timeout of 10 seconds + + response = requests.get(''https://example.com'', timeout=10) + + # Work with the response object + + # ... + + ``` + + + For more information on using the requests module see: + + - https://requests.readthedocs.io/en/latest/api/ + + ' + patterns: + - pattern-either: + - patterns: + - pattern: requests.$METHOD(..., timeout=$VAL, ...) + - metavariable-comparison: + comparison: $VAL <= 0 + metavariable: $VAL + - patterns: + - pattern: requests.$METHOD(..., timeout=$VAL, ...) + - metavariable-regex: + metavariable: $VAL + regex: (^None) + - patterns: + - pattern-not: requests.$METHOD(..., timeout=$VAL, ...) + - pattern-either: + - pattern: requests.$METHOD(..., ...) + - pattern: requests.$METHOD(...) + - metavariable-regex: + metavariable: $METHOD + regex: (get|put|delete|post|options|head|patch) + metadata: + cwe: CWE-770 + category: security + shortDescription: Allocation of resources without limits or throttling + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + security-severity: Medium + severity: WARNING + - id: gitlab-python_snmp_rule-insecure-snmp-version + languages: [python] + message: "Pysnmp was detected using versions SNMPv1 or SNMPv2. SNPMv1 and SNMPv2 are insecure\nand should\ + \ no longer be used as they do not offer encryption.\n\nIf possible, query SNMP devices using SNMPv3\ + \ instead.\n\nExample querying a device using SNMPv3 with SHA-AES:\n```\nfrom pysnmp.hlapi import *\n\ + # Create the snpm iterator\niterator = getCmd(\n SnmpEngine(),\n # Configure using SHA AES\n \ + \ UsmUserData('usr-sha-aes', 'authkey1', 'privkey1',\n authProtocol=USM_AUTH_HMAC96_SHA,\n\ + \ privProtocol=USM_PRIV_CFB128_AES),\n UdpTransportTarget(('demo.snmplabs.com', 161)),\n\ + \ ContextData(),\n ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))\n)\n```\n\nFor more\ + \ information on using SNMPv3 with `Pysnmp` see:\n- https://pysnmp.readthedocs.io/en/latest/examples/hlapi/v3arch/asyncore/sync/manager/cmdgen/snmp-versions.html#snmpv3-auth-sha-privacy-aes128\n" + metadata: + cwe: CWE-319 + category: security + shortDescription: Cleartext transmission of sensitive information + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + security-severity: Medium + pattern-either: + - pattern: pysnmp.hlapi.CommunityData(..., mpModel=0, ...) + - pattern: pysnmp.hlapi.CommunityData(..., mpModel=1, ...) + severity: WARNING + - id: gitlab-python_snmp_rule-snmp-weak-cryptography + languages: [python] + message: "Pysnmp was detected using SNMPv3 without authentication or encryption\nprotections enabled.\n\ + \n- Use of `usmNoAuthProtocol` or `usmNoPrivProtocol` indicates that\neither authentication or privacy,\ + \ respectively, is not being used. \n- The absence of `authKey` (or `authKey=None`) implies no authentication,\ + \ \nwhich is equivalent to using `usmNoAuthProtocol`. \n- The absence of `privKey` (or `privKey=None`)\ + \ implies no privacy (encryption), \nwhich is equivalent to using `usmNoPrivProtocol`.\n\nTo enhance\ + \ the security of your SNMP communications, it is recommended to use both\nauthentication and privacy\ + \ features in SNMPv3:\n\n- Use SHA for Authentication: SHA (Secure Hash Algorithm) is a more secure\ + \ option \nfor SNMP message authentication. To use SHA, set the `authProtocol` to \n`usmHMACSHAAuthProtocol`\ + \ and provide a strong `authKey`.\n- Use AES for Privacy: AES (Advanced Encryption Standard) is recommended\ + \ for \nencrypting SNMP messages. Set the `privProtocol` to `usmAesCfb128Protocol`\nor a similar AES-based\ + \ protocol and specify a strong `privKey`.\n\nExample of secure `UsmUserData` configuration:\n``` \n\ + \ from pysnmp.hlapi import UsmUserData, usmHMACSHAAuthProtocol, usmAesCfb128Protocol\n \n user_data\ + \ = UsmUserData('username','authKey', 'privKey', \n authProtocol=usmHMACSHAAuthProtocol,\n\ + \ privProtocol=usmAesCfb128Protocol)\n```\n" + metadata: + cwe: CWE-319 + category: security + shortDescription: Cleartext transmission of sensitive information + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + security-severity: Medium + pattern-either: + - pattern-regex: UsmUserData(.*usmNoAuthProtocol.*) + - pattern-regex: UsmUserData(.*usmNoPrivProtocol.*) + - pattern: 'UsmUserData(..., authKey=None, ...) + + ' + - pattern: 'UsmUserData(..., privKey=None, ...) + + ' + - pattern: 'UsmUserData(..., authProtocol=(1,3,6,1,6,3,10,1,1,1), ...) + + ' + - pattern: 'UsmUserData(..., privProtocol=(1,3,6,1,6,3,10,1,2,1), ...) + + ' + - patterns: + - pattern-not: 'UsmUserData($NAME,$AUTHKEY,"...", ...) + + ' + - pattern-not: 'UsmUserData(..., privKey=$PRIVKEY, ...) + + ' + - pattern-not: 'UsmUserData(..., privProtocol=$PRIVPROT, ...) + + ' + - pattern: 'UsmUserData(...) + + ' + severity: WARNING + - id: gitlab-python_sql_rule-hardcoded-sql-expression + languages: [python] + message: 'SQL Injection is a critical vulnerability that can lead to data or system compromise. By + + dynamically generating SQL query strings, user input may be able to influence the logic of + + the SQL statement. This could lead to an adversary accessing information they should + + not have access to, or in some circumstances, being able to execute OS functionality or code. + + + Replace all dynamically generated SQL queries with parameterized queries. In situations where + + dynamic queries must be created, never use direct user input, but instead use a map or + + dictionary of valid values and resolve them using a user supplied key. + + + For example, some database drivers do not allow parameterized queries for `>` or `<` comparison + + operators. In these cases, do not use a user supplied `>` or `<` value, but rather have the + + user + + supply a `gt` or `lt` value. The alphabetical values are then used to look up the `>` and `<` + + values to be used in the construction of the dynamic query. The same goes for other queries + + where + + column or table names are required but cannot be parameterized. + + + Example using `PreparedStatement` queries: + + ``` + + import sqlite3 + + + # Create a new database (in memory) + + con = sqlite3.connect(":memory:") + + # Get a cursor from the connection + + cur = con.cursor() + + # Create a tuple of the value to be used in the parameterized query + + params = (''user-input'',) + + # execute the statement, passing in the params for the value + + cur.execute("select name from sqlite_master where name = ?", params) + + # work with the result + + result = cur.fetchall() + + ``` + + + For more information on SQL Injection see OWASP: + + https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html + + ' + metadata: + cwe: CWE-89 + owasp: + - A1:2017-Injection + - A03:2021-Injection + - A05:2025-Injection + category: security + shortDescription: Improper neutralization of special elements used in an SQL Command ('SQL Injection') + security-severity: High + mode: taint + pattern-sources: + - patterns: + - pattern-either: + - pattern: '"$QUERY" % ... + + ' + - pattern: '"$QUERY".format(...) + + ' + - pattern: 'f"$QUERY{...}..." + + ' + - pattern: '"$QUERY" + ... + + ' + - pattern: '$TMP = "$QUERY" + + ... + + $SQL = $TMP + "..." % ... + + ' + - pattern: "$SQL = \"$QUERY\"\n...\n$SQL += ... \n" + - metavariable-regex: + metavariable: $QUERY + regex: (?i)^(SELECT|INSERT|UPDATE|DELETE)\s + pattern-sinks: + - patterns: + - pattern: $DB.execute(...) + - pattern-not: + pattern-either: + - pattern: $DB.execute("...") + - pattern: $DB.execute("$QUERY" % "...") + - pattern: $DB.execute("$QUERY" + "...") + severity: WARNING + - id: gitlab-python_ssl_rule-req-no-certvalid + languages: [python] + message: 'The application was found using the `requests` module without configuring a timeout value for + + connections. The `verify=False` argument has been set, which effectively disables the + + validation + + of server certificates. + + + This allows for an adversary who is in between the application and the target host to intercept + + potentially sensitive information or transmit malicious data. + + + To remediate this issue either remove the `verify=False` argument, or set `verify=True`to each + + `requests` call. + + + Example verifying server certificates for an HTTP GET request: + + ``` + + # Issue a GET request to https://example.com with a timeout of 10 seconds and verify the + + # server certificate explicitly. + + response = requests.get(''https://example.com'', timeout=10, verify=True) + + # Work with the response object + + # ... + + ``` + + + For more information on using the requests module see: + + - https://requests.readthedocs.io/en/latest/api/ + + ' + metadata: + cwe: CWE-295 + owasp: + - A3:2017-Sensitive Data Exposure + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + category: security + shortDescription: Improper certificate validation + security-severity: Medium + patterns: + - pattern-either: + - pattern: requests.put(..., verify=False, ...) + - pattern: requests.patch(..., verify=False, ...) + - pattern: requests.delete(..., verify=False, ...) + - pattern: requests.head(..., verify=False, ...) + - pattern: requests.options(..., verify=False, ...) + - pattern: requests.request(..., verify=False, ...) + - pattern: requests.get(..., verify=False, ...) + - pattern: requests.post(..., verify=False, ...) + severity: ERROR + - id: gitlab-python_ssl_rule-ssl-no-version + languages: [python] + message: "The application was found calling `ssl.wrap_socket` without a TLS protocol version specified.\n\ + Additionally, `ssl.wrap_socket` has been deprecated since Python 3.7. It is strongly\nrecommended\n\ + that newer applications use TLS 1.2 or 1.3 and `SSLContext.wrap_socket`.\n\nTo remediate this issue,\ + \ create a new TLS context and pass in `ssl.PROTOCOL_TLS_CLIENT`\nfor clients or `ssl.PROTOCOL_TLS_SERVER`\ + \ for servers to the `ssl.SSLContext(...)` `protocol=`\nargument. When converting the socket to a TLS\ + \ socket, use the new `SSLContext.wrap_socket`\nmethod instead.\n\n\nExample creating a TLS 1.3 client\ + \ socket connection by using a newer version of Python\n(3.11.4) and\nthe SSL module:\n```\nimport ssl\n\ + import socket\n\n# Create our initial socket\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ + \ as sock:\n # Connect the socket\n sock.connect(('www.example.org', 443))\n\n # Create a new\ + \ SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT\n # This will auto-select the highest grade\ + \ TLS protocol version (1.3)\n context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)\n #\ + \ Load our a certificates for server certificate authentication\n context.load_verify_locations('cert.pem')\n\ + \ # Create our TLS socket, and validate the server hostname matches\n with context.wrap_socket(sock,\ + \ server_hostname=\"www.example.org\") as tls_sock:\n # Send some bytes over the socket (HTTP\ + \ request in this case)\\\n data = bytes('GET / HTTP/1.1\\r\\nHost: example.org\\r\\n\\r\\n',\ + \ 'utf-8')\n sent_bytes = tls_sock.send(data)\n # Validate number of sent bytes\n \ + \ # ...\n # Read the response\n resp = tls_sock.recv()\n # Work with the response\n\ + \ # ...\n```\n\nFor more information on the ssl module see:\n- https://docs.python.org/3/library/ssl.html\n" + metadata: + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + shortDescription: Inadequate encryption strength + security-severity: Medium + category: security + patterns: + - pattern: ssl.wrap_socket() + severity: WARNING + - id: gitlab-python_ssl_rule-ssl-with-bad-version + languages: [python] + message: "The application was found calling an SSL module with SSL or TLS protocols that have known\n\ + deficiencies.\nIt is strongly recommended that newer applications use TLS 1.2 or 1.3 and\n`SSLContext.wrap_socket`.\n\ + \nIf using the `pyOpenSSL` module, please note that it has been deprecated and the Python\nCryptographic\ + \ Authority\nstrongly suggests moving to use the [pyca/cryptography](https://github.com/pyca/cryptography)\n\ + module instead.\n\nTo remediate this issue for the `ssl` module, create a new TLS context and pass in\n\ + `ssl.PROTOCOL_TLS_CLIENT` for clients or `ssl.PROTOCOL_TLS_SERVER` for servers to the\n`ssl.SSLContext(...)`\ + \ `protocol=`\nargument. When converting the socket to a TLS socket, use the new `SSLContext.wrap_socket`\n\ + method instead.\n\nExample creating a TLS 1.3 client socket connection by using a newer version of Python\n\ + (3.11.4) and\nthe SSL module:\n```\nimport ssl\nimport socket\n\n# Create our initial socket\nwith socket.socket(socket.AF_INET,\ + \ socket.SOCK_STREAM) as sock:\n # Connect the socket\n sock.connect(('www.example.org', 443))\n\ + \n # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT\n # This will auto-select\ + \ the highest grade TLS protocol version (1.3)\n context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)\n\ + \ # Load our a certificates for server certificate authentication\n context.load_verify_locations('cert.pem')\n\ + \ # Create our TLS socket, and validate the server hostname matches\n with context.wrap_socket(sock,\ + \ server_hostname=\"www.example.org\") as tls_sock:\n # Send some bytes over the socket (HTTP\ + \ request in this case)\\\n data = bytes('GET / HTTP/1.1\\r\\nHost: example.org\\r\\n\\r\\n',\ + \ 'utf-8')\n sent_bytes = tls_sock.send(data)\n # Validate number of sent bytes\n \ + \ # ...\n # Read the response\n resp = tls_sock.recv()\n # Work with the response\n\ + \ # ...\n```\n\nFor more information on the ssl module see:\n- https://docs.python.org/3/library/ssl.html\n\ + \nFor more information on pyca/cryptography and openssl see:\n- https://cryptography.io/en/latest/openssl/\n" + metadata: + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + shortDescription: Inadequate Encryption Strength + security-severity: Medium + category: security + patterns: + - pattern-either: + - pattern: ssl.PROTOCOL_SSLv2 + - pattern: ssl.PROTOCOL_SSLv3 + - pattern: ssl.PROTOCOL_TLSv1 + - pattern: ssl.PROTOCOL_TLSv1_1 + - pattern: pyOpenSSL.SSL.SSLv2_METHOD + - pattern: pyOpenSSL.SSL.SSLv23_METHOD + - pattern: pyOpenSSL.SSL.SSLv3_METHOD + - pattern: pyOpenSSL.SSL.TLSv1_METHOD + - pattern: pyOpenSSL.SSL.TLSv1_1_METHOD + severity: ERROR + - id: gitlab-python_ssl_rule-unverified-context + languages: [python] + message: "The application was found creating a SSL context using the `_create_unverified_context`.\nThis\ + \ effectively disables the validation of server certificates.\n\nThis allows for an adversary who is\ + \ in between the application and the target host to intercept\npotentially sensitive information or\ + \ transmit malicious data.\n\nTo remediate this issue remove the call to `_create_unverified_context`\ + \ and either create a\ndefault\ncontext using `ssl.create_default_context` or create a context with\ + \ TLS 1.3.\n\nExample creating a TLS 1.3 client socket connection by using a newer version of Python\n\ + (3.11.4) and\nthe SSL module:\n```\nimport ssl\nimport socket\n\n# Create our initial socket\nwith socket.socket(socket.AF_INET,\ + \ socket.SOCK_STREAM) as sock:\n # Connect the socket\n sock.connect(('www.example.org', 443))\n\ + \n # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT\n # This will auto-select\ + \ the highest grade TLS protocol version (1.3)\n context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)\n\ + \ # Load our a certificates for server certificate authentication\n context.load_verify_locations('cert.pem')\n\ + \ # Create our TLS socket, and validate the server hostname matches\n with context.wrap_socket(sock,\ + \ server_hostname=\"www.example.org\") as tls_sock:\n # Send some bytes over the socket (HTTP\ + \ request in this case)\\\n data = bytes('GET / HTTP/1.1\\r\\nHost: example.org\\r\\n\\r\\n',\ + \ 'utf-8')\n sent_bytes = tls_sock.send(data)\n # Validate number of sent bytes\n \ + \ # ...\n # Read the response\n resp = tls_sock.recv()\n # Work with the response\n\ + \ # ...\n```\n\nUnverified SSL context detected. This will permit insecure connections without\ + \ `verifyingSSL`\ncertificates. Use `ssl.create_default_context()` instead.\n" + metadata: + cwe: CWE-295 + owasp: + - A3:2017-Sensitive Data Exposure + - A07:2021-Identification and Authentication Failures + - A07:2025-Authentication Failures + category: security + shortDescription: Improper certificate validation + security-severity: Medium + pattern: ssl._create_unverified_context(...) + severity: ERROR + - id: gitlab-python_telnet_rule-import-telnib + languages: [python] + message: "The application was found using a telnet library. As telnet does not provide encryption, it\ + \ is\nstrongly recommended that communications use a more secure transport such as\nSSH.\n\nThe [paramiko](https://www.paramiko.org/)\ + \ library can be used to initiate SSH connections.\n\nExample using `paramiko` SSH client:\n```\nimport\ + \ paramiko\nimport scp\n\n# Create an SSH client\nwith paramiko.SSHClient() as ssh:\n # Load the\ + \ system host keys so we can confirm the\n # host we are connecting to is legitimate\n ssh.load_system_host_keys('/home/appuser/.ssh/known_hosts')\n\ + \n # Connect to the remote host using our SSH private key\n ssh.connect(hostname='example.org',\n\ + \ port=22,\n username='appuser',\n key_filename='/home/appuser/.ssh/private_key')\n\ + \ # Work with the connection\n```\n\nFor more information on the paramiko module see:\n- https://www.paramiko.org/\n" + metadata: + cwe: CWE-319 + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + - A04:2025-Cryptographic Failures + shortDescription: Cleartext transmission of sensitive information + security-severity: Medium + patterns: + - pattern: import telnetlib + severity: ERROR + - id: gitlab-python_tmpdir_rule-hardcodedtmp + languages: [python] + message: "The application was found creating files in shared system temporary directories\n(`/tmp` or\ + \ `/var/tmp`) without using the `tempfile.TemporaryFile` function. Depending\non how the application\ + \ uses this temporary file, an attacker may be able to create\nsymlinks that point to other files prior\ + \ to the application creating or writing\nto the target file, leading to unintended files being created\ + \ or overwritten.\n\nExample using `tempfile.TemporaryFile` to write a file:\n```\nimport tempfile\n\ + \n# Open a new temporary file using a context manager\nwith tempfile.TemporaryFile() as fp:\n # Write\ + \ some data to the temporary file\n fp.write(b'Some data')\n # Seek back to beginning of file\n\ + \ fp.seek(0)\n # Read it\n data = fp.read()\n# File is automatically closed/removed once we\ + \ exit the with context\n```\n\nFor more information on alternative tempfile functions see:\n- https://docs.python.org/3/library/tempfile.html\n" + metadata: + cwe: CWE-377 + category: security + shortDescription: Insecure temporary file + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + security-severity: Medium + pattern: $CALL("=~/^\/tmp.*/", ...) + severity: WARNING + - id: gitlab-python_tmpdir_rule-mktemp-q + languages: [python] + message: "The application was found creating temporary files with the insecure `mktemp` method.\nDepending\ + \ on how the application uses this temporary file, an attacker may be able to create\nsymlinks that\ + \ point to other files prior to the application creating or writing\nto the target file, leading to\ + \ unintended files being created or overwritten.\n\nTo remediate this issue consider using `tempfile.TemporaryFile`\ + \ instead.\n\nExample using `tempfile.TemporaryFile` to write a file:\n```\nimport tempfile\n\n# Open\ + \ a new temporary file using a context manager\nwith tempfile.TemporaryFile() as fp:\n # Write some\ + \ data to the temporary file\n fp.write(b'Some data')\n # Seek back to beginning of file\n \ + \ fp.seek(0)\n # Read it\n data = fp.read()\n# File is automatically closed/removed once we exit\ + \ the with context\n```\n\nFor more information on alternative tempfile functions see:\n- https://docs.python.org/3/library/tempfile.html\n" + metadata: + cwe: CWE-377 + category: security + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + - A01:2025-Broken Access Control + shortDescription: Insecure temporary file + security-severity: Medium + pattern: tempfile.mktemp(...) + severity: ERROR + - id: gitlab-python_urlopen_rule-urllib-urlopen + languages: [python] + message: 'The application was found passing in a non-literal value to the `urllib` methods which issue + + requests. `urllib` supports the `file://` scheme, which may allow an adversary who can control + + the URL value to read arbitrary files on the file system. + + + To remediate this issue either hardcode the URLs being used in urllib or use the `requests` + + module instead. + + + Example using the `requests` module to issue an HTTPS request: + + ``` + + import requests + + # Issue a GET request to https://example.com with a timeout of 10 seconds + + response = requests.get(''https://example.com'', timeout=10) + + # Work with the response object + + # ... + + ``` + + ' + patterns: + - pattern-either: + - patterns: + - pattern-either: + - pattern: urllib.$METHOD(...) + - pattern: urllib.request.$METHOD(...) + - pattern-not: urllib.$METHOD("...") + - pattern-not: urllib.request.$METHOD("...") + - pattern-not: urllib.$METHOD("...", ...) + - pattern-not: urllib.request.$METHOD("...", ...) + - metavariable-regex: + metavariable: $METHOD + regex: (urlopen|urlretrieve) + - patterns: + - pattern-either: + - pattern-inside: '$OPENER = urllib.URLopener(...) + + ... + + ' + - pattern-inside: '$OPENER = urllib.request.URLopener(...) + + ... + + ' + - pattern-inside: '$OPENER = urllib.FancyURLopener(...) + + ... + + ' + - pattern-inside: '$OPENER = urllib.request.FancyURLopener(...) + + ... + + ' + - pattern-either: + - pattern: $OPENER.open(...) + - pattern: $OPENER.retrieve(...) + - pattern-not: $OPENER.open("...") + - pattern-not: $OPENER.retrieve("...") + metadata: + cwe: CWE-918 + owasp: + - A1:2017-Injection + - A10:2021-Server-Side Request Forgery + - A01:2025-Broken Access Control + shortDescription: Server-side request forgery (SSRF) + security-severity: Medium + category: security + severity: WARNING + - id: gitlab-python_xml_rule-celement + languages: [python] + message: "The application was found using the `xml.etree` package for processing XML.\nPythons default\ + \ xml processors suffer from various XML parsing vulnerabilities\nand care must be taken when handling\ + \ XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities such as\ + \ eXternal XML Entity\ninjection maybe exploitable.\n\nThe `etree` package suffers from the following\ + \ security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May allow an\ + \ adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary XML.\n*\ + \ Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause the\ + \ Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\ + library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\ + \ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\ + # Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\ + \ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\ + \nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n" + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + pattern-either: + - patterns: + - pattern: xml.etree.cElementTree.fromstring(...) + - pattern-not: xml.etree.cElementTree.fromstring("...") + - pattern: xml.etree.cElementTree.parse(...) + - pattern: xml.etree.cElementTree.iterparse(...) + - pattern: xml.etree.cElementTree.XMLParser(...) + severity: WARNING + - id: gitlab-python_xml_rule-element + languages: [python] + message: "The application was found using the `xml.etree` package for processing XML.\nPythons default\ + \ xml processors suffer from various XML parsing vulnerabilities\nand care must be taken when handling\ + \ XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities such as\ + \ eXternal XML Entity\ninjection maybe exploitable.\n\nThe `etree` package suffers from the following\ + \ security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May allow an\ + \ adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary XML.\n*\ + \ Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause the\ + \ Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\ + library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\ + \ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\ + # Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\ + \ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\ + \nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n" + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + pattern-either: + - patterns: + - pattern: xml.etree.ElementTree.fromstring(...) + - pattern-not: xml.etree.ElementTree.fromstring("...") + - pattern: xml.etree.ElementTree.parse(...) + - pattern: xml.etree.ElementTree.iterparse(...) + - pattern: xml.etree.ElementTree.XMLParser(...) + severity: WARNING + - id: gitlab-python_xml_rule-etree + languages: [python] + message: "The application was found using the `lxml.etree` package for processing XML.\nPython's default\ + \ XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when handling\ + \ XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities such as\ + \ eXternal XML Entity\ninjection maybe exploitable.\n\nThe `etree` package suffers from the following\ + \ security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May allow an\ + \ adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary XML.\n*\ + \ Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause the\ + \ Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\ + library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\ + \ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\ + # Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\ + \ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\ + \nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n" + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + pattern-either: + - pattern: lxml.etree.parse(...) + - patterns: + - pattern: lxml.etree.fromstring(...) + - pattern-not: lxml.etree.fromstring("...") + - pattern: lxml.etree.RestrictedElement(...) + - pattern: lxml.etree.GlobalParserTLS(...) + - pattern: lxml.etree.getDefaultParser(...) + - pattern: lxml.etree.check_docinfo(...) + severity: WARNING + - id: gitlab-python_xml_rule-expatbuilder + languages: [python] + message: "The application was found using the `xml.dom.expatbuilder` which calls the `xml.dom.minidom`\n\ + package for processing XML. Python's default XML processors suffer from various XML parsing\nvulnerabilities\n\ + and care must be taken when handling XML data. Additionally, depending on the\nversion of Python, more\ + \ critical vulnerabilities such as eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.dom.minidom`\ + \ package suffers from the following security risks as of Python 3.7.1:\n* Billion laughs / exponential\ + \ entity expansion - May allow an adversary to cause\n a Denial of Service (DoS) against the application\ + \ parsing arbitrary XML.\n* Quadratic blowup entity expansion - Similar to above, but requires a larger\ + \ input\n to cause the Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\ + library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\ + \ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\ + # Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\ + \ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\ + \nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n" + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + pattern-either: + - patterns: + - pattern: xml.dom.expatbuilder.parse(...) + - pattern-not: xml.dom.expatbuilder.parse("...") + - pattern: xml.dom.expatbuilder.parseString(...) + severity: WARNING + - id: gitlab-python_xml_rule-expatreader + languages: [python] + message: "The application was found using the `xml.sax.expatreader` package for processing XML. Python's\n\ + default XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when\ + \ handling XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities\ + \ such as eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.sax` package suffers from the\ + \ following security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May\ + \ allow an adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary\ + \ XML.\n* Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause\ + \ the Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\ + library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\ + \ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\ + # Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\ + \ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\ + \nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n" + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + pattern-either: + - pattern: xml.dom.expatreader.parse(...) + - patterns: + - pattern: xml.dom.expatreader.parseString(...) + - pattern-not: xml.dom.expatreader.parseString("...") + - pattern: xml.dom.expatreader.parseString(...) + - pattern: xml.dom.expatreader.create_parser(...) + severity: WARNING + - id: gitlab-python_xml_rule-minidom + languages: [python] + message: "The application was found using the `xml.dom.minidom` package for processing XML. Python's\n\ + default XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when\ + \ handling XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities\ + \ such as eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.dom.minidom` package suffers\ + \ from the following security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion\ + \ - May allow an adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary\ + \ XML.\n* Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause\ + \ the Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\ + library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\ + \ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\ + # Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\ + \ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\ + \nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n" + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + pattern-either: + - patterns: + - pattern: xml.dom.minidom.parseString(...) + - pattern-not: xml.dom.minidom.parseString("...") + - pattern: xml.dom.minidom.parse(...) + severity: WARNING + - id: gitlab-python_xml_rule-pulldom + languages: [python] + message: "The application was found using the `xml.dom.pulldom` package for processing XML. Python's\n\ + default XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when\ + \ handling XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities\ + \ such as eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.dom.pulldom` package suffers\ + \ from the following security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion\ + \ - May allow an adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary\ + \ XML.\n* Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause\ + \ the Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\ + library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\ + \ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\ + # Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\ + \ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\ + \nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n" + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + pattern-either: + - patterns: + - pattern: xml.dom.pulldom.parseString(...) + - pattern-not: xml.dom.pulldom.parseString("...") + - pattern: xml.dom.pulldom.parse(...) + severity: WARNING + - id: gitlab-python_xml_rule-sax + languages: [python] + message: "The application was found using the `xml.sax` package for processing XML.\nPython's default\ + \ XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when handling\ + \ XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities such as\ + \ eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.sax` package suffers from the following\ + \ security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May allow an\ + \ adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary XML.\n*\ + \ Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause the\ + \ Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\ + library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\ + \ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\ + # Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\ + \ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\ + \nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n" + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A05:2021-Security Misconfiguration + - A02:2025-Security Misconfiguration + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + pattern-either: + - pattern: xml.sax.parse(...) + - patterns: + - pattern: xml.sax.parseString(...) + - pattern-not: xml.sax.parseString("...") + - pattern: xml.sax.make_parser(...) + severity: WARNING diff --git a/compliance-agent/rules/vendor/gitlab/rules.json b/compliance-agent/rules/vendor/gitlab/rules.json new file mode 100644 index 0000000..1c8cb26 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/rules.json @@ -0,0 +1,1045 @@ +[ + { + "id": "gitlab-csharp_cookies_rule-CookieWithoutHttpOnlyFlag", + "languages": [ + "csharp" + ], + "cwe": "CWE-1004" + }, + { + "id": "gitlab-csharp_cookies_rule-CookieWithoutSSLFlag", + "languages": [ + "csharp" + ], + "cwe": "CWE-614" + }, + { + "id": "gitlab-csharp_crypto_rule-CertificateValidationDisabled", + "languages": [ + "csharp" + ], + "cwe": "CWE-295" + }, + { + "id": "gitlab-csharp_crypto_rule-WeakCipherAlgorithm", + "languages": [ + "csharp" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-csharp_crypto_rule-WeakCipherMode", + "languages": [ + "csharp" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-csharp_crypto_rule-WeakHashingFunction", + "languages": [ + "csharp" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-csharp_crypto_rule-WeakRNG", + "languages": [ + "csharp" + ], + "cwe": "CWE-338" + }, + { + "id": "gitlab-csharp_csrf_rule-Csrf", + "languages": [ + "csharp" + ], + "cwe": "CWE-352" + }, + { + "id": "gitlab-csharp_deserialization_rule-InsecureDeserialization", + "languages": [ + "csharp" + ], + "cwe": "CWE-502" + }, + { + "id": "gitlab-csharp_endpoint_rule-UnvalidatedRedirect", + "languages": [ + "csharp" + ], + "cwe": "CWE-601" + }, + { + "id": "gitlab-csharp_injection_rule-CommandInjection", + "languages": [ + "csharp" + ], + "cwe": "CWE-78" + }, + { + "id": "gitlab-csharp_injection_rule-LdapInjection", + "languages": [ + "csharp" + ], + "cwe": "CWE-90" + }, + { + "id": "gitlab-csharp_injection_rule-SQLInjection", + "languages": [ + "csharp" + ], + "cwe": "CWE-89" + }, + { + "id": "gitlab-csharp_injection_rule-XPathInjection", + "languages": [ + "csharp" + ], + "cwe": "CWE-643" + }, + { + "id": "gitlab-csharp_injection_rule-XmlDocumentXXEInjection", + "languages": [ + "csharp" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-csharp_injection_rule-XmlReaderXXEInjection", + "languages": [ + "csharp" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-csharp_other_rule-UnsafeXSLTSettingUsed", + "languages": [ + "csharp" + ], + "cwe": "CWE-91" + }, + { + "id": "gitlab-csharp_password_rule-PasswordComplexity", + "languages": [ + "csharp" + ], + "cwe": "CWE-521" + }, + { + "id": "gitlab-csharp_path_rule-PathTraversal", + "languages": [ + "csharp" + ], + "cwe": "CWE-22" + }, + { + "id": "gitlab-csharp_validation_rule-InputValidation", + "languages": [ + "csharp" + ], + "cwe": "CWE-554" + }, + { + "id": "gitlab-csharp_xss_rule-HtmlElementXss", + "languages": [ + "csharp" + ], + "cwe": "CWE-79" + }, + { + "id": "gitlab-csharp_xss_rule-ScriptXss", + "languages": [ + "csharp" + ], + "cwe": "CWE-79" + }, + { + "id": "gitlab-go_crypto_rule-tlsversion", + "languages": [ + "go" + ], + "cwe": "CWE-757" + }, + { + "id": "gitlab-java_cookie_rule-CookieInsecure", + "languages": [ + "java" + ], + "cwe": "CWE-614" + }, + { + "id": "gitlab-java_cookie_rule-HttpResponseSplitting", + "languages": [ + "java" + ], + "cwe": "CWE-113" + }, + { + "id": "gitlab-java_cookie_rule-RequestParamToHeader", + "languages": [ + "java" + ], + "cwe": "CWE-113" + }, + { + "id": "gitlab-java_cors_rule-PermissiveCORSInjection", + "languages": [ + "java" + ], + "cwe": "CWE-942" + }, + { + "id": "gitlab-java_crypto_rule-BlowfishKeySize", + "languages": [ + "java" + ], + "cwe": "CWE-326" + }, + { + "id": "gitlab-java_crypto_rule-CipherDESInsecure", + "languages": [ + "java" + ], + "cwe": "CWE-326" + }, + { + "id": "gitlab-java_crypto_rule-CipherDESedeInsecure", + "languages": [ + "java" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-java_crypto_rule-CipherECBMode", + "languages": [ + "java" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-java_crypto_rule-CipherIntegrity", + "languages": [ + "java" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-java_crypto_rule-CipherPaddingOracle", + "languages": [ + "java" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-java_crypto_rule-CustomMessageDigest", + "languages": [ + "java" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-java_crypto_rule-HazelcastSymmetricEncryption", + "languages": [ + "java" + ], + "cwe": "CWE-326" + }, + { + "id": "gitlab-java_crypto_rule-InsufficientKeySizeRsa", + "languages": [ + "java" + ], + "cwe": "CWE-326" + }, + { + "id": "gitlab-java_crypto_rule-NullCipher", + "languages": [ + "java" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-java_crypto_rule-RsaNoPadding", + "languages": [ + "java" + ], + "cwe": "CWE-780" + }, + { + "id": "gitlab-java_crypto_rule-WeakMessageDigest", + "languages": [ + "java" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-java_crypto_rule-WeakTLSProtocol-DefaultHttpClient", + "languages": [ + "java" + ], + "cwe": "CWE-295" + }, + { + "id": "gitlab-java_crypto_rule-WeakTLSProtocol-SSLContext", + "languages": [ + "java" + ], + "cwe": "CWE-326" + }, + { + "id": "gitlab-java_crypto_rule-WeakTLSProtocolVersion", + "languages": [ + "java" + ], + "cwe": "CWE-326" + }, + { + "id": "gitlab-java_endpoint_rule-HostnameVerifier", + "languages": [ + "java" + ], + "cwe": "CWE-295" + }, + { + "id": "gitlab-java_endpoint_rule-UnvalidatedRedirect", + "languages": [ + "java" + ], + "cwe": "CWE-601" + }, + { + "id": "gitlab-java_endpoint_rule-X509TrustManager", + "languages": [ + "java" + ], + "cwe": "CWE-295" + }, + { + "id": "gitlab-java_file_rule-FileUploadFileName", + "languages": [ + "java" + ], + "cwe": "CWE-22" + }, + { + "id": "gitlab-java_file_rule-FilenameUtils", + "languages": [ + "java" + ], + "cwe": "CWE-22" + }, + { + "id": "gitlab-java_inject_rule-CommandInjection", + "languages": [ + "java" + ], + "cwe": "CWE-78" + }, + { + "id": "gitlab-java_inject_rule-ELInjection", + "languages": [ + "java" + ], + "cwe": "CWE-917" + }, + { + "id": "gitlab-java_inject_rule-FileDisclosureRequestDispatcher", + "languages": [ + "java" + ], + "cwe": "CWE-552" + }, + { + "id": "gitlab-java_inject_rule-FileDisclosureSpringFramework", + "languages": [ + "java" + ], + "cwe": "CWE-552" + }, + { + "id": "gitlab-java_inject_rule-HttpParameterPollution", + "languages": [ + "java" + ], + "cwe": "CWE-88" + }, + { + "id": "gitlab-java_inject_rule-LDAPInjection", + "languages": [ + "java" + ], + "cwe": "CWE-90" + }, + { + "id": "gitlab-java_inject_rule-OgnlInjection", + "languages": [ + "java" + ], + "cwe": "CWE-917" + }, + { + "id": "gitlab-java_inject_rule-SpotbugsPathTraversalAbsolute", + "languages": [ + "java" + ], + "cwe": "CWE-22" + }, + { + "id": "gitlab-java_ldap_rule-AnonymousLDAP", + "languages": [ + "java" + ], + "cwe": "CWE-306" + }, + { + "id": "gitlab-java_password_rule-ConstantDBPassword", + "languages": [ + "java" + ], + "cwe": "CWE-259" + }, + { + "id": "gitlab-java_password_rule-EmptyDBPassword", + "languages": [ + "java" + ], + "cwe": "CWE-306" + }, + { + "id": "gitlab-java_password_rule-HardcodePassword", + "languages": [ + "java" + ], + "cwe": "CWE-259" + }, + { + "id": "gitlab-java_perm_rule-DangerousPermissions", + "languages": [ + "java" + ], + "cwe": "CWE-732" + }, + { + "id": "gitlab-java_perm_rule-OverlyPermissiveFilePermissionInline", + "languages": [ + "java" + ], + "cwe": "CWE-732" + }, + { + "id": "gitlab-java_script_rule-ScriptInjection", + "languages": [ + "java" + ], + "cwe": "CWE-94" + }, + { + "id": "gitlab-java_script_rule-SpringSpelExpressionParser", + "languages": [ + "java" + ], + "cwe": "CWE-917" + }, + { + "id": "gitlab-java_smtp_rule-InsecureSmtp", + "languages": [ + "java" + ], + "cwe": "CWE-297" + }, + { + "id": "gitlab-java_smtp_rule-SmtpClient", + "languages": [ + "java" + ], + "cwe": "CWE-77" + }, + { + "id": "gitlab-java_ssrf_rule-SSRF", + "languages": [ + "java" + ], + "cwe": "CWE-918" + }, + { + "id": "gitlab-java_strings_rule-BadHexConversion", + "languages": [ + "java" + ], + "cwe": "CWE-704" + }, + { + "id": "gitlab-java_strings_rule-FormatStringManipulation", + "languages": [ + "java" + ], + "cwe": "CWE-134" + }, + { + "id": "gitlab-java_strings_rule-ModifyAfterValidation", + "languages": [ + "java" + ], + "cwe": "CWE-182" + }, + { + "id": "gitlab-java_strings_rule-NormalizeAfterValidation", + "languages": [ + "java" + ], + "cwe": "CWE-180" + }, + { + "id": "gitlab-java_templateinjection_rule-TemplateInjection", + "languages": [ + "java" + ], + "cwe": "CWE-94" + }, + { + "id": "gitlab-java_unsafe_rule-ExternalConfigControl", + "languages": [ + "java" + ], + "cwe": "CWE-15" + }, + { + "id": "gitlab-java_xml_rule-SAMLIgnoreComments", + "languages": [ + "java" + ], + "cwe": "CWE-1390" + }, + { + "id": "gitlab-java_xml_rule-XmlDecoder", + "languages": [ + "java" + ], + "cwe": "CWE-502" + }, + { + "id": "gitlab-java_xml_rule-XsltTransform", + "languages": [ + "java" + ], + "cwe": "CWE-91" + }, + { + "id": "gitlab-java_xss_rule-WicketXSS", + "languages": [ + "java" + ], + "cwe": "CWE-79" + }, + { + "id": "gitlab-java_xss_rule-XSSReqParamToServletWriter", + "languages": [ + "java" + ], + "cwe": "CWE-79" + }, + { + "id": "gitlab-java_xxe_rule-XMLRdr", + "languages": [ + "java" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-javascript_buf_rule-buffer-noassert-read", + "languages": [ + "javascript" + ], + "cwe": "CWE-125" + }, + { + "id": "gitlab-javascript_buf_rule-buffer-noassert-write", + "languages": [ + "javascript" + ], + "cwe": "CWE-787" + }, + { + "id": "gitlab-javascript_buf_rule-detect-new-buffer", + "languages": [ + "javascript", + "typescript" + ], + "cwe": "CWE-770" + }, + { + "id": "gitlab-javascript_dos_rule-non-literal-regexp", + "languages": [ + "javascript", + "typescript" + ], + "cwe": "CWE-185" + }, + { + "id": "gitlab-javascript_eval_rule-eval-with-expression", + "languages": [ + "javascript", + "typescript" + ], + "cwe": "CWE-95" + }, + { + "id": "gitlab-javascript_pathtraversal_rule-non-literal-fs-filename", + "languages": [ + "typescript", + "javascript" + ], + "cwe": "CWE-22" + }, + { + "id": "gitlab-javascript_random_rule-pseudo-random-bytes", + "languages": [ + "javascript", + "typescript" + ], + "cwe": "CWE-338" + }, + { + "id": "gitlab-javascript_react_rule-dangerouslysetinnerhtml", + "languages": [ + "typescript", + "javascript" + ], + "cwe": "CWE-79" + }, + { + "id": "gitlab-javascript_require_rule-non-literal-require", + "languages": [ + "javascript", + "typescript" + ], + "cwe": "CWE-95" + }, + { + "id": "gitlab-javascript_timing_rule-possible-timing-attacks", + "languages": [ + "javascript" + ], + "cwe": "CWE-208" + }, + { + "id": "gitlab-python_bind-all-interfaces_rule-general-bindall-interfaces", + "languages": [ + "python" + ], + "cwe": "CWE-1327" + }, + { + "id": "gitlab-python_crypto_rule-cipher-modes", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-cipher-blowfish", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-cipher-des", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-cipher-rc2", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-cipher-rc4", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-cipher-xor", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-encrypt-dsa-rsa", + "languages": [ + "python" + ], + "cwe": "CWE-326" + }, + { + "id": "gitlab-python_crypto_rule-crypto-hash-md5", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-hash-sha1", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-hazmat-cipher-arc4", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-hazmat-cipher-blowfish", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-hazmat-cipher-idea", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-hazmat-hash-md5", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-crypto-hazmat-hash-sha1", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-hash-md2", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-hash-md4", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-hash-md5", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-hash-sha1", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-hashlib-new-insecure-functions", + "languages": [ + "python" + ], + "cwe": "CWE-327" + }, + { + "id": "gitlab-python_crypto_rule-import-pycrypto", + "languages": [ + "python" + ], + "cwe": "CWE-1104" + }, + { + "id": "gitlab-python_deserialization_rule-cpickle", + "languages": [ + "python" + ], + "cwe": "CWE-502" + }, + { + "id": "gitlab-python_deserialization_rule-pickle", + "languages": [ + "python" + ], + "cwe": "CWE-502" + }, + { + "id": "gitlab-python_deserialization_rule-shelve", + "languages": [ + "python" + ], + "cwe": "CWE-502" + }, + { + "id": "gitlab-python_deserialization_rule-yaml-load", + "languages": [ + "python" + ], + "cwe": "CWE-502" + }, + { + "id": "gitlab-python_django_rule-django-extra-used", + "languages": [ + "python" + ], + "cwe": "CWE-89" + }, + { + "id": "gitlab-python_escaping_rule-jinja2-autoescape-false", + "languages": [ + "python" + ], + "cwe": "CWE-116" + }, + { + "id": "gitlab-python_escaping_rule-use-of-mako-templates", + "languages": [ + "python" + ], + "cwe": "CWE-79" + }, + { + "id": "gitlab-python_eval_rule-eval", + "languages": [ + "python" + ], + "cwe": "CWE-95" + }, + { + "id": "gitlab-python_exec_rule-exec-used", + "languages": [ + "python" + ], + "cwe": "CWE-95" + }, + { + "id": "gitlab-python_exec_rule-linux-command-wildcard-injection", + "languages": [ + "python" + ], + "cwe": "CWE-155" + }, + { + "id": "gitlab-python_exec_rule-os-path", + "languages": [ + "python" + ], + "cwe": "CWE-78" + }, + { + "id": "gitlab-python_exec_rule-os-popen2", + "languages": [ + "python" + ], + "cwe": "CWE-78" + }, + { + "id": "gitlab-python_exec_rule-subprocess-call", + "languages": [ + "python" + ], + "cwe": "CWE-78" + }, + { + "id": "gitlab-python_exec_rule-subprocess-shell-TRUE", + "languages": [ + "python" + ], + "cwe": "CWE-78" + }, + { + "id": "gitlab-python_file-permissions_rule-general-bad-permission", + "languages": [ + "python" + ], + "cwe": "CWE-732" + }, + { + "id": "gitlab-python_files_rule-tarfile-unsafe-members", + "languages": [ + "python" + ], + "cwe": "CWE-22" + }, + { + "id": "gitlab-python_ftp_rule-ftplib", + "languages": [ + "python" + ], + "cwe": "CWE-319" + }, + { + "id": "gitlab-python_log_rule-logging-config-insecure-listen", + "languages": [ + "python" + ], + "cwe": "CWE-94" + }, + { + "id": "gitlab-python_random_rule-random", + "languages": [ + "python" + ], + "cwe": "CWE-338" + }, + { + "id": "gitlab-python_requests_rule-request-without-timeout", + "languages": [ + "python" + ], + "cwe": "CWE-770" + }, + { + "id": "gitlab-python_snmp_rule-insecure-snmp-version", + "languages": [ + "python" + ], + "cwe": "CWE-319" + }, + { + "id": "gitlab-python_snmp_rule-snmp-weak-cryptography", + "languages": [ + "python" + ], + "cwe": "CWE-319" + }, + { + "id": "gitlab-python_sql_rule-hardcoded-sql-expression", + "languages": [ + "python" + ], + "cwe": "CWE-89" + }, + { + "id": "gitlab-python_ssl_rule-req-no-certvalid", + "languages": [ + "python" + ], + "cwe": "CWE-295" + }, + { + "id": "gitlab-python_ssl_rule-ssl-no-version", + "languages": [ + "python" + ], + "cwe": "CWE-326" + }, + { + "id": "gitlab-python_ssl_rule-ssl-with-bad-version", + "languages": [ + "python" + ], + "cwe": "CWE-326" + }, + { + "id": "gitlab-python_ssl_rule-unverified-context", + "languages": [ + "python" + ], + "cwe": "CWE-295" + }, + { + "id": "gitlab-python_telnet_rule-import-telnib", + "languages": [ + "python" + ], + "cwe": "CWE-319" + }, + { + "id": "gitlab-python_tmpdir_rule-hardcodedtmp", + "languages": [ + "python" + ], + "cwe": "CWE-377" + }, + { + "id": "gitlab-python_tmpdir_rule-mktemp-q", + "languages": [ + "python" + ], + "cwe": "CWE-377" + }, + { + "id": "gitlab-python_urlopen_rule-urllib-urlopen", + "languages": [ + "python" + ], + "cwe": "CWE-918" + }, + { + "id": "gitlab-python_xml_rule-celement", + "languages": [ + "python" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-python_xml_rule-element", + "languages": [ + "python" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-python_xml_rule-etree", + "languages": [ + "python" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-python_xml_rule-expatbuilder", + "languages": [ + "python" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-python_xml_rule-expatreader", + "languages": [ + "python" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-python_xml_rule-minidom", + "languages": [ + "python" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-python_xml_rule-pulldom", + "languages": [ + "python" + ], + "cwe": "CWE-611" + }, + { + "id": "gitlab-python_xml_rule-sax", + "languages": [ + "python" + ], + "cwe": "CWE-611" + } +] diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutHttpOnlyFlag.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutHttpOnlyFlag.cs new file mode 100644 index 0000000..be14460 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutHttpOnlyFlag.cs @@ -0,0 +1,22 @@ +// License: LGPL-3.0 License (c) security-code-scan + +using System.Net; + +class CookieWithoutHttpOnlyFlag +{ + static void BadCookie() + { + var cookie = new Cookie(); + cookie.HttpOnly = true; + var request = (HttpWebRequest)WebRequest.Create(""); + request.CookieContainer.Add(cookie); + } + + static void GoodCookie() + { + var cookie = new Cookie(); + cookie.HttpOnly = false; + var request = (HttpWebRequest)WebRequest.Create(""); + request.CookieContainer.Add(cookie); + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutHttpOnlyFlag.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutHttpOnlyFlag.yml new file mode 100644 index 0000000..dc0f002 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutHttpOnlyFlag.yml @@ -0,0 +1,49 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_cookies_rule-CookieWithoutHttpOnlyFlag" + languages: + - "csharp" + mode: "taint" + pattern-sources: + - pattern: | + var $COOKIE = new HttpCookie(...); + pattern-sinks: + - pattern: "$COOKIE" + pattern-sanitizers: + - pattern: "$COOKIE.HttpOnly = true;" + message: | + The `HttpOnly` attribute when set to `true` protects the cookie value from being accessed by + client side JavaScript such + as reading the `document.cookie` values. By enabling this protection, a website that is + vulnerable to + Cross-Site Scripting (XSS) will be able to block malicious scripts from accessing the cookie + value from JavaScript. + + Example of protecting an HttpCookie: + ``` + // Create an HttpOnly cookie. + HttpCookie someCookie = new HttpCookie("SomeCookieName", "SomeValue"); + someCookie.HttpOnly = true; + ``` + + For more information see: + https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcookie.httponly + + Session cookies should be configured with the following security directives: + + - [HTTPOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + - [Secure](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + - [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) + severity: "WARNING" + metadata: + shortDescription: "Sensitive cookie without 'HttpOnly' flag" + category: "security" + owasp: + - "A5:2017-Broken Access Control" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + cwe: "CWE-1004" + security-severity: "Low" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutSSLFlag.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutSSLFlag.cs new file mode 100644 index 0000000..2dae973 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutSSLFlag.cs @@ -0,0 +1,22 @@ +// License: LGPL-3.0 License (c) security-code-scan + +using System.Net; + +class CookieWithoutSSLFlag +{ + static void BadCookie() + { + var cookie = new Cookie(); + cookie.Secure = false; + var request = (HttpWebRequest)WebRequest.Create(""); + request.CookieContainer.Add(cookie); + } + + static void GoodCookie() + { + var cookie = new Cookie(); + cookie.Secure = true; + var request = (HttpWebRequest)WebRequest.Create(""); + request.CookieContainer.Add(cookie); + } +} \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutSSLFlag.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutSSLFlag.yml new file mode 100644 index 0000000..c49ac51 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/cookies/rule-CookieWithoutSSLFlag.yml @@ -0,0 +1,47 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_cookies_rule-CookieWithoutSSLFlag" + languages: + - "csharp" + mode: "taint" + pattern-sources: + - pattern: | + var $COOKIE = new HttpCookie(...); + pattern-sinks: + - pattern: "$COOKIE" + pattern-sanitizers: + - pattern: "$COOKIE.Secure = true;" + message: | + The `Secure` attribute when set to `true` protects the cookie value from being being + transmitted over clear text + communication paths such as HTTP. By enabling this protection, the cookie will only be sent + over HTTPS. + + Example of protecting an HttpCookie: + ``` + // Create an HttpOnly cookie. + HttpCookie someCookie = new HttpCookie("SomeCookieName", "SomeValue"); + someCookie.Secure = true; + ``` + + For more information see: + https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcookie.secure + + Session cookies should be configured with the following security directives: + + - [HTTPOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + - [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) + - [Secure](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) + severity: "WARNING" + metadata: + shortDescription: "Sensitive cookie in HTTPS session without 'Secure' attribute" + category: "security" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + cwe: "CWE-614" + security-severity: "Low" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-CertificateValidationDisabled.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-CertificateValidationDisabled.cs new file mode 100644 index 0000000..ba41858 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-CertificateValidationDisabled.cs @@ -0,0 +1,22 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Net; + +class CertificateValidationDisabled +{ + static void CustomValidationCallback() + { + ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; + } + + // Meant to simulate a legitimate custom cert validation function (one that's not hardcoded to return + // true). + static void CustomValidationWithImplementation() + { + ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => + { + Random rnd = new Random(); + + return rnd.Next(1) == 1; + }; + } +} \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-CertificateValidationDisabled.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-CertificateValidationDisabled.yml new file mode 100644 index 0000000..0c3852f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-CertificateValidationDisabled.yml @@ -0,0 +1,45 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_crypto_rule-CertificateValidationDisabled" + languages: + - "csharp" + patterns: + - pattern-inside: | + using System.Net; + ... + - pattern: "ServicePointManager.ServerCertificateValidationCallback += $CALLBACK;" + - metavariable-pattern: + metavariable: "$CALLBACK" + patterns: + - pattern-either: + - pattern: "$RETURNTYPE $FUNC(...) { return true; }" + - pattern: "(...) => true;" + message: | + The `ServicePointManager.ServerCertificateValidationCallback` event has been set + to always return `true`, which effectively disables the validation of server + certificates. + + This allows for an adversary who is in between the application and the target host to intercept + potentially sensitive information or transmit malicious data. + + Remove the callback function that is returning true to allow normal certificate validation to + proceed. + When no callback is provided, the client will validate that the certificate name matches the + hostname + that was used when creating the request. + + For more information on the `ServerCertificateValidationCallback` property see: + https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.servercertificatevalidationcallback + severity: "WARNING" + metadata: + shortDescription: "Certificate validation disabled" + category: "security" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A07:2021-Identification and Authentication Failures" + - "A07:2025-Authentication Failures" + cwe: "CWE-295" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherAlgorithm.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherAlgorithm.cs new file mode 100644 index 0000000..e41b76a --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherAlgorithm.cs @@ -0,0 +1,32 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Security.Cryptography; + +class WeakCipherAlgorithm +{ + static void DES() + { + // ruleid: csharp_crypto_rule-WeakCipherAlgorithm + DES provider = System.Security.Cryptography.DES.Create(); + + // ruleid: csharp_crypto_rule-WeakCipherAlgorithm + var provider2 = new DESCryptoServiceProvider(); + } + + static void TripleDES() + { + // ruleid: csharp_crypto_rule-WeakCipherAlgorithm + TripleDES provider = System.Security.Cryptography.TripleDES.Create(); + + // ruleid: csharp_crypto_rule-WeakCipherAlgorithm + var provider2 = new TripleDESCryptoServiceProvider(); + } + + static void RC2() + { + // ruleid: csharp_crypto_rule-WeakCipherAlgorithm + RC2 provider = System.Security.Cryptography.RC2.Create(); + + // ruleid: csharp_crypto_rule-WeakCipherAlgorithm + var provider2 = new RC2CryptoServiceProvider(); + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherAlgorithm.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherAlgorithm.yml new file mode 100644 index 0000000..ec4f6b5 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherAlgorithm.yml @@ -0,0 +1,93 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_crypto_rule-WeakCipherAlgorithm" + patterns: + - pattern-inside: | + using System.Security.Cryptography; + ... + - pattern-either: + - pattern-regex: ".*DES\\.Create\\(\\);" + - pattern: "new DESCryptoServiceProvider();" + - pattern-regex: ".*TripleDES\\.Create\\(\\);" + - pattern: "new TripleDESCryptoServiceProvider();" + - pattern-regex: ".*RC2\\.Create\\(\\);" + - pattern: "new RC2CryptoServiceProvider();" + message: | + DES, TripleDES and RC2 are all considered broken or insecure cryptographic algorithms. + If using .NET Framework greater than version 6.0 consider using `ChaCha20Poly1305` + instead as it is easier and faster than the alternatives such as `AES-256-GCM`. + + For older applications, `AES-256-GCM` is recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Example using `ChaCha20Poly1305`: + ``` + // Generate a random key + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + + // Note nonce values _must_ be regenerated every time they are used. + byte[] nonce = new byte[12]; + RandomNumberGenerator.Fill(nonce); + + byte[] authTag = new byte[16]; + byte[] cipherText; + + using (ChaCha20Poly1305 encryptor = new ChaCha20Poly1305(key)) + { + byte[] plainText = System.Text.Encoding.UTF8.GetBytes("Secret text to encrypt"); + cipherText = new byte[plainText.Length]; + encryptor.Encrypt(nonce, plainText, cipherText, authTag); + } + + using (ChaCha20Poly1305 decryptor = new ChaCha20Poly1305(key)) + { + byte[] output = new byte[cipherText.Length]; + decryptor.Decrypt(nonce, cipherText, authTag, output); + Console.WriteLine("Output: {0}", System.Text.Encoding.UTF8.GetString(output)); + } + ``` + + Example using `AES-256-GCM`: + ``` + // Generate a random key + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + + // Note nonce values _must_ be regenerated every time they are used. + byte[] nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; + RandomNumberGenerator.Fill(nonce); + + byte[] authTag = new byte[AesGcm.TagByteSizes.MaxSize]; + byte[] cipherText; + + using (AesGcm encryptor = new AesGcm(key)) + { + byte[] plainText = Encoding.UTF8.GetBytes("Secret text to encrypt"); + cipherText = new byte[plainText.Length]; + encryptor.Encrypt(nonce, plainText, cipherText, authTag); + } + + using (AesGcm decryptor = new AesGcm(key)) + { + byte[] output = new byte[cipherText.Length]; + decryptor.Decrypt(nonce, cipherText, authTag, output); + Console.WriteLine("Output: {0}", Encoding.UTF8.GetString(output)); + } + ``` + languages: + - "csharp" + severity: "WARNING" + metadata: + shortDescription: "Use of a broken or risky cryptographic algorithm" + category: "security" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + cwe: "CWE-327" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherMode.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherMode.cs new file mode 100644 index 0000000..0932ad1 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherMode.cs @@ -0,0 +1,25 @@ +// License: MIT Copyright (c) 2022-Present GitLab B.V. +using System.Security.Cryptography; + +class WeakCipherMode +{ + public static readonly int BlockBitSize = 128; + public static readonly int KeyBitSize = 256; + + static void WeakCipher() + { + new AesManaged + { + KeySize = KeyBitSize, + BlockSize = BlockBitSize, + // ruleid: csharp_crypto_rule-WeakCipherMode + Mode = CipherMode.OFB, + Padding = PaddingMode.PKCS7 + }; + + var des = DES.Create(); + + // ruleid: csharp_crypto_rule-WeakCipherMode + des.Mode = CipherMode.CTS; + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherMode.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherMode.yml new file mode 100644 index 0000000..a5ce3fe --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakCipherMode.yml @@ -0,0 +1,88 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_crypto_rule-WeakCipherMode" + languages: + - "csharp" + patterns: + - pattern-inside: | + using System.Security.Cryptography; + ... + - metavariable-regex: + metavariable: "$CIPHER" + regex: "^(ECB|CBC|OFB|CFB|CTS)$" + - pattern: "CipherMode.$CIPHER" + message: | + Cryptographic algorithms provide many different modes of operation, only some of which provide + message integrity. Without message integrity it could be possible for an adversary to attempt + to tamper with the ciphertext which could lead to compromising the encryption key. Newer + algorithms + apply message integrity to validate ciphertext has not been tampered with. + + Instead of using an algorithm that requires configuring a `CipherMode`, an algorithm + that has built-in message integrity should be used. If using .NET Framework greater + than version 6.0 consider using `ChaCha20Poly1305` or `AES-256-GCM`. + + For older applications, `AES-256-GCM` is recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are re-used. + + Example using `ChaCha20Poly1305`: + ``` + // Generate a random key + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + + ChaCha20Poly1305 encryptor = new ChaCha20Poly1305(key); + + // Note nonce values _must_ be regenerated every time they are used. + var nonce = new byte[12]; + RandomNumberGenerator.Fill(nonce); + + byte[] plainText = System.Text.Encoding.UTF8.GetBytes("Secret text to encrypt"); + byte[] cipherText = new byte[plainText.Length]; + var authTag = new byte[16]; + + encryptor.Encrypt(nonce, plainText, cipherText, authTag); + byte[] output = new byte[cipherText.Length]; + encryptor.Decrypt(nonce, cipherText, authTag, output); + Console.WriteLine("Output: {0}", System.Text.Encoding.UTF8.GetString(output)); + ``` + + Example using `AES-256-GCM`: + ``` + var plaintextBytes = Encoding.UTF8.GetBytes("Secret text to encrypt"); + var key = new byte[32]; + RandomNumberGenerator.Fill(key); + + using var aes = new AesGcm(key); + var nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; + RandomNumberGenerator.Fill(nonce); + + var cipherText = new byte[plaintextBytes.Length]; + var tag = new byte[AesGcm.TagByteSizes.MaxSize]; + + aes.Encrypt(nonce, plaintextBytes, cipherText, tag); + + // Decrypt + using (var decrypt = new AesGcm(key)) + { + var decryptedBytes = new byte[cipherText.Length]; + + decrypt.Decrypt(nonce, cipherText, tag, decryptedBytes); + + Console.WriteLine("Decrypted: {0}", Encoding.UTF8.GetString(decryptedBytes)); + } + ``` + severity: "WARNING" + metadata: + shortDescription: "Use of a broken or risky cryptographic algorithm" + category: "security" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + cwe: "CWE-327" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakHashingFunction.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakHashingFunction.cs new file mode 100644 index 0000000..d3154ca --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakHashingFunction.cs @@ -0,0 +1,34 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Security.Cryptography; + +class WeakHashingFunction +{ + static void SHA1() + { + var str = new byte[10]; + // ruleid: csharp_crypto_rule-WeakHashingFunction + var hashProvider = new SHA1CryptoServiceProvider(); + hashProvider.ComputeHash(str); + + // ruleid: csharp_crypto_rule-WeakHashingFunction + System.Security.Cryptography.SHA1.Create(); + } + + static void MD5() + { + var str = new byte[10]; + // ruleid: csharp_crypto_rule-WeakHashingFunction + var hashProvider = new MD5CryptoServiceProvider(); + hashProvider.ComputeHash(str); + + // ruleid: csharp_crypto_rule-WeakHashingFunction + System.Security.Cryptography.MD5.Create(); + } + + static void Safe() + { + var str = new byte[10]; + var hashProvider = SHA256Managed.Create(); + var hash = hashProvider.ComputeHash(str); + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakHashingFunction.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakHashingFunction.yml new file mode 100644 index 0000000..5d8e239 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakHashingFunction.yml @@ -0,0 +1,65 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_crypto_rule-WeakHashingFunction" + languages: + - "csharp" + patterns: + - pattern-either: + - patterns: + - metavariable-regex: + metavariable: "$HASH_PROVIDER" + regex: "^(SHA1CryptoServiceProvider|MD5CryptoServiceProvider)$" + - pattern: "new $HASH_PROVIDER" + - patterns: + - metavariable-regex: + metavariable: "$HASH_CLASS" + regex: "^System.Security.Cryptography.(SHA1|MD5)$" + - pattern: "$HASH_CLASS.$METHOD();" + message: | + Both MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. Currently there is no vetted Argon2id implementation for + C# so + it is recommended that PBKDF2 be used until one is available. + + Example using PBKDF2 to generate and compare passwords: + ``` + const int SaltSize = 24; + const int HashSize = 24; + // number of pbkdf2 iterations, Rfc2898DeriveBytes uses hmac-sha1 + // so set a high iteration count + const int Iterations = 1_300_000; + byte[] salt = new byte[SaltSize]; + RandomNumberGenerator.Fill(salt); + + Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes("some password", salt, Iterations); + byte[] hashBytes = pbkdf2.GetBytes(HashSize); + // Store salt and hashedBytes in a data store such as database for authentication + Console.WriteLine("Hash {0}", BitConverter.ToString(hashBytes).Replace("-", "")); + // Do a constant time comparison as to not leak data based on timing + if (CryptographicOperations.FixedTimeEquals(hashBytes, hashBytes)) { + Console.WriteLine("hashes are equal"); + } + ``` + For more information on PBKDF2 see: + https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes + + For more information on secure password storage see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + severity: "WARNING" + metadata: + shortDescription: "Use of a broken or risky cryptographic algorithm (SHA1/MD5)" + category: "security" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + cwe: "CWE-327" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakRNG.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakRNG.cs new file mode 100644 index 0000000..487dfce --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakRNG.cs @@ -0,0 +1,27 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Security.Cryptography; + +class WeakRNG +{ + static string UnsafeRNG() + { + var rnd = new Random(); + byte[] buffer = new byte[16]; + // ruleid: csharp_crypto_rule-WeakRNG + rnd.NextBytes(buffer); + // ruleid: csharp_crypto_rule-WeakRNG + rnd.Next(); + // ruleid: csharp_crypto_rule-WeakRNG + rnd.NextDouble(); + // ...and so forth. + return BitConverter.ToString(buffer); + } + + static string Safe() + { + var rnd = RandomNumberGenerator.Create(); + byte[] buffer = new byte[16]; + rnd.GetBytes(buffer); + return BitConverter.ToString(buffer); + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakRNG.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakRNG.yml new file mode 100644 index 0000000..8d4fff1 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/crypto/rule-WeakRNG.yml @@ -0,0 +1,39 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_crypto_rule-WeakRNG" + languages: + - "csharp" + patterns: + - pattern: "(Random $RNG).$METHOD(...);" + - focus-metavariable: "$RNG" + message: | + Depending on the context, generating weak random numbers may expose cryptographic functions + which rely on these numbers to be exploitable. When generating numbers for sensitive values + such as tokens, nonces, and cryptographic keys, it is recommended that the + `RandomNumberGenerator` class be used. + + Example `RandomNumberGenerator` usage: + ``` + Int32 randInt = RandomNumberGenerator.GetInt32(32000); + byte[] randomBytes = new byte[64]; + RandomNumberGenerator.Fill(randomBytes); + Console.WriteLine("Random Int32: {0}", randInt); + Console.WriteLine("Random Bytes: {0}", BitConverter.ToString(randomBytes).Replace("-", "")); + ``` + + For more information see: + https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator + severity: "WARNING" + metadata: + shortDescription: "Use of cryptographically weak Pseudo-Random Number Generator + (PRNG)" + category: "security" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + cwe: "CWE-338" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/csrf/rule-Csrf.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/csrf/rule-Csrf.cs new file mode 100644 index 0000000..fd047c6 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/csrf/rule-Csrf.cs @@ -0,0 +1,193 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Web.Mvc; + +class Csrf +{ + // ruleid: csharp_csrf_rule-Csrf + [HttpPost] + public ActionResult ControllerMethod1(string input) + { + return null; + } + + // ruleid: csharp_csrf_rule-Csrf + [HttpDelete] + public ActionResult ControllerMethod2(string input) + { + return null; + } + + // ruleid: csharp_csrf_rule-Csrf + [HttpPatch] + public ActionResult ControllerMethod3(string input) + { + return null; + } + + // ruleid: csharp_csrf_rule-Csrf + [HttpPut] + public ActionResult ControllerMethod4(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod5(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpDelete] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod6(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPatch] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod7(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPut] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod8(string input) + { + return null; + } +} + +[AutoValidateAntiforgeryToken] +class CsrfWithAutoValidate +{ + // ok: csharp_csrf_rule-Csrf + [HttpPost] + public ActionResult ControllerMethod1(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpDelete] + public ActionResult ControllerMethod2(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPatch] + public ActionResult ControllerMethod3(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPut] + public ActionResult ControllerMethod4(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod5(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpDelete] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod6(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPatch] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod7(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPut] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod8(string input) + { + return null; + } +} + +[ValidateAntiForgeryToken] +class CsrfWithAutoValidate +{ + // ok: csharp_csrf_rule-Csrf + [HttpPost] + public ActionResult ControllerMethod1(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpDelete] + public ActionResult ControllerMethod2(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPatch] + public ActionResult ControllerMethod3(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPut] + public ActionResult ControllerMethod4(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod5(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpDelete] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod6(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPatch] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod7(string input) + { + return null; + } + + // ok: csharp_csrf_rule-Csrf + [HttpPut] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod8(string input) + { + return null; + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/csrf/rule-Csrf.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/csrf/rule-Csrf.yml new file mode 100644 index 0000000..9175563 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/csrf/rule-Csrf.yml @@ -0,0 +1,73 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_csrf_rule-Csrf" + languages: + - "csharp" + patterns: + - pattern: | + [$HTTPMETHOD] + public $RET $FOO(...) { + ... + } + - pattern-not: | + [ValidateAntiForgeryToken] + public $RET $FOO(...) { + ... + } + - pattern-not-inside: | + [AutoValidateAntiforgeryToken] + class $CLASS{ + ... + } + - pattern-not-inside: | + [ValidateAntiForgeryToken] + class $CLASS{ + ... + } + - metavariable-regex: + metavariable: "$HTTPMETHOD" + regex: "Http(Post|Delete|Patch|Put)" + message: | + The application failed to protect against Cross-Site Request Forgery (CSRF) + due to not including the `[ValidateAntiForgeryToken]` attribute on an + HTTP method handler that could change user state (usually in the form of POST or PUT + methods). + + The vulnerability can be exploited by an adversary creating a link or form on a third + party site and tricking an authenticated victim to access them. + + Add the `[ValidateAntiForgeryToken]` to all methods which take in user data and change + user state (such as updating a database with a new value). This is especially true for + functionality such as updating passwords or other security sensitive functions. + + Alternatively, applications can enable a global + [AutoValidateAntiforgeryTokenAttribute](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.autovalidateantiforgerytokenattribute) + filter. + + For more information on ValidateAntiForgeryToken and other CSRF protections in .NET + see the following URL: + https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery + + Additionally, consider setting all session cookies to have the `SameSite=Strict` attribute. + It should be noted that this may impact usability when sharing links across other mediums. + It is recommended that a two cookie based approach is taken, as outlined in the + [Top level + navigations](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-08#section-8.8.2) + section + of the SameSite RFC. + + For more information on CSRF see OWASP's guide: + https://owasp.org/www-community/attacks/csrf + severity: "WARNING" + metadata: + shortDescription: "Potential Cross-Site Request Forgery (CSRF)" + category: "security" + owasp: + - "A5:2017-Broken Access Control" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + cwe: "CWE-352" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/deserialization/rule-InsecureDeserialization.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/deserialization/rule-InsecureDeserialization.cs new file mode 100644 index 0000000..43812f0 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/deserialization/rule-InsecureDeserialization.cs @@ -0,0 +1,172 @@ +// License: LGPL-3.0 License (c) security-code-scan + +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using RequestDataDemo.Models; +using System.Collections.Generic; +using System.Collections; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; +using System.Runtime.Serialization.Formatters.Soap; +using System.Runtime.Serialization; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web.UI; +using System.Web; +using System.Xml; +using System; + + +class InsecureDeserialization { + private void ConvertData(string json) + { + // ok: csharp_deserialization_rule-InsecureDeserialization + JsonSerializer.Deserialize(json); + } +} + +namespace RequestDataDemo.Controllers +{ + [Serializable] + public class ExampleData + { + public string Username { get; set; } + public int Age { get; set; } + } + + [ApiController] + [Route("api/[controller]")] + public class RequestDataController : ControllerBase + { + private readonly ILogger _logger; + + public RequestDataController(ILogger logger) + { + _logger = logger; + } + + [HttpGet("cookie")] + public ActionResult GetFromCookie([FromQuery] string key) + { + var cookie = Request.Cookies[key]; + + byte[] data = Convert.FromBase64String(cookie.Value); + + MemoryStream memoryStream = new MemoryStream(data); + BinaryFormatter formatter = new BinaryFormatter(); + // ruleid: csharp_deserialization_rule-InsecureDeserialization + ExampleData deserializedData = (ExampleData)formatter.Deserialize(memoryStream); + + return Ok(deserializedData.Username); + } + + [HttpGet("header")] + public ActionResult GetFromHeader([FromHeader] string headerName) + { + var headerVal = Request.Headers[headerName]; + + byte[] data = Convert.FromBase64String(headerVal); + + MemoryStream memoryStream = new MemoryStream(data); + SoapFormatter formatter = new SoapFormatter(); + // ruleid: csharp_deserialization_rule-InsecureDeserialization + ExampleData deserializedData = (ExampleData)formatter.Deserialize(memoryStream); + + return Ok(deserializedData.Username); + } + + [HttpPost("form")] + public ActionResult GetFromForm([FromForm] string key) + { + var formVal = Request.Form[key]; + + byte[] data = Convert.FromBase64String(formVal); + + MemoryStream memoryStream = new MemoryStream(data); + NetDataContractSerializer formatter = new NetDataContractSerializer(); + // ruleid: csharp_deserialization_rule-InsecureDeserialization + ExampleData deserializedData = (ExampleData)formatter.Deserialize(memoryStream); + + return Ok(deserializedData.Username); + } + + [HttpGet("query")] + public ActionResult GetFromQuery([FromQuery] string param) + { + var queryVal = Request.QueryString[param]; + + byte[] data = Convert.FromBase64String(queryVal); + + MemoryStream memoryStream = new MemoryStream(data); + LosFormatter formatter = new LosFormatter(); + // ruleid: csharp_deserialization_rule-InsecureDeserialization + ExampleData deserializedData = (ExampleData)formatter.Deserialize(memoryStream); + + return Ok(deserializedData.Username); + } + } + + public static string FromHttpContext(string key) + { + HttpContext context = new DefaultHttpContext(); + string cookieValue = context.Request.Cookies[key]; + byte[] data = Convert.FromBase64String(cookieValue); + + MemoryStream memoryStream = new MemoryStream(data); + BinaryFormatter formatter = new BinaryFormatter(); + // ruleid: csharp_deserialization_rule-InsecureDeserialization + ExampleData deserializedData = (ExampleData)formatter.Deserialize(memoryStream); + + return Ok(deserializedData.Username); + } + + public static string FromEnvVar(string name) + { + string val = Environment.GetEnvironmentVariable(name); + + byte[] data = Convert.FromBase64String(val); + MemoryStream memoryStream = new MemoryStream(data); + BinaryFormatter formatter = new BinaryFormatter(); + + // ruleid: csharp_deserialization_rule-InsecureDeserialization + ExampleData deserializedData = (ExampleData)formatter.Deserialize(memoryStream); + + return Ok(deserializedData.Username); + } + + public static ExampleData ReadAndDeserializeFile(string filePath) + { + // Check if the file exists + if (File.Exists(filePath)) + { + string content = File.ReadAllText(filePath); + byte[] data = Encoding.UTF8.GetBytes(content); + + using (Stream stream = new MemoryStream(data)) + { + BinaryFormatter formatter = new BinaryFormatter(); + // ruleid: csharp_deserialization_rule-InsecureDeserialization + return (ExampleData)formatter.Deserialize(data).Username; + } + } + + return null; + } + + public static string SafeExample(string fileName) + { + FileStream fs = new FileStream(fileName, FileMode.Open); + XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); + DataContractSerializer serializer = new DataContractSerializer(typeof(ExampleData)); + + // ok: csharp_deserialization_rule-InsecureDeserialization + ExampleData deserializedData = (ExampleData)serializer.ReadObject(reader, true); + + reader.Close(); + fs.Close(); + + return deserializedData.Username; + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/deserialization/rule-InsecureDeserialization.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/deserialization/rule-InsecureDeserialization.yml new file mode 100644 index 0000000..9a82c60 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/deserialization/rule-InsecureDeserialization.yml @@ -0,0 +1,87 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_deserialization_rule-InsecureDeserialization" + mode: "taint" + pattern-sources: + - pattern: "Request.Cookies[...]" + - pattern: "Request.Cookies.Get(...)" + - pattern: "Request.Form[...]" + - pattern: "Request.Form.Get(...)" + - pattern: "Request.Headers[...]" + - pattern: "Request.Headers.Get(...)" + - pattern: "Request.QueryString[...]" + - pattern: "Request.QueryString.Get(...)" + - pattern: "Request.Body" + - pattern: "$CTX.Request.Cookies[...]" + - pattern: "$CTX.Request.Cookies.Get(...)" + - pattern: "$CTX.Request.Form[...]" + - pattern: "$CTX.Request.Form.Get(...)" + - pattern: "$CTX.Request.Headers[...]" + - pattern: "$CTX.Request.Headers.Get(...)" + - pattern: "$CTX.Request.QueryString[...]" + - pattern: "$CTX.Request.QueryString.Get(...)" + - pattern: "$CTX.Request.Body" + - pattern: "System.IO.File.ReadAllText(...)" + - pattern: "System.IO.File.ReadAllTextAsync(...)" + - pattern: "System.IO.File.ReadAllLines(...)" + - pattern: "System.IO.File.ReadAllLinesAsync(...)" + - pattern: "System.IO.File.ReadAllBytes(...)" + - pattern: "System.IO.File.ReadAllBytesAsync(...)" + - pattern: "System.IO.File.ReadLines(...)" + - pattern: "System.IO.File.ReadLinesAsync(...)" + - pattern: "System.Environment.GetEnvironmentVariable(...)" + pattern-sinks: + - pattern: "(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $OBJ).Deserialize(...)" + - pattern: "(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $OBJ).UnsafeDeserialize(...)" + - pattern: "(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $OBJ).UnsafeDeserializeMethod(...)" + - pattern: "(System.Runtime.Serialization.Formatters.Soap.SoapFormatter $OBJ).Deserialize(...)" + - pattern: "(System.Runtime.Serialization.NetDataContractSerializer $OBJ).Deserialize(...)" + - pattern: "(System.Web.UI.LosFormatter $OBJ).Deserialize(...)" + languages: + - "csharp" + message: | + Deserialization attacks exploit the process of reading serialized data and turning it back into an + object. By constructing malicious objects and serializing them, an adversary may attempt to: + + - Inject code that is executed upon object construction, which occurs during the deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized data but are + read in during deserialization. + + Microsoft recommends no longer using the following serialization formats: + + - BinaryFormatter + - SoapFormatter + - NetDataContractSerializer + - LosFormatter + - ObjectStateFormatter + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format chosen allows + the application to specify exactly which object types are allowed to be deserialized. Additionally, when + deserializing, never deserialize to base object types like `Object` and only cast to the exact object + type that is expected. + + To protect against mass assignment, only allow deserialization of the specific fields that are required. + If this is not easily done, consider creating an intermediary type that can be serialized with only the + necessary fields exposed. + + For more information see Microsoft's deserialization security guide: + https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide + + For more details on deserialization attacks in general, see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + + It should be noted that [tools exist](https://github.com/pwntester/ysoserial.net) to automatically create + exploit code for these vulnerabilities. + metadata: + shortDescription: "Deserialization of potentially untrusted data" + category: "security" + cwe: "CWE-502" + owasp: + - "A8:2017-Insecure Deserialization" + - "A08:2021-Software and Data Integrity Failures" + - "A08:2025-Software or Data Integrity Failures" + security-severity: "High" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/endpoint/rule-UnvalidatedRedirect.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/endpoint/rule-UnvalidatedRedirect.cs new file mode 100644 index 0000000..926cd3e --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/endpoint/rule-UnvalidatedRedirect.cs @@ -0,0 +1,81 @@ +// License: LGPL-3.0 License (c) security-code-scan +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Specialized; + + +namespace dotNetMVC.Controllers.Endpoint +{ + // ref: csharp_endpoint_rule-UnvalidatedRedirect + public class UnvalidatedRedirectController : Controller + { + + // GET: UnvalidatedRedirectController + public ActionResult Index() + { + return View("Views/Endpoint/UnvalidatedRedirect/index.cshtml"); + } + + [HttpGet] + public IActionResult LogOn(string returnUrl) + { + if (!String.IsNullOrEmpty(returnUrl)) + { + // ruleid: csharp_endpoint_rule-UnvalidatedRedirect + return Redirect(returnUrl); + } + // ruleid: csharp_endpoint_rule-UnvalidatedRedirect + return new RedirectResult(returnUrl); + } + + [HttpGet] + public IActionResult LogOn2(string returnUrl) + { + if (Url.IsLocalUrl(returnUrl)) + { + // ok: csharp_endpoint_rule-UnvalidatedRedirect + return RedirectPermanent(returnUrl); + } + // ruleid: csharp_endpoint_rule-UnvalidatedRedirect + return RedirectPermanent(returnUrl); + } + + [HttpGet] + public IActionResult LogOnTryCreate(string returnUrl) + { + if (Uri.TryCreate(returnUrl, UriKind.Relative, out var result)) + { + // ruleid: csharp_endpoint_rule-UnvalidatedRedirect + return Redirect(result.ToString()); + } + // ruleid: csharp_endpoint_rule-UnvalidatedRedirect + return Redirect(returnUrl); + } + + [HttpGet] + // sample end point: https://localhost:7084/UnvalidatedRedirect/logonAction?at=TestPoint + public IActionResult LogOnAction(string at) + { + string url = Url.Action(at, "Home"); + // ok: csharp_endpoint_rule-UnvalidatedRedirect + return Redirect(url); + } + + [HttpGet] + // sample end point: https://localhost:7084/UnvalidatedRedirect/LogOnRouteUrl?at=TESTPoint + public IActionResult LogOnRouteUrl(string at) + { + string url = Url.RouteUrl(at); + // ok: csharp_endpoint_rule-UnvalidatedRedirect + return Redirect(url); + } + + // GET https://localhost:44355/UnvalidatedRedirect/Get?path=testPoint + public ActionResult Get(string path) + { + string url = Url.HttpRouteUrl(path, null); + // ok: csharp_endpoint_rule-UnvalidatedRedirect + return Redirect(url); + } + } +} \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/endpoint/rule-UnvalidatedRedirect.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/endpoint/rule-UnvalidatedRedirect.yml new file mode 100644 index 0000000..3f27b73 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/endpoint/rule-UnvalidatedRedirect.yml @@ -0,0 +1,89 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_endpoint_rule-UnvalidatedRedirect" + languages: + - "csharp" + mode: "taint" + pattern-sources: + - patterns: + - pattern: "$SRC" + - pattern-inside: | + public $RET $FUNC(...,$SRC,...){...} + - patterns: + - pattern: "$SRC" + - pattern-inside: | + if (Uri.TryCreate(..., ..., $SRC)){ + ... + } + pattern-sanitizers: + - pattern: "Url.Action(...)" + - pattern: "Url.HttpRouteUrl(...)" + - pattern: "Url.RouteUrl(...)" + pattern-sinks: + - patterns: + - pattern-either: + - patterns: + - pattern-either: + - pattern: "return $METHOD(...)" + - pattern: "return new $METHOD(...)" + - pattern: | + if (!Url.IsLocalUrl(...)) { + ... + return $METHOD(...) + } + - patterns: + - pattern-not-inside: | + if (Url.IsLocalUrl(...)) { + ... + } + - pattern-not-inside: | + if (!Url.IsLocalUrl(...)) { + return $X + } + ... + - pattern-either: + - pattern: "$METHOD(...)" + - pattern: "new $METHOD(...)" + - metavariable-pattern: + metavariable: "$METHOD" + pattern-either: + - pattern: "Redirect" + - pattern: "RedirectPermanent" + - pattern: "RedirectToRoute" + - pattern: "RedirectToRoutePermanent" + - pattern: "RedirectResult" + message: | + The application may allow open redirects if created using user supplied input. Open redirects + are + commonly + abused in phishing attacks where the original domain or URL looks like a legitimate link, but + then + redirects a user to a malicious site. An example would be + `https://example.com/redirect?url=https://%62%61%64%2e%63%6f%6d%2f%66%61%6b%65%6c%6f%67%69%6e` + which, + when decoded, turns into `bad.com/fakelogin`. + + Never redirect a client based on user input. It is recommended that the list of target links + to + redirect a user to are contained server side, and retrieved using a numerical value + as an index to return the link to be redirected to. For example, `/redirect?id=1` would cause + the + application to look up the `1` index and return a URL such as `https://example.com`. This URL + would + then be used to redirect the user, using the 301 response code and `Location` header. + + For more information on open redirects see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html + metadata: + shortDescription: "URL redirection to untrusted site 'open redirect'" + category: "security" + owasp: + - "A1:2017-Injection" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + cwe: "CWE-601" + security-severity: "Info" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-CommandInjection.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-CommandInjection.cs new file mode 100644 index 0000000..0b21762 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-CommandInjection.cs @@ -0,0 +1,155 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Diagnostics; + +class CommandInjection +{ + static void ProcessWithStartInfoDirectUs1() + { + var p = new Process(); + // ok: csharp_injection_rule-CommandInjection + p.StartInfo.FileName = "exportLegacy.exe"; + // ruleid: csharp_injection_rule-CommandInjection + p.StartInfo.Arguments = " -user " + Console.ReadLine() + " -role user"; + p.Start(); + } + + static void ProcessWithStartInfoDirectUs2() + { + var p = new Process(); + // @"C:\Program Files\Internet Explorer\iexplore.exe" + // ruleid: csharp_injection_rule-CommandInjection + p.StartInfo.FileName = Console.ReadLine(); + // ok: csharp_injection_rule-CommandInjection + p.StartInfo.Arguments = "www.example.com"; + p.Start(); + } + + static void ProcessWithStartInfoDirectUs3() + { + // @"C:\Program Files\Internet Explorer\iexplore.exe" + string arguments = Console.ReadLine(); + var p = new Process(); + // ok: csharp_injection_rule-CommandInjection + p.StartInfo.FileName = @"C:\Program Files\Internet Explorer\iexplore.exe"; + // ruleid: csharp_injection_rule-CommandInjection + p.StartInfo.Arguments = arguments; + p.Start(); + } + + static void ProcessWithStartInfoDirectS1() + { + var p = new Process(); + // @"C:\Program Files\Internet Explorer\iexplore.exe" + // ok: csharp_injection_rule-CommandInjection + p.StartInfo.FileName = @"C:\Program Files\Internet Explorer\iexplore.exe"; + // ok: csharp_injection_rule-CommandInjection + p.StartInfo.Arguments = "www.example.com"; + p.Start(); + } + + static void ProcessWithStartInfoDirectS2() + { + var p = new Process(); + String arguments = "www.example.com"; + String fileName = @"C:\Program Files\Internet Explorer\iexplore.exe"; + // @"C:\Program Files\Internet Explorer\iexplore.exe" + // ok: csharp_injection_rule-CommandInjection + p.StartInfo.FileName = fileName; + // ok: csharp_injection_rule-CommandInjection + p.StartInfo.Arguments = arguments; + p.Start(); + } + + static void ProcessWithStartInfoObject() + { + // ruleid: csharp_injection_rule-CommandInjection + ProcessStartInfo info = new ProcessStartInfo(Console.ReadLine()); + // ruleid: csharp_injection_rule-CommandInjection + info.Arguments = Console.ReadLine(); + // ruleid: csharp_injection_rule-CommandInjection + Process.Start(info); + } + + static void ProcessDirectUs() + { + // ruleid: csharp_injection_rule-CommandInjection + Process.Start(Console.ReadLine()); + } + + static void ProcessDirectS() + { + // ok: csharp_injection_rule-CommandInjection + Process.Start("notepad.exe"); + } + + static void Safe() + { + var program = "notepad.exe"; + // ok: csharp_injection_rule-CommandInjection + Process.Start(program); + } + + static void ProcessWithStartInfoDirectUsingSafe() + { + String arguments = "www.example.com"; + String fileName = @"C:\Program Files\Internet Explorer\iexplore.exe"; + using (var p = new Process()) + { + // @"C:\Program Files\Internet Explorer\iexplore.exe" + // ok: csharp_injection_rule-CommandInjection + p.StartInfo.FileName = fileName; + // ok: csharp_injection_rule-CommandInjection + p.StartInfo.Arguments = arguments; + p.Start(); + } + } + + static void ProcessWithStartInfoDirectUsing() + { + using (var p = new Process()) + { + // @"C:\Program Files\Internet Explorer\iexplore.exe" + // ruleid: csharp_injection_rule-CommandInjection + p.StartInfo.FileName = fileName; + // ruleid: csharp_injection_rule-CommandInjection + p.StartInfo.Arguments = arguments; + p.Start(); + } + } + + static void ProcessWithStartInfoDirectUsingUnSafe2() + { + using (Process myProcess = new Process()) + { + ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(); + + // ruleid: csharp_injection_rule-CommandInjection + myProcessStartInfo.Arguments = Console.ReadLine(); + myProcessStartInfo.UseShellExecute = false; + + myProcessStartInfo.RedirectStandardError = true; + myProcessStartInfo.RedirectStandardOutput = true; + myProcess.StartInfo = myProcessStartInfo; + myProcess.Start(); + } + } + + private static void processInsideBlock(string arg) + { + var process = new Process + { + StartInfo = new ProcessStartInfo + { + // ok: csharp_injection_rule-CommandInjection + FileName = @"C:\Program Files\Internet Explorer\iexplore.exe", + // ruleid: csharp_injection_rule-CommandInjection + Arguments = $"{arg}", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; + + process.Start(); + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-CommandInjection.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-CommandInjection.yml new file mode 100644 index 0000000..0816250 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-CommandInjection.yml @@ -0,0 +1,105 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_injection_rule-CommandInjection" + languages: + - "csharp" + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + ... + (System.Diagnostics.Process $PROC).Start(...); + - pattern-either: + - patterns: + - pattern: "(System.Diagnostics.Process $PROC).StartInfo.FileName = <...$ARG...>;" + - pattern-not: "(System.Diagnostics.Process $PROC).StartInfo.FileName = + \"...\";" + - patterns: + - pattern: "(System.Diagnostics.Process $PROC).StartInfo.Arguments = <...$ARG...>;" + - pattern-not: "(System.Diagnostics.Process $PROC).StartInfo.Arguments = + \"...\";" + - patterns: + - pattern: "System.Diagnostics.Process.Start($ARG);" + - pattern-not: "System.Diagnostics.Process.Start(\"...\");" + - patterns: + - pattern-not: "$PSINFO.Arguments = \"...\";" + - pattern-not: "$PSINFO.FileName = \"...\";" + - pattern-not: "new System.Diagnostics.ProcessStartInfo(\"...\");" + - pattern-not: "new System.Diagnostics.ProcessStartInfo();" + - pattern-either: + - pattern: "new System.Diagnostics.ProcessStartInfo(...);" + - pattern: "$PSINFO.Arguments = <...$ARG...>;" + - pattern: "$PSINFO.FileName = <...$ARG...>;" + - patterns: + - pattern-inside: | + new System.Diagnostics.ProcessStartInfo{ + ... + } + - pattern-not: "Arguments = \"...\"" + - pattern-not: "FileName = \"...\"" + - pattern-either: + - pattern: "Arguments = ..." + - pattern: "FileName = ..." + message: | + OS command injection is a critical vulnerability that can lead to a full system + compromise as it may allow an adversary to pass in arbitrary commands or arguments + to be executed. + + User input should never be used in constructing commands or command arguments + to functions which execute OS commands. This includes filenames supplied by + user uploads or downloads. + + Ensure your application does not: + + - Use user-supplied information in the process name to execute. + - Use user-supplied information in an OS command execution function which does + not escape shell meta-characters. + - Use user-supplied information in arguments to OS commands. + + The application should have a hardcoded set of arguments that are to be passed + to OS commands. If filenames are being passed to these functions, it is + recommended that a hash of the filename be used instead, or some other unique + identifier. It is strongly recommended that a native library that implements + the same functionality be used instead of using OS system commands, due to the + risk of unknown attacks against third party commands. + + When specifying the OS command, ensure the application uses the full path + information, otherwise the OS may attempt to look up which process to execute + and could be vulnerable to untrusted search path vulnerabilities (CWE-426). + + Example of safely executing an OS command: + ``` + public void ExecuteCommand(string userFileData) { + // generate a random filename, do not using user input + string fileName = "C:\\Temp\\" + Guid.NewGuid(); + File.WriteAllText(fileName, userFileData); + + using (Process process = new Process()) + { + // hardcode the full process path + ProcessStartInfo processInfo = new ProcessStartInfo("C:\\App\\FileReader.exe"); + // only pass in trust arguments, and never direct user input. + processInfo.Arguments = fileName; + processInfo.UseShellExecute = false; + process.StartInfo = processInfo; + process.Start(); + } + } + ``` + + For more information on OS command injection, see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html + severity: "ERROR" + metadata: + shortDescription: "Improper neutralization of special elements used in an OS command + ('OS Command Injection')" + category: "security" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + cwe: "CWE-78" + security-severity: "High" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-LdapInjection.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-LdapInjection.cs new file mode 100644 index 0000000..eee0a2e --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-LdapInjection.cs @@ -0,0 +1,169 @@ +// License: LGPL-3.0 License (c) security-code-scan + +using System.DirectoryServices; +using System.DirectoryServices.AccountManagement; +using System.DirectoryServices.Protocols; +using System.Net; + +// ref: csharp_injection_rule-LdapInjection +namespace consoleApp.cSharp.Injection +{ + internal class LdapInjection : IScenarioRunner + { + string ldapserver = "127.0.0.1:3889"; + string ldapbasedn = "dc=example,dc=org"; + string ldapuser = "cn=admin,dc=example,dc=org"; + string ldappassword = "adminpassword"; + + public void SentReqTest(string classname) + { + try + { + using var ldapConnection = new LdapConnection(new LdapDirectoryIdentifier("127.0.0.1", 3889), new NetworkCredential("cn=admin,dc=example,dc=org", "adminpassword"), AuthType.Basic); + ldapConnection.SessionOptions.ProtocolVersion = 3; + ldapConnection.Bind(); + + string baseDn = "dc=example,dc=org"; + string filter = $"(objectClass={classname})"; + + // ruleid: csharp_injection_rule-LdapInjection + SearchRequest searchReq = new SearchRequest( + baseDn, + filter, + System.DirectoryServices.Protocols.SearchScope.Subtree, + null + ); + + SearchResponse searchRes = (SearchResponse)ldapConnection.SendRequest(searchReq); + + foreach (SearchResultEntry en in searchRes.Entries) + { + foreach (DirectoryAttribute att in en.Attributes.Values) + { + Console.WriteLine($"{att.Name}: {att[0]}"); + } + + Console.WriteLine("******"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + + Console.WriteLine("\n***End SentReqTest***\n"); + } + + public void UseDirectorySearcherFilterTest(string classname) + { + string ldapfilter = $"(objectClass={classname})"; + + try + { + string DN = ""; + using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapserver + "/" + ldapbasedn, ldapuser, ldappassword, AuthenticationTypes.None)) + { + entry.Path = "LDAP://" + ldapserver + "/" + ldapbasedn; + + DirectorySearcher ds = new DirectorySearcher(entry); + ds.SearchScope = System.DirectoryServices.SearchScope.Subtree; + + // ok: csharp_injection_rule-LdapInjection + ds.Filter = "(objectClass=*)"; + // ruleid: csharp_injection_rule-LdapInjection + ds.Filter = $"(objectClass={classname})"; + + SearchResult result = ds.FindOne(); + + if (result != null) + { + foreach (string propertyName in result.Properties.PropertyNames) + { + Console.WriteLine($"{propertyName}: {result.Properties[propertyName][0]}"); + } + } + } + } + catch (Exception ex) { + Console.WriteLine(ex.Message); + } + + Console.WriteLine("\n*** End UseDirectorySearcherPathTest ***\n"); + } + + public void UseDirectorySearcherPathTest(string pathPara) + { + string ldapfilter = "(objectClass=*)"; + + try + { + using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapserver + "/" + ldapbasedn, ldapuser, ldappassword, AuthenticationTypes.None)) + { + // ruleid: csharp_injection_rule-LdapInjection + entry.Path = "LDAP://" + ldapserver + "/" + pathPara; + + // ruleid: csharp_injection_rule-LdapInjection + DirectorySearcher ds = new DirectorySearcher(entry); + ds.SearchScope = System.DirectoryServices.SearchScope.Subtree; + + // ok: csharp_injection_rule-LdapInjection + ds.Filter = string.Format(ldapfilter); + + SearchResult result = ds.FindOne(); + + if (result != null) + { + foreach (string propertyName in result.Properties.PropertyNames) + { + Console.WriteLine($"{propertyName}: {result.Properties[propertyName][0]}"); + } + } + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + + Console.WriteLine("\n***End UseDirectorySearcherPathTest***\n"); + } + + public void UserPrincipleTest(string samAccountName) + { + try + { + PrincipalContext context = new PrincipalContext(ContextType.Machine); + UserPrincipal userPrincipal = new UserPrincipal(context); + + // ruleid: csharp_injection_rule-LdapInjection + userPrincipal.SamAccountName = samAccountName; + + // ruleid: csharp_injection_rule-LdapInjection + UserPrincipal.FindByIdentity(context, samAccountName); + + using (PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal)) + { + PrincipalSearchResult foundUser = searcher.FindAll() as PrincipalSearchResult; + + if (foundUser != null) + { + foreach (var item in foundUser.AsQueryable().ToArray()) + { + Console.WriteLine(item.SamAccountName.ToString()); + }; + } + else + { + Console.WriteLine("User not found."); + } + } + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + + Console.WriteLine("\n***End UserPrincipleTest***\n"); + } + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-LdapInjection.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-LdapInjection.yml new file mode 100644 index 0000000..86f2953 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-LdapInjection.yml @@ -0,0 +1,105 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_injection_rule-LdapInjection" + languages: + - "csharp" + mode: taint + pattern-sources: + - patterns: + - pattern-inside: | + $RET $METHOD(...,$VAR,...){...} + - pattern: "$VAR" + pattern-sinks: + - pattern: "System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(...)" + - pattern: "new System.DirectoryServices.DirectoryEntry(...)" + - pattern: "new System.DirectoryServices.DirectorySearcher(...)" + - pattern: "new System.DirectoryServices.Protocols.SearchRequest(...)" + - patterns: + - focus-metavariable: $TAINTED + - pattern-either: + - pattern: "(System.DirectoryServices.DirectoryEntry $SOURCE).Path = $TAINTED" + - pattern: "(System.DirectoryServices.DirectorySearcher $SEARCHER).Filter = $TAINTED" + - pattern: "(System.DirectoryServices.Protocols.SearchRequest $SEARCHREQ).Filter = $TAINTED" + - pattern: "(System.DirectoryServices.Protocols.SearchRequest $SEARCHREQ).DistinguishedName = $TAINTED" + - pattern: "(System.DirectoryServices.AccountManagement.UserPrincipal $SEARCHREQ).$PROP = $TAINTED" + message: | + LDAP injection attacks exploit LDAP queries to influence how data is returned by + the LDAP, or in this case an Active Directory server. + + It is recommended that newer applications use the `System.DirectoryServices.AccountManagement` + API instead of `DirectorySearcher` API as it hides the complexity of querying LDAP directly. + However, + the `AccountManagement` API is still susceptible to LDAP injection if a user inputs LDAP + queries, + including LDAP filter characters such as `*`. + + It is recommended that all input passed to LDAP querying systems encode the following values: + + - Any occurrence of the null character must be escaped as “\00”. + - Any occurrence of the open parenthesis character must be escaped as “\28”. + - Any occurrence of the close parenthesis character must be escaped as “\29”. + - Any occurrence of the asterisk character must be escaped as “\2a”. + - Any occurrence of the backslash character must be escaped as “\5c”. + + Example code that safely encodes input for use in an LDAP query using the `AccountManagement` + API: + ``` + using System.DirectoryServices.AccountManagement; + + string EncodeLDAPString(string input) { + // Note the \ character is replaced first + char[] chars = new char[] { '\\', '\0', '(', ')', '*' }; + string[] encoded = new string[] { "\\5c", "\\00", "\\28", "\\29", "\\2a" }; + + for (int i = 0; i < chars.Length; i++) + { + input = input.Replace(chars[i].ToString(), encoded[i]); + } + + return input; + } + + // unsafe, do not use without encoding first + string userInput = "Administrator"; + PrincipalContext AD = new PrincipalContext(ContextType.Domain, "ad.example.dev"); + + UserPrincipal u = new UserPrincipal(AD); + string encodedUserName = EncodeLDAPString(userInput); + + // The AD search term, encoded prior to calling search + u.SamAccountName = encodedUserName; + + // Search for user + PrincipalSearcher search = new PrincipalSearcher(u); + + // Use FindOne to only return a single result + UserPrincipal result = (UserPrincipal)search.FindOne(); + search.Dispose(); + + // show some details + if (result != null) { + Console.WriteLine("User: {0}", result.DisplayName); + } else { + Console.WriteLine("user not found"); + } + ``` + + The same encoding method shown in `EncodeLDAPString` can also be used when using the + older `DirectorySearcher` API. + + For more information see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html + severity: "WARNING" + metadata: + shortDescription: "Improper neutralization of special elements used in an LDAP + query ('LDAP Injection')" + category: "security" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + cwe: "CWE-90" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-SQLInjection.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-SQLInjection.cs new file mode 100644 index 0000000..ef2ef37 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-SQLInjection.cs @@ -0,0 +1,164 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Data.Entity; +using System.Data.Entity.Core.EntityClient; +using System.Data.Odbc; +using System.Data.OleDb; +using System.Data.SqlClient; +using MySql.Data.MySqlClient; +using Npgsql; +using Oracle.ManagedDataAccess.Client; +using Cassandra; +using System.Data.Linq; + +class SQLInjection +{ + static void QueryWithUserInput(DbContext ctx, string input) + { + var cmd = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + // ruleid: csharp_injection_rule-SQLInjection + ctx.Database.ExecuteSqlCommand(cmd); + // ruleid: csharp_injection_rule-SQLInjection + ctx.Database.ExecuteSqlCommandAsync(cmd); + // ruleid: csharp_injection_rule-SQLInjection + var items = db.Database.SqlQuery(cmd).ToList(); + var safecmd = "SELECT * FROM Users" + // ok: csharp_injection_rule-SQLInjection + var items = db.Database.SqlQuery(safecmd).ToList(); + } + + static void QueryTwoWithUserInput(string input) + { + // Define the connection string + string connectionString = "Data Source=.;Initial Catalog=YourDatabase;Integrated Security=True"; + DataContext dbContext = new DataContext(connectionString); + string sqlQuery = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + + // ruleid: csharp_injection_rule-SQLInjection + var result = dbContext.ExecuteQuery(sqlQuery); + + // ruleid: csharp_injection_rule-SQLInjection + var results = dbContext.ExecuteQuery(typeof(object), sqlQuery); + + // Define a raw SQL command to update user age + string updateCommand = "UPDATE Users SET Age = {0} WHERE Id = '" + input + "'"; + + // ruleid: csharp_injection_rule-SQLInjection + int rowsAffected = dbContext.ExecuteCommand(updateCommand, 35); + + string safeCommand = "UPDATE Users SET Age = {0} WHERE Id = {1}" ; + // ok: csharp_injection_rule-SQLInjection + int rows = dbContext.ExecuteCommand(safeCommand, 35, 1); + } + + static void QueryWithUserInputSqlClient(string input) + { + // ruleid: csharp_injection_rule-SQLInjection + var cmd = new SqlCommand("SELECT * FROM Users WHERE username = '" + input + "' and role='user'"); + cmd.ExecuteReader(); + } + + static void QueryWithUserInputCommandText(string input) + { + SqlCommand sqlCmd = new SqlCommand(); + // ruleid: csharp_injection_rule-SQLInjection + sqlCmd.CommandText = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + sqlCmd.CommandText = "abc"; + sqlCmd.ExecuteReader(); + + var oracleCmd = new OracleCommand(); + // ruleid: csharp_injection_rule-SQLInjection + oracleCmd.CommandText = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + oracleCmd.CommandText = "abc"; + oracleCmd.ExecuteReader(); + + var npgsqlCmd = new NpgsqlCommand(); + // ruleid: csharp_injection_rule-SQLInjection + npgsqlCmd.CommandText = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + npgsqlCmd.CommandText = "abc"; + npgsqlCmd.ExecuteReader(); + + var mySqlCmd = new MySqlCommand(); + // ruleid: csharp_injection_rule-SQLInjection + mySqlCmd.CommandText = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + mySqlCmd.CommandText = "abc"; + mySqlCmd.ExecuteReader(); + + var entityCmd = new EntityCommand(); + // ruleid: csharp_injection_rule-SQLInjection + entityCmd.CommandText = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + entityCmd.CommandText = "abc"; + entityCmd.ExecuteReader(); + + OdbcCommand odbcCmd = new OdbcCommand(); + // ruleid: csharp_injection_rule-SQLInjection + odbcCmd.CommandText = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + odbcCmd.CommandText = "abc"; + odbcCmd.ExecuteReader(); + + var oleDbCmd = new OleDbCommand(); + // ruleid: csharp_injection_rule-SQLInjection + oleDbCmd.CommandText = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + oleDbCmd.CommandText = "abc"; + oleDbCmd.ExecuteReader(); + + // Check with formatted strings too. + // ruleid: csharp_injection_rule-SQLInjection + oleDbCmd.CommandText = String.Format("SELECT * FROM Users WHERE username = '{0}' and role='user'", input); + oleDbCmd.ExecuteReader(); + } + + static void SafeSanitized(DbContext ctx, string input) + { + var cmd = "SELECT * FROM Users WHERE username = @username and role='user'"; + // ok: csharp_injection_rule-SQLInjection + ctx.Database.ExecuteSqlCommand( + cmd, + new SqlParameter("@username", input)); + } + + static void SafeConstant(DbContext ctx) + { + var cmd = "SELECT * FROM Users"; + // ok: csharp_injection_rule-SQLInjection + ctx.Database.ExecuteSqlCommand(cmd); + } + + static void SafeConstantSqlClient() + { + // ok: csharp_injection_rule-SQLInjection + var cmd = new SqlCommand("SELECT * FROM Users"); + cmd.ExecuteReader(); + } + + static void SafeSanitizedSqlClient(string input) + { + // ok: csharp_injection_rule-SQLInjection + var cmd = new SqlCommand("SELECT * FROM Users WHERE username = '@username' and role='user'"); + cmd.Parameters.AddWithValue("@username", input); + cmd.Parameters["@username"].Value = input; + cmd.ExecuteReader(); + } + + static void exampleMySqlClient(string input) + { + var cmd = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; + // ruleid: csharp_injection_rule-SQLInjection + var dtRow = MySqlHelper.ExecuteDataRow(Connection.ConnectionStr, cmd); + var cmd = "SELECT * FROM Users WHERE username = 'abc' and role='user'"; + // ok: csharp_injection_rule-SQLInjection + var dtRow = MySqlHelper.ExecuteDataRow(Connection.ConnectionStr, cmd); + + } + + static void exampleCassandra(string userInput) + { + var cluster=Cluster.Builder().AddContactPoint("127.0.0.1").Build(); + var session=cluster.Connect("test_keyspace"); + string query="SELECT * FROM users WHERE id="+userInput; + // ruleid: csharp_injection_rule-SQLInjection + session.Execute(query); + query = "SELECT * FROM Users WHERE username = 'abc' and role='user'"; + // ok: csharp_injection_rule-SQLInjection + session.Execute(query); + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-SQLInjection.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-SQLInjection.yml new file mode 100644 index 0000000..d80b772 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-SQLInjection.yml @@ -0,0 +1,153 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_injection_rule-SQLInjection" + languages: + - "csharp" + patterns: + - pattern-either: + - patterns: + - metavariable-pattern: + metavariable: "$FUNC" + pattern-either: + - pattern: "SqlQuery" + - pattern: "ExecuteSqlCommand" + - pattern: "ExecuteSqlCommandAsync" + - pattern: "ExecuteSqlRaw" + - pattern: "ExecuteSqlRawAsync" + - pattern: "FromSqlRaw" + - pattern: "FromSql" + - pattern: "GetSqlStringCommand" + - pattern: "ExecuteDataSet" + - pattern: "ExecuteReader" + - pattern: "ExecuteNonQuery" + - pattern: "ExecuteScalar" + - pattern: "CreateSQLQuery" + - pattern-either: + - pattern: "$DB.$FUNC($ARG, ...)" + - pattern: "$DB.$FUNC<$CC>($ARG, ...)" + - pattern-not: "$DB.$FUNC(\"...\", ...)" + - pattern-not: "$DB.$FUNC<$CC>(\"...\", ...)" + - patterns: + - pattern-inside: | + using System.Data.Linq; + ... + - pattern-either: + - patterns: + - pattern: "(DataContext $CTX).ExecuteQuery<$TRESULT>($ARG, ...)" + - pattern-not: "(DataContext $CTX).ExecuteQuery<$TRESULT>(\"...\", ...)" + - patterns: + - pattern: "(DataContext $CTX).ExecuteQuery($TYPE, $ARG, ...)" + - pattern-not: "(DataContext $CTX).ExecuteQuery($TYPE, \"...\", ...)" + - patterns: + - pattern: "(DataContext $CTX).ExecuteCommand($ARG, ...)" + - pattern-not: "(DataContext $CTX).ExecuteCommand(\"...\", ...)" + - patterns: + - metavariable-pattern: + metavariable: "$IMPL" + pattern-either: + - pattern: "SqlCommand" + - pattern: "OracleCommand" + - pattern: "NpgsqlCommand" + - pattern: "MySqlCommand" + - pattern: "EntityCommand" + - pattern: "OdbcCommand" + - pattern: "OleDbCommand" + - pattern: "SqliteCommand" + - pattern-either: + - patterns: + - pattern: "new $IMPL($ARG, ...);" + - pattern-not: "new $IMPL(\"...\", ...);" + - patterns: + - pattern: "($IMPL $CMD).CommandText = <...$ARG...>;" + - pattern-not: "($IMPL $CMD).CommandText = \"...\";" + - patterns: + - metavariable-pattern: + metavariable: "$FUNC" + pattern-either: + - pattern: "ExecuteDataRow" + - pattern: "ExecuteDataRowAsync" + - pattern: "ExecuteDataset" + - pattern: "ExecuteDatasetAsync" + - pattern: "ExecuteNonQuery" + - pattern: "ExecuteNonQueryAsync" + - pattern: "ExecuteReader" + - pattern: "ExecuteReaderAsync" + - pattern: "ExecuteScalar" + - pattern: "ExecuteScalarAsync" + - pattern: "UpdateDataSet" + - pattern: "UpdateDataSetAsync" + - pattern-inside: | + using MySql.Data.MySqlClient; + ... + - pattern: "MySqlHelper.$FUNC($CONN, $ARG, ...)" + - pattern-not: "MySqlHelper.$FUNC($CONN, \"...\", ...)" + - patterns: + - pattern-inside: | + using Cassandra; + ... + - pattern-not: "$SESS.Execute(\"...\", ...)" + - pattern-either: + - pattern: "(Session $SESS).Execute($ARG, ...)" + - patterns: + - pattern-inside: | + var $SESS = $CLUSTER.Connect(...); + ... + - pattern: "$SESS.Execute($ARG, ...)" + message: | + SQL Injection is a critical vulnerability that can lead to data or system compromise. By + dynamically generating SQL query strings, user input may be able to influence the logic of + the SQL statement. This could lead to an adversary accessing information they should + not have access to, or in some circumstances, being able to execute OS functionality or code. + + Replace all dynamically generated SQL queries with parameterized queries. In situations where + dynamic queries must be created, never use direct user input, but instead use a map or + dictionary of valid values and resolve them using a user supplied key. + + For example, some database drivers do not allow parameterized queries for `>` or `<` comparison + operators. In these cases, do not use a user supplied `>` or `<` value, but rather have the + user + supply a `gt` or `lt` value. The alphabetical values are then used to look up the `>` and `<` + values to be used in the construction of the dynamic query. The same goes for other queries + where + column or table names are required but cannot be parameterized. + + Example using parameterized queries with `SqlCommand`: + ``` + string userInput = "someUserInput"; + string connectionString = ...; + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + String sql = "SELECT name, value FROM table where name=@Name"; + + using (SqlCommand command = new SqlCommand(sql, connection)) + { + command.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar); + command.Parameters["@Name"].Value = userInput; + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1)); + } + } + } + } + ``` + + For more information on SQL Injection see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html + severity: "WARNING" + metadata: + shortDescription: "Improper Neutralization of Special Elements used in an SQL + Command ('SQL Injection')" + category: "security" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + cwe: "CWE-89" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XPathInjection.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XPathInjection.cs new file mode 100644 index 0000000..42eefc3 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XPathInjection.cs @@ -0,0 +1,87 @@ +// License: LGPL-3.0 License (c) security-code-scan + +using System.Xml; +using System.Xml.Linq; +using System.Xml.Schema; +using System.Xml.XPath; + +class XPathInjection +{ + static void QueryWithUserInput() + { + var input = Console.ReadLine(); + var doc = new XmlDocument {XmlResolver = null}; + doc.Load("/config.xml"); + + // ruleid: csharp_injection_rule-XPathInjection + var results = doc.SelectNodes("/Config/Devices/Device[id='" + input + "']"); + + // ruleid: csharp_injection_rule-XPathInjection + var result = doc.SelectSingleNode("/Config/Devices/Device[id='" + input + "']")!; + + result.SelectSingleNode("/Config/Devices/Device[id='" + input + "']"); + + XPathNavigator navigator = doc.CreateNavigator()!; + // ruleid: csharp_injection_rule-XPathInjection + navigator.Compile(input); + // ruleid: csharp_injection_rule-XPathInjection + navigator.Evaluate(input); + // ruleid: csharp_injection_rule-XPathInjection + navigator.Matches(input); + // ruleid: csharp_injection_rule-XPathInjection + navigator.Select(input); + // ruleid: csharp_injection_rule-XPathInjection + navigator.SelectAncestors(input, input, false); + // ruleid: csharp_injection_rule-XPathInjection + navigator.SelectChildren(input, input); + // ruleid: csharp_injection_rule-XPathInjection + navigator.SelectDescendants(input, input, false); + // ruleid: csharp_injection_rule-XPathInjection + navigator.SelectSingleNode(input); + } + + static void LinqExtensionQueryWithUserInput() + { + var input = Console.ReadLine(); + XDocument d = XDocument.Parse(""); + // ruleid: csharp_injection_rule-XPathInjection + d.XPathEvaluate("/root/" + input); + // ruleid: csharp_injection_rule-XPathInjection + d.XPathSelectElement("/root/" + input); + // ruleid: csharp_injection_rule-XPathInjection + d.XPathSelectElements("/root/" + input); + } + + static void XPathWithUserInput() + { + var input = Console.ReadLine(); + XmlSchemaXPath path = new XmlSchemaXPath + { + // ruleid: csharp_injection_rule-XPathInjection + XPath = input + }; + + var path2 = new XmlSchemaXPath(); + // ruleid: csharp_injection_rule-XPathInjection + path2.XPath = input; + } + + static void Safe() + { + var doc = new XmlDocument {XmlResolver = null}; + doc.Load("/config.xml"); + + var results = doc.SelectNodes("/Config/Devices/Device[id='123']"); + + XmlNode result = doc.SelectSingleNode("/Config/Devices/Device[id='123']")!; + + result.SelectSingleNode("/Config/Devices/Device[id='123']"); + + XDocument d = XDocument.Parse(""); + d.XPathEvaluate("/root"); + d.XPathSelectElement("/root"); + d.XPathSelectElements("/root"); + + var cookieParameterNames = new HashSet(cookieParameters.Select(c => c.Name)); + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XPathInjection.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XPathInjection.yml new file mode 100644 index 0000000..ce74ea5 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XPathInjection.yml @@ -0,0 +1,91 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_injection_rule-XPathInjection" + languages: + - "csharp" + patterns: + - pattern-inside: | + using System.Xml; + ... + - pattern-either: + - patterns: + - metavariable-regex: + metavariable: "$FUNC" + regex: "^(SelectNodes|SelectSingleNode|Compile|Evaluate|Matches|Select|SelectAncestors|SelectChildren|SelectDescendants)$" + - metavariable-regex: + metavariable: "$TY" + regex: "^(XPathNavigator|XmlDocument|XmlNode|XmlDocumentXPathExtensions)$" + - pattern: "($TY $VAR).$FUNC(<...$ARG...>, ...)" + - pattern-not: "($TY $VAR).$FUNC(\"...\", ...)" + - patterns: + - pattern-inside: | + using System.Xml.Linq; + ... + - metavariable-regex: + metavariable: "$FUNC" + regex: "^(XPathEvaluate|XPathSelectElement|XPathSelectElements)$" + - pattern: "$VAR.$FUNC(<...$ARG...>, ...)" + - pattern-not: "$VAR.$FUNC(\"...\", ...)" + - patterns: + - pattern-inside: | + using System.Xml.Schema; + ... + - pattern-either: + - patterns: + - pattern: "$VAR.XPath = <...$ARG...>;" + - pattern-not: "$VAR.XPath = \"...\"" + - patterns: + - pattern: "new XmlSchemaXPath { XPath = <...$ARG...> };" + - focus-metavariable: "$ARG" + message: | + XPath injection is a vulnerability that can allow an adversary to inject or modify how an XML + query + is structured. Depending on the logic of the original query, this could lead to adversaries + extracting unauthorized information or in rare cases bypassing authorization checks. + + It is recommended that LINQ to XML is used instead of XPath for querying XML documents. Care + must be taken to **not** call these LINQ functions with user input as they can still lead to + XPath + injection: + + - `XPathEvaluate` + - `XPathSelectElement` + - `XPathSelectElements` + + Example using LINQ to XML to safely extract the first user from a list of users: + ``` + // XDocument is safe from XXE attacks as the resolver is disabled by default + XDocument doc = XDocument.Load("users.xml"); + XNamespace ns = "urn:users-schema"; + + string userInput = "LastName"; + + // Get all the users. + var user = doc.Descendants(ns + "user") + .Select(u => new { + FirstName = (string)u.Element(ns + "first-name"), + LastName = (string)u.Element(ns + "last-name") + }).Where(u => u.LastName == userInput).FirstOrDefault(); + + Console.WriteLine(user.FirstName + " " + user.LastName); + ``` + + For more information on LINQ to XML security see: + https://learn.microsoft.com/en-us/dotnet/standard/linq/linq-xml-security + + For more information on XML security see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net + severity: "INFO" + metadata: + shortDescription: "Improper neutralization of data within XPath expressions ('XPath + Injection')" + category: "security" + cwe: "CWE-643" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlDocumentXXEInjection.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlDocumentXXEInjection.cs new file mode 100644 index 0000000..5518c48 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlDocumentXXEInjection.cs @@ -0,0 +1,54 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Xml; + +namespace consoleAppDNF4.CSharp.Injection +{ + internal class XXEInjection : IScenarioRunner + { + private void TestXMlDocument(string path) + { + try + { + XmlDocument xmlDocUnSafe = new XmlDocument(); + // ruleid: csharp_injection_rule-XmlDocumentXXEInjection + xmlDocUnSafe.Load(path); + Console.WriteLine(xmlDocUnSafe.InnerText); + + XmlDocument xmlDocSafe = new XmlDocument(); + xmlDocSafe.XmlResolver = null; + // ok: csharp_injection_rule-XmlDocumentXXEInjection + xmlDocSafe.Load(path); + Console.WriteLine(xmlDocSafe.InnerText); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message.ToString()); + } + } + + private void TestXMlDocument2(string path) + { + string xxePayload = $"]>" + + "&win;"; + string xml = "" + xxePayload; + + try + { + XmlDocument xmlDocUnSafe = new XmlDocument(); + // ruleid: csharp_injection_rule-XmlDocumentXXEInjection + xmlDocUnSafe.LoadXml(xml); + Console.WriteLine("with Resolver " + xmlDocUnSafe.InnerText); + + XmlDocument xmlDocSafe = new XmlDocument(); + xmlDocSafe.XmlResolver = null; + // ok: csharp_injection_rule-XmlDocumentXXEInjection + xmlDocSafe.LoadXml(xml); + Console.WriteLine("null Resolver " + xmlDocSafe.InnerText); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message.ToString()); + } + } + } +} \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlDocumentXXEInjection.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlDocumentXXEInjection.yml new file mode 100644 index 0000000..ec78bc8 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlDocumentXXEInjection.yml @@ -0,0 +1,54 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_injection_rule-XmlDocumentXXEInjection" + languages: + - "csharp" + mode: "taint" + pattern-sinks: + - patterns: + - pattern-not-inside: | + (XmlDocument $DOC).XmlResolver = null; + ... + - pattern-either: + - pattern: "(XmlDocument $DOC).Load(...);" + - pattern: "(XmlDocument $DOC).LoadXml(...);" + pattern-sources: + - pattern: "var $DOC = new System.Xml.XmlDocument(...);" + - patterns: + - pattern: "var $DOC = new System.Xml.XmlDocument {...};" + - pattern-not: "var $DOC = new System.Xml.XmlDocument {...,XmlResolver = null,...};" + message: | + External XML entities are a feature of XML parsers that allow documents to contain references + to + other documents or data. This feature can be abused to read files, communicate with external + hosts, + exfiltrate data, or cause a Denial of Service (DoS). + + XML parsers and document loaders must be configured to not resolve entities. This can be done + by: + - Ensuring you are running a version of .NET Framework greater than 4.5.2 (released in 2014). + - Using `XDocument` which disables entity resolution and is generally safe from DoS. + - Setting `XmlDocument`'s `XmlResolver` to null. + + Example of safely loading an XML file using `XmlDocument`: + ``` + XmlDocument document = new XmlDocument(); + document.XmlResolver = null; + document.Load("users.xml"); + ``` + + For more information on XML security, see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net + severity: "WARNING" + metadata: + shortDescription: "Improper restriction of XML external entity reference ('XXE')" + category: "security" + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlReaderXXEInjection.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlReaderXXEInjection.cs new file mode 100644 index 0000000..de4e57e --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlReaderXXEInjection.cs @@ -0,0 +1,104 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Xml; + +namespace consoleAppDNF4.CSharp.Injection +{ + internal class XXEInjection : IScenarioRunner + { + private void TestReaderSettings(string path) + { + try + { + var settings = new XmlReaderSettings(); + settings.ProhibitDtd = false; + settings.DtdProcessing = DtdProcessing.Parse; + + // ruleid: csharp_injection_rule-XmlReaderXXEInjection + XmlReader reader = XmlReader.Create(path, settings); + + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element) + { + Console.WriteLine("Inner XML: " + reader.ReadInnerXml()); + } + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message.ToString()); + } + } + + private void TestReaderSettings2(string path) + { + try + { + var settings = new XmlReaderSettings(); + settings.DtdProcessing = DtdProcessing.Prohibit; + + // ok: csharp_injection_rule-XmlReaderXXEInjection + XmlReader reader = XmlReader.Create(path, settings); + + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element) + { + Console.WriteLine("Inner XML: " + reader.ReadInnerXml()); + } + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message.ToString()); + } + } + + private void TestReaderSettingsSafe(string path) + { + try + { + var settings = new XmlReaderSettings(); + settings.ProhibitDtd = false; + + // ruleid: csharp_injection_rule-XmlReaderXXEInjection + XmlReader reader = XmlReader.Create(path, settings); + + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element) + { + Console.WriteLine("Inner XML: " + reader.ReadInnerXml()); + } + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message.ToString()); + } + } + + private void TestReaderWithoutSettings(string path) + { + try + { + // ok: csharp_injection_rule-XmlReaderXXEInjection + XmlReader reader = XmlReader.Create(path); + + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element) + { + Console.WriteLine("Inner XML: " + reader.ReadInnerXml()); + } + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message.ToString()); + } + } + } +} + + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlReaderXXEInjection.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlReaderXXEInjection.yml new file mode 100644 index 0000000..f817fdc --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/injection/rule-XmlReaderXXEInjection.yml @@ -0,0 +1,53 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_injection_rule-XmlReaderXXEInjection" + languages: + - "csharp" + mode: "taint" + pattern-sinks: + - patterns: + - pattern-either: + - pattern-inside: | + $SETTINGS.ProhibitDtd = false; + ... + - pattern-inside: | + $SETTINGS.DtdProcessing = DtdProcessing.Parse; + ... + - pattern: "System.Xml.XmlReader.Create(..., $SETTINGS);" + pattern-sources: + - pattern: "var $SETTINGS = new XmlReaderSettings();" + message: | + External XML entities are a feature of XML parsers that allow documents to contain references + to + other documents or data. This feature can be abused to read files, communicate with external + hosts, + exfiltrate data, or cause a Denial of Service (DoS). + + XML parsers and document loaders must be configured to not resolve entities. This can be done + by: + - Ensuring you are running a version of .NET Framework greater than 4.5.2 (released in 2014). + - Setting `XmlTextReader`'s `ProhibitDtd` to `true` + - Setting `XmlReaderSettings` `DtdProcessing` to `DtdProcessing.Prohibit` + + Example of safely loading an XML file using `XmlDocument`: + ``` + var settings = new XmlReaderSettings(); + settings.DtdProcessing = DtdProcessing.Prohibit; + XmlReader reader = XmlReader.Create(path, settings); + ``` + + For more information on XML security, see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net + severity: "WARNING" + metadata: + shortDescription: "Improper restriction of XML external entity reference ('XXE')" + category: "security" + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + security-severity: "MEDIUM" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/other/rule-UnsafeXSLTSettingUsed.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/other/rule-UnsafeXSLTSettingUsed.cs new file mode 100644 index 0000000..1e9731f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/other/rule-UnsafeXSLTSettingUsed.cs @@ -0,0 +1,56 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Xml.Xsl; + +class UnsafeXSLTSettingsUsed +{ + static void Unsafe() + { + XslCompiledTransform transform = new XslCompiledTransform(); + // ruleid: csharp_other_rule-UnsafeXSLTSettingUsed + XsltSettings settings = new XsltSettings() {EnableScript = true}; + transform.Load("foo", settings, null); + + XslCompiledTransform transform = new XslCompiledTransform(); + // ruleid: csharp_other_rule-UnsafeXSLTSettingUsed + XsltSettings settings = new XsltSettings() {EnableDocumentFunction = true}; + transform.Load("foo", settings, null); + + XslCompiledTransform transform = new XslCompiledTransform(); + // ruleid: csharp_other_rule-UnsafeXSLTSettingUsed + XsltSettings settings = new XsltSettings() {EnableScript=false, EnableDocumentFunction = true}; + transform.Load(dd, settings, null); + + XslCompiledTransform transform = new XslCompiledTransform(); + // ruleid: csharp_other_rule-UnsafeXSLTSettingUsed + XsltSettings settings = new XsltSettings() {EnableScript=true, EnableDocumentFunction = false}; + transform.Load("foo", settings, null); + + XsltSettings settings2 = new XsltSettings(); + // ruleid: csharp_other_rule-UnsafeXSLTSettingUsed + settings2.EnableScript = true; + transform.Load("foo", settings2, null); + + XsltSettings settings3 = new XsltSettings(); + // ruleid: csharp_other_rule-UnsafeXSLTSettingUsed + settings3.EnableDocumentFunction = true; + transform.Load("foo", settings3, null); + } + + static void unSafeRead() + { + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.Load("docxml.xml"); + + XslCompiledTransform xslt = new XslCompiledTransform(); + // ruleid: csharp_other_rule-UnsafeXSLTSettingUsed + xslt.Load("docxsl.xslt", new XsltSettings() { EnableDocumentFunction = true }, null); + } + + static void Safe() + { + XslCompiledTransform transform = new XslCompiledTransform(); + // ok: csharp_other_rule-UnsafeXSLTSettingUsed + XsltSettings settings = new XsltSettings(); + transform.Load("foo", settings, null); + } +} \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/other/rule-UnsafeXSLTSettingUsed.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/other/rule-UnsafeXSLTSettingUsed.yml new file mode 100644 index 0000000..7dbd766 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/other/rule-UnsafeXSLTSettingUsed.yml @@ -0,0 +1,87 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_other_rule-UnsafeXSLTSettingUsed" + patterns: + - pattern-either: + - patterns: + - pattern: "new XsltSettings() {...,$OPTIONS,...};" + - metavariable-pattern: + metavariable: "$OPTIONS" + pattern-either: + - pattern: "EnableDocumentFunction = true" + - pattern: "EnableScript = true" + - patterns: + - pattern: "$SETTINGS.$OPT = true;" + - pattern: | + var $SETTINGS = new XsltSettings(); + ... + $SETTINGS.$OPT = true; + - metavariable-pattern: + metavariable: "$OPT" + pattern-either: + - pattern: "EnableDocumentFunction" + - pattern: "EnableScript" + message: | + By setting `XsltSettings.EnableScript` to true, an adversary who is able to influence the + loaded + XSL document could directly inject code to compromise the system. It is strongly + recommended that an alternative approach is used to work with XML data. + + For increased security: + + - Never process user-supplied XSL style sheets + - Ensure `XsltSettings.EnableScript` is set to false + - Ensure `XsltSettings.EnableDocumentFunction` is set to false + + If the application must calculate values from XML input, instead of using XSL scripts to + execute functions, modify the XML document prior to running the + `XslCompiledTransform.Transform` method. + + Example of modifying the XML prior to running `Transform`: + ``` + const String filename = "number.xml"; + const String stylesheet = "calc.xsl"; + + // Compile the style sheet. + XsltSettings xslt_settings = new XsltSettings(); + xslt_settings.EnableScript = false; // disable script + xslt_settings.EnableDocumentFunction = false; // disable document() function + XslCompiledTransform xslt = new XslCompiledTransform(); + XmlResolver resolver = null; // set a null entity resolver + xslt.Load(stylesheet, xslt_settings, resolver); + + // Load the XML source file, using XDocument for safety + XDocument doc = XDocument.Load(filename); + + // do our modifications to the document before the transformation + // instead of inside of a script. + doc.Element("data").Add(new XElement("circle", new XElement("radius", 12))); + + // Create an XmlWriter. + XmlWriterSettings settings = new XmlWriterSettings(); + settings.OmitXmlDeclaration = true; + settings.Indent = true; + XmlWriter writer = XmlWriter.Create("output.xml", settings); + // Finally, execute the transformation. + xslt.Transform(doc.CreateReader(), writer); + writer.Close(); + ``` + + For more information on security considerations when using XSL see the following URLs: + - https://learn.microsoft.com/en-us/dotnet/standard/data/xml/xslt-security-considerations + - https://learn.microsoft.com/en-us/dotnet/api/system.xml.xsl.xslcompiledtransform?view=net-7.0#security-considerations + languages: + - "csharp" + severity: "WARNING" + metadata: + shortDescription: "XML injection (aka Blind XPath injection)" + category: "security" + cwe: "CWE-91" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + security-severity: "High" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/password/rule-PasswordComplexity.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/password/rule-PasswordComplexity.cs new file mode 100644 index 0000000..a36c639 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/password/rule-PasswordComplexity.cs @@ -0,0 +1,66 @@ +// License: LGPL-3.0 License (c) security-code-scan +using dotNetMVC.Data; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddIdentity(options => +{ + // ok: csharp_password_rule-PasswordComplexity + options.Password.RequireDigit = true; + // ok: csharp_password_rule-PasswordComplexity + options.Password.RequireLowercase = true; + // ok: csharp_password_rule-PasswordComplexity + options.Password.RequireNonAlphanumeric = true; + // ok: csharp_password_rule-PasswordComplexity + options.Password.RequireUppercase = true; +}) + .AddEntityFrameworkStores() + .AddDefaultTokenProviders(); + +builder.Services.Configure(options => +{ + // ruleid: csharp_password_rule-PasswordComplexity + options.Password.RequiredLength = 5; + // ok: csharp_password_rule-PasswordComplexity + options.Password.RequiredUniqueChars = 1; +}); + + +namespace BTCPayServer.Hosting +{ + public class Startup + { + public void ConfigureServices(IServiceCollection services) + { + services.AddIdentityCore(options => + { + // ok: csharp_password_rule-PasswordComplexity + options.Password.RequireUppercase = true; + // ruleid: csharp_password_rule-PasswordComplexity + options.Password.RequireNonAlphanumeric = false; + }).AddEntityFrameworkStores() + .AddDefaultTokenProviders(); + + services.Configure(options => + { + // ok: csharp_password_rule-PasswordComplexity + options.Password.RequireDigit = true; + // ruleid: csharp_password_rule-PasswordComplexity + options.Password.RequiredLength = 6; + // ruleid: csharp_password_rule-PasswordComplexity + options.Password.RequireLowercase = false; + // ruleid: csharp_password_rule-PasswordComplexity + options.Password.RequireNonAlphanumeric = false; + // ruleid: csharp_password_rule-PasswordComplexity + options.Password.RequireUppercase = false; + // ruleid: csharp_password_rule-PasswordComplexity + options.Password.RequireUppercase = false; + }); + } + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/password/rule-PasswordComplexity.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/password/rule-PasswordComplexity.yml new file mode 100644 index 0000000..38a89cc --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/password/rule-PasswordComplexity.yml @@ -0,0 +1,54 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_password_rule-PasswordComplexity" + languages: + - "csharp" + pattern-either: + - pattern: "$OPT.Password.RequireDigit = false;" + - pattern: "$OPT.Password.RequireLowercase = false;" + - pattern: "$OPT.Password.RequireNonAlphanumeric = false;" + - pattern: "$OPT.Password.RequireUppercase = false;" + - patterns: + - pattern: "$OPT.Password.RequiredLength = $LEN;" + - metavariable-comparison: + metavariable: "$LEN" + comparison: "$LEN < 8" + - patterns: + - pattern: "$OPT.Password.RequiredUniqueChars = $LEN;" + - metavariable-comparison: + metavariable: "$LEN" + comparison: "$LEN < 1" + message: | + The application's `PasswordValidator.RequiredLength` property allows passwords + to be less than 8 characters. Consider requiring a length of at least 8 or more + characters to reduce the chance of passwords being brute forced. + + Example of setting the RequiredLength to 8 in ASP.NET Core Identity: + ``` + builder.Services.Configure(options => + { + // Default Password settings. + options.Password.RequireDigit = true; + options.Password.RequireLowercase = true; + options.Password.RequireNonAlphanumeric = true; + options.Password.RequireUppercase = true; + options.Password.RequiredLength = 8; + options.Password.RequiredUniqueChars = 1; + }); + ``` + + For more information on configuring ASP.NET Core Identity see: + https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration + severity: "WARNING" + metadata: + shortDescription: "Weak password requirements" + category: "security" + cwe: "CWE-521" + owasp: + - "A2:2017-Broken Authentication" + - "A07:2021-Identification and Authentication Failures" + - "A07:2025-Authentication Failures" + security-severity: "Info" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/path/rule-PathTraversal.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/path/rule-PathTraversal.cs new file mode 100644 index 0000000..201da10 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/path/rule-PathTraversal.cs @@ -0,0 +1,24 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System; +using System.Web; +using System.Diagnostics; +using Microsoft.AspNetCore.Mvc; + +public class PathTraversal : Controller +{ + [HttpGet] + public string Get(string myParam) + { + // ruleid: csharp_path_rule-PathTraversal + byte[] fileBytes = System.IO.File.ReadAllBytes(myParam); + return "ok"; + } + + public IActionResult Download(string fileName) + { + // ruleid: csharp_path_rule-PathTraversal + byte[] fileBytes = System.IO.File.ReadAllBytes(fileName); + return null; + } +} + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/path/rule-PathTraversal.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/path/rule-PathTraversal.yml new file mode 100644 index 0000000..99e6efb --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/path/rule-PathTraversal.yml @@ -0,0 +1,153 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_path_rule-PathTraversal" + languages: + - "csharp" + mode: "taint" + pattern-sources: + - patterns: + - pattern-inside: | + public class $CLASS : Controller { + ... + } + - pattern: "$PARAM" + - pattern-either: + - patterns: + - metavariable-regex: + metavariable: "$HTTP_ANNO" + regex: "^(Http)" + - pattern-inside: | + [$HTTP_ANNO] + public string $METHOD(...,$PARAM,...){...} + - pattern-inside: | + public IActionResult $METHOD(...,$PARAM,...){...} + pattern-sanitizers: + - pattern-either: + - pattern: "(Microsoft.Extensions.FileProviders.PhysicalFileProvider $E).GetFileInfo(...)" + - pattern: "(System.Web.HttpServerUtility $E).MapPath(...)" + - pattern: "(System.Web.HttpServerUtilityBase $E).MapPath(...)" + - pattern: "(System.Web.HttpRequest $E).MapPath(...)" + pattern-sinks: + - pattern-either: + - pattern: "System.IO.Directory.Delete(...)" + - pattern: "System.IO.Directory.GetFiles(...)" + - pattern: "System.IO.Directory.Move(...)" + - pattern: "System.IO.File.AppendAllLines(...)" + - pattern: "System.IO.File.AppendAllLinesAsync(...)" + - pattern: "System.IO.File.AppendAllText(...)" + - pattern: "System.IO.File.AppendAllTextAsync(...)" + - pattern: "System.IO.File.AppendText(...)" + - pattern: "System.IO.File.Copy(...)" + - pattern: "System.IO.File.Create(...)" + - pattern: "System.IO.File.CreateText(...)" + - pattern: "System.IO.File.Delete(...)" + - pattern: "System.IO.File.Move(...)" + - pattern: "System.IO.File.Open(...)" + - pattern: "System.IO.File.OpenRead(...)" + - pattern: "System.IO.File.OpenText(...)" + - pattern: "System.IO.File.OpenWrite(...)" + - pattern: "System.IO.File.ReadAllBytes(...)" + - pattern: "System.IO.File.ReadAllBytesAsync(...)" + - pattern: "System.IO.File.ReadAllLines(...)" + - pattern: "System.IO.File.ReadAllLinesAsync(...)" + - pattern: "System.IO.File.ReadAllText(...)" + - pattern: "System.IO.File.ReadAllTextAsync(...)" + - pattern: "System.IO.File.ReadLines(...)" + - pattern: "System.IO.File.Replace(...)" + - pattern: "System.IO.File.SetAccessControl(...)" + - pattern: "System.IO.File.WriteAllBytes(...)" + - pattern: "System.IO.File.WriteAllBytesAsync(...)" + - pattern: "System.IO.File.WriteAllLines(...)" + - pattern: "System.IO.File.WriteAllLinesAsync(...)" + - pattern: "System.IO.File.WriteAllText(...)" + - pattern: "System.IO.File.WriteAllTextAsync(...)" + - pattern: "new System.IO.FileInfo(...)" + - pattern: "(System.IO.FileInfo $E).CopyTo(...)" + - pattern: "(System.IO.FileInfo $E).MoveTo(...)" + - pattern: "(System.IO.FileInfo $E).Replace(...)" + - pattern: "System.Reflection.Assembly.LoadFile(...)" + - pattern: "System.Reflection.Assembly.LoadFrom(...)" + - pattern: "System.Reflection.Assembly.ReflectionOnlyLoadFrom(...)" + - pattern: "System.Reflection.Assembly.UnsafeLoadFrom(...)" + - pattern: "System.AppDomain.AppendPrivatePath(...)" + - pattern: "System.Xml.XmlReader.Create(...)" + - pattern: "new System.IO.StreamReader.ctor(...)" + - pattern: "new System.IO.StreamWriter.ctor(...)" + - pattern: "new System.IO.FileStream.ctor(...)" + - pattern: "new System.Web.Mvc.FilePathResult(...)" + - pattern: "new Microsoft.AspNetCore.Mvc.PhysicalFileResult(...)" + - pattern: "(Microsoft.AspNetCore.Mvc.RazorPages.PageModel $E).PhysicalFile(...)" + - pattern: "(System.Web.UI.WebControls.FileUpload $E).SaveAs(...)" + - pattern: "(System.Web.HttpResponse $E).TransmitFile(...)" + - pattern: "(System.Web.HttpResponse $E).WriteFile(...)" + - pattern: "(System.Web.HttpResponseBase $E).TransmitFile(...)" + - pattern: "(System.Web.HttpResponseBase $E).WriteFile(...)" + - pattern: "(System.IO.Compression.ZipFileExtensions $E).CreateEntryFromFile(...)" + - pattern: "(System.IO.Compression.ZipFileExtensions $E).ExtractToFile(...)" + - pattern: "(System.IO.Compression.ZipFileExtensions $E).ExtractToDirectory(...)" + - pattern: "(System.Net.WebClient $E).DownloadFile(...)" + - pattern: "(System.Net.WebClient $E).DownloadFileAsync(...)" + - pattern: "(System.Net.WebClient $E).DownloadFileTaskAsync(...)" + message: | + The application dynamically constructs file or path information. If the path + information comes from user input, it could be abused to read sensitive files, + access other users data, or aid in exploitation to gain further system access. + + User input should never be used in constructing paths or files for interacting + with the filesystem. This includes filenames supplied by user uploads or downloads. + If possible consider hashing user input or replacing it with unique values and + use `System.IO.Path.GetFullPath` to resolve and validate the path information + prior to processing any file functionality. + + Example using `Path.GetFullPath` and not allowing direct user input: + ``` + // store user input alongside an ID we control + struct userData + { + public string userFilename; + public Guid id; + } + + class Program + { + public static void Main() + { + userData data = new userData(); + // user input, saved only as a reference + data.userFilename = "..\\test.txt"; + + // random id as the filename + data.id = Guid.NewGuid(); + + // restrict all file processing to this directory only + string basePath = "C:\\Restricted\\"; + + // resolve the full path, but only use our random generated id + string fullPath = Path.GetFullPath(basePath + data.id); + + // verify the path is contained within our basePath + if (!fullPath.StartsWith(basePath)) { + Console.WriteLine("Invalid path specified!"); + return; + } + // process / work with file + } + } + ``` + + For more information on path traversal issues see OWASP: + https://owasp.org/www-community/attacks/Path_Traversal + metadata: + shortDescription: "Improper limitation of a pathname to a restricted directory + ('Path Traversal')" + category: "security" + cwe: "CWE-22" + owasp: + - "A5:2017-Broken Access Control" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + security-severity: "Medium" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/validation/rule-InputValidation.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/validation/rule-InputValidation.cs new file mode 100644 index 0000000..d97c828 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/validation/rule-InputValidation.cs @@ -0,0 +1,18 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System.Web.Mvc; +public class InputValidation +{ + // ruleid: csharp_validation_rule-InputValidation + [HttpPost] + [ValidateAntiForgeryToken] + [ValidateInput(false)] + public ActionResult ControllerMethod1(string input) { + return null; + } + + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult ControllerMethod2(string input) { + return null; + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/validation/rule-InputValidation.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/validation/rule-InputValidation.yml new file mode 100644 index 0000000..688dd5d --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/validation/rule-InputValidation.yml @@ -0,0 +1,52 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_validation_rule-InputValidation" + languages: + - "csharp" + patterns: + - pattern: | + [ValidateInput(false)] + public $RET $FOO(...) + { + ... + } + message: | + By using the `[ValidateInput(false)]` attribute in a controller + class, the application will disable request validation for that + method. This disables ASP.NET from examining requests for injection + attacks such as Cross-Site-Scripting (XSS). + + If possible, re-enable validation by using `ValidateInput(true)`. + In some cases this may not be possible, in which case ensure how the + request data used is validated and this method does not + output user input directly into the view. + + For more information on protecting ASP.NET Core applications from XSS see: + https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting + + Example of enabling `ValidateInput` attribute: + ``` + class ControllerClass + { + [ValidateInput(true)] + public void SomeActionMethod() + { + } + } + ``` + + For more information on ASP.NET request validation see OWASP: + https://owasp.org/www-community/ASP-NET_Request_Validation + severity: "WARNING" + metadata: + shortDescription: "ASP.NET input validation disabled" + category: "security" + cwe: "CWE-554" + owasp: + - "A6:2017-Security Misconfiguration" + - "A04:2021-Insecure Design" + - "A05:2025-Injection" + security-severity: "Info" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-HtmlElementXss.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-HtmlElementXss.cs new file mode 100644 index 0000000..c9e51c7 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-HtmlElementXss.cs @@ -0,0 +1,94 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System; +using System.IO; +using System.Web; +using System.Web.Mvc; +using System.Web.Optimization; +using System.Web.UI; +using System.Web.WebPages; + +// ref: csharp_xss_rule-HtmlElementXss +namespace dotNetFrameworkWebApp.Controllers.XSS +{ + public class XssController : Controller + { + // sample: http://172.21.156.246/xss/WriteHtml + public object WriteHtml(string alert) + { + string qs = Request.QueryString["alert"]; + string form = Request.Form["alert"]; + string headers = Request.Headers[0]; + string paras = Request.Params["alert"]; + string path = Request.Path; + string rawURL = Request.RawUrl; + string URL = Request.Url.ToString(); + + StringWriter stringWriter = new StringWriter(); + + HtmlTextWriter writer = new HtmlTextWriter(stringWriter); + + // ruleid: csharp_xss_rule-HtmlElementXss + writer.Write($"QueryString: {qs}
"); + + // ok: csharp_xss_rule-HtmlElementXss + writer.Write(HttpUtility.HtmlEncode("")); + + string sanitize = HttpUtility.HtmlEncode(""); + // ok: csharp_xss_rule-HtmlElementXss + writer.WriteFullBeginTag(sanitize); + + // ruleid: csharp_xss_rule-HtmlElementXss + writer.Write(""); + + // ruleid: csharp_xss_rule-HtmlElementXss + writer.WriteBeginTag(""); + + // ruleid: csharp_xss_rule-HtmlElementXss + writer.WriteEndTag(""); + + writer.EndRender(); + + // ruleid: csharp_xss_rule-HtmlElementXss + writer.AddAttribute(HtmlTextWriterAttribute.Width, "\">"); + writer.RenderBeginTag(HtmlTextWriterTag.Span); + writer.Write("Content inside the span"); + writer.RenderEndTag(); + + // ok: csharp_xss_rule-HtmlElementXss + writer.RenderBeginTag(HtmlTextWriterTag.Div); + // ruleid: csharp_xss_rule-HtmlElementXss + writer.WriteAttribute("class", "''>"); + writer.RenderEndTag(); + + writer.RenderBeginTag(HtmlTextWriterTag.Div); + // ruleid: csharp_xss_rule-HtmlElementXss + writer.AddStyleAttribute("color", "\">"); + writer.EndRender(); + + writer.RenderBeginTag(HtmlTextWriterTag.Div); + // ruleid: csharp_xss_rule-HtmlElementXss + writer.WriteStyleAttribute("color", "\">"); + writer.EndRender(); + + writer.Flush(); + return Content(stringWriter.ToString(), "text/html"); + } + } + + public ActionResult createRaw(string alert) + { + string dynamicContent = ""; + var htmlHelper = new HtmlHelper(new ViewContext(), new ViewPage()); + // ruleid: csharp_xss_rule-HtmlElementXss + var rawHtml = htmlHelper.Raw(dynamicContent).ToHtmlString(); + + // ruleid: csharp_xss_rule-HtmlElementXss + Response.Write(rawHtml); + return Content("Alert shown from htmlHelper.Raw"); + } + + public string directReturn(string alert) + { + return ""; + } +} \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-HtmlElementXss.yml b/compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-HtmlElementXss.yml new file mode 100644 index 0000000..18e86d6 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-HtmlElementXss.yml @@ -0,0 +1,102 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "csharp_xss_rule-HtmlElementXss" + mode: "taint" + pattern-sources: + - patterns: + - pattern: "$PARAM" + - pattern-inside: | + $RET $METHOD(...,$PARAM,...){...} + - pattern: "Request.Cookies[...]" + - pattern: "Request.Cookies.Get(...)" + - pattern: "Request.Form[...]" + - pattern: "Request.Form.Get(...)" + - pattern: "Request.Headers[...]" + - pattern: "Request.Headers.Get(...)" + - pattern: "Request.QueryString[...]" + - pattern: "Request.QueryString.Get(...)" + - pattern: "Request.Params[...]" + - pattern: "Request.RawUrl" + - pattern: "Request.Url" + - pattern: "Request.Path" + - pattern: "Request.Body" + - pattern: "$CTX.Request.Cookies[...]" + - pattern: "$CTX.Request.Cookies.Get(...)" + - pattern: "$CTX.Request.Form[...]" + - pattern: "$CTX.Request.Form.Get(...)" + - pattern: "$CTX.Request.Headers[...]" + - pattern: "$CTX.Request.Headers.Get(...)" + - pattern: "$CTX.Request.QueryString[...]" + - pattern: "$CTX.Request.QueryString.Get(...)" + - pattern: "$CTX.Request.Body" + pattern-sanitizers: + - patterns: + - metavariable-regex: + metavariable: "$FUNC" + regex: "(SerializeObject|HtmlAttributeEncode|HtmlEncode|HtmlFormUrlEncode|UrlEncode|UrlPathEncode|XmlAttributeEncode|XmlEncode|Encode)" + - pattern: "$CLASS.$FUNC(...)" + pattern-sinks: + - pattern: "(System.Web.Mvc.HtmlHelper $E).Raw(...)" + - pattern: "(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper $E).Raw(...)" + - pattern: "Response.Write(...)" + - pattern: "(System.Web.UI.HtmlTextWriter $E).AddAttribute(...)" + - pattern: "(System.Web.UI.HtmlTextWriter $E).AddStyleAttribute(...)" + - pattern: "(System.Web.UI.HtmlTextWriter $E).RenderBeginTag(...)" + - pattern: "(System.Web.UI.HtmlTextWriter $E).Write(...)" + - pattern: "(System.Web.UI.HtmlTextWriter $E).WriteAttribute(...)" + - pattern: "(System.Web.UI.HtmlTextWriter $E).WriteBeginTag(...)" + - pattern: "(System.Web.UI.HtmlTextWriter $E).WriteEndTag(...)" + - pattern: "(System.Web.UI.HtmlTextWriter $E).WriteFullBeginTag(...)" + - pattern: "(System.Web.UI.HtmlTextWriter $E).WriteStyleAttribute(...)" + languages: + - "csharp" + message: | + Cross Site Scripting (XSS) is an attack which exploits a web application or system to treat + user input + as markup or script code. It is important to encode the data depending on the specific context + it + is used in. There are at least six context types: + + - Inside HTML tags `
context 1
` + - Inside attributes: `
` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + User input that is displayed within the application must be encoded, sanitized or validated + to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be + taken + to not mix server-side templating with client-side templating, as the server-side templating + will + not encode things like {{ 7*7 }} which may execute client-side templating features. + + It is _NOT_ advised to encode user input prior to inserting into a data store. The data will + need to be + encoded depending on context of where it is output. It is much safer to force the displaying + system to + handle the encoding and not attempt to guess how it should be encoded. + + Consider using built-in framework capabilities for automatically encoding user input. + Depending + on output context, consider using the following `System.Text.Encodings.Web` encoders: + + - [HtmlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.htmlencoder) + - [JavaScriptEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder) + - [UrlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.urlencoder) + + For more information on protecting ASP.NET Core applications from XSS see: + https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting#accessing-encoders-in-code + metadata: + shortDescription: "Improper neutralization of input during web page generation + ('Cross-site Scripting')" + category: "security" + cwe: "CWE-79" + owasp: + - "A7:2017-Cross-Site Scripting (XSS)" + - "A03:2021-Injection" + - "A05:2025-Injection" + security-severity: "Medium" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-ScriptXss.cs b/compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-ScriptXss.cs new file mode 100644 index 0000000..a8679a9 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/csharp/xss/rule-ScriptXss.cs @@ -0,0 +1,102 @@ +// License: LGPL-3.0 License (c) security-code-scan +using System; +using System.Text; +using System.Web; +using System.Web.Security.AntiXss; +using System.Web.UI; + +namespace donNetWebFormPages.Views.Injection +{ + // ref: csharp_xss_rule-ScriptXss + public partial class xss : Page + { + // sample url: http://172.21.153.221/Views/Injection/xss?quary=alert(%27a%27) + protected void Page_Load(object sender, EventArgs e) + { + string name = Request.QueryString["quary"]; + StringBuilder cstext2 = new StringBuilder(); + cstext2.Append(""); + } + + protected void onBtnSubmitClk(object sender, EventArgs e) + { + string script = txtInput.Text; + // ruleid: csharp_xss_rule-ScriptXss + ScriptManager.RegisterStartupScript(Page, typeof(Page), "StartupScript", script, true); + lblOutput.Text = "You entered: " + script; + } + + protected void onBtnSubmitClk1(object sender, EventArgs e) + { + string script = txtInput.Text; + // ruleid: csharp_xss_rule-ScriptXss + ScriptManager.RegisterStartupScript(Page, typeof(Page), "StartupScript", script, true); + ClientScriptManager cs = Page.ClientScript; + StringBuilder cstext1 = new StringBuilder(); + cstext1.Append("` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + Script blocks alone have multiple ways they need to be encoded. Extra care must be taken if + user input + is ever output inside of script tags. + + User input that is displayed within the application must be encoded, sanitized or validated + to ensure it cannot be treated as HTML or executed as JavaScript code. Care must also be + taken + to not mix server-side templating with client-side templating, as the server-side templating + will + not encode things like {{ 7*7 }} which may execute client-side templating features. + + It is _NOT_ advised to encode user input prior to inserting into a data store. The data will + need to be + encoded depending on context of where it is output. It is much safer to force the displaying + system to + handle the encoding and not attempt to guess how it should be encoded. + + Use Wicket's built in escaping feature by calling `Component.setEscapeModelStrings(true);` + + For more information on Wicket components see: + - https://nightlies.apache.org/wicket/apidocs/9.x/org/apache/wicket/Component.html + + For more information on XSS see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html + metadata: + shortDescription: "Improper neutralization of input during web page generation + ('Cross-site Scripting')" + category: "security" + cwe: "CWE-79" + owasp: + - "A7:2017-Cross-Site Scripting (XSS)" + - "A03:2021-Injection" + - "A05:2025-Injection" + security-severity: "Medium" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-XSSReqParamToServletWriter.java b/compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-XSSReqParamToServletWriter.java new file mode 100644 index 0000000..ae8541a --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-XSSReqParamToServletWriter.java @@ -0,0 +1,59 @@ +// License: LGPL-3.0 License (c) find-sec-bugs +// scaffold: dependencies=org.owasp.encoder.encoder@1.2.3 +package xss; + +import org.owasp.encoder.Encode; + +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Map; + +// Also contains vulnerabilities found under ids: XSS_SERVLET,SERVLET_PARAMETER +public class XSSReqParamToServletWriter extends HttpServlet { + + protected void danger(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + String input1 = req.getParameter("input1"); + // ruleid: java_xss_rule-XSSReqParamToServletWriter + resp.getWriter().write(input1); + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + String input1 = req.getParameter("input1"); // BAD + String sessionId = req.getRequestedSessionId(); // BAD + String queryString = req.getQueryString(); // BAD + + String referrer = req.getHeader("Referer"); //Should have a higher priority + if (referrer != null && referrer.startsWith("http://company.ca")) { + // Header access + String host = req.getHeader("Host"); // BAD + String referer = req.getHeader("Referer"); // BAD + String userAgent = req.getHeader("User-Agent"); // BAD + } + + PrintWriter writer = resp.getWriter(); + // ruleid: java_xss_rule-XSSReqParamToServletWriter + writer.write(input1); + } + + + protected void danger3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + String input1 = req.getParameter("input1"); + // ruleid: java_xss_rule-XSSReqParamToServletWriter + resp.getWriter().write(input1); + } + + protected void ok2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + String input1 = req.getParameter("input1"); + PrintWriter writer = resp.getWriter(); + // ok: java_xss_rule-XSSReqParamToServletWriter + writer.write(Encode.forHtml(input1)); + } +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-XSSReqParamToServletWriter.yml b/compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-XSSReqParamToServletWriter.yml new file mode 100644 index 0000000..6564cad --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/java/xss/rule-XSSReqParamToServletWriter.yml @@ -0,0 +1,165 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "java_xss_rule-XSSReqParamToServletWriter" + languages: + - "java" + mode: "taint" + pattern-sources: + - pattern: (javax.servlet.http.HttpServletRequest $R).$METHOD(...) + - pattern: (java.util.Scanner $S).$METHOD(...) + - pattern: (java.util.stream.Stream).$METHOD(...) + - pattern: (java.util.StringJoiner $SJ).toString(...) + - pattern: (java.sql.ResultSet.getString $R).$METHOD(...) + - pattern: (java.lang.System $S).getProperty(...) + - pattern: (java.lang.System $S).getenv(...) + - pattern: (java.lang.StringBuilder $SB).toString(...) + - pattern: (java.io.FileInputStream $F).read(...) + - pattern: (java.io.FileReader $F).read(...) + - pattern: (java.net.Socket $S).getInputStream(...) + - pattern: (java.net.Socket $S).getOutputStream(...) + - pattern: (java.net.DatagramSocket $S).receive(...) + - pattern: (java.net.DatagramSocket $S).getInputStream(...) + - pattern: java.nio.file.Files.readAllBytes(...) + - pattern: java.nio.file.Files.readAllLines(...) + - pattern: java.nio.file.Files.lines(...) + - pattern: java.nio.file.Files.newBufferedReader(...) + - pattern: org.apache.commons.io.IOUtils.toString(...) + - pattern: org.apache.commons.io.IOUtils.readLines(...) + - pattern: org.apache.commons.io.IOUtils.toByteArray(...) + - pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).readValue(...) + - pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).treeToValue(...) + - pattern: $CLASS.$METHOD(..., (javax.servlet.http.HttpServletRequest $R), ...) + - pattern: $FUNC(..., (javax.servlet.http.HttpServletRequest $R), ...) + - patterns: + - pattern-inside: + $FUNC(..., String $X, ...) { ... } + - focus-metavariable: $X + pattern-propagators: + - pattern: $LIST.add($X) + from: $X + to: $LIST + - pattern: $MAP.put(..., $X) + from: $X + to: $MAP + - pattern: $STR.concat($X) + from: $X + to: $STR + - pattern: $STR = String.format(..., $X, ...) + from: $X + to: $STR + - pattern: $STR = String.join(..., $X, ...) + from: $X + to: $STR + pattern-sanitizers: + - pattern: org.owasp.encoder.Encode.forHtml(...) + - pattern: org.owasp.esapi.ESAPI.encoder().encodeForHTML(...) + - pattern: org.apache.commons.text.StringEscapeUtils.escapeHtml3(...) + - pattern: org.apache.commons.text.StringEscapeUtils.escapeHtml4(...) + - pattern: org.owasp.benchmark.helpers.Utils.encodeForHTML(...) + pattern-sinks: + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().print(...) + - patterns: + - pattern-inside: | + $W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + ... + - pattern: $W.print(...); + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().println(...) + - patterns: + - pattern-inside: | + $W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + ... + - pattern: $W.println(...); + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().format(...) + - patterns: + - pattern-inside: | + $W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + ... + - pattern: $W.format(...); + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().append(...) + - patterns: + - pattern-inside: | + $W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + ... + - pattern: $W.append(...); + - pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().write(...) + - patterns: + - pattern-inside: | + $W = (javax.servlet.http.HttpServletResponse $R).getWriter(); + ... + - pattern: $W.write(...); + message: | + The application is returning user-supplied data from an HTTP request directly into an HTTP + response output + writer. This could lead to Cross Site Scripting (XSS) if the input were malicious + script code and the application server is not properly validating the output. + + XSS is an attack which exploits a web application or system to treat user input + as markup or script code. It is important to encode the data depending on the specific context + it is used in. There are at least six context types: + + - Inside HTML tags `
context 1
` + - Inside attributes: `
` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + Script blocks alone have multiple ways they need to be encoded. Extra care must be taken if + user input + is ever output inside of script tags. + + User input that is displayed within the application must be encoded, sanitized or validated + to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be + taken + to not mix server-side templating with client-side templating, as the server-side templating + will + not encode things like {{ 7*7 }} which may execute client-side templating features. + + It is _NOT_ advised to encode user input prior to inserting into a data store. The data will + need to be + encoded depending on context of where it is output. It is much safer to force the displaying + system to + handle the encoding and not attempt to guess how it should be encoded. + + If possible do not use user input directly in the output to the response writer. + + If the application must output user-supplied input, it will need to encode the data depending + on + the output context. + + Consider using [Apache Commons Text](https://commons.apache.org/proper/commons-text/) + `StringEscapeUtils` methods for various context. Please note there is no way to safely + output script code in most circumstances, regardless of encoding. If calling the HTTP + response writer directly, ensure that the `Content-Type` is set to `text/plain` so it will + not be accidentally interpreted by HTML by modern browsers. + ``` + // Get user input + String htmlInput = request.getParameter("userInput"); + // Encode the input using the Html4 encoder + String htmlEncoded = StringEscapeUtils.escapeHtml4(htmlInput); + // Force the HTTP response to be content type of text/plain so it is not interpreted as HTML + response.setContentType("text/plain"); + // Ensure UTF-8 + response.setCharacterEncoding("UTF-8"); + // Write response + response.getWriter().write(htmlEncoded); + ``` + + For more information on XSS see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html + severity: "WARNING" + metadata: + shortDescription: "Improper neutralization of input during web page generation + ('Cross-site Scripting')" + category: "security" + cwe: "CWE-79" + owasp: + - "A7:2017-Cross-Site Scripting (XSS)" + - "A03:2021-Injection" + - "A05:2025-Injection" + technology: + - "java" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/java/xxe/rule-XMLRdr.java b/compliance-agent/rules/vendor/gitlab/upstream/java/xxe/rule-XMLRdr.java new file mode 100644 index 0000000..e29dedb --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/java/xxe/rule-XMLRdr.java @@ -0,0 +1,36 @@ +// License: LGPL-3.0 License (c) find-sec-bugs +package xxe; + +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; +import org.xml.sax.helpers.XMLReaderFactory; + +import javax.xml.parsers.ParserConfigurationException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +public class XMLRdr { + private static void receiveXMLStream(final InputStream inStream, + final DefaultHandler defHandler) + throws ParserConfigurationException, SAXException, IOException { + // ... + XMLReader reader = XMLReaderFactory.createXMLReader(); + // ruleid: java_xxe_rule-XMLRdr + reader.parse(new InputSource(inStream)); + } + + + public static void main(String[] args) throws ParserConfigurationException, + SAXException, IOException { + + String xmlString = "" + + " ]>&foo;"; // Tainted input + + InputStream is = new ByteArrayInputStream(xmlString.getBytes()); + receiveXMLStream(is, new DefaultHandler()); + } +} + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/java/xxe/rule-XMLRdr.yml b/compliance-agent/rules/vendor/gitlab/upstream/java/xxe/rule-XMLRdr.yml new file mode 100644 index 0000000..cbb7c9f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/java/xxe/rule-XMLRdr.yml @@ -0,0 +1,56 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "java_xxe_rule-XMLRdr" + languages: + - "java" + message: | + External XML entities are a feature of XML parsers that allow documents to contain references + to + other documents or data. This feature can be abused to read files, communicate with external + hosts, + exfiltrate data, or cause a Denial of Service (DoS). + + The XMLReaderFactory has been deprecated. It is recommended that + [SAXParserFactory](https://docs.oracle.com/javase/9/docs/api/javax/xml/parsers/SAXParserFactory.html) + be used + instead. Additionally when using the SAXParser it must be configured to disallow doctypes, + which will + protect against the majority of XXE attacks. + + Example creating a SAXParser with disallowing the doctypes feature enabled: + ``` + // Create a SAXParserFactory + SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); + // Enable the feature which disallows { + // ruleid: javascript_dos_rule-non-literal-regexp + const arr = longStr.match(req.body.regex) + res.send("Check server console") + }) + + // http://localhost:3000/dos/regex_injection_dos/match/safe/1 + app.post('/dos/regex_injection_dos/match/safe/1', (req, res) => { + // ok: javascript_dos_rule-non-literal-regexp + const arr = longStr.match(/a/) + res.send("Check server console") + }) + + // http://localhost:3000/dos/regex_injection_dos/search/1 + app.post('/dos/regex_injection_dos/search/1', (req, res) => { + // ruleid: javascript_dos_rule-non-literal-regexp + const arr = longStr.search(req.body.regex) + res.send("Check server console") + }) + + // http://localhost:3000/dos/regex_injection_dos/search/safe/1 + app.get('/dos/regex_injection_dos/search/safe/1', (req, res) => { + // ok: javascript_dos_rule-non-literal-regexp + const arr = longStr.search(/a/) + res.send("Check server console") + }) + + // http://localhost:3000/dos/regex_injection_dos/re2/safe/1 + app.post('/dos/regex_injection_dos/re2/safe/1', (req, res) => { + // ok: javascript_dos_rule-non-literal-regexp + var re = new RE2(req.body.regex) + re.exec(longStr) + res.send("Check server console") + }) + + function test_positives_constructor(someVar, obj) { + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral1 = new RegExp("double-quoted string" + someVar, optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral2 = new RegExp('single-quoted string' + someVar) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral3 = new RegExp('single-quoted string' + someVar, optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral4 = new RegExp(`template string ${someVar}`) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral5 = new RegExp(`template string ${someVar}`, optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral6 = new RegExp(someVar + "double-quoted string") + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral7 = new RegExp(someVar + "double-quoted string", optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral8 = new RegExp(someVar + 'single-quoted string') + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral9 = new RegExp(someVar + 'single-quoted string', optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral10 = new RegExp(someVar) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral11 = new RegExp(someVar, optionalFlags) + } + + function test_positives_function(someVar, obj) { + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral1 = RegExp("double-quoted string" + someVar, optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral2 = RegExp('single-quoted string' + someVar) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral3 = RegExp('single-quoted string' + someVar, optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral4 = RegExp(`template string ${someVar}`) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral5 = RegExp(`template string ${someVar}`, optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral6 = RegExp(someVar + "double-quoted string") + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral7 = RegExp(someVar + "double-quoted string", optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral8 = RegExp(someVar + 'single-quoted string') + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral9 = RegExp(someVar + 'single-quoted string', optionalFlags) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral10 = RegExp(someVar) + // ruleid: javascript_dos_rule-non-literal-regexp + nonLiteral11 = RegExp(someVar, optionalFlags) + } + + function test_negatives_constructor() { + // ok: javascript_dos_rule-non-literal-regexp + literal1 = new RegExp('boom') + // ok: javascript_dos_rule-non-literal-regexp + literal2 = new RegExp("boom") + // ok: javascript_dos_rule-non-literal-regexp + literal3 = new RegExp(/pow!/) + + // ok: javascript_dos_rule-non-literal-regexp + literalWithFlags1 = new RegExp('pew', optionalFlags) + // ok: javascript_dos_rule-non-literal-regexp + literalWithFlags2 = new RegExp("pew", optionalFlags) + // ok: javascript_dos_rule-non-literal-regexp + literalWithFlags3 = new RegExp(/pew!/, optionalFlags) + } + + function test_negatives_function() { + // ok: javascript_dos_rule-non-literal-regexp + literal1 = RegExp('boom') + // ok: javascript_dos_rule-non-literal-regexp + literal2 = RegExp("boom") + // ok: javascript_dos_rule-non-literal-regexp + literal3 = RegExp(/pow!/) + + // ok: javascript_dos_rule-non-literal-regexp + literalWithFlags1 = RegExp('pew', optionalFlags) + // ok: javascript_dos_rule-non-literal-regexp + literalWithFlags2 = RegExp("pew", optionalFlags) + // ok: javascript_dos_rule-non-literal-regexp + literalWithFlags3 = RegExp(/pew!/, optionalFlags) + } + + function test_negatives_function_var() { + var text = 'boom'; + // ok: javascript_dos_rule-non-literal-regexp + literal1 = RegExp(text) + // ok: javascript_dos_rule-non-literal-regexp + literal2 = RegExp(text + "sd") + + var text = 'boom'; + // ok: javascript_dos_rule-non-literal-regexp + literalWithFlags1 = new RegExp(text, optionalFlags) + // ok: javascript_dos_rule-non-literal-regexp + literalWithFlags2 = new RegExp(text + "sd", optionalFlags) + } +} \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/dos/rule-non-literal-regexp.yml b/compliance-agent/rules/vendor/gitlab/upstream/javascript/dos/rule-non-literal-regexp.yml new file mode 100644 index 0000000..0f813b7 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/dos/rule-non-literal-regexp.yml @@ -0,0 +1,73 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "javascript_dos_rule-non-literal-regexp" + languages: + - "javascript" + - "typescript" + pattern-either: + - patterns: + - pattern: | + new RegExp(...) + - pattern-not: | + new RegExp("...", ...) + - pattern-not: | + new RegExp(/.../, ...) + - patterns: + - pattern: | + RegExp(...) + - pattern-not: | + RegExp("...", ...) + - pattern-not: | + RegExp(/.../, ...) + - patterns: + - pattern: | + "...".$METHOD(...) + - pattern-not: | + "...".$METHOD("...") + - pattern-not: | + "...".$METHOD(/.../) + - metavariable-regex: + metavariable: $METHOD + regex: "^(match|search)$" + message: | + The `RegExp` constructor was called with a non-literal value. If an adversary were able to + supply a malicious regex, they could cause a Regular Expression Denial of Service (ReDoS) + against the application. In Node applications, this could cause the entire application to no + longer be responsive to other users' requests. + + To remediate this issue, never allow user-supplied regular expressions. Instead, the regular + expression should be hardcoded. If this is not possible, consider using an alternative regular + expression engine such as [node-re2](https://www.npmjs.com/package/re2). RE2 is a safe alternative + that does not support backtracking, which is what leads to ReDoS. + + Example using re2 which does not support backtracking (Note: it is still recommended to + never use user-supplied input): + ``` + // Import the re2 module + const RE2 = require('re2'); + + function match(userSuppliedRegex, userInput) { + // Create a RE2 object with the user supplied regex, this is relatively safe + // due to RE2 not supporting backtracking which can be abused to cause long running + // queries + var re = new RE2(userSuppliedRegex); + // Execute the regular expression against some userInput + var result = re.exec(userInput); + // Work with the result + } + ``` + + For more information on Regular Expression DoS see: + - https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS + metadata: + cwe: "CWE-185" + shortDescription: "Regular expression with non-literal value" + category: "security" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + security-severity: "Medium" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/eval/rule-eval-with-expression.js b/compliance-agent/rules/vendor/gitlab/upstream/javascript/eval/rule-eval-with-expression.js new file mode 100644 index 0000000..8aa3292 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/eval/rule-eval-with-expression.js @@ -0,0 +1,163 @@ +// License: MIT (c) JS Foundation and other contributors, https://js.foundation + +window.testEval = function (name) { + window.globalName = name; + // ruleid: javascript_eval_rule-eval-with-expression + eval(`console.log("${name}");`); + // ruleid: javascript_eval_rule-eval-with-expression + eval(name); + //ruleid: javascript_eval_rule-eval-with-expression + eval("console.log('" + name + "');"); + + // Direct call to eval, uses local scope + // ok: javascript_eval_rule-eval-with-expression + eval("console.log(name);"); + + // Indirect Call to eval, only accesses global vars + // This looks like a harmless string but contains user input variable data that gets evaluated. + //ruleid: javascript_eval_rule-eval-with-expression + (0, eval)(`console.log("${name}");`); + + // ok: javascript_eval_rule-eval-with-expression + (0, eval)(`console.log(globalName);`); + + // call through alias + //ruleid: javascript_eval_rule-eval-with-expression + var foo = eval; + foo(`console.log("${name}");`); + + // ok: javascript_eval_rule-eval-with-expression + var foo = eval; + foo(`console.log(globalName);`); + + //ruleid: javascript_eval_rule-eval-with-expression + this.eval("console.log('" + name + "');"); + + // ok: javascript_eval_rule-eval-with-expression + this.eval("console.log(globalName);"); + + // Indirect call through member access + const obj = { eval }; + //ruleid: javascript_eval_rule-eval-with-expression + obj.eval("console.log('" + name + "');"); + + // Indirect call through conditional operator + //ruleid: javascript_eval_rule-eval-with-expression + eval?.(`console.log("${name}");`); + + //ok: javascript_eval_rule-eval-with-expression + eval?.(`console.log(globalName);`); +}; + +window.testSetTimeout = function (name) { + window.myname = name; + + // Exploit using http://localhost:3000/dangerous-sinks?name=hi%27);print();// + // ruleid: javascript_eval_rule-eval-with-expression + setTimeout(`console.log('${name}');`, 1000); + + // ok: javascript_eval_rule-eval-with-expression + setTimeout("console.log(myname);", 1000); + + // ok: javascript_eval_rule-eval-with-expression + setTimeout(function () { + console.log("setTimeout Safe Sink 2 : " + name); + }, 500); + + // Passing user input to setTimeout + const userScript = function () { + console.log("setTimeout Safe Sink 3 : " + name); + }; + + // ok: javascript_eval_rule-eval-with-expression + setTimeout(userScript, 500); + + // Exploit using http://localhost:3000/dangerous-sinks?name=hi%22);print();// + // ruleid: javascript_eval_rule-eval-with-expression + setTimeout("console.log('setTimeout Sink 5 : " + name + "');", 1000); + + window.x = 10; + window.y = 22; + // this will evaluate, but variables in this format can never break out of the code. + // ok: javascript_eval_rule-eval-with-expression + setTimeout("console.log('setTimeout Sink 6 :' + (x+y));", 1000); + + // ok: javascript_eval_rule-eval-with-expression + setTimeout("console.log(x+y);", 1000); +}; + +window.testSetInterval = function (name) { + window.myname = name; + + // Exploit using http://localhost:3000/dangerous-sinks?name=hi%27);print();// + // ruleid: javascript_eval_rule-eval-with-expression + window.intervalId1 = setInterval(`console.log('${name}');`, 1000); + + // ok: javascript_eval_rule-eval-with-expression + window.intervalId2 = setInterval("console.log(myname);", 1000); + + // ok: javascript_eval_rule-eval-with-expression + window.intervalId3 = setInterval(function () { + console.log("setTimeout Safe Sink 2 : " + name); + }, 500); + + // Passing user input to setTimeout + const userScript = function () { + console.log("setTimeout Safe Sink 3 : " + name); + }; + + // ok: javascript_eval_rule-eval-with-expression + window.intervalId4 = setInterval(userScript, 500); + + // Exploit using http://localhost:3000/dangerous-sinks?name=hi%22);print();// + // ruleid: javascript_eval_rule-eval-with-expression + window.intervalId5 = setInterval( + "console.log('setTimeout Sink 5 : " + name + "');", + 1000 + ); + + window.x = 10; + window.y = 22; + // ok: javascript_eval_rule-eval-with-expression + window.intervalId6 = setInterval( + "console.log('setTimeout Sink 6 :' + (x+y));", + 1000 + ); +}; + +window.testFunctionConstructor = function (name) { + // To exploit - http://localhost:3000/dangerous-sinks?name=hi%22;alert(1);var%20a=%221 + // ruleid: javascript_eval_rule-eval-with-expression + const sayHello = new Function( + `return function (name) { var str = "Hello, ${name}"; return str; }` + )(); + console.log(sayHello(name)); + + // To exploit - http://localhost:3000/dangerous-sinks?name=%22%27;alert(1);// + // ruleid: javascript_eval_rule-eval-with-expression + const userFormula = "var str = '" + name + "'; return str;"; + const sum = Function(userFormula)(); + console.log(sum); + + const userFormula2 = + "return function (a) {var str = 'Hello, ' + a; return str;}"; + // ok: javascript_eval_rule-eval-with-expression + const sum2 = new Function("a", userFormula2)(); + console.log(sum2(name)); + + // ok: javascript_eval_rule-eval-with-expression + const sayHello2 = Function( + "return function (name) { return `Hello, ${name}` }" + )(); + // call the function + console.log(sayHello2(name)); + + // To exploit: http://localhost:3000/dangerous-sinks?name=hi%22);print();// + // ruleid: javascript_eval_rule-eval-with-expression + const userData = `console.log("Function constructor call - ${name}");`; + console.log(Function(userData)()); + + // ruleid: javascript_eval_rule-eval-with-expression + const userData2 = `console.log("Function constructor call - ${name}");`; + console.log(new Function(userData2)()); +}; diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/eval/rule-eval-with-expression.yml b/compliance-agent/rules/vendor/gitlab/upstream/javascript/eval/rule-eval-with-expression.yml new file mode 100644 index 0000000..f4df539 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/eval/rule-eval-with-expression.yml @@ -0,0 +1,143 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "javascript_eval_rule-eval-with-expression" + languages: + - "javascript" + - "typescript" + patterns: + - pattern-either: + - patterns: + - pattern: | + eval($OBJ) + - pattern-not: | + eval("...") + - patterns: + - pattern: | + $A.eval($OBJ) + - pattern-not: | + $A.eval("...") + - patterns: + - pattern: | + (..., eval)($OBJ) + - pattern-not: | + (..., eval)("...") + - patterns: + - pattern: | + $ALIAS = eval; + ... + $ALIAS($OBJ) + - pattern-not: | + $ALIAS = eval; + ... + $ALIAS("...") + - pattern: | + new Function(..., "..." + $OBJ + "...") + - pattern: | + $BODY = "..." + $OBJ + "..." + ... + new Function(..., $BODY) + - pattern: | + new Function(..., `...${...}...`) + - pattern: | + $BODY = `...${...}...` + ... + new Function(..., $BODY) + - pattern: | + Function(..., "..." + $OBJ + "...") + - pattern: | + $BODY = "..." + $OBJ + "..." + ... + Function(..., $BODY) + - pattern: | + $BODY = `...${...}...` + ... + Function(..., $BODY) + - pattern: | + Function(..., `...${...}...`) + - pattern: | + setTimeout("..." + $OBJ + "...", ...) + - pattern: | + setTimeout(`...${...}...`, ...) + - pattern: | + setInterval("..." + $OBJ + "...", ...) + - pattern: | + setInterval(`...${...}...`, ...) + - pattern-not: | + setTimeout("...", ...) + - pattern-not: | + setInterval("...", ...) + severity: "WARNING" + message: | + The application was found calling the `eval` function OR Function() + constructor OR setTimeout() OR setInterval() methods. If the + + variables or strings or functions passed to these methods contains user-supplied input, an adversary could attempt to execute arbitrary + + JavaScript + + code. This could lead to a full system compromise in Node applications or Cross-site Scripting + + (XSS) in web applications. + + + To remediate this issue, remove all calls to above methods and consider alternative methods for + + executing + + the necessary business logic. There is almost no safe method of calling `eval` or other above stated sinks with + + user-supplied input. + + Instead, consider alternative methods such as using property accessors to dynamically access + + values. + + + Example using property accessors to dynamically access an object's property: + + ``` + + // Define an object + + const obj = {key1: 'value1', key2: 'value2'}; + + // Get key dynamically from user input + + const key = getUserInput(); + + // Check if the key exists in our object and return it, or a default empty string + + const value = (obj.hasOwnProperty(key)) ? obj[key] : ''; + + // Work with the value + + ``` + + + For more information on why not to use `eval`, and alternatives see: + + - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval! + + Other References: + + - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function + + - https://developer.mozilla.org/en-US/docs/Web/API/setTimeout + + - https://developer.mozilla.org/en-US/docs/Web/API/setInterval + metadata: + cwe: "CWE-95" + shortDescription: "Improper neutralization of directives in dynamically evaluated + code ('Eval Injection')" + category: "security" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + # yamllint disable + source-rule-url: "https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-eval-with-expression.js" + # yamllint enable + security-severity: "High" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/pathtraversal/rule-non-literal-fs-filename.js b/compliance-agent/rules/vendor/gitlab/upstream/javascript/pathtraversal/rule-non-literal-fs-filename.js new file mode 100644 index 0000000..e140724 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/pathtraversal/rule-non-literal-fs-filename.js @@ -0,0 +1,267 @@ +// License: MIT (c) GitLab Inc. + +const fs = require('node:fs'); +import fs2 from "fs"; + +function negative(argOne, argTwo) { + + // string args + fs2.appendFile('foo', data, callback) + fs.appendFileSync('foo', data) + fs.chmod('foo', mode, callback) + fs.chmodSync('foo', mode) + fs.chown('foo', uid, gid, callback) + fs.chownSync('foo', uid, gid) + fs.createReadStream('foo') + fs.createWriteStream('foo') + fs.exists('foo', callback) + fs.existsSync('foo', callback) + fs.lchmod('foo', mode, callback) + fs.lchmodSync('foo', mode) + fs.lchown('foo', uid, gid, callback) + fs.lchownSync('foo', uid, gid) + fs.link('foo', 'bar', callback) + fs.linkSync('foo', 'bar') + fs.lstat('foo', callback) + fs.lstatSync('foo') + fs.mkdir('foo', callback) + fs.mkdirSync('foo') + fs.open('foo', callback) + fs.openSync('foo') + fs.readdir('foo', callback) + fs.readdirSync('foo') + fs.readFile('foo', callback) + fs.readFileSync('foo') + fs.readlink('foo', callback) + fs.readlinkSync('foo') + fs.realpath('foo', callback) + fs.realpathSync('foo') + fs.rename('foo', 'bar', callback) + fs.renameSync('foo', 'bar') + fs.rmdir('foo', callback) + fs.rmdirSync('foo') + fs.stat('foo', callback) + fs.statSync('foo') + fs.symlink('foo', 'bar', callback) + fs.symlinkSync('foo', 'bar') + fs.truncate('foo', callback) + fs.truncateSync('foo') + fs.unlink('foo', callback) + fs.unlinkSync('foo') + fs.unwatchFile('foo') + fs.utimes('foo', callback) + fs.utimesSync('foo') + fs.watch('foo') + fs.watchFile('foo', listener) + fs.writeFile('foo', callback) + fs.writeFileSync('foo') + + // constant string arguments + strArgOne = 'foo' + strArgTwo = 'bar' + fs.appendFile(strArgOne, data, callback) + fs.appendFileSync(strArgOne, data) + fs.chmod(strArgOne, mode, callback) + fs.chmodSync(strArgOne, mode) + fs.chown(strArgOne, uid, gid, callback) + fs.chownSync(strArgOne, uid, gid) + fs.createReadStream(strArgOne) + fs.createWriteStream(strArgOne) + fs.exists(strArgOne, callback) + fs.existsSync(strArgOne, callback) + fs.lchmod(strArgOne, mode, callback) + fs.lchmodSync(strArgOne, mode) + fs.lchown(strArgOne, uid, gid, callback) + fs.lchownSync(strArgOne, uid, gid) + fs.link(strArgOne, strArgTwo, callback) + fs.linkSync(strArgOne, strArgTwo) + fs.lstat(strArgOne, callback) + fs.lstatSync(strArgOne) + fs.mkdir(strArgOne, callback) + fs.mkdirSync(strArgOne) + fs.open(strArgOne, callback) + fs.openSync(strArgOne) + fs.readdir(strArgOne, callback) + fs.readdirSync(strArgOne) + fs.readFile(strArgOne, callback) + fs.readFileSync(strArgOne) + fs.readlink(strArgOne, callback) + fs.readlinkSync(strArgOne) + fs.realpath(strArgOne, callback) + fs.realpathSync(strArgOne) + fs.rename(strArgOne, strArgTwo, callback) + fs.renameSync(strArgOne, strArgTwo) + fs.rmdir(strArgOne, callback) + fs.rmdirSync(strArgOne) + fs.stat(strArgOne, callback) + fs.statSync(strArgOne) + fs.symlink(strArgOne, strArgTwo, callback) + fs.symlinkSync(strArgOne, strArgTwo) + fs.truncate(strArgOne, callback) + fs.truncateSync(strArgOne) + fs.unlink(strArgOne, callback) + fs.unlinkSync(strArgOne) + fs.unwatchFile(strArgOne) + fs.utimes(strArgOne, callback) + fs.utimesSync(strArgOne) + fs.watch(strArgOne) + fs.watchFile(strArgOne, listener) + fs.writeFile(strArgOne, callback) + fs.writeFileSync(strArgOne) + + const notfs = require("test"); + notfs.appendFile(argOne, data, callback) + notfs.appendFileSync(argOne, data) + notfs.chmod(argOne, mode, callback) + notfs.chmodSync(argOne, mode) + notfs.chown(argOne, uid, gid, callback) + notfs.chownSync(argOne, uid, gid) + notfs.createReadStream(argOne) + notfs.createWriteStream(argOne) + notfs.exists(argOne, callback) + notfs.existsSync(argOne, callback) + notfs.lchmod(argOne, mode, callback) + notfs.lchmodSync(argOne, mode) + notfs.lchown(argOne, uid, gid, callback) + notfs.lchownSync(argOne, uid, gid) + notfs.link(argOne, argTwo, callback) + notfs.linkSync(argOne, argTwo) + notfs.lstat(argOne, callback) + notfs.lstatSync(argOne) + notfs.mkdir(argOne, callback) + notfs.mkdirSync(argOne) + notfs.open(argOne, callback) + notfs.openSync(argOne) + notfs.readdir(argOne, callback) + notfs.readdirSync(argOne) + notfs.readFile(argOne, callback) + notfs.readFileSync(argOne) + notfs.readlink(argOne, callback) + notfs.readlinkSync(argOne) + notfs.realpath(argOne, callback) + notfs.realpathSync(argOne) + notfs.rename(argOne, argTwo, callback) + notfs.renameSync(argOne, argTwo) + notfs.rmdir(argOne, callback) + notfs.rmdirSync(argOne) + notfs.stat(argOne, callback) + notfs.statSync(argOne) + notfs.symlink(argOne, argTwo, callback) + notfs.symlinkSync(argOne, argTwo) + notfs.truncate(argOne, callback) + notfs.truncateSync(argOne) + notfs.unlink(argOne, callback) + notfs.unlinkSync(argOne) + notfs.unwatchFile(argOne) + notfs.utimes(argOne, callback) + notfs.utimesSync(argOne) + notfs.watch(argOne) + notfs.watchFile(argOne, listener) + notfs.writeFile(argOne, callback) + notfs.writeFileSync(argOne) +} + +function positive(argOne, argTwo) { + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.appendFile(argOne, data, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.appendFileSync(argOne, data) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.chmod(argOne, mode, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.chmodSync(argOne, mode) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.chown(argOne, uid, gid, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.chownSync(argOne, uid, gid) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.createReadStream(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.createWriteStream(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.exists(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.existsSync(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.lchmod(argOne, mode, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.lchmodSync(argOne, mode) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.lchown(argOne, uid, gid, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.lchownSync(argOne, uid, gid) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.link(argOne, argTwo, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.linkSync(argOne, argTwo) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.lstat(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.lstatSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.mkdir(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.mkdirSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.open(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.openSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.readdir(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.readdirSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.readFile(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.readFileSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.readlink(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.readlinkSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.realpath(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.realpathSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.rename(argOne, argTwo, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.renameSync(argOne, argTwo) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.rmdir(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.rmdirSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.stat(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.statSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.symlink(argOne, argTwo, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.symlinkSync(argOne, argTwo) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.truncate(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.truncateSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.unlink(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.unlinkSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.unwatchFile(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.utimes(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.utimesSync(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.watch(argOne) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.watchFile(argOne, listener) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.writeFile(argOne, callback) + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs.writeFileSync(argOne) + + + // ruleid: javascript_pathtraversal_rule-non-literal-fs-filename + fs2.writeFileSync(argOne) +} diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/pathtraversal/rule-non-literal-fs-filename.yml b/compliance-agent/rules/vendor/gitlab/upstream/javascript/pathtraversal/rule-non-literal-fs-filename.yml new file mode 100644 index 0000000..c0d8dcf --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/pathtraversal/rule-non-literal-fs-filename.yml @@ -0,0 +1,163 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "javascript_pathtraversal_rule-non-literal-fs-filename" + languages: + - "typescript" + - "javascript" + patterns: + - pattern-either: + - pattern-inside: | + import $MOD from $IMP + ... + - pattern-inside: | + $MOD = require($IMP) + ... + - metavariable-comparison: + metavariable: "$IMP" + comparison: "$IMP in ['fs', 'node:fs', 'fs/promises', 'node:fs/promises', 'fs-extra']" + - pattern-not: "$MOD.appendFile(\"...\", ...)" + - pattern-not: "$MOD.appendFileSync(\"...\", ...)" + - pattern-not: "$MOD.chmod(\"...\", ...)" + - pattern-not: "$MOD.chmodSync(\"...\", ...)" + - pattern-not: "$MOD.chown(\"...\", ...)" + - pattern-not: "$MOD.chownSync(\"...\", ...)" + - pattern-not: "$MOD.createReadStream(\"...\", ...)" + - pattern-not: "$MOD.createWriteStream(\"...\", ...)" + - pattern-not: "$MOD.exists(\"...\", ...)" + - pattern-not: "$MOD.existsSync(\"...\", ...)" + - pattern-not: "$MOD.lchmod(\"...\", ...)" + - pattern-not: "$MOD.lchmodSync(\"...\", ...)" + - pattern-not: "$MOD.lchown(\"...\", ...)" + - pattern-not: "$MOD.lchownSync(\"...\", ...)" + - pattern-not: "$MOD.link(\"...\", \"...\", ...)" + - pattern-not: "$MOD.linkSync(\"...\", \"...\", ...)" + - pattern-not: "$MOD.lstat(\"...\", ...)" + - pattern-not: "$MOD.lstatSync(\"...\", ...)" + - pattern-not: "$MOD.mkdir(\"...\", ...)" + - pattern-not: "$MOD.mkdirSync(\"...\", ...)" + - pattern-not: "$MOD.open(\"...\", ...)" + - pattern-not: "$MOD.openSync(\"...\", ...)" + - pattern-not: "$MOD.readdir(\"...\", ...)" + - pattern-not: "$MOD.readdirSync(\"...\", ...)" + - pattern-not: "$MOD.readFile(\"...\", ...)" + - pattern-not: "$MOD.readFileSync(\"...\", ...)" + - pattern-not: "$MOD.readlink(\"...\", ...)" + - pattern-not: "$MOD.readlinkSync(\"...\", ...)" + - pattern-not: "$MOD.realpath(\"...\", ...)" + - pattern-not: "$MOD.realpathSync(\"...\", ...)" + - pattern-not: "$MOD.rename(\"...\", \"...\", ...)" + - pattern-not: "$MOD.renameSync(\"...\", \"...\", ...)" + - pattern-not: "$MOD.rmdir(\"...\", ...)" + - pattern-not: "$MOD.rmdirSync(\"...\", ...)" + - pattern-not: "$MOD.stat(\"...\", ...)" + - pattern-not: "$MOD.statSync(\"...\", ...)" + - pattern-not: "$MOD.symlink(\"...\", \"...\", ...)" + - pattern-not: "$MOD.symlinkSync(\"...\", \"...\", ...)" + - pattern-not: "$MOD.truncate(\"...\", ...)" + - pattern-not: "$MOD.truncateSync(\"...\", ...)" + - pattern-not: "$MOD.unlink(\"...\", ...)" + - pattern-not: "$MOD.unlinkSync(\"...\", ...)" + - pattern-not: "$MOD.unwatchFile(\"...\", ...)" + - pattern-not: "$MOD.utimes(\"...\", ...)" + - pattern-not: "$MOD.utimesSync(\"...\", ...)" + - pattern-not: "$MOD.watch(\"...\", ...)" + - pattern-not: "$MOD.watchFile(\"...\", ...)" + - pattern-not: "$MOD.writeFile(\"...\", ...)" + - pattern-not: "$MOD.writeFileSync(\"...\", ...)" + - pattern-either: + - pattern: "$MOD.appendFile(...)" + - pattern: "$MOD.appendFileSync(...)" + - pattern: "$MOD.chmod(...)" + - pattern: "$MOD.chmodSync(...)" + - pattern: "$MOD.chown(...)" + - pattern: "$MOD.chownSync(...)" + - pattern: "$MOD.createReadStream(...)" + - pattern: "$MOD.createWriteStream(...)" + - pattern: "$MOD.exists(...)" + - pattern: "$MOD.existsSync(...)" + - pattern: "$MOD.lchmod(...)" + - pattern: "$MOD.lchmodSync(...)" + - pattern: "$MOD.lchown(...)" + - pattern: "$MOD.lchownSync(...)" + - pattern: "$MOD.link(...)" + - pattern: "$MOD.linkSync(...)" + - pattern: "$MOD.lstat(...)" + - pattern: "$MOD.lstatSync(...)" + - pattern: "$MOD.mkdir(...)" + - pattern: "$MOD.mkdirSync(...)" + - pattern: "$MOD.open(...)" + - pattern: "$MOD.openSync(...)" + - pattern: "$MOD.readdir(...)" + - pattern: "$MOD.readdirSync(...)" + - pattern: "$MOD.readFile(...)" + - pattern: "$MOD.readFileSync(...)" + - pattern: "$MOD.readlink(...)" + - pattern: "$MOD.readlinkSync(...)" + - pattern: "$MOD.realpath(...)" + - pattern: "$MOD.realpathSync(...)" + - pattern: "$MOD.rename(...)" + - pattern: "$MOD.renameSync(...)" + - pattern: "$MOD.rmdir(...)" + - pattern: "$MOD.rmdirSync(...)" + - pattern: "$MOD.stat(...)" + - pattern: "$MOD.statSync(...)" + - pattern: "$MOD.symlink(...)" + - pattern: "$MOD.symlinkSync(...)" + - pattern: "$MOD.truncate(...)" + - pattern: "$MOD.truncateSync(...)" + - pattern: "$MOD.unlink(...)" + - pattern: "$MOD.unlinkSync(...)" + - pattern: "$MOD.unwatchFile(...)" + - pattern: "$MOD.utimes(...)" + - pattern: "$MOD.utimesSync(...)" + - pattern: "$MOD.watch(...)" + - pattern: "$MOD.watchFile(...)" + - pattern: "$MOD.writeFile(...)" + - pattern: "$MOD.writeFileSync(...)" + message: | + The application dynamically constructs file or path information. If the path + information comes from user-supplied input, it could be abused to read sensitive files, + access other users' data, or aid in exploitation to gain further system access. + + User input should never be used in constructing paths or files for interacting + with the filesystem. This includes filenames supplied by user uploads or downloads. + If possible, consider hashing user input or using unique values and + use `path.normalize` to resolve and validate the path information + prior to processing any file functionality. + + Example using `path.normalize` and not allowing direct user input: + ``` + // User input, saved only as a reference + // id is a randomly generated UUID to be used as the filename + const userData = {userFilename: userSuppliedFilename, id: crypto.randomUUID()}; + // Restrict all file processing to this directory only + const basePath = '/app/restricted/'; + + // Create the full path, but only use our random generated id as the filename + const joinedPath = path.join(basePath, userData.id); + // Normalize path, removing any '..' + const fullPath = path.normalize(joinedPath); + // Verify the fullPath is contained within our basePath + if (!fullPath.startsWith(basePath)) { + console.log("Invalid path specified!"); + } + // Process / work with file + // ... + ``` + + For more information on path traversal issues see OWASP: + https://owasp.org/www-community/attacks/Path_Traversal + metadata: + shortDescription: "Improper limitation of a pathname to a restricted directory + ('Path Traversal')" + cwe: "CWE-22" + owasp: + - "A5:2017-Broken Access Control" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + security-severity: "Medium" + category: "security" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/random/rule-pseudo-random-bytes.js b/compliance-agent/rules/vendor/gitlab/upstream/javascript/random/rule-pseudo-random-bytes.js new file mode 100644 index 0000000..d3e7532 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/random/rule-pseudo-random-bytes.js @@ -0,0 +1,22 @@ +// License: MIT (c) JS Foundation and other contributors, https://js.foundation +// source: https://github.com/nodesecurity/eslint-plugin-security/blob/master/test/detect-pseudoRandomBytes.js +// hash: edd1ae2 + +'use strict'; + +const RuleTester = require('eslint').RuleTester; +const tester = new RuleTester(); + +const ruleName = 'detect-pseudoRandomBytes'; +const invalid = 'crypto.pseudoRandomBytes'; + + +tester.run(ruleName, require(`../rules/${ruleName}`), { + valid: [{ code: 'crypto.randomBytes' }], + invalid: [ + { + code: invalid, + errors: [{ message: 'Found crypto.pseudoRandomBytes which does not produce cryptographically strong numbers' }] + } + ] +}); diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/random/rule-pseudo-random-bytes.yml b/compliance-agent/rules/vendor/gitlab/upstream/javascript/random/rule-pseudo-random-bytes.yml new file mode 100644 index 0000000..a984bf2 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/random/rule-pseudo-random-bytes.yml @@ -0,0 +1,38 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "javascript_random_rule-pseudo-random-bytes" + languages: + - "javascript" + - "typescript" + pattern: "crypto.pseudoRandomBytes" + severity: "WARNING" + message: | + Depending on the context, generating weak random numbers may expose cryptographic functions, + which rely on these numbers, to be exploitable. When generating numbers for sensitive values + such as tokens, nonces, and cryptographic keys, it is recommended that the `randomBytes` method + of the `crypto` module be used instead of `pseudoRandomBytes`. + + Example using `randomBytes`: + ``` + // Generate 256 bytes of random data + const randomBytes = crypto.randomBytes(256); + ``` + + For more information on JavaScript Cryptography see: + https://nodejs.org/api/crypto.html#cryptorandombytessize-callback + metadata: + cwe: "CWE-338" + shortDescription: "Use of cryptographically weak pseudo-random number generator + (PRNG)" + category: "security" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + # yamllint disable + source-rule-url: "https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-pseudoRandomBytes.js" + # yamllint enable + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/react/rule-dangerouslysetinnerhtml.js b/compliance-agent/rules/vendor/gitlab/upstream/javascript/react/rule-dangerouslysetinnerhtml.js new file mode 100644 index 0000000..9348658 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/react/rule-dangerouslysetinnerhtml.js @@ -0,0 +1,25 @@ +// License: MIT (c) GitLab Inc. + +const App = () => { + const data = 'lorem ipsum'; + + // ruleid:javascript_react_rule-dangerouslysetinnerhtml + return ( +
+ ); +} + +const App2 = () => { + const data = 'lorem ipsum'; + + // ok:javascript_react_rule-dangerouslysetinnerhtml + return ( +
+ {data} +
+ ); +} + +export default App; diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/react/rule-dangerouslysetinnerhtml.yml b/compliance-agent/rules/vendor/gitlab/upstream/javascript/react/rule-dangerouslysetinnerhtml.yml new file mode 100644 index 0000000..dfbbafa --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/react/rule-dangerouslysetinnerhtml.yml @@ -0,0 +1,64 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "javascript_react_rule-dangerouslysetinnerhtml" + languages: + - "typescript" + - "javascript" + pattern-either: + - pattern: | + <$X dangerouslySetInnerHTML=... /> + - pattern: | + {dangerouslySetInnerHTML: ...} + severity: "WARNING" + message: | + The application was found calling `dangerouslySetInnerHTML` which may lead to Cross Site + Scripting (XSS). By default, React components will encode the data properly before rendering. + Calling `dangerouslySetInnerHTML` disables this encoding and allows raw markup + and JavaScript to be executed. + + XSS is an attack which exploits a web application or system to treat + user input as markup or script code. It is important to encode the data, depending on the + specific context it is used in. There are at least six context types: + + - Inside HTML tags `
context 1
` + - Inside attributes: `
` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + Script blocks alone have multiple ways they need to be encoded. Extra care must be taken if + user input + is ever output inside of script tags. + + User input that is displayed within the application must be encoded, sanitized or validated + to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be + taken + to not mix server-side templating with client-side templating, as the server-side templating + will + not encode things like {{ 7*7 }} which may execute client-side templating features. + + It is _NOT_ advised to encode user input prior to inserting into a data store. The data will + need to be + encoded depending on context of where it is output. It is much safer to force the displaying + system to + handle the encoding and not attempt to guess how it should be encoded. + + Remove the call to `dangerouslySetInnerHTML` or ensure that the data used in this call does + not come from user-supplied input. + + For more information on dangerously setting inner HTML see: + - https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html + metadata: + cwe: "CWE-79" + owasp: + - "A7:2017-Cross-Site Scripting (XSS)" + - "A03:2021-Injection" + - "A05:2025-Injection" + shortDescription: "Improper neutralization of input during web page generation + ('Cross-site Scripting')" + category: "security" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/require/rule-non-literal-require.js b/compliance-agent/rules/vendor/gitlab/upstream/javascript/require/rule-non-literal-require.js new file mode 100644 index 0000000..e25ea88 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/require/rule-non-literal-require.js @@ -0,0 +1,22 @@ +// License: MIT (c) JS Foundation and other contributors, https://js.foundation +// source: https://github.com/nodesecurity/eslint-plugin-security/blob/master/test/detect-non-literal-require.js +// hash: edd1ae2 +'use strict'; + +const RuleTester = require('eslint').RuleTester; +const tester = new RuleTester(); + +const ruleName = 'detect-non-literal-require'; +const invalid = 'var a = require(c)'; + + +tester.run(ruleName, require(`../rules/${ruleName}`), { + valid: [{ code: 'var a = require(\'b\')' }], + invalid: [ + { + code: invalid, + errors: [{ message: 'Found non-literal argument in require' }] + } + ] +}); + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/require/rule-non-literal-require.yml b/compliance-agent/rules/vendor/gitlab/upstream/javascript/require/rule-non-literal-require.yml new file mode 100644 index 0000000..b81110b --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/require/rule-non-literal-require.yml @@ -0,0 +1,34 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "javascript_require_rule-non-literal-require" + languages: + - "javascript" + - "typescript" + patterns: + - pattern: "require($OBJ)" + - pattern-not: "require('...')" + severity: "WARNING" + message: | + The application was found to dynamically import a module by calling `require` using a + non-literal string. An adversary might be able to read the first line of + arbitrary files. If they had write access to the file system, they may also be able to + execute arbitrary code. + + To remediate this issue, use a hardcoded string literal when calling `require`. Never call it + it with dynamically created variables or user-supplied data. + metadata: + cwe: "CWE-95" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + shortDescription: "Improper neutralization of directives in dynamically evaluated + code ('Eval Injection')" + category: "security" + # yamllint disable + source-rule-url: "https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-non-literal-require.js" + # yamllint enable + security-severity: "Low" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/timing/rule-possible-timing-attacks.js b/compliance-agent/rules/vendor/gitlab/upstream/javascript/timing/rule-possible-timing-attacks.js new file mode 100644 index 0000000..2250f79 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/timing/rule-possible-timing-attacks.js @@ -0,0 +1,39 @@ +// License: MIT (c) JS Foundation and other contributors, https://js.foundation +// source: https://github.com/nodesecurity/eslint-plugin-security/blob/master/test/detect-possible-timing-attacks.js +// hash: edd1ae2 +'use strict'; + +const RuleTester = require('eslint').RuleTester; +const tester = new RuleTester(); + +const ruleName = 'detect-possible-timing-attacks'; +const Rule = require(`../rules/${ruleName}`); + +const valid = 'if (age === 5) {}'; +const invalidLeft = 'if (password === \'mypass\') {}'; +const invalidRight = 'if (\'mypass\' === password) {}'; + + +// We only check with one string "password" and operator "===" +// to KISS. + +tester.run(`${ruleName} (left side)`, Rule, { + valid: [{ code: valid }], + invalid: [ + { + code: invalidLeft, + errors: [{ message: 'Potential timing attack, left side: true' }] + } + ] +}); + + +tester.run(`${ruleName} (right side)`, Rule, { + valid: [{ code: valid }], + invalid: [ + { + code: invalidRight, + errors: [{ message: 'Potential timing attack, right side: true' }] + } + ] +}); diff --git a/compliance-agent/rules/vendor/gitlab/upstream/javascript/timing/rule-possible-timing-attacks.yml b/compliance-agent/rules/vendor/gitlab/upstream/javascript/timing/rule-possible-timing-attacks.yml new file mode 100644 index 0000000..4affb2f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/javascript/timing/rule-possible-timing-attacks.yml @@ -0,0 +1,527 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "javascript_timing_rule-possible-timing-attacks" + languages: + - "javascript" + patterns: + - pattern-not: "if ($Z == null) { ... };" + - pattern-not: "if ($Z === null) { ... };" + - pattern-not: "if ($Z != null) { ... };" + - pattern-not: "if ($Z !== null) { ... };" + - pattern-not: "if ($Q != undefined) { ... };" + - pattern-not: "if ($Q !== undefined) { ... };" + - pattern-not: "if ($Q == undefined) { ... };" + - pattern-not: "if ($Q === undefined) { ... };" + - pattern-not: "return $Y == null;" + - pattern-not: "return $Y === null;" + - pattern-not: "return $Y != null;" + - pattern-not: "return $Y !== null;" + - pattern-not: "return $Y == undefined;" + - pattern-not: "return $Y === undefined;" + - pattern-not: "return $Y != undefined;" + - pattern-not: "return $Y !== undefined;" + - pattern-either: + - pattern: | + if (password == $X) { + ... + } + - pattern: | + if ($X == password) { + ... + } + - pattern: | + if (password === $X) { + ... + } + - pattern: | + if ($X === password) { + ... + } + - pattern: | + if (pass == $X) { + ... + } + - pattern: | + if ($X == pass) { + ... + } + - pattern: | + if (pass === $X) { + ... + } + - pattern: | + if ($X === pass) { + ... + } + - pattern: | + if (secret == $X) { + ... + } + - pattern: | + if ($X == secret) { + ... + } + - pattern: | + if (secret === $X) { + ... + } + - pattern: | + if ($X === secret) { + ... + } + - pattern: | + if (api == $X) { + ... + } + - pattern: | + if ($X == api) { + ... + } + - pattern: | + if (api === $X) { + ... + } + - pattern: | + if ($X === api) { + ... + } + - pattern: | + if (apiKey == $X) { + ... + } + - pattern: | + if ($X == apiKey) { + ... + } + - pattern: | + if (apiKey === $X) { + ... + } + - pattern: | + if ($X === apiKey) { + ... + } + - pattern: | + if (apiSecret == $X) { + ... + } + - pattern: | + if ($X == apiSecret) { + ... + } + - pattern: | + if (apiSecret === $X) { + ... + } + - pattern: | + if ($X === apiSecret) { + ... + } + - pattern: | + if (token == $X) { + ... + } + - pattern: | + if ($X == token) { + ... + } + - pattern: | + if (token === $X) { + ... + } + - pattern: | + if ($X === token) { + ... + } + - pattern: | + if (hash == $X) { + ... + } + - pattern: | + if ($X == hash) { + ... + } + - pattern: | + if (hash === $X) { + ... + } + - pattern: | + if ($X === hash) { + ... + } + - pattern: | + if (auth_token == $X) { + ... + } + - pattern: | + if ($X == auth_token) { + ... + } + - pattern: | + if (auth_token === $X) { + ... + } + - pattern: | + if ($X === auth_token) { + ... + } + - pattern: | + if (password != $X) { + ... + } + - pattern: | + if ($X != password) { + ... + } + - pattern: | + if (password !== $X) { + ... + } + - pattern: | + if ($X !== password) { + ... + } + - pattern: | + if (pass != $X) { + ... + } + - pattern: | + if ($X != pass) { + ... + } + - pattern: | + if (pass !== $X) { + ... + } + - pattern: | + if ($X !== pass) { + ... + } + - pattern: | + if (secret != $X) { + ... + } + - pattern: | + if ($X != secret) { + ... + } + - pattern: | + if (secret !== $X) { + ... + } + - pattern: | + if ($X !== secret) { + ... + } + - pattern: | + if (api != $X) { + ... + } + - pattern: | + if ($X != api) { + ... + } + - pattern: | + if (api !== $X) { + ... + } + - pattern: | + if ($X !== api) { + ... + } + - pattern: | + if (apiKey != $X) { + ... + } + - pattern: | + if ($X != apiKey) { + ... + } + - pattern: | + if (apiKey !== $X) { + ... + } + - pattern: | + if ($X !== apiKey) { + ... + } + - pattern: | + if (apiSecret != $X) { + ... + } + - pattern: | + if ($X != apiSecret) { + ... + } + - pattern: | + if (apiSecret !== $X) { + ... + } + - pattern: | + if ($X !== apiSecret) { + ... + } + - pattern: | + if (token != $X) { + ... + } + - pattern: | + if ($X != token) { + ... + } + - pattern: | + if (token !== $X) { + ... + } + - pattern: | + if ($X !== token) { + ... + } + - pattern: | + if (hash != $X) { + ... + } + - pattern: | + if ($X != hash) { + ... + } + - pattern: | + if (hash !== $X) { + ... + } + - pattern: | + if ($X !== hash) { + ... + } + - pattern: | + if (auth_token != $X) { + ... + } + - pattern: | + if ($X != auth_token) { + ... + } + - pattern: | + if (auth_token !== $X) { + ... + } + - pattern: | + if ($X !== auth_token) { + ... + } + - pattern: | + return $X === auth_token; + - pattern: | + return auth_token === $X; + - pattern: | + return $X === token; + - pattern: | + return token === $X; + - pattern: | + return $X === hash; + - pattern: | + return hash === $X; + - pattern: | + return $X === password; + - pattern: | + return password === $X; + - pattern: | + return $X === pass; + - pattern: | + return pass === $X; + - pattern: | + return $X === apiKey; + - pattern: | + return apiKey === $X; + - pattern: | + return $X === apiSecret; + - pattern: | + return apiSecret === $X; + - pattern: | + return $X === api_key; + - pattern: | + return api_key === $X; + - pattern: | + return $X === api_secret; + - pattern: | + return api_secret === $X; + - pattern: | + return $X === secret; + - pattern: | + return secret === $X; + - pattern: | + return $X === api; + - pattern: | + return api === $X; + - pattern: | + return $X == auth_token; + - pattern: | + return auth_token == $X; + - pattern: | + return $X == token; + - pattern: | + return token == $X; + - pattern: | + return $X == hash; + - pattern: | + return hash == $X; + - pattern: | + return $X == password; + - pattern: | + return password == $X; + - pattern: | + return $X == pass; + - pattern: | + return pass == $X; + - pattern: | + return $X == apiKey; + - pattern: | + return apiKey == $X; + - pattern: | + return $X == apiSecret; + - pattern: | + return apiSecret == $X; + - pattern: | + return $X == api_key; + - pattern: | + return api_key == $X; + - pattern: | + return $X == api_secret; + - pattern: | + return api_secret == $X; + - pattern: | + return $X == secret; + - pattern: | + return secret == $X; + - pattern: | + return $X == api; + - pattern: | + return api == $X; + - pattern: | + return $X !== auth_token; + - pattern: | + return auth_token !== $X; + - pattern: | + return $X !== token; + - pattern: | + return token !== $X; + - pattern: | + return $X !== hash; + - pattern: | + return hash !== $X; + - pattern: | + return $X !== password; + - pattern: | + return password !== $X; + - pattern: | + return $X !== pass; + - pattern: | + return pass !== $X; + - pattern: | + return $X !== apiKey; + - pattern: | + return apiKey !== $X; + - pattern: | + return $X !== apiSecret; + - pattern: | + return apiSecret !== $X; + - pattern: | + return $X !== api_key; + - pattern: | + return api_key !== $X; + - pattern: | + return $X !== api_secret; + - pattern: | + return api_secret !== $X; + - pattern: | + return $X !== secret; + - pattern: | + return secret !== $X; + - pattern: | + return $X !== api; + - pattern: | + return api !== $X; + - pattern: | + return $X != auth_token; + - pattern: | + return auth_token != $X; + - pattern: | + return $X != token; + - pattern: | + return token != $X; + - pattern: | + return $X != hash; + - pattern: | + return hash != $X; + - pattern: | + return $X != password; + - pattern: | + return password != $X; + - pattern: | + return $X != pass; + - pattern: | + return pass != $X; + - pattern: | + return $X != apiKey; + - pattern: | + return apiKey != $X; + - pattern: | + return $X != apiSecret; + - pattern: | + return apiSecret != $X; + - pattern: | + return $X != api_key; + - pattern: | + return api_key != $X; + - pattern: | + return $X != api_secret; + - pattern: | + return api_secret != $X; + - pattern: | + return $X != secret; + - pattern: | + return secret != $X; + - pattern: | + return $X != api; + - pattern: | + return api != $X; + severity: "WARNING" + message: | + The application was found executing string comparisons using one of `===`, `!==`, `==` or `!=` + against security sensitive values. String comparisons like this are not constant time, meaning + the + first character found not to match in the two strings will immediately exit the conditional + statement. + This allows an adversary to calculate or observe small timing differences depending on the + strings + passed to this comparison. This potentially allows an adversary the ability to brute force a + string + that will match the expected value by monitoring different character values. + + To remediate this issue, use the `crypto.timingSafeEqual` method when comparing strings. + + Example using `crypto.timingSafeEqual` to safely compare strings: + ``` + function constantTimeIsPasswordEqual(userInput) { + // Retrieve the password from a secure data store such as a KMS or Hashicorp's vault. + const password = getPasswordFromSecureDataStore(); + // Use crypto timingSafeEqual to ensure the comparison is done in constant time. + return crypto.timingSafeEqual(Buffer.from(userInput, 'utf-8'), Buffer.from(password, + 'utf-8')); + } + ``` + + For more information on constant time comparison see: + - https://nodejs.org/api/crypto.html#crypto_crypto_timingsafeequal_a_b + metadata: + cwe: "CWE-208" + shortDescription: "Observable timing discrepancy" + category: "security" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + security-severity: "Medium" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/assert/rule-assert-used.py b/compliance-agent/rules/vendor/gitlab/upstream/python/assert/rule-assert-used.py new file mode 100644 index 0000000..bef9956 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/assert/rule-assert-used.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# License: MIT (c) GitLab Inc. + +# ruleid: python_assert_rule-assert-used +assert True + +def test_function(): + # ruleid: python_assert_rule-assert-used + assert 1 == 1 + +def test_function2(): + # ruleid: python_assert_rule-assert-used + assert("test") diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/assert/rule-assert-used.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/assert/rule-assert-used.yml new file mode 100644 index 0000000..d29c7b8 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/assert/rule-assert-used.yml @@ -0,0 +1,52 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_assert_rule-assert-used" + languages: + - "python" + message: | + The application was found using `assert` in non-test code. Usually reserved for debug and test + code, the `assert` + function is commonly used to test conditions before continuing execution. However, enclosed + code will be removed + when compiling Python code to optimized byte code. Depending on the assertion and subsequent + logic, this could + lead to undefined behavior of the application or application crashes. + + To remediate this issue, remove the `assert` calls. If necessary, replace them with either `if` + conditions or + `try/except` blocks. + + Example using `try/except` instead of `assert`: + ``` + # Below try/except is equal to the assert statement of: + # assert user.is_authenticated(), "user must be authenticated" + try: + if not user.is_authenticated(): + raise AuthError("user must be authenticated") + except AuthError as e: + # Handle error + # ... + # Return, do not continue processing + return + ``` + metadata: + cwe: "CWE-754" + category: "security" + shortDescription: "Improper check for unusual or exceptional conditions" + owasp: + - "A6:2017-Security Misconfiguration" + - "A05:2021-Security Misconfiguration" + - "A10:2025-Mishandling of Exceptional Conditions" + security-severity: "Info" + patterns: + - pattern: "assert(...)" + - pattern-not-inside: | + import pytest + ... + - pattern-not-inside: | + import unittest + ... + severity: "INFO" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/bind_all_interfaces/rule-general-bindall-interfaces.py b/compliance-agent/rules/vendor/gitlab/upstream/python/bind_all_interfaces/rule-general-bindall-interfaces.py new file mode 100644 index 0000000..cc187d7 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/bind_all_interfaces/rule-general-bindall-interfaces.py @@ -0,0 +1,10 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/binding.py +# hash: 8eee173 + +import socket + +# ruleid: python_bind-all-interfaces_rule-general-bindall-interfaces +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +s.bind(('0.0.0.0', 31137)) +s.bind(('192.168.0.1', 8080)) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/bind_all_interfaces/rule-general-bindall-interfaces.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/bind_all_interfaces/rule-general-bindall-interfaces.yml new file mode 100644 index 0000000..b642e26 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/bind_all_interfaces/rule-general-bindall-interfaces.yml @@ -0,0 +1,57 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_bind-all-interfaces_rule-general-bindall-interfaces" + languages: + - "python" + message: | + Binding to all network interfaces can potentially open up a service to + traffic on unintended interfaces, that may not be properly documented or + secured. By passing "0.0.0.0", "::" or an empty string as the address to the `socket.bind` + function, + the application will bind to all interfaces. + + Consider passing in the interface ip address through an environment variable, + configuration file, or by determining the primary interface(s) IP address. + + Example getting the IP address from an environment variable `IP_ADDRESS`: + ``` + # Get the IP_ADDRESS env variable, or bind to + # 127.0.0.1 if it is not set + address = os.getenv("IP_ADDRESS", "127.0.0.1") + # Create an internet socket + sock = socket.socket(socket.AF_INET) + # Set the port to listen on + port = 9777 + # Bind to the address and port combination + sock.bind((address, port)) + # Listen for connections + sock.listen() + # Handle the connection + ``` + patterns: + - pattern-either: + - pattern: | + $S = socket.socket(...) + ... + $S.bind(("0.0.0.0", ...)) + - pattern: | + $S = socket.socket(...) + ... + $S.bind(("::", ...)) + - pattern: | + $S = socket.socket(...) + ... + $S.bind(("", ...)) + metadata: + category: "security" + owasp: + - "A6:2017-Security Misconfiguration" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + shortDescription: "Binding to an unrestricted IP address" + cwe: "CWE-1327" + security-severity: "Low" + severity: "INFO" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-cipher-modes.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-cipher-modes.py new file mode 100644 index 0000000..34a2f0d --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-cipher-modes.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/cipher-modes.py +# hash: 8eee173 + +from cryptography.hazmat.primitives.ciphers.modes import CBC +from cryptography.hazmat.primitives.ciphers.modes import ECB + + +# Insecure mode +# ruleid: python_crypto_rule-cipher-modes +mode = ECB(iv) + +# Secure cipher and mode +cipher = AES.new(key, blockalgo.MODE_CTR, iv) + +# Secure mode +mode = CBC(iv) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-cipher-modes.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-cipher-modes.yml new file mode 100644 index 0000000..f34f74b --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-cipher-modes.yml @@ -0,0 +1,79 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-cipher-modes" + languages: + - "python" + message: | + Cryptographic algorithms provide many different modes of operation, only some of which provide + message integrity. Without message integrity it could be possible for an adversary to attempt + to tamper with the ciphertext which could lead to compromising the encryption key. Newer + algorithms + apply message integrity to validate ciphertext has not been tampered with. + + Instead of using an algorithm that requires configuring a cipher mode, an algorithm + that has built-in message integrity should be used. Consider using `ChaCha20Poly1305` or + `AES-256-GCM` instead. + + For older applications that don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is + recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Example using `ChaCha20Poly1305`: + ``` + import os + # Import ChaCha20Poly1305 from cryptography + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = ChaCha20Poly1305.generate_key() + # Create a new ChaCha20Poly1305 instance with our secure key + chacha = ChaCha20Poly1305(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = chacha.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + chacha.decrypt(nonce, cipher_text, aad) + ``` + + Example using `AESGCM`: + ``` + import os + # Import AESGCM from cryptography + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = AESGCM.generate_key(bit_length=128) + # Create a new AESGCM instance with our secure key + aesgcm = AESGCM(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + aesgcm.decrypt(nonce, cipher_text, aad) + ``` + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + pattern: "cryptography.hazmat.primitives.ciphers.modes.ECB(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-blowfish.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-blowfish.py new file mode 100644 index 0000000..1b1742a --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-blowfish.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ciphers.py +# hash: 8eee173 + +from Crypto.Cipher import Blowfish as pycrypto_blowfish +from Cryptodome.Cipher import Blowfish as pycryptodomex_blowfish + + +iv = Random.new().read(bs) +key = b'An arbitrarily long key' +plaintext = b'docendo discimus ' +plen = bs - divmod(len(plaintext),bs)[1] +padding = [plen]*plen +padding = pack('b'*plen, *padding) +bs = pycrypto_blowfish.block_size +# ruleid: python_crypto_rule-crypto-cipher-blowfish +cipher = pycrypto_blowfish.new(key, pycrypto_blowfish.MODE_CBC, iv) +msg = iv + cipher.encrypt(plaintext + padding) +bs = pycryptodomex_blowfish.block_size +# ruleid: python_crypto_rule-crypto-cipher-blowfish +cipher = pycryptodomex_blowfish.new(key, pycryptodomex_blowfish.MODE_CBC, iv) +msg = iv + cipher.encrypt(plaintext + padding) + + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-blowfish.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-blowfish.yml new file mode 100644 index 0000000..0bddb0f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-blowfish.yml @@ -0,0 +1,82 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-cipher-blowfish" + languages: + - "python" + message: | + The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created in + 1993. Smaller key sizes may make the ciphertext vulnerable to [birthday + attacks](https://en.wikipedia.org/wiki/Birthday_attack). While no known attacks against + Blowfish + exist, it should never be used to encrypt files over 4GB in size. If possible consider + using ChaCha20Poly1305 or AES-GCM instead of Blowfish. + + For older applications that don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is + recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example using `ChaCha20Poly1305`: + ``` + import os + # Import ChaCha20Poly1305 from cryptography + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = ChaCha20Poly1305.generate_key() + # Create a new ChaCha20Poly1305 instance with our secure key + chacha = ChaCha20Poly1305(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = chacha.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + chacha.decrypt(nonce, cipher_text, aad) + ``` + + Example using `AESGCM`: + ``` + import os + # Import AESGCM from cryptography + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = AESGCM.generate_key(bit_length=128) + # Create a new AESGCM instance with our secure key + aesgcm = AESGCM(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + aesgcm.decrypt(nonce, cipher_text, aad) + ``` + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "Cryptodome.Cipher.Blowfish.new(...)" + - pattern: "Crypto.Cipher.Blowfish.new(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-des.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-des.py new file mode 100644 index 0000000..4913a4b --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-des.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ciphers.py +# hash: 8eee173 + +from Crypto.Cipher import DES as pycrypto_des +from Cryptodome.Cipher import DES as pycryptodomex_des +from Crypto import Random +from Crypto.Util import Counter + +key = b'-8B key-' +plaintext = b'We are no longer the knights who say ni!' +nonce = Random.new().read(pycrypto_des.block_size/2) +ctr = Counter.new(pycrypto_des.block_size*8/2, prefix=nonce) +# ruleid: python_crypto_rule-crypto-cipher-des +cipher = pycrypto_des.new(key, pycrypto_des.MODE_CTR, counter=ctr) +msg = nonce + cipher.encrypt(plaintext) +nonce = Random.new().read(pycryptodomex_des.block_size/2) +ctr = Counter.new(pycryptodomex_des.block_size*8/2, prefix=nonce) +# ruleid: python_crypto_rule-crypto-cipher-des +cipher = pycryptodomex_des.new(key, pycryptodomex_des.MODE_CTR, counter=ctr) +msg = nonce + cipher.encrypt(plaintext) + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-des.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-des.yml new file mode 100644 index 0000000..fe42b44 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-des.yml @@ -0,0 +1,80 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-cipher-des" + languages: + - "python" + message: | + DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms. + Newer algorithms apply message integrity to validate ciphertext has not been tampered + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + alternatives such as `AES-256-GCM`. + + For older applications that don't have support for `ChaCha20Poly1305`, + `AES-256-GCM` is recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example using `ChaCha20Poly1305`: + ``` + import os + # Import ChaCha20Poly1305 from cryptography + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = ChaCha20Poly1305.generate_key() + # Create a new ChaCha20Poly1305 instance with our secure key + chacha = ChaCha20Poly1305(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = chacha.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + chacha.decrypt(nonce, cipher_text, aad) + ``` + + Example using `AESGCM`: + ``` + import os + # Import AESGCM from cryptography + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = AESGCM.generate_key(bit_length=128) + # Create a new AESGCM instance with our secure key + aesgcm = AESGCM(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + aesgcm.decrypt(nonce, cipher_text, aad) + ``` + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "Cryptodome.Cipher.DES.new(...)" + - pattern: "Crypto.Cipher.DES.new(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc2.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc2.py new file mode 100644 index 0000000..1cfa0f8 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc2.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ciphers.py +# hash: 8eee173 + +from Crypto.Cipher import ARC2 as pycrypto_arc2 +from Cryptodome.Cipher import ARC2 as pycryptodomex_arc2 +from Crypto import Random + +key = b'Sixteen byte key' +iv = Random.new().read(pycrypto_arc2.block_size) +# ruleid: python_crypto_rule-crypto-cipher-rc2 +cipher = pycrypto_arc2.new(key, pycrypto_arc2.MODE_CFB, iv) +msg = iv + cipher.encrypt(b'Attack at dawn') +# ruleid: python_crypto_rule-crypto-cipher-rc2 +cipher = pycryptodomex_arc2.new(key, pycryptodomex_arc2.MODE_CFB, iv) +msg = iv + cipher.encrypt(b'Attack at dawn') + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc2.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc2.yml new file mode 100644 index 0000000..c7929b3 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc2.yml @@ -0,0 +1,80 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-cipher-rc2" + languages: + - "python" + message: | + DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms. + Newer algorithms apply message integrity to validate ciphertext has not been tampered + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + alternatives such as `AES-256-GCM`. + + For older applications that don't have support for `ChaCha20Poly1305`, + `AES-256-GCM` is recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example using `ChaCha20Poly1305`: + ``` + import os + # Import ChaCha20Poly1305 from cryptography + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = ChaCha20Poly1305.generate_key() + # Create a new ChaCha20Poly1305 instance with our secure key + chacha = ChaCha20Poly1305(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = chacha.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + chacha.decrypt(nonce, cipher_text, aad) + ``` + + Example using `AESGCM`: + ``` + import os + # Import AESGCM from cryptography + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = AESGCM.generate_key(bit_length=128) + # Create a new AESGCM instance with our secure key + aesgcm = AESGCM(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + aesgcm.decrypt(nonce, cipher_text, aad) + ``` + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "Cryptodome.Cipher.ARC2.new(...)" + - pattern: "Crypto.Cipher.ARC2.new" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc4.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc4.py new file mode 100644 index 0000000..4fb8685 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc4.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ciphers.py +# hash: 8eee173 + +from Crypto.Cipher import ARC4 as pycrypto_arc4 +from Cryptodome.Cipher import ARC4 as pycryptodomex_arc4 +from Crypto.Hash import SHA +from Crypto import Random + +key = b'Very long and confidential key' +nonce = Random.new().read(16) +tempkey = SHA.new(key+nonce).digest() +# ruleid: python_crypto_rule-crypto-cipher-rc4 +cipher = pycrypto_arc4.new(tempkey) +msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL') +# ruleid: python_crypto_rule-crypto-cipher-rc4 +cipher = pycryptodomex_arc4.new(tempkey) +msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL') diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc4.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc4.yml new file mode 100644 index 0000000..1ca7819 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-rc4.yml @@ -0,0 +1,80 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-cipher-rc4" + languages: + - "python" + message: | + DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms. + Newer algorithms apply message integrity to validate ciphertext has not been tampered + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + alternatives such as `AES-256-GCM`. + + For older applications that don't have support for `ChaCha20Poly1305`, + `AES-256-GCM` is recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example using `ChaCha20Poly1305`: + ``` + import os + # Import ChaCha20Poly1305 from cryptography + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = ChaCha20Poly1305.generate_key() + # Create a new ChaCha20Poly1305 instance with our secure key + chacha = ChaCha20Poly1305(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = chacha.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + chacha.decrypt(nonce, cipher_text, aad) + ``` + + Example using `AESGCM`: + ``` + import os + # Import AESGCM from cryptography + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = AESGCM.generate_key(bit_length=128) + # Create a new AESGCM instance with our secure key + aesgcm = AESGCM(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + aesgcm.decrypt(nonce, cipher_text, aad) + ``` + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "Cryptodome.Cipher.ARC4.new(...)" + - pattern: "Crypto.Cipher.ARC4.new(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-xor.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-xor.py new file mode 100644 index 0000000..21e82a2 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-xor.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ciphers.py +# hash: 8eee173 + +from Crypto.Cipher import XOR as pycrypto_xor +from Cryptodome.Cipher import XOR as pycryptodomex_xor + +key = b'Super secret key' +plaintext = b'Encrypt me' +# ruleid: python_crypto_rule-crypto-cipher-xor +cipher = pycrypto_xor.new(key) +msg = cipher.encrypt(plaintext) +# ruleid: python_crypto_rule-crypto-cipher-xor +cipher = pycryptodomex_xor.new(key) +msg = cipher.encrypt(plaintext) + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-xor.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-xor.yml new file mode 100644 index 0000000..0b146e8 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-cipher-xor.yml @@ -0,0 +1,80 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-cipher-xor" + languages: + - "python" + message: | + The application was found using the `xor` algorithm, which can be trivially decoded. + Newer algorithms apply message integrity to validate ciphertext has not been tampered + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + alternatives such as `AES-256-GCM`. + + For older applications that don't have support for `ChaCha20Poly1305`, + `AES-256-GCM` is recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example using `ChaCha20Poly1305`: + ``` + import os + # Import ChaCha20Poly1305 from cryptography + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = ChaCha20Poly1305.generate_key() + # Create a new ChaCha20Poly1305 instance with our secure key + chacha = ChaCha20Poly1305(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = chacha.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + chacha.decrypt(nonce, cipher_text, aad) + ``` + + Example using `AESGCM`: + ``` + import os + # Import AESGCM from cryptography + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = AESGCM.generate_key(bit_length=128) + # Create a new AESGCM instance with our secure key + aesgcm = AESGCM(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + aesgcm.decrypt(nonce, cipher_text, aad) + ``` + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "Cryptodome.Cipher.XOR.new(...)" + - pattern: "Crypto.Cipher.XOR.new(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-encrypt-dsa-rsa.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-encrypt-dsa-rsa.py new file mode 100644 index 0000000..b5eae69 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-encrypt-dsa-rsa.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/weak_cryptographic_key_sizes.py +# hash: 8eee173 + +from cryptography.hazmat import backends +from cryptography.hazmat.primitives.asymmetric import dsa +from cryptography.hazmat.primitives.asymmetric import rsa +from Crypto.PublicKey import DSA as pycrypto_dsa +from Crypto.PublicKey import RSA as pycrypto_rsa +from Cryptodome.PublicKey import DSA as pycryptodomex_dsa +from Cryptodome.PublicKey import RSA as pycryptodomex_rsa + + +# Correct +dsa.generate_private_key(key_size=2048, + backend=backends.default_backend()) +rsa.generate_private_key(public_exponent=65537, + key_size=2048, + backend=backends.default_backend()) +pycrypto_dsa.generate(bits=2048) +pycrypto_rsa.generate(bits=2048) +pycryptodomex_dsa.generate(bits=2048) +pycryptodomex_rsa.generate(bits=2048) + +# Also correct: without keyword args +dsa.generate_private_key(4096, + backends.default_backend()) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +rsa.generate_private_key(3, + 4096, + backends.default_backend()) +pycrypto_dsa.generate(4096) +pycrypto_rsa.generate(4096) +pycryptodomex_dsa.generate(4096) +pycryptodomex_rsa.generate(4096) + +# Incorrect: weak key sizes +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +dsa.generate_private_key(key_size=1024, + backend=backends.default_backend()) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +rsa.generate_private_key(public_exponent=65537, + key_size=1024, + backend=backends.default_backend()) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +pycrypto_dsa.generate(bits=1024) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +pycrypto_rsa.generate(bits=1024) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +pycryptodomex_dsa.generate(bits=1024) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +pycryptodomex_rsa.generate(bits=1024) + +# Also incorrect: without keyword args +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +dsa.generate_private_key(512, + backends.default_backend()) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +rsa.generate_private_key(3, + 512, + backends.default_backend()) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +pycrypto_dsa.generate(512) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +pycrypto_rsa.generate(512) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +pycryptodomex_dsa.generate(512) +# ruleid: python_crypto_rule-crypto-encrypt-dsa-rsa +pycryptodomex_rsa.generate(512) + +# Don't crash when the size is variable +rsa.generate_private_key(public_exponent=65537, + key_size=some_key_size, + backend=backends.default_backend()) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-encrypt-dsa-rsa.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-encrypt-dsa-rsa.yml new file mode 100644 index 0000000..f180f44 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-encrypt-dsa-rsa.yml @@ -0,0 +1,80 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-encrypt-dsa-rsa" + languages: + - "python" + message: | + The application is generating an RSA key that is less than the recommended 2048 bits. + The National Institute of Standards and Technology (NIST) deprecated signing Digital + Certificates that contained RSA Public Keys of 1024 bits in December 2010. While + 1024-bit RSA keys have not been factored yet, advances in compute may make it possible + in the near future. + + Consider upgrading to the newer asymmetric algorithm such as `X25519` which handles + the complexities of generating key pairs and choosing correct key sizes for you: + ``` + from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey + + # Generate a private key for use in the exchange. + private_key = X25519PrivateKey.generate() + # Work with private key/exchange with a peer's + # public key to created a shared and derived key + # ... + ``` + + Otherwise use a key size greater than 2048 when generating RSA keys: + ``` + from cryptography.hazmat.primitives.asymmetric import rsa + # Generate a private key of 4096 bits + private_key = rsa.generate_private_key( + # do not change the exponent value from 65537 + public_exponent=65537, + key_size=4096, + ) + # Work with the private key to sign/encrypt data + # ... + ``` + + For more information on using the cryptography module see: + - https://cryptography.io/en/latest + metadata: + cwe: "CWE-326" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Inadequate encryption strength" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: | + cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(...,key_size=$SIZE,...) + - pattern: | + cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key($EXP, $SIZE,...) + - pattern: | + cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key($SIZE, ...) + - pattern: | + cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key(...,key_size=$SIZE,...) + - pattern: | + cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key($EXP, $SIZE, ...) + - pattern: "cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key($SIZE,...)" + - pattern: "Crypto.PublicKey.RSA.generate($SIZE, ...)" + - pattern: "Crypto.PublicKey.DSA.generate($SIZE, ...)" + - pattern: "Cryptodome.PublicKey.DSA.generate($SIZE, ...)" + - pattern: "Cryptodome.PublicKey.RSA.generate($SIZE, ...)" + - pattern: "Crypto.PublicKey.DSA.generate(bits=$SIZE, ...)" + - pattern: "Cryptodome.PublicKey.DSA.generate(bits=$SIZE, ...)" + - pattern: "pycrypto_rsa.generate(bits=$SIZE, ...)" + - pattern: "pycrypto_dsa.generate(bits=$SIZE, ...)" + - pattern: "pycryptodomex_rsa.generate(bits=$SIZE, ...)" + - pattern: "pycryptodomex_rsa.generate($SIZE, ...)" + - pattern: "pycryptodomex_dsa.generate(bits=$SIZE, ...)" + - pattern: "pycryptodomex_dsa.generate($SIZE, ...)" + - metavariable-comparison: + comparison: "$SIZE < 2048" + metavariable: "$SIZE" + severity: "ERROR" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-md5.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-md5.py new file mode 100644 index 0000000..b3959f1 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-md5.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/crypto-md5.py +# hash: 8eee173 + +from Crypto.Hash import MD5 as pycrypto_md5 +from Cryptodome.Hash import MD5 as pycryptodomex_md5 + +# ruleid: python_crypto_rule-crypto-hash-md5 +pycrypto_md5.new() + +# ruleid: python_crypto_rule-crypto-hash-md5 +pycryptodomex_md5.new() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-md5.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-md5.yml new file mode 100644 index 0000000..c218737 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-md5.yml @@ -0,0 +1,56 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-hash-md5" + languages: + - "python" + message: | + The application was found using an insecure or risky digest or signature algorithm. MD5 + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + a custom algorithm is prone to errors. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example of creating a SHA-384 hash using the `cryptography` package: + ``` + from cryptography.hazmat.primitives import hashes + # Create a SHA384 digest + digest = hashes.Hash(hashes.SHA384()) + # Update the digest with some initial data + digest.update(b"some data to hash") + # Add more data to the digest + digest.update(b"some more data") + # Finalize the digest as bytes + result = digest.finalize() + ``` + + For more information on secure password storage see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "Crypto.Hash.MD5.new(...)" + - pattern: "Cryptodome.Hash.MD5.new (...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-sha1.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-sha1.py new file mode 100644 index 0000000..75a074f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-sha1.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/crypto-md5.py +# hash: 8eee173 + +from Crypto.Hash import SHA as pycrypto_sha +from Cryptodome.Hash import SHA as pycryptodomex_sha + +# ruleid: python_crypto_rule-crypto-hash-sha1 +pycrypto_sha.new() + +# ruleid: python_crypto_rule-crypto-hash-sha1 +pycryptodomex_sha.new() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-sha1.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-sha1.yml new file mode 100644 index 0000000..2270e61 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hash-sha1.yml @@ -0,0 +1,56 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-hash-sha1" + languages: + - "python" + message: | + The application was found using an insecure or risky digest or signature algorithm. MD5 + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + a custom algorithm is prone to errors. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example of creating a SHA-384 hash using the `cryptography` package: + ``` + from cryptography.hazmat.primitives import hashes + # Create a SHA384 digest + digest = hashes.Hash(hashes.SHA384()) + # Update the digest with some initial data + digest.update(b"some data to hash") + # Add more data to the digest + digest.update(b"some more data") + # Finalize the digest as bytes + result = digest.finalize() + ``` + + For more information on secure password storage see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "Crypto.Hash.SHA.new(...)" + - pattern: "Cryptodome.Hash.SHA.new (...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-arc4.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-arc4.py new file mode 100644 index 0000000..2b919d0 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-arc4.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ciphers.py +# hash: 8eee173 + +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.hazmat.primitives.ciphers import algorithms + +# ruleid: python_crypto_rule-crypto-hazmat-cipher-arc4 +cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) +encryptor = cipher.encryptor() +ct = encryptor.update(b"a secret message") + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-arc4.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-arc4.yml new file mode 100644 index 0000000..e93a94c --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-arc4.yml @@ -0,0 +1,74 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-hazmat-cipher-arc4" + languages: + - "python" + message: | + DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms. + Newer algorithms apply message integrity to validate ciphertext has not been tampered + with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the + alternatives such as `AES-256-GCM`. + + For older applications that don't have support for `ChaCha20Poly1305`, + `AES-256-GCM` is recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Example using `ChaCha20Poly1305`: + ``` + import os + # Import ChaCha20Poly1305 from cryptography + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = ChaCha20Poly1305.generate_key() + # Create a new ChaCha20Poly1305 instance with our secure key + chacha = ChaCha20Poly1305(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = chacha.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + chacha.decrypt(nonce, cipher_text, aad) + ``` + + Example using `AESGCM`: + ``` + import os + # Import AESGCM from cryptography + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = AESGCM.generate_key(bit_length=128) + # Create a new AESGCM instance with our secure key + aesgcm = AESGCM(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + aesgcm.decrypt(nonce, cipher_text, aad) + ``` + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + pattern: "cryptography.hazmat.primitives.ciphers.algorithms.ARC4(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-blowfish.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-blowfish.py new file mode 100644 index 0000000..679f250 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-blowfish.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ciphers.py +# hash: 8eee173 + +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.hazmat.primitives.ciphers import algorithms + +# ruleid: python_crypto_rule-crypto-hazmat-cipher-blowfish +cipher = Cipher(algorithms.Blowfish(key), mode=None, backend=default_backend()) +encryptor = cipher.encryptor() +ct = encryptor.update(b"a secret message") + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-blowfish.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-blowfish.yml new file mode 100644 index 0000000..e852050 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-blowfish.yml @@ -0,0 +1,76 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-hazmat-cipher-blowfish" + languages: + - "python" + message: | + The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created in + 1993. Smaller key sizes may make the ciphertext vulnerable to [birthday + attacks](https://en.wikipedia.org/wiki/Birthday_attack). While no known attacks against + Blowfish + exist, it should never be used to encrypt files over 4GB in size. If possible consider + using ChaCha20Poly1305 or AES-GCM instead of Blowfish. + + For older applications that don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is + recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Example using `ChaCha20Poly1305`: + ``` + import os + # Import ChaCha20Poly1305 from cryptography + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = ChaCha20Poly1305.generate_key() + # Create a new ChaCha20Poly1305 instance with our secure key + chacha = ChaCha20Poly1305(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = chacha.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + chacha.decrypt(nonce, cipher_text, aad) + ``` + + Example using `AESGCM`: + ``` + import os + # Import AESGCM from cryptography + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = AESGCM.generate_key(bit_length=128) + # Create a new AESGCM instance with our secure key + aesgcm = AESGCM(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + aesgcm.decrypt(nonce, cipher_text, aad) + ``` + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + pattern: "cryptography.hazmat.primitives.ciphers.algorithms.Blowfish(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-idea.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-idea.py new file mode 100644 index 0000000..6fb6e51 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-idea.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ciphers.py +# hash: 8eee173 + +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.hazmat.primitives.ciphers import algorithms + +# ruleid: python_crypto_rule-crypto-hazmat-cipher-idea +cipher = Cipher(algorithms.IDEA(key), mode=None, backend=default_backend()) +encryptor = cipher.encryptor() +ct = encryptor.update(b"a secret message") + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-idea.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-idea.yml new file mode 100644 index 0000000..dc07e18 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-cipher-idea.yml @@ -0,0 +1,76 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto-hazmat-cipher-idea" + languages: + - "python" + message: | + The IDEA encryption algorithm was meant as a drop-in replacement for DES and was created in + 1991. A number of [vulnerabilities and + exploits](https://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm#Security) have + been identified to work against IDEA and + it is no longer recommended. If possible consider + using ChaCha20Poly1305 or AES-GCM instead of Blowfish. + + For older applications that don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is + recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Example using `ChaCha20Poly1305`: + ``` + import os + # Import ChaCha20Poly1305 from cryptography + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = ChaCha20Poly1305.generate_key() + # Create a new ChaCha20Poly1305 instance with our secure key + chacha = ChaCha20Poly1305(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = chacha.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + chacha.decrypt(nonce, cipher_text, aad) + ``` + + Example using `AESGCM`: + ``` + import os + # Import AESGCM from cryptography + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + # Our plaintext to encrypt + plain_text = b"Secret text to encrypt" + # We do not require authenticated but unencrypted data, so set to None + aad = None + # Generate a secure key + key = AESGCM.generate_key(bit_length=128) + # Create a new AESGCM instance with our secure key + aesgcm = AESGCM(key) + # Note: nonce values _must_ be regenerated every time they are used. + nonce = os.urandom(12) + # Encrypt our plaintext + cipher_text = aesgcm.encrypt(nonce, plain_text, aad) + # Decrypt the plain text using the nonce and cipher_text + aesgcm.decrypt(nonce, cipher_text, aad) + ``` + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + shortDescription: "Use of a Broken or Risky Cryptographic Algorithm" + security-severity: "Medium" + category: "security" + pattern: "cryptography.hazmat.primitives.ciphers.algorithms.IDEA(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-md5.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-md5.py new file mode 100644 index 0000000..bac1dc0 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-md5.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/crypto-md5.py +# hash: 8eee173 + +from cryptography.hazmat.primitives import hashes + +# ruleid: python_crypto_rule-crypto.hazmat-hash-md5 +hashes.MD5() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-md5.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-md5.yml new file mode 100644 index 0000000..8427a10 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-md5.yml @@ -0,0 +1,50 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto.hazmat-hash-md5" + languages: + - "python" + message: | + The application was found using an insecure or risky digest or signature algorithm. MD2, MD5 + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + a custom algorithm is prone to errors. + + Example of creating a SHA-384 hash using the `cryptography` package: + ``` + from cryptography.hazmat.primitives import hashes + # Create a SHA384 digest + digest = hashes.Hash(hashes.SHA384()) + # Update the digest with some initial data + digest.update(b"some data to hash") + # Add more data to the digest + digest.update(b"some more data") + # Finalize the digest as bytes + result = digest.finalize() + ``` + + For more information on secure password storage see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + category: "security" + pattern: "cryptography.hazmat.primitives.hashes.MD5(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-sha1.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-sha1.py new file mode 100644 index 0000000..200756f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-sha1.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/crypto-md5.py +# hash: 8eee173 + +from cryptography.hazmat.primitives import hashes + +# ruleid: python_crypto_rule-crypto.hazmat-hash-sha1 +hashes.SHA1() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-sha1.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-sha1.yml new file mode 100644 index 0000000..7a5a83c --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-crypto-hazmat-hash-sha1.yml @@ -0,0 +1,50 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-crypto.hazmat-hash-sha1" + languages: + - "python" + message: | + The application was found using an insecure or risky digest or signature algorithm. MD2, MD5 + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + a custom algorithm is prone to error. + + Example of creating a SHA-384 hash using the `cryptography` package: + ``` + from cryptography.hazmat.primitives import hashes + # Create a SHA384 digest + digest = hashes.Hash(hashes.SHA384()) + # Update the digest with some initial data + digest.update(b"some data to hash") + # Add more data to the digest + digest.update(b"some more data") + # Finalize the digest as bytes + result = digest.finalize() + ``` + + For more information on secure password storage see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + pattern: "cryptography.hazmat.primitives.hashes.SHA1(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md2.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md2.py new file mode 100644 index 0000000..84905ea --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md2.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/crypto-md5.py +# hash: 8eee173 + +from Crypto.Hash import MD2 as pycrypto_md2 +from Cryptodome.Hash import MD2 as pycryptodomex_md2 + +# ruleid: python_crypto_rule-hash-md2 +pycrypto_md2.new() +# ruleid: python_crypto_rule-hash-md2 +pycryptodomex_md2.new() + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md2.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md2.yml new file mode 100644 index 0000000..2f969f1 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md2.yml @@ -0,0 +1,54 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-hash-md2" + languages: + - "python" + message: | + The application was found using an insecure or risky digest or signature algorithm. MD2, MD5 + and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example of creating a SHA-384 hash using the `cryptography` package: + ``` + from cryptography.hazmat.primitives import hashes + # Create a SHA384 digest + digest = hashes.Hash(hashes.SHA384()) + # Update the digest with some initial data + digest.update(b"some data to hash") + # Add more data to the digest + digest.update(b"some more data") + # Finalize the digest as bytes + result = digest.finalize() + ``` + + For more information on secure password storage see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "Crypto.Hash.MD2.new(...)" + - pattern: "Cryptodome.Hash.MD2.new (...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md4.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md4.py new file mode 100644 index 0000000..bd026ba --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md4.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/crypto-md5.py +# hash: 8eee173 + +from Crypto.Hash import MD4 as pycrypto_md4 +from Cryptodome.Hash import MD4 as pycryptodomex_md4 + +# ruleid: python_crypto_rule-hash-md4 +pycrypto_md4.new() + +# ruleid: python_crypto_rule-hash-md4 +pycryptodomex_md4.new() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md4.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md4.yml new file mode 100644 index 0000000..fc48267 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md4.yml @@ -0,0 +1,54 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-hash-md4" + languages: + - "python" + message: | + The application was found using an insecure or risky digest or signature algorithm. MD2, MD4, + MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example of creating a SHA-384 hash using the `cryptography` package: + ``` + from cryptography.hazmat.primitives import hashes + # Create a SHA384 digest + digest = hashes.Hash(hashes.SHA384()) + # Update the digest with some initial data + digest.update(b"some data to hash") + # Add more data to the digest + digest.update(b"some more data") + # Finalize the digest as bytes + result = digest.finalize() + ``` + + For more information on secure password storage see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "Crypto.Hash.MD4.new(...)" + - pattern: "Cryptodome.Hash.MD4.new (...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md5.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md5.py new file mode 100644 index 0000000..cb2b83f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md5.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/crypto-md5.py +# hash: 8eee173 + +import hashlib + +# ruleid: python_crypto_rule-hash-md5 +hashlib.md5(1) +# ruleid: python_crypto_rule-hash-md5 +hashlib.md5(1).hexdigest() + +# ruleid: python_crypto_rule-hash-md5 +abc = str.replace(hashlib.md5("1"), "###") + +# ruleid: python_crypto_rule-hash-md5 +print(hashlib.md5("1")) + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md5.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md5.yml new file mode 100644 index 0000000..9374e34 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-md5.yml @@ -0,0 +1,51 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-hash-md5" + languages: + - "python" + message: | + The application was found using an insecure or risky digest or signature algorithm. MD2, MD4, + MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example of creating a SHA-384 hash using the `cryptography` package: + ``` + from cryptography.hazmat.primitives import hashes + # Create a SHA384 digest + digest = hashes.Hash(hashes.SHA384()) + # Update the digest with some initial data + digest.update(b"some data to hash") + # Add more data to the digest + digest.update(b"some more data") + # Finalize the digest as bytes + result = digest.finalize() + ``` + + For more information on secure password storage see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + pattern: "hashlib.md5(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-sha1.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-sha1.py new file mode 100644 index 0000000..1ede530 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-sha1.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/crypto-md5.py +# hash: 8eee173 + +import hashlib + +# ruleid: python_crypto_rule-hash-sha1 +hashlib.sha1(1) + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-sha1.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-sha1.yml new file mode 100644 index 0000000..e078474 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hash-sha1.yml @@ -0,0 +1,51 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-hash-sha1" + languages: + - "python" + message: | + The application was found using an insecure or risky digest or signature algorithm. MD2, MD4, + MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. + + Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for + new applications, instead consider using the [cryptography](https://cryptography.io/) package. + + Example of creating a SHA-384 hash using the `cryptography` package: + ``` + from cryptography.hazmat.primitives import hashes + # Create a SHA384 digest + digest = hashes.Hash(hashes.SHA384()) + # Update the digest with some initial data + digest.update(b"some data to hash") + # Add more data to the digest + digest.update(b"some more data") + # Finalize the digest as bytes + result = digest.finalize() + ``` + + For more information on secure password storage see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + + For more information on the cryptography module see: + - https://cryptography.io/en/latest/ + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + pattern: "hashlib.sha1(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hashlib-new-insecure-functions.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hashlib-new-insecure-functions.py new file mode 100644 index 0000000..46b1cad --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hashlib-new-insecure-functions.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/hashlib_new_insecure_functions.py +# hash: 8eee173 + +import hashlib + +# ruleid: python_crypto_rule-hashlib-new-insecure-functions +hashlib.new('md5') +# ruleid: python_crypto_rule-hashlib-new-insecure-functions +hashlib.new('md4', 'test') +# ruleid: python_crypto_rule-hashlib-new-insecure-functions +hashlib.new(name='md5', string='test') +# ruleid: python_crypto_rule-hashlib-new-insecure-functions +hashlib.new('MD4', string='test') +# ruleid: python_crypto_rule-hashlib-new-insecure-functions +hashlib.new(string='test', name='MD5') +# ruleid: python_crypto_rule-hashlib-new-insecure-functions +hashlib.new('sha1') +# ruleid: python_crypto_rule-hashlib-new-insecure-functions +hashlib.new(string='test', name='SHA1') +# ruleid: python_crypto_rule-hashlib-new-insecure-functions +hashlib.new('sha', string='test') +# ruleid: python_crypto_rule-hashlib-new-insecure-functions +hashlib.new(name='SHA', string='test') + +# Test that plugin does not flag valid hash functions. +hashlib.new('sha256') +hashlib.new('SHA512') + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hashlib-new-insecure-functions.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hashlib-new-insecure-functions.yml new file mode 100644 index 0000000..2c772d2 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-hashlib-new-insecure-functions.yml @@ -0,0 +1,51 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-hashlib-new-insecure-functions" + languages: + - "python" + message: | + The application was found using an insecure or risky digest or signature algorithm. MD2, MD4, + MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions. + + This means + that two different values, when hashed, can lead to the same hash value. If the application is + trying + to use these hash methods for storing passwords, then it is recommended to switch to a + password hashing + algorithm such as Argon2id or PBKDF2. + It is strongly recommended that a standard digest algorithm be chosen instead as implementing + a custom algorithm is prone to errors. + + Example using `hashlib.sha384()` to create a SHA384 hash: + ``` + import hashlib + # Create a SHA384 digest + digest = hashlib.sha384() + # Update the digest with some initial data + digest.update(b"some data to hash") + # Add more data to the digest + digest.update(b"some more data") + # Finalize the digest as bytes + digest.digest() + ``` + metadata: + cwe: "CWE-327" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of a broken or risky cryptographic algorithm" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "hashlib.new(\"=~/[M|m][D|d][4|5]/\", ...)" + - pattern: "hashlib.new(..., name=\"=~/[M|m][D|d][4|5]/\", ...)" + - pattern: "hashlib.new('sha1')" + - pattern: "hashlib.new(..., name='SHA1')" + - pattern: "hashlib.new('sha', string='test')" + - pattern: "hashlib.new(name='SHA', string='test')" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-import-pycrypto.py b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-import-pycrypto.py new file mode 100644 index 0000000..47a5b92 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-import-pycrypto.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/pycrypto.py +# hash: 8eee173 + +# ruleid: python_crypto_rule-import-pycrypto +import Crypto.Cipher +# ruleid: python_crypto_rule-import-pycrypto +import Crypto.Hash +# ruleid: python_crypto_rule-import-pycrypto +import Crypto.IO +# ruleid: python_crypto_rule-import-pycrypto +import Crypto.Protocol +# ruleid: python_crypto_rule-import-pycrypto +import Crypto.PublicKey +# ruleid: python_crypto_rule-import-pycrypto +import Crypto.Random +# ruleid: python_crypto_rule-import-pycrypto +import Crypto.Signature +# ruleid: python_crypto_rule-import-pycrypto +import Crypto.Util + +from . import CryptoMaterialsCacheEntry + +def test_pycrypto(): + key = b'Sixteen byte key' + iv = Random.new().read(AES.block_size) + cipher = pycrypto_arc2.new(key, AES.MODE_CFB, iv) + factory = CryptoMaterialsCacheEntry() + + +def test_pycrypto(): + key = b'Sixteen byte key' + iv = Random.new().read(AES.block_size) + cipher = pycrypto_arc2.new(key, AES.MODE_CFB, iv) + factory = CryptoMaterialsCacheEntry() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-import-pycrypto.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-import-pycrypto.yml new file mode 100644 index 0000000..2d47335 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/crypto/rule-import-pycrypto.yml @@ -0,0 +1,35 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_crypto_rule-import-pycrypto" + languages: + - "python" + message: | + The application was detected importing `pycrypto`. This package has been deprecated as it + contains + security vulnerabilities. + + To remediate this issue, consider using the [cryptography](https://cryptography.io/) + package instead. + metadata: + cwe: "CWE-1104" + owasp: + - "A9:2017-Using Components with Known Vulnerabilities" + - "A06:2021-Vulnerable and Outdated Components" + - "A03:2025-Software Supply Chain Failures" + category: "security" + shortDescription: "Use of unmaintained third party components" + security-severity: "Medium" + pattern-either: + - pattern: "import pycryto" + - pattern: "import Crypto.Cipher" + - pattern: "import Crypto.Hash" + - pattern: "import Crypto.IO" + - pattern: "import Crypto.Protocol" + - pattern: "import Crypto.PublicKey" + - pattern: "import Crypto.Random" + - pattern: "import Crypto.Signature" + - pattern: "import Crypto.Util" + severity: "ERROR" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-cpickle.py b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-cpickle.py new file mode 100644 index 0000000..0d2455b --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-cpickle.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/pickle_deserialize.py +# hash: 8eee173 + +import cPickle +import StringIO + +# cPickle +# ruleid: python_deserialization_rule-cpickle +serialized = cPickle.dumps({(): []}) +# ruleid: python_deserialization_rule-cpickle +print(cPickle.loads(serialized)) + +file_obj = StringIO.StringIO() +# ruleid: python_deserialization_rule-cpickle +cPickle.dump((1,), file_obj) +file_obj.seek(0) +# ruleid: python_deserialization_rule-cpickle +print(cPickle.load(file_obj)) + +file_obj.seek(0) +# ruleid: python_deserialization_rule-cpickle +print(cPickle.Unpickler(file_obj).load()) + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-cpickle.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-cpickle.yml new file mode 100644 index 0000000..1d93799 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-cpickle.yml @@ -0,0 +1,77 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_deserialization_rule-cpickle" + languages: + - "python" + message: | + The application was found using `cPickle` which is vulnerable to deserialization attacks. + Deserialization attacks exploit the process of reading serialized data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format + chosen allows + the application to specify exactly which object types are allowed to be deserialized. + + To protect against mass assignment, only allow deserialization of the specific fields that are + required. If this is not easily done, consider creating an intermediary type that + can be serialized with only the necessary fields exposed. + + Example JSON deserializer using an intermediary type that is validated against a schema to + ensure + it is safe from mass assignment: + ``` + import jsonschema + + # Create a schema to validate our user-supplied input against + # an intermediary object + intermediary_schema = { + "type" : "object", + "properties" : { + "name": {"type" : "string"} + }, + "required": ["name"], + # Protect against random properties being added to the object + "additionalProperties": False, + } + # If a user attempted to add "'is_admin': True" it would cause a validation error + intermediary_object = {'name': 'test user'} + + try: + # Validate the user supplied intermediary object against our schema + jsonschema.validate(instance=intermediary_object, schema=intermediary_schema) + user_object = {'user': + { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with the user_object + except jsonschema.exceptions.ValidationError as ex: + # Gracefully handle validation errors + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + metadata: + cwe: "CWE-502" + owasp: + - "A8:2017-Insecure Deserialization" + - "A08:2021-Software and Data Integrity Failures" + - "A08:2025-Software or Data Integrity Failures" + category: "security" + shortDescription: "Deserialization of untrusted data" + security-severity: "High" + pattern: "cPickle.$FUNC(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-pickle.py b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-pickle.py new file mode 100644 index 0000000..2c751a2 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-pickle.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/pickle_deserialize.py +# hash: 8eee173 + +import _pickle +import pickle +import os + +# pickle +pick = pickle.dumps({'a': 'b', 'c': 'd'}) + +with open('serialized.pkl', 'wb') as file: + pickle.dump([1, 2, '3'], file) + +# Unpickle +# ruleid: python_deserialization_rule-pickle +print(pickle.loads(pick)) +# ruleid: python_deserialization_rule-pickle +print(_pickle.loads(pick)) + +with open('serialized.pkl', 'rb') as file: + # ruleid: python_deserialization_rule-pickle + print(pickle.load(file)) + +with open('serialized.pkl', 'rb') as file: + # ruleid: python_deserialization_rule-pickle + print(_pickle.load(file)) + +with open('serialized.pkl', 'rb') as file: + # ruleid: python_deserialization_rule-pickle + print(pickle.Unpickler(file).load()) + +with open('serialized.pkl', 'rb') as file: + # ruleid: python_deserialization_rule-pickle + print(_pickle.Unpickler(file).load()) + +# Delete the file "serialized.pkl" +os.remove('serialized.pkl') + +# This will run the following command and list all the directories: ls ~ +# But this is okay because this string is not controlled by the attacker. +# And so hard-coded strings are okay. +# ok: python_deserialization_rule-pickle +pickle.loads(b"cos\nsystem\n(S\'ls ~\'\ntR.") + +aa = ["a", 'b', 3] +# ruleid: python_deserialization_rule-pickle +print(pickle.loads(pickle.dumps(aa))) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-pickle.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-pickle.yml new file mode 100644 index 0000000..11eddb3 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-pickle.yml @@ -0,0 +1,85 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_deserialization_rule-pickle" + languages: + - "python" + message: | + The application was found using `pickle` which is vulnerable to deserialization attacks. + Deserialization attacks exploit the process of reading serialized data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format + chosen allows the application to specify exactly which object types are allowed to be deserialized. + + To protect against mass assignment, only allow deserialization of the specific fields that are + required. If this is not easily done, consider creating an intermediary type that + can be serialized with only the necessary fields exposed. + + Example JSON deserializer using an intermediary type that is validated against a schema to ensure + it is safe from mass assignment: + ``` + import jsonschema + + # Create a schema to validate our user-supplied input against + # an intermediary object + intermediary_schema = { + "type" : "object", + "properties" : { + "name": {"type" : "string"} + }, + "required": ["name"], + # Protect against random properties being added to the object + "additionalProperties": False, + } + # If a user attempted to add "'is_admin': True" it would cause a validation error + intermediary_object = {'name': 'test user'} + + try: + # Validate the user supplied intermediary object against our schema + jsonschema.validate(instance=intermediary_object, schema=intermediary_schema) + user_object = {'user': + { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with the user_object + except jsonschema.exceptions.ValidationError as ex: + # Gracefully handle validation errors + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + metadata: + cwe: "CWE-502" + owasp: + - "A8:2017-Insecure Deserialization" + - "A08:2021-Software and Data Integrity Failures" + - "A08:2025-Software or Data Integrity Failures" + category: "security" + shortDescription: "Deserialization of untrusted data" + security-severity: "High" + patterns: + - pattern-either: + - patterns: + - pattern: "pickle.$METHOD(...)" + - pattern-not: "pickle.$METHOD(\"...\")" + - patterns: + - pattern: "_pickle.$METHOD(...)" + - pattern-not: "_pickle.$METHOD(\"...\")" + - metavariable-regex: + metavariable: "$METHOD" + regex: "(load|loads|Unpickler)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-shelve.py b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-shelve.py new file mode 100644 index 0000000..dd1aba8 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-shelve.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python +# License: MIT (c) GitLab Inc. + +# ruleid: python_deserialization_rule-shelve +shelve.open() +# ruleid: python_deserialization_rule-shelve +shelve.DbfilenameShelf() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-shelve.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-shelve.yml new file mode 100644 index 0000000..a6f39ea --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-shelve.yml @@ -0,0 +1,79 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_deserialization_rule-shelve" + languages: + - "python" + message: | + The application was found using `shelve` which is vulnerable to deserialization attacks as + it calls `pickle` internally. + Deserialization attacks exploit the process of reading serialized data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format + chosen allows + the application to specify exactly which object types are allowed to be deserialized. + + To protect against mass assignment, only allow deserialization of the specific fields that are + required. If this is not easily done, consider creating an intermediary type that + can be serialized with only the necessary fields exposed. + + Example JSON deserializer using an intermediary type that is validated against a schema to + ensure + it is safe from mass assignment: + ``` + import jsonschema + + # Create a schema to validate our user-supplied input against + # an intermediary object + intermediary_schema = { + "type" : "object", + "properties" : { + "name": {"type" : "string"} + }, + "required": ["name"], + # Protect against random properties being added to the object + "additionalProperties": False, + } + # If a user attempted to add "'is_admin': True" it would cause a validation error + intermediary_object = {'name': 'test user'} + + try: + # Validate the user supplied intermediary object against our schema + jsonschema.validate(instance=intermediary_object, schema=intermediary_schema) + user_object = {'user': + { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with the user_object + except jsonschema.exceptions.ValidationError as ex: + # Gracefully handle validation errors + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + metadata: + cwe: "CWE-502" + owasp: + - "A8:2017-Insecure Deserialization" + - "A08:2021-Software and Data Integrity Failures" + - "A08:2025-Software or Data Integrity Failures" + category: "security" + shortDescription: "Deserialization of untrusted data" + security-severity: "High" + pattern-either: + - pattern: "shelve.$FUNC(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-yaml-load.py b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-yaml-load.py new file mode 100644 index 0000000..e28196d --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-yaml-load.py @@ -0,0 +1,35 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/yaml_load.py +# hash: 8eee173 + +import json +import yaml + +def test_yaml_load(): + ystr = yaml.dump({'a': 1, 'b': 2, 'c': 3}) + # ruleid: python_deserialization_rule-yaml-load + y = yaml.load(ystr, Loader=yaml.FullLoader) + yaml.dump(y) + try: + yaml.load(ystr, Loader=yaml.CSafeLoader) + # ruleid: python_deserialization_rule-yaml-load + yaml.load(ystr, Loader=yaml.Loader) + # ruleid: python_deserialization_rule-yaml-load + yaml.load(ystr, Loader=yaml.CLoader) + # ruleid: python_deserialization_rule-yaml-load + yaml.load(ystr, Loader=yaml.UnsafeLoader) + # ruleid: python_deserialization_rule-yaml-load + yaml.load_all(ystr, Loader=yaml.Loader) + # ruleid: python_deserialization_rule-yaml-load + yaml.load_all(ystr, Loader=yaml.CLoader) + # ruleid: python_deserialization_rule-yaml-load + yaml.load_all(ystr, Loader=yaml.UnsafeLoader) + # ruleid: python_deserialization_rule-yaml-load + yaml.load_all(ystr, Loader=yaml.FullLoader) + except AttributeError: + # CSafeLoader only exists if you build yaml with LibYAML + y = yaml.load(ystr, Loader=yaml.SafeLoader) + +def test_json_load(): + # no issue should be found + j = json.load("{}") diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-yaml-load.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-yaml-load.yml new file mode 100644 index 0000000..1733c11 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/deserialization/rule-yaml-load.yml @@ -0,0 +1,73 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_deserialization_rule-yaml-load" + languages: + - "python" + message: | + The application was found using an unsafe version of `yaml` load which is vulnerable to + deserialization attacks. Deserialization attacks exploit the process of reading serialized + data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + To remediate this issue, use `safe_load()` or call `yaml.load()` with the `Loader` argument + set to + `yaml.SafeLoader`. + + Example loading YAML using `safe_load`: + ``` + import yaml + + # Use safe_load to load data into an intermediary object + intermediary_object = yaml.safe_load("""user: + name: 'test user'""" + ) + # Create our real object, copying over only the necessary fields + user_object = {'user': { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['user']['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with user_object + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + patterns: + - pattern-inside: | + import yaml + ... + - pattern-not-inside: | + from ruamel.yaml import YAML + ... + - pattern-either: + - pattern: "yaml.unsafe_load(...)" + - pattern: "yaml.$LD(..., Loader=yaml.$LOADER, ...)" + - pattern: "yaml.$LD($DATA)" + - metavariable-regex: + metavariable: "$LOADER" + regex: "(Loader|UnsafeLoader|CLoader|FullLoader)" + - metavariable-regex: + metavariable: "$LD" + regex: "(load|load_all)" + metadata: + cwe: "CWE-502" + owasp: + - "A8:2017-Insecure Deserialization" + - "A08:2021-Software and Data Integrity Failures" + - "A08:2025-Software or Data Integrity Failures" + category: "security" + shortDescription: "Deserialization of untrusted data" + security-severity: "High" + severity: "ERROR" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/django/rule-django-extra-used.py b/compliance-agent/rules/vendor/gitlab/upstream/python/django/rule-django-extra-used.py new file mode 100644 index 0000000..4377ee5 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/django/rule-django-extra-used.py @@ -0,0 +1,36 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/django_sql_injection_extra.py +# hash: 8eee173 + +from django.contrib.auth.models import User + +User.objects.filter(username='admin').extra( + select={'test': 'secure'}, + where=['secure'], + tables=['secure'] +) +User.objects.filter(username='admin').extra({'test': 'secure'}) +User.objects.filter(username='admin').extra(select={'test': 'secure'}) +User.objects.filter(username='admin').extra(where=['secure']) + +User.objects.filter(username='admin').extra(dict(could_be='insecure')) +# ruleid: python_django_rule-django-extra-used +User.objects.filter(username='admin').extra(select=dict(could_be='insecure')) +query = '"username") AS "username", * FROM "auth_user" WHERE 1=1 OR "username"=? --' +User.objects.filter(username='admin').extra(select={'test': query}) +User.objects.filter(username='admin').extra(select={'test': '%secure' % 'nos'}) +User.objects.filter(username='admin').extra(select={'test': '{}secure'.format('nos')}) + +where_var = ['1=1) OR 1=1 AND (1=1'] +User.objects.filter(username='admin').extra(where=where_var) +# ruleid: python_django_rule-django-extra-used +User.objects.filter(username='admin').extra(where=userinput) +where_str = '1=1) OR 1=1 AND (1=1' +User.objects.filter(username='admin').extra(where=[where_str]) +User.objects.filter(username='admin').extra(where=['%secure' % 'nos']) +User.objects.filter(username='admin').extra(where=['{}secure'.format('no')]) + +tables_var = ['django_content_type" WHERE "auth_user"."username"="admin'] +User.objects.all().extra(tables=tables_var).distinct() +tables_str = 'django_content_type" WHERE "auth_user"."username"="admin' +User.objects.all().extra(tables=[tables_str]).distinct() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/django/rule-django-extra-used.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/django/rule-django-extra-used.yml new file mode 100644 index 0000000..4adbb2c --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/django/rule-django-extra-used.yml @@ -0,0 +1,91 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_django_rule-django-extra-used" + languages: + - "python" + message: | + SQL Injection is a critical vulnerability that can lead to data or system compromise. By + dynamically generating SQL query strings, user input may be able to influence the logic of + the SQL statement. This could lead to an adversary accessing information they should + not have access to, or in some circumstances, being able to execute OS functionality or code. + + Replace all dynamically generated SQL queries with parameterized queries. In situations where + dynamic queries must be created, never use direct user input, but instead use a map or + dictionary of valid values and resolve them using a user supplied key. + + For example, some database drivers do not allow parameterized queries for `>` or `<` comparison + operators. In these cases, do not use a user supplied `>` or `<` value, but rather have the + user + supply a `gt` or `lt` value. The alphabetical values are then used to look up the `>` and `<` + values to be used in the construction of the dynamic query. The same goes for other queries + where + column or table names are required but cannot be parameterized. + + The `QuerySet.extra` API method will be deprecated as it a source of SQL Injection + vulnerabilities and other problems. This method is especially risky as callers + will need to do their own escaping of any parameters that come from user-supplied + information. + + To remediate this issue, do not use `extra` but use other `QuerySet` methods to achieve + the same goals. If for some reason this is not feasible, consider using the `RawSQL` method + and making sure that all arguments, including user-supplied ones, are only used in + `params` + + + While not recommended due to [potential SQL + Injection](https://docs.djangoproject.com/en/4.2/ref/models/expressions/#raw-sql-expressions), + below is an example using `RawSQL`, + passing in user-supplied data as a `param` which will escape the input: + ``` + # If dealing with integer based user input, restrict the values to integers only using the + # path configuration: path('/someview/', views.some_view, + name='someview'), + + # views.py + def some_view(request, user_supplied_id): + # Never use string interpolation in the `sql` parameter. + # Never quote the `%s` string format such as `... where id='%s'` as this could lead to SQL + Injection. + # Pass the user supplied data only in the `params` parameter. + for obj in DBObject.objects.all().annotate( + val=RawSQL(sql="select id from some_secondary_table where id=%s", + params=[user_supplied_id])): + # Work with the results from the query + # ... + ``` + + For more information on QuerySet see: + - https://docs.djangoproject.com/en/4.2/ref/models/querysets/#queryset-api + + For more information on SQL Injection see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html + patterns: + - pattern: "$X.objects. ... .extra(..., $K = $V, ...)" + - pattern-not-inside: | + $V = ['...'] + ... + - metavariable-pattern: + metavariable: "$V" + patterns: + - pattern: "$V" + - pattern-not: "[..., '...', ...]" + - pattern-not: "{..., '...': '...', ...}" + - pattern-not: "\"...\"" + - pattern-not: "[..., \"...\" % \"...\", ...]" + - pattern-not: "{..., $L: \"...\" % \"...\", ...}" + - pattern-not: "{..., $L: \"...\".format(\"...\"), ...}" + - pattern-not: "[..., \"...\".format(\"...\"), ...]" + metadata: + cwe: "CWE-89" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + category: "security" + shortDescription: "Improper neutralization of special elements used in an SQL + Command ('SQL Injection')" + security-severity: "High" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-jinja2-autoescape-false.py b/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-jinja2-autoescape-false.py new file mode 100644 index 0000000..61a77c9 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-jinja2-autoescape-false.py @@ -0,0 +1,41 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/jinja2_templating.py +# hash: 8eee173 + +import jinja2 +from jinja2 import Environment, select_autoescape +templateLoader = jinja2.FileSystemLoader( searchpath="/" ) +something = '' + +Environment(loader=templateLoader, load=templateLoader, autoescape=True) +templateEnv = jinja2.Environment(autoescape=True, + loader=templateLoader ) +# ruleid: python_escaping_rule-jinja2-autoescape-false +Environment(loader=templateLoader, load=templateLoader, autoescape=something) +# ruleid: python_escaping_rule-jinja2-autoescape-false +templateEnv = jinja2.Environment(autoescape=False, loader=templateLoader ) +# ruleid: python_escaping_rule-jinja2-autoescape-false +Environment(loader=templateLoader, + load=templateLoader, + autoescape=False) + +# ruleid: python_escaping_rule-jinja2-autoescape-false +Environment(loader=templateLoader, + load=templateLoader) + +Environment(loader=templateLoader, autoescape=select_autoescape()) + +Environment(loader=templateLoader, + autoescape=select_autoescape(['html', 'htm', 'xml'])) + + +def fake_func(): + return 'foobar' +# ruleid: python_escaping_rule-jinja2-autoescape-false +Environment(loader=templateLoader, autoescape=fake_func()) + +# ok: python_escaping_rule-jinja2-autoescape-false +templateEnv = jinja2.Environment(autoescape=True, loader=templateLoader) + +# ok: python_escaping_rule-jinja2-autoescape-false +Environment(loader=templateLoader, load=templateLoader, autoescape=select_autoescape(['html', 'htm', 'xml'])) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-jinja2-autoescape-false.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-jinja2-autoescape-false.yml new file mode 100644 index 0000000..a0a7c6a --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-jinja2-autoescape-false.yml @@ -0,0 +1,168 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_escaping_rule-jinja2-autoescape-false" + languages: + - "python" + message: | + The application was found using Jinja2 `Environment` without autoescaping enabled. If using in + the context of HTML this could lead to Cross-Site Scripting (XSS) attacks when rendering with + user-supplied input. + + Unfortunately, Jinja2 does not support context-aware escaping, meaning it is insufficient to + protect against + XSS for the various web contexts. It is important to encode the data depending on the specific + context + it + is used in. There are at least six context types: + + - Inside HTML tags `
context 1
` + - Inside attributes: `
` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + Script blocks alone have multiple ways they need to be encoded. Extra care must be taken if + user input + is ever output inside of script tags. + + User input that is displayed within the application must be encoded, sanitized or validated + to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be + taken + to not mix server-side templating with client-side templating, as the server-side templating + will + not encode things like {{ 7*7 }} which may execute client-side templating features. + + It is _NOT_ advised to encode user input prior to inserting into a data store. The data will + need to be + encoded depending on context of where it is output. It is much safer to force the displaying + system to + handle the encoding and not attempt to guess how it should be encoded. + + To handle different contexts, one approach would be to write custom Jinja2 filters. Below is + an example + that escapes or encodes links and potentially malicious script, note this does not include + other contexts + such as CSS or attributes: + ``` + from jinja2 import Environment, select_autoescape, FileSystemLoader + from jinja2 import pass_eval_context + from markupsafe import Markup, escape + + @pass_eval_context + def escape_link(eval_ctx, value): + bad_link = "#JinjatmplZ" + # Block any values that start with // as that could be used to inject + # links to third party pages see: + https://en.wikipedia.org/wiki/Wikipedia:Protocol-relative_URL + if value.startswith('//'): + return bad_link + + # Only allow relative links + # if you want to allow links that start with http or ws replace with below: + # if not value.startswith('/'): and not value.startswith('http') and not + value.startswith('ws') + if not value.startswith('/'): + return bad_link + + # Alternatively, you could only call escape if autoescape is true + # if eval_ctx.autoescape: + # return escape(value) + # else + # return value + + return escape(value) + + # Create a replacement table + js_replacement = str.maketrans({ + '"': "\\u0022", + '`': "\\u0060", + '&': "\\u0026", + '\'': "\\u0027", + '+': "\\u002b", + '/': "\\/", + '<': "\\u003c", + '>': "\\u003e", + '\\': "\\\\", + '(': "\\u0028", + ')': "\\u0029", + }) + + @pass_eval_context + def escape_js(eval_ctx, value): + """ + Escape the input for use in ", + script_context="alert(1);alert`1`",) + ) + + # Sample template: + """ + + + + My Webpage + + +

My Webpage

+ {{ html_context }} + link + + + + """ + ``` + + For more information on autoescape see: + - https://jinja.palletsprojects.com/en/3.1.x/api/#autoescaping + + For more information on XSS see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html + metadata: + cwe: "CWE-116" + owasp: + - "A7:2017-Cross-Site Scripting (XSS)" + - "A03:2021-Injection" + - "A05:2025-Injection" + category: "security" + shortDescription: "Improper encoding or escaping of output" + security-severity: "Medium" + patterns: + - pattern-inside: | + import jinja2 + ... + - pattern-not: "jinja2.Environment(..., autoescape=True, ...)" + - pattern-not: "jinja2.Environment(..., autoescape=jinja2.select_autoescape(...),...)" + - pattern-not: "jinja2.Environment(..., autoescape=select_autoescape(...), ...)" + - pattern: "jinja2.Environment(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-use-of-mako-templates.py b/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-use-of-mako-templates.py new file mode 100644 index 0000000..ff18fda --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-use-of-mako-templates.py @@ -0,0 +1,34 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/mako_templating.py +# hash: 8eee173 + +from mako.template import Template +from mako.lookup import TemplateLookup +import mako + +from mako import template + +# ruleid: python_escaping_rule-use-of-mako-templates +Template("hello") + +# XXX(fletcher): for some reason, bandit is missing the one below. keeping it +# in for now so that if it gets fixed inadvertently we know. +# ruleid: python_escaping_rule-use-of-mako-templates +mako.template.Template("hern") + +# Disable default filters so no filters are applied. +# ruleid: python_escaping_rule-use-of-mako-templates +template.Template("hern", default_filters=[]) + +# rule ok: python_escaping_rule-use-of-mako-templates +template = Template("hern", default_filters=['h']) # 'h' is the HTML escape filter + +# ruleid: python_escaping_rule-use-of-mako-templates +TemplateLookup(directories=['/tmp']) + +# rule ok: python_escaping_rule-use-of-mako-templates +TemplateLookup(directories=['/tmp'], default_filters=['h']) # 'h' is the HTML escape filter + +# Disable default filters so no filters are applied. +# ruleid: python_escaping_rule-use-of-mako-templates +TemplateLookup(directories=['/tmp'], default_filters=[]) \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-use-of-mako-templates.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-use-of-mako-templates.yml new file mode 100644 index 0000000..826a1f6 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/escaping/rule-use-of-mako-templates.yml @@ -0,0 +1,147 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_escaping_rule-use-of-mako-templates" + languages: + - "python" + message: | + The application was found using mako templates without `default_filters` + being passed to the `Template` or `TemplateLookup` constructors. If using + in the context of HTML, this could lead to Cross-Site Scripting (XSS) attacks + when rendering with user-supplied input. + + Unfortunately, Jinja2 does not support context-aware escaping, meaning it + is insufficient to protect against XSS for the various web contexts. It is + important to encode the data depending on the specific context it is used in. + There are at least six context types: + + - Inside HTML tags `
context 1
` + - Inside attributes: `
` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: + `link` + + Script blocks alone have multiple ways they need to be encoded. Extra care + must be taken if user input is ever output inside of script tags. + + User input that is displayed within the application must be encoded, + sanitized or validated to ensure it cannot be treated as HTML or executed + as Javascript code. Care must also be taken to not mix server-side templating + with client-side templating, as the server-side templating will not encode things + like {{ 7*7 }} which may execute client-side templating features. + + It is _NOT_ advised to encode user input prior to inserting into a data + store. The data will need to be encoded depending on context of where it is output. + It is much safer to force the displaying system to handle the encoding and + not attempt to guess how it should be encoded. + + To handle different contexts, one approach would be to write custom mako + filters. Below is an example that escapes or encodes links and + potentially malicious script, note this does not include other contexts + such as CSS or attributes: + ``` + # filters.py module: + + def escape_link(value): + bad_link = "#JinjatmplZ" + # Block any values that start with // as that could be used to inject + # links to third party pages see: + https://en.wikipedia.org/wiki/Wikipedia:Protocol-relative_URL + if value.startswith('//'): + return bad_link + + # Only allow relative links + # if you want to allow links that start with http or ws replace with below: + # if not value.startswith('/'): and not value.startswith('http') and not + value.startswith('ws') + if not value.startswith('/'): + return bad_link + + return value + + # Create a replacement table + js_replacement = str.maketrans({ + '\0': "\\u0000", + '\t': "\\t", + '\n': "\\n", + '\v': "\\u000b", + '\f': "\\f`", + '\r': "\\r", + '"': "\\u0022", + '`': "\\u0060", + '&': "\\u0026", + '\'': "\\u0027", + '+': "\\u002b", + '/': "\\/", + '<': "\\u003c", + '>': "\\u003e", + '\\': "\\\\", + '(': "\\u0028", + ')': "\\u0029", + }) + + def escape_js(value): + # Escape the input for use in + + + """ + + # Load our template with default filters and our imported filters for + # usage in template files + t = Template(template_text, + # By default enable the html filter with 'h' + default_filters=['h'], + # Import our custom filters + imports=["from filters import escape_link, escape_js"]) + + # Render our template + print(t.render(html_context="", + link_context="/# onclick=alert(1)", + script_context="alert(1)",) + ) + ``` + metadata: + cwe: "CWE-79" + category: "security" + owasp: + - "A7:2017-Cross-Site Scripting (XSS)" + - "A03:2021-Injection" + - "A05:2025-Injection" + shortDescription: "Improper neutralization of input during web page generation ('Cross-site Scripting')" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "mako.template.Template(...)" + - pattern: "mako.lookup.TemplateLookup(...)" + - pattern-not: "mako.lookup.TemplateLookup(..., default_filters=[\"...\"])" + - pattern-not: "mako.template.Template(..., default_filters=[\"...\"])" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/eval/rule-eval.py b/compliance-agent/rules/vendor/gitlab/upstream/python/eval/rule-eval.py new file mode 100644 index 0000000..ab224da --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/eval/rule-eval.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python + +# SETUP + +import os + +content = """ +__import__('datetime').datetime.now() +""" +with open("eval.input","w+") as f: + f.write(content) + +# NOTES +# String Literals f, """ """, r'', b'', fr"", etc should all be detected by "...", but still some tests are added as assurance. + +# single string argument +#ok: python_eval_rule-eval +eval("1+1") + +# literal string concatenation +#ok: python_eval_rule-eval +print(eval("1"+"+"+"1")) + +# implicit string concatenation +#ok: python_eval_rule-eval +eval("1+" "1") + +plus="+" +one= "1" + +# variable string concatenation +#ok: python_eval_rule-eval +eval("1"+plus+"1") + +# format string with single argument +#ok: python_eval_rule-eval +eval(f"1{plus}1") + +# raw format string with single argument +#ok: python_eval_rule-eval +eval(rf"1{plus}1") + +# format string with multiple arguments +#ok: python_eval_rule-eval +eval(f"1{plus}{one}") + +# single string interpolation +#known false positive, semgrep limitations in understanding of Python string interpolations +#ok: python_eval_rule-eval +eval("1%s"%"+1") + +# multiple string interpolation +#known false positive, semgrep limitations in understanding of Python string interpolations +#ok: python_eval_rule-eval +eval( "1 %s %s" % ("+", "1") ) + + +# string concatenation with casted integer constant +#known false positive, semgrep limitations in understanding of Python string constants +#ok: python_eval_rule-eval +#eval("1+"+str(1)) +#TODO: enable once SemGrep's String Constant Propagation improves. + +# string literal and standard library call +#ok: python_eval_rule-eval +print(eval("os.getcwd()")) + +# format string literal and standard library call +#ok: python_eval_rule-eval +print(eval(f"os.getcwd()")) + +# format string literal and standard library call +#ok: python_eval_rule-eval +print(eval(r"os.getcwd()")) + +# triple-quote string literal and standard library call +#ok: python_eval_rule-eval +print(eval("""os.getcwd()""")) + +#following call evaluates a hard-coded string which results in a predetermined behavior and a harmless output +#ok: python_eval_rule-eval +content = eval("__builtins__.open('eval.input','r').read()") +print(content) + +print( + #following call, as opposed to the previous one, evaluates a string with known procedence but unknown content and thus exhibits a non-deterministic, externally-controlled behavior + #ruleid: python_eval_rule-eval + eval( + content + ) +) + +print( + #this call evaluates a hard-coded expression which is parametrized using str.format and externally provided input + #ruleid: python_eval_rule-eval + eval(r"__builtins__.open('{}','r').read()".format(input())) +) + +print( + #this call evaluates a hard-coded expression which is parametrized using string interpolation and externally provided input + #ruleid: python_eval_rule-eval + eval(r"__builtins__.open('%s','r').read()" % input()) +) + +#ok: python_eval_rule-eval +eval("os.chmod('%s', 0o666)" % 'eval.input') + +# User-defined functions and methods named "eval" should not trigger a finding. + +class Foo(object): + + #ok: python_eval_rule-eval + def eval(self): + print("User-defined eval method") + + def foo(self): + #ok: python_eval_rule-eval + self.eval() + +class Bar(object): + def bar(self,input): + #ruleid: python_eval_rule-eval + eval(input) + + def eval(input): + print("User-defined eval method") + #ok: python_eval_rule-eval + eval(input) + +#ok: python_eval_rule-eval +Foo().eval() + +class MyClass: + def __init__(): + return + def eval(input): + print('harmless') + +#ruleid: python_eval_rule-eval +eval(content) + +# call without arguments, superfluous but not dangerous. +#ok: python_eval_rule-eval +eval() + +#ok: python_eval_rule-eval +def eval(input): + print("Harmless user-defined eval function") + +#known false positive, requires reflection or ability to compare eval.__module__=='builtins' +#ok: python_eval_rule-eval +eval(content) + + +# TEARDOWN + +os.remove("eval.input") diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/eval/rule-eval.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/eval/rule-eval.yml new file mode 100644 index 0000000..359cce5 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/eval/rule-eval.yml @@ -0,0 +1,53 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_eval_rule-eval" + languages: + - "python" + message: | + The application was found calling the `eval` function with non-literal data. If the variable contains + user-controlled data, either partially or fully, an adversary could compromise the entire system by + executing arbitrary Python code. + + To remediate this issue, remove all calls to `eval` and consider alternative methods for executing + the necessary business logic. There is almost no safe method of calling `eval` with user-supplied input. + + If the application only needs to convert strings into objects, consider using `json.loads`. In + some cases `ast.literal_eval` is recommended, but this should be avoided as it can still suffer + from other issues such as the ability for malicious code to crash the python interpreter or application. + + Example using `json.loads`` to load in arbitrary data to create data structures: + ``` + # User supplied data as a blob of JSON + user_supplied_data = """{"user": "test", "metadata": [1,2,3]}""" + # Load the JSON + user_object = json.loads(user_supplied_data) + # Manually add protected properties _after_ loading, never before + user_object["is_admin"] = False + # Work with the object + ``` + patterns: + - pattern: "eval($X,...)" + - pattern-not: | + eval("...") + - pattern-not: | + eval("..." % <... "..." ...>) + - pattern-not: | + eval(<... "...".format( "..." ) ...>) + - pattern-not-inside: | + def eval(...): + ... + ... + metadata: + cwe: "CWE-95" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + category: "security" + shortDescription: "Improper neutralization of directives in dynamically evaluated + code ('Eval Injection')" + security-severity: "High" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-exec-used.py b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-exec-used.py new file mode 100644 index 0000000..e7c4e07 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-exec-used.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# License: MIT (c) GitLab Inc. + +from flask import Flask, request + +app = Flask(__name__) +# Literal strings are ok +com = ''' +import os +os.system('ls -l') +''' + + +@app.route('/exec', methods=['POST']) +def exec_route(): + user_input = request.form['input'] + + # ruleid: python_exec_rule-exec-used + exec(f"{user_input}") + + # ruleid: python_exec_rule-exec-used + exec("Hello {0}!" % user_input) + + # ruleid: python_exec_rule-exec-used + exec(user_input) + + +@app.route('/safe', methods=['GET']) +def exec_safe_route(): + text = 'exec is evil' + com = f"print('{text}')" + + # rule ok: + exec(com) + + # rule ok: + exec(com) + + # rule ok: + exec("2 + 3") + + # rule ok: + exec("print('hello world!')") + + return "no response" + + +if __name__ == '__main__': + app.run(debug=True) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-exec-used.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-exec-used.yml new file mode 100644 index 0000000..79e4e00 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-exec-used.yml @@ -0,0 +1,46 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_exec_rule-exec-used" + languages: + - "python" + message: | + The application was found calling the `exec` function with a non-literal variable. If the + variable comes from user-supplied input, an adversary could compromise the entire system by + executing arbitrary python code. + + To remediate this issue, remove all calls to `exec` and consider alternative methods for + executing the necessary business logic. There is almost no safe method of calling `eval` + with user-supplied input. + + If the application only needs to convert strings into objects, consider using `json.loads`. + In some cases `ast.literal_eval` is recommended, but this should be avoided as it can still + suffer from other issues such as the ability for malicious code to crash the python + interpreter or application. + + Example using `json.loads`` to load in arbitrary data to create data structures: + ``` + # User supplied data as a blob of JSON + user_supplied_data = """{"user": "test", "metadata": [1,2,3]}""" + # Load the JSON + user_object = json.loads(user_supplied_data) + # Manually add protected properties _after_ loading, never before + user_object["is_admin"] = False + # Work with the object + ``` + metadata: + cwe: "CWE-95" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + category: "security" + shortDescription: "Improper neutralization of directives in dynamically evaluated + code ('Eval Injection')" + security-severity: "High" + patterns: + - pattern: "exec(...)" + - pattern-not: "exec(\"...\")" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-linux-command-wildcard-injection.py b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-linux-command-wildcard-injection.py new file mode 100644 index 0000000..d4c3b2f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-linux-command-wildcard-injection.py @@ -0,0 +1,89 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/wildcard-injection.py +# hash: 8eee173 + +import os as o +import os +import subprocess +import subprocess as subp +import sys + +# Vulnerable to wildcard injection +# ruleid: python_exec_rule-linux-command-wildcard-injection +o.system("/bin/tar xvzf *") +# ruleid: python_exec_rule-linux-command-wildcard-injection +o.system('/bin/chown *') +# ruleid: python_exec_rule-linux-command-wildcard-injection +o.popen('/bin/chmod *') +# ruleid: python_exec_rule-linux-command-wildcard-injection +subp.Popen('/bin/chown *', shell=True) + +# Not vulnerable to wildcard injection +# rule ok: python_exec_rule-linux-command-wildcard-injection +subp.Popen('/bin/rsync *') +# rule ok: python_exec_rule-linux-command-wildcard-injection +subp.Popen("/bin/chmod *") +# rule ok: python_exec_rule-linux-command-wildcard-injection +subp.Popen(['/bin/chown', '*']) +# rule ok: python_exec_rule-linux-command-wildcard-injection +subp.Popen(["/bin/chmod", sys.argv[1], "*"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) +# rule ok: python_exec_rule-linux-command-wildcard-injection +o.spawnvp(os.P_WAIT, 'tar', ['tar', 'xvzf', '*']) + +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.system("tar *") +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.popen("chmod 777 *") +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.popen("chown root:root *") +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.popen("rsync -avz * destination/") +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.popen("tar cvf archive.tar *") + +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.system("tar *") +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.popen("chmod 777 *", 'r', -1) +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.popen("chown root:root *", 'r', -1) +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.popen("rsync -avz * destination/", 'r', -1) +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.popen("tar cvf archive.tar *", 'r', -1) + +# ruleid: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("tar *", shell=True, stdout=subprocess.PIPE) +# ruleid: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("chmod 777 *", shell=True, stderr=subprocess.PIPE) +# ruleid: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("chown root:root *", shell=True, stdin=subprocess.PIPE) +# ruleid: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("rsync -avz * destination/", shell=True, cwd="/tmp") + +# ruleid: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("tar abc?", shell=True) +# ruleid: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("chmod 777 secret?.txt", shell=True) +# ruleid: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("chown root:root secret?.txt", shell=True) +# ruleid: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("rsync -avz secret?.txt destination/", shell=True) +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.system("cat secret?.txt") + +# ruleid: python_exec_rule-linux-command-wildcard-injection +stdout, stderr = subprocess.Popen('ls -la *', shell=True, stdout=subprocess.PIPE, text=True).communicate() +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.system('grep "some_search_term" *.py') +options = {"stdout": subprocess.PIPE} +# rule ok: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("ls", shell=True, **options) +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.system("ls *.txt") +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.system('grep "some_search_term" *.py') +# ruleid: python_exec_rule-linux-command-wildcard-injection +subprocess.Popen("rm *.tmp", shell=True) +# ruleid: python_exec_rule-linux-command-wildcard-injection +os.system("tar czf logs.tar.gz *.log") \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-linux-command-wildcard-injection.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-linux-command-wildcard-injection.yml new file mode 100644 index 0000000..aa774d8 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-linux-command-wildcard-injection.yml @@ -0,0 +1,52 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: + - id: "python_exec_rule-linux-command-wildcard-injection" + languages: + - "python" + message: | + Detected use of the wildcard character in a system call that spawns a shell. This subjects the + wildcard to normal shell expansion, which can have unintended consequences if there exist any + non-standard file names. For instance, a file named `-e sh script.sh` could cause issues when + expanded by the shell and executed as a command. Consider using a different method to achieve + the same result, such as using the `glob` module to expand the wildcard before passing it to the + system call. Or if the command is static, consider hardcoding the command instead of using a + wildcard. + + For example, the below code uses the glob module to expand the wildcard and get a list of all + CSV files in the current directory. This list is then used in the subprocess.run call, instead of a + wildcard. This avoids the potential issues that can arise from using a wildcard in a system call. + ``` + import glob + import subprocess + + # Secure way to process all CSV files + files = glob.glob('*.csv') + for file in files: + subprocess.run(['process_data', file]) + ``` + + metadata: + category: "security" + cwe: "CWE-155" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + shortDescription: "Improper neutralization of wildcards or matching symbols" + security-severity: "High" + patterns: + - pattern-either: + - pattern: |- + os.$X("$CMD", ...) + - pattern: |- + subprocess.Popen("$CMD", shell=True, ...) + - metavariable-regex: + metavariable: $CMD + regex: '(.*?)(\*|\?)' + - pattern-not-inside: |- + os.spawnvp(...) + metavariable-regex: + X: "(system|popen|popen2|popen3|popen4)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-path.py b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-path.py new file mode 100644 index 0000000..a702cd2 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-path.py @@ -0,0 +1,3 @@ +# License: MIT (c) GitLab Inc. +# TODO: Placeholder file; add example code. + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-path.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-path.yml new file mode 100644 index 0000000..0d4545e --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-path.yml @@ -0,0 +1,30 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_exec_rule-os-path" + languages: + - "python" + message: | + Starting a process with a shell; seems safe, but may be changed in the future, consider + rewriting without shell + pattern-either: + - pattern: "os.system(\"...\", ...)" + - pattern: "$OS.popen(\"...\", ...)" + - pattern: "$OS.popen2(\"...\", ...)" + - pattern: "$OS.popen3(\"...\", ...)" + - pattern: "$OS.popen4(\"...\", ...)" + - pattern: "commands.getoutput(\"...\", ...)" + - pattern: "commands.getstatusoutput(\"...\", ...)" + metadata: + cwe: "CWE-78" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + shortDescription: "Improper neutralization of special elements used in an OS Command + ('OS Command Injection')" + security-severity: "High" + category: "security" + severity: "INFO" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-popen2.py b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-popen2.py new file mode 100644 index 0000000..c07750a --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-popen2.py @@ -0,0 +1,31 @@ +# License: MIT (c) GitLab Inc. + +import subprocess +import os +from subprocess import Popen as pop + +# ruleid: python_exec_rule-os-popen2 +os.system("") +# ruleid: python_exec_rule-os-popen2 +os.popen("") +# ruleid: python_exec_rule-os-popen2 +os.popen2("") +# ruleid: python_exec_rule-os-popen2 +os.popen3("") +# ruleid: python_exec_rule-os-popen2 +os.popen4("") +# ruleid: python_exec_rule-os-popen2 +popen2.popen2("") +# ruleid: python_exec_rule-os-popen2 +popen2.popen3("") +# ruleid: python_exec_rule-os-popen2 +popen2.popen4("") +# ruleid: python_exec_rule-os-popen2 +popen2.Popen3("") +# ruleid: python_exec_rule-os-popen2 +popen2.Popen4("") +# ruleid: python_exec_rule-os-popen2 +commands.getoutput("") +# ruleid: python_exec_rule-os-popen2 +commands.getstatusoutput("") + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-popen2.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-popen2.yml new file mode 100644 index 0000000..d0ba0c4 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-os-popen2.yml @@ -0,0 +1,36 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_exec_rule-os-popen2" + languages: + - "python" + message: | + Starting a process with a shell; seems safe, but may be changed in the future, consider + rewriting without shell + patterns: + - pattern-either: + - pattern: "os.system(...)" + - pattern: "os.popen(...)" + - pattern: "os.popen2(...)" + - pattern: "os.popen3(...)" + - pattern: "os.popen4(...)" + - pattern: "popen2.popen2(...)" + - pattern: "popen2.popen3(...)" + - pattern: "popen2.popen4(...)" + - pattern: "popen2.Popen3(...)" + - pattern: "popen2.Popen4(...)" + - pattern: "commands.getoutput(...)" + - pattern: "commands.getstatusoutput(\"\")" + metadata: + cwe: "CWE-78" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + shortDescription: "Improper neutralization of special elements used in an OS Command + ('OS Command Injection')" + security-severity: "High" + category: "security" + severity: "INFO" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-call.py b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-call.py new file mode 100644 index 0000000..addecae --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-call.py @@ -0,0 +1,62 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/subprocess_shell.py +# hash: 8eee173 + +import subprocess +from subprocess import Popen as pop + +def Popen(*args, **kwargs): + print('hi') + + def __len__(self): + return 0 + +# safe +pop('/bin/gcc --version', shell=True) +Popen('/bin/gcc --version', shell=True) + +subprocess.Popen('/bin/gcc --version', shell=True) +# ruleid: python_exec_rule-subprocess-call +subprocess.Popen(['/bin/gcc', '--version'], shell=False) +# ruleid: python_exec_rule-subprocess-call +subprocess.Popen(['/bin/gcc', '--version']) + +# ruleid: python_exec_rule-subprocess-call +subprocess.call(["/bin/ls", + "-l" + ]) +subprocess.call('/bin/ls -l', shell=True) + +# ruleid: python_exec_rule-subprocess-call +subprocess.check_call(['/bin/ls', '-l'], shell=False) +subprocess.check_call('/bin/ls -l', shell=True) + +# ruleid: python_exec_rule-subprocess-call +subprocess.check_output(['/bin/ls', '-l']) +subprocess.check_output('/bin/ls -l', shell=True) + +# ruleid: python_exec_rule-subprocess-call +subprocess.run(['/bin/ls', '-l']) +subprocess.run('/bin/ls -l', shell=True) + +subprocess.Popen('/bin/ls *', shell=True) +subprocess.Popen('/bin/ls %s' % ('something'), shell=True) +subprocess.Popen('/bin/ls {}'.format('something'), shell=True) + +command = "/bin/ls" + unknown_function() +subprocess.Popen(command, shell=True) + +subprocess.Popen('/bin/ls && cat /etc/passwd', shell=True) + +constant_command = 'pwd' +subprocess.call(constant_command, shell=True) +# ruleid: python_exec_rule-subprocess-call +subprocess.call(constant_command, shell=False) + +# unsafe +user_command = input() +# ruleid: python_exec_rule-subprocess-call +subprocess.run([user_command]) +# ruleid: python_exec_rule-subprocess-call +subprocess.run(user_command) +subprocess.run(user_command, shell=True) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-call.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-call.yml new file mode 100644 index 0000000..f80bea8 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-call.yml @@ -0,0 +1,43 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_exec_rule-subprocess-call" + languages: + - "python" + message: | + Python possesses many mechanisms to invoke an external executable. However, + doing so may present a security issue if appropriate care is not taken to + sanitize any user provided or variable input. This plugin test is part of a + family of tests built to check for process spawning and warn appropriately. + Specifically, this test looks for the spawning of a subprocess without the + use of a command shell. This type of subprocess invocation is not + vulnerable to shell injection attacks, but care should still be taken to + ensure validity of input. + patterns: + - pattern-not: "subprocess.$FUNC($ARG, shell=<... True ...>)" + - pattern-not: "subprocess.$FUNC($ARG, shell=<... 'True' ...>)" + - pattern-not: "subprocess.$FUNC($ARG, shell=<... \"True\" ...>)" + - pattern-either: + - pattern: | + subprocess.$FUNC($ARG, shell=False) + - pattern: | + subprocess.$FUNC($ARG, shell=0) + - pattern: | + subprocess.$FUNC($ARG, shell={...}) + - pattern: | + subprocess.$FUNC($ARG, shell=[...]) + - pattern: | + subprocess.$FUNC($ARG) + metadata: + cwe: "CWE-78" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + shortDescription: "Improper neutralization of special elements used in an OS Command + ('OS Command Injection')" + security-severity: "High" + category: "security" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-shell-TRUE.py b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-shell-TRUE.py new file mode 100644 index 0000000..919633c --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-shell-TRUE.py @@ -0,0 +1,60 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/subprocess_shell.py +# hash: 8eee173 + +import subprocess +from subprocess import Popen as pop + +def Popen(*args, **kwargs): + print('hi') + + def __len__(self): + return 0 + +pop('/bin/gcc --version', shell=True) +# ruleid: python_exec_rule-subprocess-shell-TRUE +Popen('/bin/gcc --version', shell=True) + +subprocess.Popen('/bin/gcc --version', shell=True) +subprocess.Popen(['/bin/gcc', '--version'], shell=False) +subprocess.Popen(['/bin/gcc', '--version']) + +subprocess.call(["/bin/ls", + "-l" + ]) +subprocess.call('/bin/ls -l', shell=True) + +subprocess.check_call(['/bin/ls', '-l'], shell=False) +subprocess.check_call('/bin/ls -l', shell=True) + +subprocess.check_output(['/bin/ls', '-l']) +subprocess.check_output('/bin/ls -l', shell=True) + +subprocess.run(['/bin/ls', '-l']) +subprocess.run('/bin/ls -l', shell=True) + +subprocess.Popen('/bin/ls *', shell=True) +subprocess.Popen('/bin/ls %s' % ('something',), shell=True) +subprocess.Popen('/bin/ls {}'.format('something'), shell=True) + +command = "/bin/ls" + unknown_function() +subprocess.Popen(command, shell=True) + +subprocess.Popen('/bin/ls && cat /etc/passwd', shell=True) + +command = 'pwd' +subprocess.call(command, shell='True') +subprocess.call(command, shell='False') +subprocess.call(command, shell='None') +subprocess.call(command, shell=1) + +subprocess.call(command, shell=Popen()) +subprocess.call(command, shell=[True]) +subprocess.call(command, shell={'IS': 'True'}) +subprocess.call(command, shell=command) + +subprocess.call(command, shell=False) +subprocess.call(command, shell=0) +subprocess.call(command, shell=[]) +subprocess.call(command, shell={}) +subprocess.call(command, shell=None) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-shell-TRUE.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-shell-TRUE.yml new file mode 100644 index 0000000..2c7ec04 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/exec/rule-subprocess-shell-TRUE.yml @@ -0,0 +1,24 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_exec_rule-subprocess-shell-TRUE" + languages: + - "python" + message: | + subprocess call - check for execution of untrusted input + patterns: + - pattern-not: "subprocess.$FUNC(..., shell=True, ...)" + - pattern: "$FOO(..., shell=True, ...)" + metadata: + cwe: "CWE-78" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + shortDescription: "Improper neutralization of special elements used in an OS Command + ('OS Command Injection')" + security-severity: "High" + category: "security" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/file_permissions/rule-general-bad-permission.py b/compliance-agent/rules/vendor/gitlab/upstream/python/file_permissions/rule-general-bad-permission.py new file mode 100644 index 0000000..00f3cce --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/file_permissions/rule-general-bad-permission.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# License: MIT (c) GitLab Inc. + +import os + +# ruleid: python_file-permissions_rule-general-bad-permission +os.chmod(key_file, 0o777) +# ruleid: python_file-permissions_rule-general-bad-permission +os.chmod('/etc/hosts', 0o777) +# ruleid: python_file-permissions_rule-general-bad-permission +os.chmod('/tmp/oh_hai', 0x1ff) +# ruleid: python_file-permissions_rule-general-bad-permission +os.chmod('/tmp/oh_hai', 0o007) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/file_permissions/rule-general-bad-permission.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/file_permissions/rule-general-bad-permission.yml new file mode 100644 index 0000000..dca0a2f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/file_permissions/rule-general-bad-permission.yml @@ -0,0 +1,41 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_file-permissions_rule-general-bad-permission" + languages: + - "python" + message: | + The application was found setting file permissions to overly permissive values. Consider + using the following values if the application user is the only process to access + the file: + + - 0400 - read only access to the file + - 0200 - write only access to the file + - 0600 - read/write access to the file + + Example creating a file with read/write permissions for the application user: + ``` + # Use octal values to set 0o600 (read/write access to the file) for the current + # user + os.chmod('somefile.txt', 0o600) + ``` + + For all other values please see: + https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation + metadata: + shortDescription: "Incorrect permission assignment for critical resource" + cwe: "CWE-732" + category: "security" + owasp: + - "A5:2017-Broken Access Control" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + security-severity: "Medium" + patterns: + - pattern: "os.chmod(...,$MASK)" + - metavariable-regex: + metavariable: "$MASK" + regex: "(0x..f|0o..[2,3,7]|stat.S_IXGRP|stat.S_IWOTH)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/files/rule-tarfile-unsafe-members.py b/compliance-agent/rules/vendor/gitlab/upstream/python/files/rule-tarfile-unsafe-members.py new file mode 100644 index 0000000..ef3eb2f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/files/rule-tarfile-unsafe-members.py @@ -0,0 +1,52 @@ +# License: MIT (c) GitLab Inc. +import sys +import tarfile +import tempfile + + +def unsafe_archive_handler(filename): + tar = tarfile.open(filename) + # ruleid: python_files_rule-tarfile-unsafe-members + tar.extractall(path=tempfile.mkdtemp()) + tar.close() + + +def managed_members_archive_handler(filename): + tar = tarfile.open(filename) + # ruleid: python_files_rule-tarfile-unsafe-members + tar.extractall(path=tempfile.mkdtemp(), members=members_filter(tar)) + tar.close() + + +def list_members_archive_handler(filename): + tar = tarfile.open(filename) + # ruleid: python_files_rule-tarfile-unsafe-members + tar.extractall(path=tempfile.mkdtemp(), members=[]) + tar.close() + + +def provided_members_archive_handler(filename): + tar = tarfile.open(filename) + # ruleid: python_files_rule-tarfile-unsafe-members + tarfile.extractall(path=tempfile.mkdtemp(), members=tar) + tar.close() + + +def members_filter(tarfile): + result = [] + for member in tarfile.getmembers(): + if '../' in member.name: + print('Member name container directory traversal sequence') + continue + elif (member.issym() or member.islnk()) and ('../' in member.linkname): + print('Symlink to external resource') + continue + result.append(member) + return result + + +if __name__ == "__main__": + if len(sys.argv) > 1: + filename = sys.argv[1] + unsafe_archive_handler(filename) + managed_members_archive_handler(filename) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/files/rule-tarfile-unsafe-members.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/files/rule-tarfile-unsafe-members.yml new file mode 100644 index 0000000..be9b8ef --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/files/rule-tarfile-unsafe-members.yml @@ -0,0 +1,109 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_files_rule-tarfile-unsafe-members" + languages: + - "python" + message: | + The application may be vulnerable to a path traversal if it extracts untrusted archive files. + This vulnerability is colloquially known as 'Zip Slip'. Archive files may contain folders + which, + when extracted, may write outside of the intended directory. This is exploited by including + path traversal characters such as `../../other/directory` to overwrite or place files in system + or application directories. + + Extra care must be taken when extracting archive files as there are numerous concerns: + + - If possible, generate unique filenames instead of using the archives file names, as it may be + possible for users to overwrite files if the filenames are the same. + - Validate file paths are written with a prefixed, known trusted directory. + - Only process regular files and not symbolic links, as some applications may attempt to + read/follow + the symbolic link, leading to arbitrary file read / write vulnerabilities. + + Example of securely processing an archive file: + ``` + import tarfile + import uuid + # import os + + tar = tarfile.open('some.tar') + + # Max number of allowed files in our archive + max_files = 10 + # Max size for all files in archive + max_size = 1024 * 1024 * 10 # 10MB + # Max size per file in archive + max_file_size = 1024 * 1024 # 1MB + + # Validate number of files in archive + if len(tar.getmembers()) > max_files: + raise Exception("Too many files in archive") + + total_size = 0 + # Loop over all files to see if we exceed max size + # if so, do not process any of them. + for f in tar.getmembers(): + total_size += f.size + if total_size >= max_size: + raise Exception("Archive files exceeded max file size") + + # Iterate over files now that we know the total size is within limits + for f in tar.getmembers(): + # Internally this calls TarInfo.isreg() which ensures + # the file is a regular file and not a sym link or directory + if not f.isfile(): + continue + + # Optional, set a limit on each file size + if f.size > max_file_size: + raise Exception(f"File {f.name} too large: {f.size}") + + # If original names are required, ensure that only the + # filename is used: + # filename = os.path.basename(f.name) + + # More secure, generate a UUID4 value instead + filename = uuid.uuid4().hex + + # Reset the archive filename to the basename + # Newer versions of python (3.11.4+) should use: + # new_tar = old_tar.replace(name=...new name...) + f.name = filename + + # Extract the file into a restricted directory, with our + # own user's attributes, not the file from the archive + tar.extract(f, '/opt/app/restricted/', set_attrs=False) + ``` + + For more information on tarfile see: + - https://docs.python.org/3/library/tarfile.html + metadata: + cwe: "CWE-22" + owasp: + - "A5:2017-Broken Access Control" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + shortDescription: "Improper limitation of a pathname to a restricted directory + ('Path Traversal')" + security-severity: "Medium" + category: "security" + patterns: + - pattern-inside: | + import tarfile + ... + - pattern-either: + - patterns: + - pattern-inside: | + $TAR = tarfile.open(...) + ... + - pattern-either: + - pattern: "$TAR.extractall(...)" + - pattern: "tarfile.extractall(..., members=$TAR)" + - pattern: "$TAR.extractall(..., members=[])" + - patterns: + - pattern: "tarfile.extractall(...)" + - pattern: "tarfile.extractall(..., members=[])" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ftp/rule-ftplib.py b/compliance-agent/rules/vendor/gitlab/upstream/python/ftp/rule-ftplib.py new file mode 100644 index 0000000..20637e1 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ftp/rule-ftplib.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ftplib.py +# hash: 8eee173 + +from ftplib import FTP + +# ruleid: python_ftp_rule-ftplib +ftp = FTP('ftp.debian.org') +ftp.login() + +ftp.cwd('debian') +ftp.retrlines('LIST') + +ftp.quit() + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ftp/rule-ftplib.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/ftp/rule-ftplib.yml new file mode 100644 index 0000000..a05d038 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ftp/rule-ftplib.yml @@ -0,0 +1,55 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_ftp_rule-ftplib" + languages: + - "python" + message: | + The application was found using an FTP library. As FTP does not provide encryption, it is + strongly recommended that any file transfers be done over a more secure transport such as + SSH. + + The [paramiko](https://www.paramiko.org/) library can be used with an SCP module to allow + secure file transfers. + + Example using `paramiko` SSH client and the `scp` module: + ``` + import paramiko + import scp + + # Create an SSH client + with paramiko.SSHClient() as ssh: + # Load the system host keys so we can confirm the + # host we are connecting to is legitimate + ssh.load_system_host_keys('/home/appuser/.ssh/known_hosts') + + # Connect to the remote host using our SSH private key + ssh.connect(hostname='example.org', + port=22, + username='appuser', + key_filename='/home/appuser/.ssh/private_key') + + # Create an SCP client with the ssh transport and copy files + with scp.SCPClient(ssh.get_transport()) as secure_copy: + secure_copy.get('remote/test.file', 'local/test.file') + secure_copy.put('local/some.file', 'remote/some.file') + ``` + + For more information on the paramiko module see: + - https://www.paramiko.org/ + + For more information on the scp module see: + - https://github.com/jbardin/scp.py + metadata: + cwe: "CWE-319" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Cleartext transmission of sensitive information" + security-severity: "Medium" + pattern: "ftplib.$ANYTHING(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/log/rule-logging-config-insecure-listen.py b/compliance-agent/rules/vendor/gitlab/upstream/python/log/rule-logging-config-insecure-listen.py new file mode 100644 index 0000000..01f7af8 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/log/rule-logging-config-insecure-listen.py @@ -0,0 +1,10 @@ +# License: MIT (c) GitLab Inc. +# source: https://github.com/PyCQA/bandit/blob/main/examples/logging_config_insecure_listen.py (incl modifications) + +import logging +from logging import config as aliased_cfg + +# ruleid: python_log_rule-logging-config-insecure-listen +logging.config.listen(9999) # FAIL +# ruleid: python_log_rule-logging-config-insecure-listen +aliased_cfg.listen(8888) # FAIL diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/log/rule-logging-config-insecure-listen.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/log/rule-logging-config-insecure-listen.yml new file mode 100644 index 0000000..066ebac --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/log/rule-logging-config-insecure-listen.yml @@ -0,0 +1,35 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_log_rule-logging-config-insecure-listen" + languages: + - "python" + message: | + The application was found calling the `logging.config.listen`` function, which provides the + ability to listen for + external configuration files over a socket server. This listen socket parses part of the + configuration and calls + `eval` on the supplied configuration file. A local user, or an adversary who is able to + exploit + a Server Side Request Forgery (SSRF) attack to communicate over localhost, would be able to + execute arbitrary + code by passing in a logging config that contains python code. + + To remediate the issue, remove the call to `logging.config.listen` method. + + For more information on the listen functionality see: + - https://docs.python.org/3/library/logging.config.html#logging.config.listen + metadata: + cwe: "CWE-94" + shortDescription: "Improper control of generation of code ('Code Injection')" + category: "security" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + security-severity: "High" + patterns: + - pattern: "logging.config.listen(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/random/rule-random.py b/compliance-agent/rules/vendor/gitlab/upstream/python/random/rule-random.py new file mode 100644 index 0000000..829ce15 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/random/rule-random.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/random_module.py +# hash: 8eee173 + +import random +import os +import somelib + +# ruleid: python_random_rule-random +bad = random.random() +# ruleid: python_random_rule-random +bad = random.randrange() +# ruleid: python_random_rule-random +bad = random.randint() +# ruleid: python_random_rule-random +bad = random.choice() +# ruleid: python_random_rule-random +bad = random.uniform() +# ruleid: python_random_rule-random +bad = random.triangular() + +good = os.urandom() +good = random.SystemRandom() + +unknown = random() +unknown = somelib.a.random() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/random/rule-random.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/random/rule-random.yml new file mode 100644 index 0000000..d4d72ad --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/random/rule-random.yml @@ -0,0 +1,48 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_random_rule-random" + languages: + - "python" + message: | + Depending on the context, generating weak random numbers may expose cryptographic functions, + which rely on these numbers, to be exploitable. When generating numbers for sensitive values + such as tokens, nonces, and cryptographic keys, it is recommended that the `secrets` module + be used instead. + + Example using the secrets module: + ``` + import secrets + + # Generate a secure random 64 byte array + random_bytes = secrets.token_bytes(64) + print(random_bytes) + + # Generate a secure random 64 byte array as a hex string + random_bytes_hex = secrets.token_hex(64) + + # Generate a secure random 64 byte array base64 encoded for use in URLs + random_string = secrets.token_urlsafe(64) + ``` + + For more information on the `secrets` module see: + - https://docs.python.org/3/library/secrets.html + metadata: + cwe: "CWE-338" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + category: "security" + shortDescription: "Use of cryptographically weak pseudo-random number generator (PRNG)" + security-severity: "Low" + pattern-either: + - pattern: "random.random(...)" + - pattern: "random.randrange(...)" + - pattern: "random.randint(...)" + - pattern: "random.choice(...)" + - pattern: "random.uniform(...)" + - pattern: "random.triangular(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/requests/rule-request-without-timeout.py b/compliance-agent/rules/vendor/gitlab/upstream/python/requests/rule-request-without-timeout.py new file mode 100644 index 0000000..fb17624 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/requests/rule-request-without-timeout.py @@ -0,0 +1,67 @@ +# License: MIT (c) GitLab Inc. +import requests + +# ruleid: python_requests_rule-request-without-timeout +requests.get('https://gmail.com') +# ruleid: python_requests_rule-request-without-timeout +requests.get('https://gmail.com', timeout=None) +requests.get('https://gmail.com', timeout=5) +# ruleid: python_requests_rule-request-without-timeout +requests.get('https://gmail.com', timeout=None, headers={'authorization': f'token 8675309'}) +requests.get('https://gmail.com', timeout=5, headers={'authorization': f'token 8675309'}) +# ruleid: python_requests_rule-request-without-timeout +requests.get('https://gmail.com', headers={'authorization': f'token 8675309'}) +# ruleid: python_requests_rule-request-without-timeout +requests.get('https://gmail.com', headers={'authorization': f'token 8675309'}, timeout=None) +requests.get('https://gmail.com', headers={'authorization': f'token 8675309'}, timeout=5) +# ruleid: python_requests_rule-request-without-timeout +requests.post('https://gmail.com') +# ruleid: python_requests_rule-request-without-timeout +requests.post('https://gmail.com', timeout=None) +requests.post('https://gmail.com', timeout=5) +requests.post('https://gmail.com', timeout=5, headers={'authorization': f'token 8675309'}) +requests.post('https://gmail.com', headers={'authorization': f'token 8675309'}, timeout=5) +# ruleid: python_requests_rule-request-without-timeout +requests.put('https://gmail.com') +# ruleid: python_requests_rule-request-without-timeout +requests.put('https://gmail.com', timeout=None) +requests.put('https://gmail.com', timeout=5) +requests.put('https://gmail.com', timeout=5, headers={'authorization': f'token 8675309'}) +requests.put('https://gmail.com', headers={'authorization': f'token 8675309'}, timeout=5) +# ruleid: python_requests_rule-request-without-timeout +requests.delete('https://gmail.com') +# ruleid: python_requests_rule-request-without-timeout +requests.delete('https://gmail.com', timeout=None) +requests.delete('https://gmail.com', timeout=5) +requests.delete('https://gmail.com', timeout=5, headers={'authorization': f'token 8675309'}) +requests.delete('https://gmail.com', headers={'authorization': f'token 8675309'}, timeout=5) +# ruleid: python_requests_rule-request-without-timeout +requests.patch('https://gmail.com') +# ruleid: python_requests_rule-request-without-timeout +requests.patch('https://gmail.com', timeout=None) +requests.patch('https://gmail.com', timeout=5) +requests.patch('https://gmail.com', timeout=5, headers={'authorization': f'token 8675309'}) +requests.patch('https://gmail.com', headers={'authorization': f'token 8675309'}, timeout=5) +# ruleid: python_requests_rule-request-without-timeout +requests.options('https://gmail.com') +# ruleid: python_requests_rule-request-without-timeout +requests.options('https://gmail.com', timeout=None) +requests.options('https://gmail.com', timeout=5) +requests.options('https://gmail.com', timeout=5, headers={'authorization': f'token 8675309'}) +requests.options('https://gmail.com', headers={'authorization': f'token 8675309'}, timeout=5) +# ruleid: python_requests_rule-request-without-timeout +requests.head('https://gmail.com') +# ruleid: python_requests_rule-request-without-timeout +requests.head('https://gmail.com', timeout=None) +requests.head('https://gmail.com', timeout=5) +requests.head('https://gmail.com', timeout=5, headers={'authorization': f'token 8675309'}) +requests.head('https://gmail.com', headers={'authorization': f'token 8675309'}, timeout=5) + + +def get(url): + # ruleid: python_requests_rule-request-without-timeout + return requests.get(url) + + +def get(url, timeout=10): + return requests.get(url, timeout=timeout) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/requests/rule-request-without-timeout.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/requests/rule-request-without-timeout.yml new file mode 100644 index 0000000..6c633e3 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/requests/rule-request-without-timeout.yml @@ -0,0 +1,55 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_requests_rule-request-without-timeout" + languages: + - "python" + message: | + The application was found using the `requests` module without configuring a timeout value for + connections. This could lead to uncontrolled resource consumption where the application could + run out of + socket descriptors, effectively causing a Denial of Service (DoS). + + To remediate this issue, pass in a `timeout=` argument to each `requests` call. + + Example using a timeout for an HTTP GET request: + ``` + # Issue a GET request to https://example.com with a timeout of 10 seconds + response = requests.get('https://example.com', timeout=10) + # Work with the response object + # ... + ``` + + For more information on using the requests module see: + - https://requests.readthedocs.io/en/latest/api/ + patterns: + - pattern-either: + - patterns: + - pattern: "requests.$METHOD(..., timeout=$VAL, ...)" + - metavariable-comparison: + comparison: "$VAL <= 0" + metavariable: "$VAL" + - patterns: + - pattern: "requests.$METHOD(..., timeout=$VAL, ...)" + - metavariable-regex: + metavariable: "$VAL" + regex: "(^None)" + - patterns: + - pattern-not: "requests.$METHOD(..., timeout=$VAL, ...)" + - pattern-either: + - pattern: "requests.$METHOD(..., ...)" + - pattern: "requests.$METHOD(...)" + - metavariable-regex: + metavariable: "$METHOD" + regex: "(get|put|delete|post|options|head|patch)" + metadata: + cwe: "CWE-770" + category: "security" + shortDescription: "Allocation of resources without limits or throttling" + owasp: + - "A6:2017-Security Misconfiguration" + - "A05:2021-Security Misconfiguration" + security-severity: "Medium" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-insecure-snmp-version.py b/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-insecure-snmp-version.py new file mode 100644 index 0000000..2086d23 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-insecure-snmp-version.py @@ -0,0 +1,10 @@ +# License: MIT (c) GitLab Inc. +# source: https://bandit.readthedocs.io/en/latest/_modules/bandit/plugins/snmp_security_check.html#snmp_insecure_version_check + +from pysnmp.hlapi import CommunityData + +# SHOULD FAIL +# ruleid: python_snmp_rule-insecure-snmp-version +a = CommunityData('public', mpModel=0) +# ruleid: python_snmp_rule-insecure-snmp-version +b = CommunityData('public', mpModel=1) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-insecure-snmp-version.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-insecure-snmp-version.yml new file mode 100644 index 0000000..e43d3d4 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-insecure-snmp-version.yml @@ -0,0 +1,45 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_snmp_rule-insecure-snmp-version" + languages: + - "python" + message: | + Pysnmp was detected using versions SNMPv1 or SNMPv2. SNPMv1 and SNMPv2 are insecure + and should no longer be used as they do not offer encryption. + + If possible, query SNMP devices using SNMPv3 instead. + + Example querying a device using SNMPv3 with SHA-AES: + ``` + from pysnmp.hlapi import * + # Create the snpm iterator + iterator = getCmd( + SnmpEngine(), + # Configure using SHA AES + UsmUserData('usr-sha-aes', 'authkey1', 'privkey1', + authProtocol=USM_AUTH_HMAC96_SHA, + privProtocol=USM_PRIV_CFB128_AES), + UdpTransportTarget(('demo.snmplabs.com', 161)), + ContextData(), + ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) + ) + ``` + + For more information on using SNMPv3 with `Pysnmp` see: + - https://pysnmp.readthedocs.io/en/latest/examples/hlapi/v3arch/asyncore/sync/manager/cmdgen/snmp-versions.html#snmpv3-auth-sha-privacy-aes128 + metadata: + cwe: "CWE-319" + category: "security" + shortDescription: "Cleartext transmission of sensitive information" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + security-severity: "Medium" + pattern-either: + - pattern: "pysnmp.hlapi.CommunityData(..., mpModel=0, ...)" + - pattern: "pysnmp.hlapi.CommunityData(..., mpModel=1, ...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-snmp-weak-cryptography.py b/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-snmp-weak-cryptography.py new file mode 100644 index 0000000..408192b --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-snmp-weak-cryptography.py @@ -0,0 +1,125 @@ +# License: MIT (c) GitLab Inc. + +from pysnmp.hlapi import * + + +# SNMPv3 User details +username = 'myUsername' +auth_key = 'myAuthKey' +priv_key = 'myPrivKey' + + +# auth MD5, privacy DES +# ok: python_snmp_rule-snmp-weak-cryptography +user_data1 = UsmUserData(username, auth_key, priv_key) +print(f"auth MD5, privacy DES : \n {user_data1}") + + +# auth SHA, privacy AES128 +# ok: python_snmp_rule-snmp-weak-cryptography +user_data2 = UsmUserData(username, auth_key, priv_key, + authProtocol=usmHMACSHAAuthProtocol, + privProtocol=usmAesCfb128Protocol) +print("\nauth SHA, privacy AES128 : \n", user_data2) + +# auth MD5, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data3 = UsmUserData(username, auth_key) +print("\nauth MD5, no privacy : \n",user_data3) + +# auth MD5, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data4 = UsmUserData(username, auth_key, privKey=None) +print("\nauth MD5, no privacy : \n",user_data4) + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data5 = UsmUserData(username, authKey=None, privKey=None) +print("\nno auth, no privacy : \n",user_data5) + + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data6 = UsmUserData(username) +print("\nno auth, no privacy : \n",user_data6) + +# MD5 auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data7 = UsmUserData(username, authKey=auth_key, privKey=priv_key, privProtocol = usmNoPrivProtocol) +print("\nauth MD5, no privacy : \n",user_data7) + + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data8 = UsmUserData(username, authKey=None, authProtocol=usmNoAuthProtocol, privKey=None, privProtocol=usmNoPrivProtocol) +print("\nno auth, no privacy : \n",user_data8) + + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data9 = UsmUserData(username, authKey=auth_key, authProtocol=usmNoAuthProtocol) +print("\nno auth, no privacy : \n",user_data9) + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data10 = UsmUserData(username, privKey=None, privProtocol=usmNoPrivProtocol) +print("\nno auth, no privacy : \n",user_data10) + + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data11 = UsmUserData(username, authKey=auth_key, privKey=None, authProtocol=(1,3,6,1,6,3,10,1,1,1), privProtocol=(1,3,6,1,6,3,10,1,2,1)) +print("\nno auth, no privacy : \n",user_data11) + +# MD5 auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data12 = UsmUserData(username, authKey=auth_key, privKey=priv_key, privProtocol=(1,3,6,1,6,3,10,1,2,1)) +print("\nauth MD5, no privacy : \n",user_data12) + + +# SHA auth, AES privacy +# ok: python_snmp_rule-snmp-weak-cryptography +user_data13 = UsmUserData(username, authKey=auth_key, authProtocol=(1,3,6,1,6,3,10,1,1,3), privKey=priv_key, privProtocol=(1,3,6,1,6,3,10,1,2,4)) +print("\nSHA auth, AES privacy : \n",user_data13) + + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data14 = UsmUserData(username, authKey=auth_key, authProtocol=(1,3,6,1,6,3,10,1,1,1)) +print("\nno auth, no privacy : \n",user_data14) + + +# auth MD5, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data15 = UsmUserData(username, auth_key, None) +print("\nauth MD5, no privacy : \n",user_data15) + + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data16 = UsmUserData(username, None, None) +print("\nno auth, no privacy : \n",user_data16) + + +# auth SHA, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data17 = UsmUserData(username, auth_key, authProtocol=usmHMACSHAAuthProtocol, securityEngineId=None, securityName=None) +print("\nauth SHA, no privacy : \n",user_data17) + + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data18 = UsmUserData(username, securityEngineId=None, securityName=None) +print("\nno auth, no privacy : \n",user_data18) + + +# MD5 auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data19 = UsmUserData(username, authKey=auth_key, authProtocol=(1,3,6,1,6,3,10,1,1,2)) +print("\nMD5 auth, no privacy : \n",user_data19) + + +# no auth, no privacy +# ruleid: python_snmp_rule-snmp-weak-cryptography +user_data20 = UsmUserData(username, None, securityEngineId=None, securityName=None) +print("\nauth MD5, no privacy : \n",user_data15) \ No newline at end of file diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-snmp-weak-cryptography.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-snmp-weak-cryptography.yml new file mode 100644 index 0000000..0e8806c --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/snmp/rule-snmp-weak-cryptography.yml @@ -0,0 +1,67 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_snmp_rule-snmp-weak-cryptography" + languages: + - "python" + message: | + Pysnmp was detected using SNMPv3 without authentication or encryption + protections enabled. + + - Use of `usmNoAuthProtocol` or `usmNoPrivProtocol` indicates that + either authentication or privacy, respectively, is not being used. + - The absence of `authKey` (or `authKey=None`) implies no authentication, + which is equivalent to using `usmNoAuthProtocol`. + - The absence of `privKey` (or `privKey=None`) implies no privacy (encryption), + which is equivalent to using `usmNoPrivProtocol`. + + To enhance the security of your SNMP communications, it is recommended to use both + authentication and privacy features in SNMPv3: + + - Use SHA for Authentication: SHA (Secure Hash Algorithm) is a more secure option + for SNMP message authentication. To use SHA, set the `authProtocol` to + `usmHMACSHAAuthProtocol` and provide a strong `authKey`. + - Use AES for Privacy: AES (Advanced Encryption Standard) is recommended for + encrypting SNMP messages. Set the `privProtocol` to `usmAesCfb128Protocol` + or a similar AES-based protocol and specify a strong `privKey`. + + Example of secure `UsmUserData` configuration: + ``` + from pysnmp.hlapi import UsmUserData, usmHMACSHAAuthProtocol, usmAesCfb128Protocol + + user_data = UsmUserData('username','authKey', 'privKey', + authProtocol=usmHMACSHAAuthProtocol, + privProtocol=usmAesCfb128Protocol) + ``` + metadata: + cwe: "CWE-319" + category: "security" + shortDescription: "Cleartext transmission of sensitive information" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + security-severity: "Medium" + pattern-either: + - pattern-regex: "UsmUserData(.*usmNoAuthProtocol.*)" + - pattern-regex: "UsmUserData(.*usmNoPrivProtocol.*)" + - pattern: | + UsmUserData(..., authKey=None, ...) + - pattern: | + UsmUserData(..., privKey=None, ...) + - pattern: | + UsmUserData(..., authProtocol=(1,3,6,1,6,3,10,1,1,1), ...) + - pattern: | + UsmUserData(..., privProtocol=(1,3,6,1,6,3,10,1,2,1), ...) + - patterns: + - pattern-not: | + UsmUserData($NAME,$AUTHKEY,"...", ...) + - pattern-not: | + UsmUserData(..., privKey=$PRIVKEY, ...) + - pattern-not: | + UsmUserData(..., privProtocol=$PRIVPROT, ...) + - pattern: | + UsmUserData(...) + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/sql/rule-hardcoded-sql-expression.py b/compliance-agent/rules/vendor/gitlab/upstream/python/sql/rule-hardcoded-sql-expression.py new file mode 100644 index 0000000..b871a0b --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/sql/rule-hardcoded-sql-expression.py @@ -0,0 +1,131 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/sql_statements.py +# hash: 8eee173 + +import sqlalchemy + +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("SELECT * FROM foo WHERE id = '%s'" % identifier) +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("INSERT INTO foo VALUES ('a', 'b', '%s')" % value) +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM foo WHERE id = '%s'" % identifier) +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("UPDATE foo SET value = 'b' WHERE id = '%s'" % identifier) +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("SELECT * FROM foo WHERE id = '" + identifier + "'") +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("SELECT * FROM foo WHERE id = '{}'".format(identifier)) + +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute("SELECT * FROM foo WHERE id = '%s'", identifier) +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute("INSERT INTO foo VALUES ('a', 'b', '%s')", value) +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM foo WHERE id = '%s'", identifier) +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute("UPDATE foo SET value = 'b' WHERE id = '%s'", identifier) + +# real world false positives +choices=[('server_list', _("Select from active instances"))] +print("delete from the cache as the first argument") + +def select_note_by_id(conn, id=None): + query = "SELECT * FROM notes" + if id: + query = query + " WHERE id = '%s'" % id + cur = conn.cursor() + # ruleid: python_sql_rule-hardcoded-sql-expression + cur.execute(query) + rows = cur.fetchall() + return rows + +# ok: python_sql_rule-hardcoded-sql-expression +foo.execute("unrelated to select and sql" % identifier) + +# ok: python_sql_rule-hardcoded-sql-expression +foo.execute("updated" % identifier) + +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute('SELECT * FROM dual') + +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute('CREATE TABLE %s' % tableName) + +ctStm = 'CREATE TABLE ' +ctStm = ctStm + ' %s' % tableName +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute(ctStm) + +upStm = 'UPDATE foo WHERE user = %s' % 'admin' +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute(upStm) + +upStm2 = f'UPDATE foo WHERE user = "admin"' +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute(upStm2) + +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute(f'UPDATE foo WHERE user = "admin"') + + +s1 = "DELETE FROM tableX WHERE colY <= " +s1 += str(response_data['delete_record']) +# ruleid: python_sql_rule-hardcoded-sql-expression +db.execute(s1) + +s2 = "DELETE FROM tableX WHERE colY <= " + str(response_data['delete_record']) +# ruleid: python_sql_rule-hardcoded-sql-expression +db.execute(s2) + +s3 = "DELETE FROM tableX WHERE id <= %s" % "something constant" +# ok: python_sql_rule-hardcoded-sql-expression +db.execute(s3) + +s4 = "DELETE FROM tableX WHERE colY <= " +s4 += "delete_record" +# ok: python_sql_rule-hardcoded-sql-expression +db.execute(s4) + +con = sqlite3.connect(filepath) +cur = con.cursor() +foo = getSomeVar() +bar = getAnotherVar() +bazConst = "this is a literal" +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM tableX WHERE colY <= " + str(response_data['delete_record'])) +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM tableX WHERE id = '" + bar + "'") +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM tableX WHERE id = '" + bar + "'" + " AND somethingElse <= " + foo) +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM tableX WHERE id = '" + bar + "'" + " AND somethingElse = '" + foo + "'") +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM tableX WHERE id <= " + "something constant") +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM tableX WHERE id <= %s" % bar) +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM tableX WHERE id <= %s" % "something constant") +# ok: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM tableX WHERE id <= %s" % bazConst) + +# This is a false positive result since 3 is a constant. +# ruleid: python_sql_rule-hardcoded-sql-expression +cur.execute("DELETE FROM tableX WHERE id <= " + str(3)) + + +# Get user input for login +username = input("Enter your username: ") +password = input("Enter your password: ") + +# Vulnerable Query: Directly embedding user input into the SQL query +query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'" +print(f"Executing query: {query}") # Debugging purpose +# ruleid: python_sql_rule-hardcoded-sql-expression +cursor.execute(query) + +# ruleid: python_sql_rule-hardcoded-sql-expression +cursor.execute(f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'") + +# ok: python_sql_rule-hardcoded-sql-expression +cursor.execute(f"SELECT * FROM users WHERE username = 'abc'") diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/sql/rule-hardcoded-sql-expression.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/sql/rule-hardcoded-sql-expression.yml new file mode 100644 index 0000000..a964b3b --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/sql/rule-hardcoded-sql-expression.yml @@ -0,0 +1,86 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_sql_rule-hardcoded-sql-expression" + languages: + - "python" + message: | + SQL Injection is a critical vulnerability that can lead to data or system compromise. By + dynamically generating SQL query strings, user input may be able to influence the logic of + the SQL statement. This could lead to an adversary accessing information they should + not have access to, or in some circumstances, being able to execute OS functionality or code. + + Replace all dynamically generated SQL queries with parameterized queries. In situations where + dynamic queries must be created, never use direct user input, but instead use a map or + dictionary of valid values and resolve them using a user supplied key. + + For example, some database drivers do not allow parameterized queries for `>` or `<` comparison + operators. In these cases, do not use a user supplied `>` or `<` value, but rather have the + user + supply a `gt` or `lt` value. The alphabetical values are then used to look up the `>` and `<` + values to be used in the construction of the dynamic query. The same goes for other queries + where + column or table names are required but cannot be parameterized. + + Example using `PreparedStatement` queries: + ``` + import sqlite3 + + # Create a new database (in memory) + con = sqlite3.connect(":memory:") + # Get a cursor from the connection + cur = con.cursor() + # Create a tuple of the value to be used in the parameterized query + params = ('user-input',) + # execute the statement, passing in the params for the value + cur.execute("select name from sqlite_master where name = ?", params) + # work with the result + result = cur.fetchall() + ``` + + For more information on SQL Injection see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html + metadata: + cwe: "CWE-89" + owasp: + - "A1:2017-Injection" + - "A03:2021-Injection" + - "A05:2025-Injection" + category: "security" + shortDescription: "Improper neutralization of special elements used in an SQL + Command ('SQL Injection')" + security-severity: "High" + mode: taint + pattern-sources: + - patterns: + - pattern-either: + - pattern: | + "$QUERY" % ... + - pattern: | + "$QUERY".format(...) + - pattern: | + f"$QUERY{...}..." + - pattern: | + "$QUERY" + ... + - pattern: | + $TMP = "$QUERY" + ... + $SQL = $TMP + "..." % ... + - pattern: | + $SQL = "$QUERY" + ... + $SQL += ... + - metavariable-regex: + metavariable: $QUERY + regex: (?i)^(SELECT|INSERT|UPDATE|DELETE)\s + pattern-sinks: + - patterns: + - pattern: $DB.execute(...) + - pattern-not: + pattern-either: + - pattern: $DB.execute("...") + - pattern: $DB.execute("$QUERY" % "...") + - pattern: $DB.execute("$QUERY" + "...") + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-req-no-certvalid.py b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-req-no-certvalid.py new file mode 100644 index 0000000..e20baab --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-req-no-certvalid.py @@ -0,0 +1,27 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/requests-ssl-verify-disabled.py +# hash: 8eee173 + +import requests + +requests.get('https://gmail.com', verify=True) +# ruleid: python_ssl_rule-req-no-certvalid +requests.get('https://gmail.com', verify=False) +requests.post('https://gmail.com', verify=True) +# ruleid: python_ssl_rule-req-no-certvalid +requests.post('https://gmail.com', verify=False) +requests.put('https://gmail.com', verify=True) +# ruleid: python_ssl_rule-req-no-certvalid +requests.put('https://gmail.com', verify=False) +requests.delete('https://gmail.com', verify=True) +# ruleid: python_ssl_rule-req-no-certvalid +requests.delete('https://gmail.com', verify=False) +requests.patch('https://gmail.com', verify=True) +# ruleid: python_ssl_rule-req-no-certvalid +requests.patch('https://gmail.com', verify=False) +requests.options('https://gmail.com', verify=True) +# ruleid: python_ssl_rule-req-no-certvalid +requests.options('https://gmail.com', verify=False) +requests.head('https://gmail.com', verify=True) +# ruleid: python_ssl_rule-req-no-certvalid +requests.head('https://gmail.com', verify=False) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-req-no-certvalid.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-req-no-certvalid.yml new file mode 100644 index 0000000..ac30a75 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-req-no-certvalid.yml @@ -0,0 +1,51 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_ssl_rule-req-no-certvalid" + languages: + - "python" + message: | + The application was found using the `requests` module without configuring a timeout value for + connections. The `verify=False` argument has been set, which effectively disables the + validation + of server certificates. + + This allows for an adversary who is in between the application and the target host to intercept + potentially sensitive information or transmit malicious data. + + To remediate this issue either remove the `verify=False` argument, or set `verify=True`to each + `requests` call. + + Example verifying server certificates for an HTTP GET request: + ``` + # Issue a GET request to https://example.com with a timeout of 10 seconds and verify the + # server certificate explicitly. + response = requests.get('https://example.com', timeout=10, verify=True) + # Work with the response object + # ... + ``` + + For more information on using the requests module see: + - https://requests.readthedocs.io/en/latest/api/ + metadata: + cwe: "CWE-295" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A07:2021-Identification and Authentication Failures" + - "A07:2025-Authentication Failures" + category: "security" + shortDescription: "Improper certificate validation" + security-severity: "Medium" + patterns: + - pattern-either: + - pattern: "requests.put(..., verify=False, ...)" + - pattern: "requests.patch(..., verify=False, ...)" + - pattern: "requests.delete(..., verify=False, ...)" + - pattern: "requests.head(..., verify=False, ...)" + - pattern: "requests.options(..., verify=False, ...)" + - pattern: "requests.request(..., verify=False, ...)" + - pattern: "requests.get(..., verify=False, ...)" + - pattern: "requests.post(..., verify=False, ...)" + severity: "ERROR" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-no-version.py b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-no-version.py new file mode 100644 index 0000000..fac4efd --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-no-version.py @@ -0,0 +1,41 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ssl-insecure-version.py +# hash: 8eee173 + +import ssl +from pyOpenSSL import SSL + +ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv2) +SSL.Context(method=SSL.SSLv2_METHOD) +SSL.Context(method=SSL.SSLv23_METHOD) + +herp_derp(ssl_version=ssl.PROTOCOL_SSLv2) +herp_derp(method=SSL.SSLv2_METHOD) +herp_derp(method=SSL.SSLv23_METHOD) + +# strict tests +ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv3) +ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1) +SSL.Context(method=SSL.SSLv3_METHOD) +SSL.Context(method=SSL.TLSv1_METHOD) + +herp_derp(ssl_version=ssl.PROTOCOL_SSLv3) +herp_derp(ssl_version=ssl.PROTOCOL_TLSv1) +herp_derp(method=SSL.SSLv3_METHOD) +herp_derp(method=SSL.TLSv1_METHOD) + +# ruleid: python_ssl_rule-ssl-no-version +ssl.wrap_socket() + +def open_ssl_socket(version=ssl.PROTOCOL_SSLv2): + pass + +def open_ssl_socket(version=SSL.SSLv2_METHOD): + pass + +def open_ssl_socket(version=SSL.SSLv23_METHOD): + pass + +# this one will pass ok +def open_ssl_socket(version=SSL.TLSv1_1_METHOD): + pass diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-no-version.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-no-version.yml new file mode 100644 index 0000000..9965f8a --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-no-version.yml @@ -0,0 +1,64 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_ssl_rule-ssl-no-version" + languages: + - "python" + message: | + The application was found calling `ssl.wrap_socket` without a TLS protocol version specified. + Additionally, `ssl.wrap_socket` has been deprecated since Python 3.7. It is strongly + recommended + that newer applications use TLS 1.2 or 1.3 and `SSLContext.wrap_socket`. + + To remediate this issue, create a new TLS context and pass in `ssl.PROTOCOL_TLS_CLIENT` + for clients or `ssl.PROTOCOL_TLS_SERVER` for servers to the `ssl.SSLContext(...)` `protocol=` + argument. When converting the socket to a TLS socket, use the new `SSLContext.wrap_socket` + method instead. + + + Example creating a TLS 1.3 client socket connection by using a newer version of Python + (3.11.4) and + the SSL module: + ``` + import ssl + import socket + + # Create our initial socket + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + # Connect the socket + sock.connect(('www.example.org', 443)) + + # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT + # This will auto-select the highest grade TLS protocol version (1.3) + context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) + # Load our a certificates for server certificate authentication + context.load_verify_locations('cert.pem') + # Create our TLS socket, and validate the server hostname matches + with context.wrap_socket(sock, server_hostname="www.example.org") as tls_sock: + # Send some bytes over the socket (HTTP request in this case)\ + data = bytes('GET / HTTP/1.1\r\nHost: example.org\r\n\r\n', 'utf-8') + sent_bytes = tls_sock.send(data) + # Validate number of sent bytes + # ... + # Read the response + resp = tls_sock.recv() + # Work with the response + # ... + ``` + + For more information on the ssl module see: + - https://docs.python.org/3/library/ssl.html + metadata: + cwe: "CWE-326" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + shortDescription: "Inadequate encryption strength" + security-severity: "Medium" + category: "security" + patterns: + - pattern: "ssl.wrap_socket()" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-with-bad-version.py b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-with-bad-version.py new file mode 100644 index 0000000..a47eab1 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-with-bad-version.py @@ -0,0 +1,58 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/ssl-insecure-version.py +# hash: 8eee173 + +import ssl +from pyOpenSSL import SSL + +# ruleid: python_ssl_rule-ssl-with-bad-version +ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv2) +# ruleid: python_ssl_rule-ssl-with-bad-version +SSL.Context(method=SSL.SSLv2_METHOD) +# ruleid: python_ssl_rule-ssl-with-bad-version +SSL.Context(method=SSL.SSLv23_METHOD) + +# ruleid: python_ssl_rule-ssl-with-bad-version +herp_derp(ssl_version=ssl.PROTOCOL_SSLv2) +# ruleid: python_ssl_rule-ssl-with-bad-version +herp_derp(method=SSL.SSLv2_METHOD) +# ruleid: python_ssl_rule-ssl-with-bad-version +herp_derp(method=SSL.SSLv23_METHOD) + +# strict tests +# ruleid: python_ssl_rule-ssl-with-bad-version +ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv3) +# ruleid: python_ssl_rule-ssl-with-bad-version +ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1) +# ruleid: python_ssl_rule-ssl-with-bad-version +SSL.Context(method=SSL.SSLv3_METHOD) +# ruleid: python_ssl_rule-ssl-with-bad-version +SSL.Context(method=SSL.TLSv1_METHOD) + +# ruleid: python_ssl_rule-ssl-with-bad-version +herp_derp(ssl_version=ssl.PROTOCOL_SSLv3) +# ruleid: python_ssl_rule-ssl-with-bad-version +herp_derp(ssl_version=ssl.PROTOCOL_TLSv1) +# ruleid: python_ssl_rule-ssl-with-bad-version +herp_derp(method=SSL.SSLv3_METHOD) +# ruleid: python_ssl_rule-ssl-with-bad-version +herp_derp(method=SSL.TLSv1_METHOD) + +ssl.wrap_socket() + +# ruleid: python_ssl_rule-ssl-with-bad-version +def open_ssl_socket(version=ssl.PROTOCOL_SSLv2): + pass + +# ruleid: python_ssl_rule-ssl-with-bad-version +def open_ssl_socket(version=SSL.SSLv2_METHOD): + pass + +# ruleid: python_ssl_rule-ssl-with-bad-version +def open_ssl_socket(version=SSL.SSLv23_METHOD): + pass + +# this one will pass ok +# ruleid: python_ssl_rule-ssl-with-bad-version +def open_ssl_socket(version=SSL.TLSv1_1_METHOD): + pass diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-with-bad-version.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-with-bad-version.yml new file mode 100644 index 0000000..34dbe9c --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-ssl-with-bad-version.yml @@ -0,0 +1,81 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_ssl_rule-ssl-with-bad-version" + languages: + - "python" + message: | + The application was found calling an SSL module with SSL or TLS protocols that have known + deficiencies. + It is strongly recommended that newer applications use TLS 1.2 or 1.3 and + `SSLContext.wrap_socket`. + + If using the `pyOpenSSL` module, please note that it has been deprecated and the Python + Cryptographic Authority + strongly suggests moving to use the [pyca/cryptography](https://github.com/pyca/cryptography) + module instead. + + To remediate this issue for the `ssl` module, create a new TLS context and pass in + `ssl.PROTOCOL_TLS_CLIENT` for clients or `ssl.PROTOCOL_TLS_SERVER` for servers to the + `ssl.SSLContext(...)` `protocol=` + argument. When converting the socket to a TLS socket, use the new `SSLContext.wrap_socket` + method instead. + + Example creating a TLS 1.3 client socket connection by using a newer version of Python + (3.11.4) and + the SSL module: + ``` + import ssl + import socket + + # Create our initial socket + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + # Connect the socket + sock.connect(('www.example.org', 443)) + + # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT + # This will auto-select the highest grade TLS protocol version (1.3) + context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) + # Load our a certificates for server certificate authentication + context.load_verify_locations('cert.pem') + # Create our TLS socket, and validate the server hostname matches + with context.wrap_socket(sock, server_hostname="www.example.org") as tls_sock: + # Send some bytes over the socket (HTTP request in this case)\ + data = bytes('GET / HTTP/1.1\r\nHost: example.org\r\n\r\n', 'utf-8') + sent_bytes = tls_sock.send(data) + # Validate number of sent bytes + # ... + # Read the response + resp = tls_sock.recv() + # Work with the response + # ... + ``` + + For more information on the ssl module see: + - https://docs.python.org/3/library/ssl.html + + For more information on pyca/cryptography and openssl see: + - https://cryptography.io/en/latest/openssl/ + metadata: + cwe: "CWE-326" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + shortDescription: "Inadequate Encryption Strength" + security-severity: "Medium" + category: "security" + patterns: + - pattern-either: + - pattern: "ssl.PROTOCOL_SSLv2" + - pattern: "ssl.PROTOCOL_SSLv3" + - pattern: "ssl.PROTOCOL_TLSv1" + - pattern: "ssl.PROTOCOL_TLSv1_1" + - pattern: "pyOpenSSL.SSL.SSLv2_METHOD" + - pattern: "pyOpenSSL.SSL.SSLv23_METHOD" + - pattern: "pyOpenSSL.SSL.SSLv3_METHOD" + - pattern: "pyOpenSSL.SSL.TLSv1_METHOD" + - pattern: "pyOpenSSL.SSL.TLSv1_1_METHOD" + severity: "ERROR" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-unverified-context.py b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-unverified-context.py new file mode 100644 index 0000000..86c3571 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-unverified-context.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/unverified_context.py hash: 8eee173 + +import ssl + +# Correct +context = ssl.create_default_context() + +# Incorrect: unverified context +# ruleid: python_ssl_rule-unverified-context +context = ssl._create_unverified_context() + +import ssl + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-unverified-context.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-unverified-context.yml new file mode 100644 index 0000000..c7fc63f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/ssl/rule-unverified-context.yml @@ -0,0 +1,62 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_ssl_rule-unverified-context" + languages: + - "python" + message: | + The application was found creating a SSL context using the `_create_unverified_context`. + This effectively disables the validation of server certificates. + + This allows for an adversary who is in between the application and the target host to intercept + potentially sensitive information or transmit malicious data. + + To remediate this issue remove the call to `_create_unverified_context` and either create a + default + context using `ssl.create_default_context` or create a context with TLS 1.3. + + Example creating a TLS 1.3 client socket connection by using a newer version of Python + (3.11.4) and + the SSL module: + ``` + import ssl + import socket + + # Create our initial socket + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + # Connect the socket + sock.connect(('www.example.org', 443)) + + # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT + # This will auto-select the highest grade TLS protocol version (1.3) + context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) + # Load our a certificates for server certificate authentication + context.load_verify_locations('cert.pem') + # Create our TLS socket, and validate the server hostname matches + with context.wrap_socket(sock, server_hostname="www.example.org") as tls_sock: + # Send some bytes over the socket (HTTP request in this case)\ + data = bytes('GET / HTTP/1.1\r\nHost: example.org\r\n\r\n', 'utf-8') + sent_bytes = tls_sock.send(data) + # Validate number of sent bytes + # ... + # Read the response + resp = tls_sock.recv() + # Work with the response + # ... + ``` + + Unverified SSL context detected. This will permit insecure connections without `verifyingSSL` + certificates. Use `ssl.create_default_context()` instead. + metadata: + cwe: "CWE-295" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A07:2021-Identification and Authentication Failures" + - "A07:2025-Authentication Failures" + category: "security" + shortDescription: "Improper certificate validation" + security-severity: "Medium" + pattern: "ssl._create_unverified_context(...)" + severity: "ERROR" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/telnet/rule-import-telnib.py b/compliance-agent/rules/vendor/gitlab/upstream/python/telnet/rule-import-telnib.py new file mode 100644 index 0000000..c5c80a6 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/telnet/rule-import-telnib.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/telnetlib.py +# hash: 8eee173 + +# ruleid: python_telnet_rule-import-telnib +import telnetlib +import getpass + +host = sys.argv[1] + +username = raw_input('Username:') +password = getpass.getpass() +tn = telnetlib.Telnet(host) + +tn.read_until("login: ") +tn.write(username + "\n") +if password: + tn.read_until("Password: ") + tn.write(password + "\n") + +tn.write("ls\n") +tn.write("exit\n") + +print(tn.read_all()) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/telnet/rule-import-telnib.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/telnet/rule-import-telnib.yml new file mode 100644 index 0000000..7cb11fb --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/telnet/rule-import-telnib.yml @@ -0,0 +1,48 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_telnet_rule-import-telnib" + languages: + - "python" + message: | + The application was found using a telnet library. As telnet does not provide encryption, it is + strongly recommended that communications use a more secure transport such as + SSH. + + The [paramiko](https://www.paramiko.org/) library can be used to initiate SSH connections. + + Example using `paramiko` SSH client: + ``` + import paramiko + import scp + + # Create an SSH client + with paramiko.SSHClient() as ssh: + # Load the system host keys so we can confirm the + # host we are connecting to is legitimate + ssh.load_system_host_keys('/home/appuser/.ssh/known_hosts') + + # Connect to the remote host using our SSH private key + ssh.connect(hostname='example.org', + port=22, + username='appuser', + key_filename='/home/appuser/.ssh/private_key') + # Work with the connection + ``` + + For more information on the paramiko module see: + - https://www.paramiko.org/ + metadata: + cwe: "CWE-319" + category: "security" + owasp: + - "A3:2017-Sensitive Data Exposure" + - "A02:2021-Cryptographic Failures" + - "A04:2025-Cryptographic Failures" + shortDescription: "Cleartext transmission of sensitive information" + security-severity: "Medium" + patterns: + - pattern: "import telnetlib" + severity: "ERROR" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-hardcodedtmp.py b/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-hardcodedtmp.py new file mode 100644 index 0000000..5fb1d16 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-hardcodedtmp.py @@ -0,0 +1,15 @@ +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/hardcoded-tmp.py +# hash: 8eee173 + +# ruleid: python_tmpdir_rule-hardcodedtmp +with open('/tmp/abc', 'w') as f: + f.write('def') + +# ok +with open('/abc/tmp', 'w') as f: + f.write('def') + +# Negative test +with open('/foo/bar', 'w') as f: + f.write('def') diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-hardcodedtmp.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-hardcodedtmp.yml new file mode 100644 index 0000000..0a3e6a7 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-hardcodedtmp.yml @@ -0,0 +1,43 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_tmpdir_rule-hardcodedtmp" + languages: + - "python" + message: | + The application was found creating files in shared system temporary directories + (`/tmp` or `/var/tmp`) without using the `tempfile.TemporaryFile` function. Depending + on how the application uses this temporary file, an attacker may be able to create + symlinks that point to other files prior to the application creating or writing + to the target file, leading to unintended files being created or overwritten. + + Example using `tempfile.TemporaryFile` to write a file: + ``` + import tempfile + + # Open a new temporary file using a context manager + with tempfile.TemporaryFile() as fp: + # Write some data to the temporary file + fp.write(b'Some data') + # Seek back to beginning of file + fp.seek(0) + # Read it + data = fp.read() + # File is automatically closed/removed once we exit the with context + ``` + + For more information on alternative tempfile functions see: + - https://docs.python.org/3/library/tempfile.html + metadata: + cwe: "CWE-377" + category: "security" + shortDescription: "Insecure temporary file" + owasp: + - "A5:2017-Broken Access Control" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + security-severity: "Medium" + pattern: "$CALL(\"=~/^\\/tmp.*/\", ...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-mktemp-q.py b/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-mktemp-q.py new file mode 100644 index 0000000..008ad5e --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-mktemp-q.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/mktemp.py +# hash: 8eee173 + +from tempfile import mktemp +import tempfile.mktemp as mt +import tempfile as tmp + +foo = 'hi' + +# ruleid: python_tmpdir_rule-mktemp-q +mktemp(foo) +# ruleid: python_tmpdir_rule-mktemp-q +tempfile.mktemp('foo') +# ruleid: python_tmpdir_rule-mktemp-q +mt(foo) +# ruleid: python_tmpdir_rule-mktemp-q +tmp.mktemp(foo) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-mktemp-q.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-mktemp-q.yml new file mode 100644 index 0000000..12171fe --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/tmpdir/rule-mktemp-q.yml @@ -0,0 +1,44 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_tmpdir_rule-mktemp-q" + languages: + - "python" + message: | + The application was found creating temporary files with the insecure `mktemp` method. + Depending on how the application uses this temporary file, an attacker may be able to create + symlinks that point to other files prior to the application creating or writing + to the target file, leading to unintended files being created or overwritten. + + To remediate this issue consider using `tempfile.TemporaryFile` instead. + + Example using `tempfile.TemporaryFile` to write a file: + ``` + import tempfile + + # Open a new temporary file using a context manager + with tempfile.TemporaryFile() as fp: + # Write some data to the temporary file + fp.write(b'Some data') + # Seek back to beginning of file + fp.seek(0) + # Read it + data = fp.read() + # File is automatically closed/removed once we exit the with context + ``` + + For more information on alternative tempfile functions see: + - https://docs.python.org/3/library/tempfile.html + metadata: + cwe: "CWE-377" + category: "security" + owasp: + - "A5:2017-Broken Access Control" + - "A01:2021-Broken Access Control" + - "A01:2025-Broken Access Control" + shortDescription: "Insecure temporary file" + security-severity: "Medium" + pattern: "tempfile.mktemp(...)" + severity: "ERROR" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/urlopen/rule-urllib-urlopen.py b/compliance-agent/rules/vendor/gitlab/upstream/python/urlopen/rule-urllib-urlopen.py new file mode 100644 index 0000000..295de43 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/urlopen/rule-urllib-urlopen.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/urlopen.py +# hash: 8eee173 +import os +import ssl +import urllib +import urllib2 + +# Python 3 +import urllib.request + +# Six +import six + +ssl._create_default_https_context = ssl._create_unverified_context + +# Set up a sample file for tainted input +with open('a123.txt', 'w') as file1: + file1.write("https://abc.com/") + +with open('a123.txt', 'r') as file1: + url_from_user = file1.read() +filename = 'abc.txt' +http_url = 'http://abc.com' + +# urllib +url = urllib.quote('abc.com') +# ok: python_urlopen_rule-urllib-urlopen +urllib.urlopen(http_url) +# ok: python_urlopen_rule-urllib-urlopen +urllib.urlopen("http://abc.com") +# ruleid: python_urlopen_rule-urllib-urlopen +urllib.urlopen(url_from_user) +# ok: python_urlopen_rule-urllib-urlopen +urllib.urlretrieve('http://abc.com', 'abc.txt') +# ruleid: python_urlopen_rule-urllib-urlopen +urllib.urlretrieve(url_from_user, 'abc2.txt') + +opener = urllib.URLopener() +# ruleid: python_urlopen_rule-urllib-urlopen +opener.open(url_from_user) +# ruleid: python_urlopen_rule-urllib-urlopen +opener.retrieve(url_from_user) +# ok: python_urlopen_rule-urllib-urlopen +opener.open('file:///bin/ls') +# ok: python_urlopen_rule-urllib-urlopen +opener.retrieve('file:///bin/ls') + +opener = urllib.FancyURLopener() +# ruleid: python_urlopen_rule-urllib-urlopen +opener.open(url_from_user) +# ruleid: python_urlopen_rule-urllib-urlopen +opener.retrieve(url_from_user) +# ok: python_urlopen_rule-urllib-urlopen +opener.open('file:///bin/ls') +# ok: python_urlopen_rule-urllib-urlopen +opener.retrieve('file:///bin/ls') + +# urllib2 +handler = urllib2.HTTPBasicAuthHandler() +handler.add_password(realm='test', uri='http://mysite.com', user='bob', passwd='123') +opener = urllib2.build_opener(handler) +urllib2.install_opener(opener) +urllib2.urlopen('file:///bin/ls') +urllib2.urlopen(url_from_user) +urllib2.Request('file:///bin/ls') + +# Python 3 +# ruleid: python_urlopen_rule-urllib-urlopen +urllib.request.urlopen(url_from_user) +# ok: python_urlopen_rule-urllib-urlopen +urllib.request.urlopen('file:///bin/ls') +# ruleid: python_urlopen_rule-urllib-urlopen +urllib.request.urlretrieve(url_from_user, 'abc.txt') +# ok: python_urlopen_rule-urllib-urlopen +urllib.request.urlretrieve('file:///bin/ls',filename) + +opener = urllib.request.URLopener() +# ruleid: python_urlopen_rule-urllib-urlopen +opener.open(url_from_user) +# ruleid: python_urlopen_rule-urllib-urlopen +opener.retrieve(url_from_user) +# ok: python_urlopen_rule-urllib-urlopen +opener.open('file:///bin/ls') +# ok: python_urlopen_rule-urllib-urlopen +opener.retrieve('file:///bin/ls') + +opener = urllib.request.FancyURLopener() +# ruleid: python_urlopen_rule-urllib-urlopen +opener.open(url_from_user) +# ruleid: python_urlopen_rule-urllib-urlopen +opener.retrieve(url_from_user) +# ok: python_urlopen_rule-urllib-urlopen +opener.open('file:///bin/ls') +# ok: python_urlopen_rule-urllib-urlopen +opener.retrieve('file:///bin/ls') + +# Six +six.moves.urllib.request.urlopen('file:///bin/ls') +six.moves.urllib.request.urlretrieve('file:///bin/ls', 'abc3.txt') + +opener = six.moves.urllib.request.URLopener() +# ruleid: python_urlopen_rule-urllib-urlopen +opener.open(url_from_user) +# ruleid: python_urlopen_rule-urllib-urlopen +opener.retrieve(url_from_user) +# ok: python_urlopen_rule-urllib-urlopen +opener.open('file:///bin/ls') +# ok: python_urlopen_rule-urllib-urlopen +opener.retrieve('file:///bin/ls') + +opener = six.moves.urllib.request.FancyURLopener() +# ruleid: python_urlopen_rule-urllib-urlopen +opener.open(url_from_user) +# ruleid: python_urlopen_rule-urllib-urlopen +opener.retrieve(url_from_user) +# ok: python_urlopen_rule-urllib-urlopen +opener.open('file:///bin/ls') +# ok: python_urlopen_rule-urllib-urlopen +opener.retrieve('file:///bin/ls') + +# Clean up +os.remove('a123.txt') +os.remove('abc.txt') +os.remove('abc2.txt') +os.remove('abc3.txt') diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/urlopen/rule-urllib-urlopen.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/urlopen/rule-urllib-urlopen.yml new file mode 100644 index 0000000..b7ba020 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/urlopen/rule-urllib-urlopen.yml @@ -0,0 +1,66 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_urlopen_rule-urllib-urlopen" + languages: + - "python" + message: | + The application was found passing in a non-literal value to the `urllib` methods which issue + requests. `urllib` supports the `file://` scheme, which may allow an adversary who can control + the URL value to read arbitrary files on the file system. + + To remediate this issue either hardcode the URLs being used in urllib or use the `requests` + module instead. + + Example using the `requests` module to issue an HTTPS request: + ``` + import requests + # Issue a GET request to https://example.com with a timeout of 10 seconds + response = requests.get('https://example.com', timeout=10) + # Work with the response object + # ... + ``` + patterns: + - pattern-either: + - patterns: + - pattern-either: + - pattern: "urllib.$METHOD(...)" + - pattern: "urllib.request.$METHOD(...)" + - pattern-not: "urllib.$METHOD(\"...\")" + - pattern-not: "urllib.request.$METHOD(\"...\")" + - pattern-not: "urllib.$METHOD(\"...\", ...)" + - pattern-not: "urllib.request.$METHOD(\"...\", ...)" + - metavariable-regex: + metavariable: "$METHOD" + regex: "(urlopen|urlretrieve)" + - patterns: + - pattern-either: + - pattern-inside: | + $OPENER = urllib.URLopener(...) + ... + - pattern-inside: | + $OPENER = urllib.request.URLopener(...) + ... + - pattern-inside: | + $OPENER = urllib.FancyURLopener(...) + ... + - pattern-inside: | + $OPENER = urllib.request.FancyURLopener(...) + ... + - pattern-either: + - pattern: "$OPENER.open(...)" + - pattern: "$OPENER.retrieve(...)" + - pattern-not: "$OPENER.open(\"...\")" + - pattern-not: "$OPENER.retrieve(\"...\")" + metadata: + cwe: "CWE-918" + owasp: + - "A1:2017-Injection" + - "A10:2021-Server-Side Request Forgery" + - "A01:2025-Broken Access Control" + shortDescription: "Server-side request forgery (SSRF)" + security-severity: "Medium" + category: "security" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-celement.py b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-celement.py new file mode 100644 index 0000000..f1ceeb6 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-celement.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/xml_etree_celementtree.py +# hash: 8eee173 + +import xml.etree.cElementTree as badET +import defusedxml.cElementTree as goodET + +xmlString = "\nTove\nJani\nReminder\nDon't forget me this weekend!\n" + +# unsafe +tree = badET.fromstring(xmlString) +print(tree) +# ruleid: python_xml_rule-celement +badET.parse('filethatdoesntexist.xml') +# ruleid: python_xml_rule-celement +badET.iterparse('filethatdoesntexist.xml') +# ruleid: python_xml_rule-celement +a = badET.XMLParser() + +# safe +tree = goodET.fromstring(xmlString) +print(tree) +# ok: python_xml_rule-celement +goodET.parse('filethatdoesntexist.xml') +# ok: python_xml_rule-celement +goodET.iterparse('filethatdoesntexist.xml') +# ok: python_xml_rule-celement +a = goodET.XMLParser() + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-celement.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-celement.yml new file mode 100644 index 0000000..a49efd9 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-celement.yml @@ -0,0 +1,59 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_xml_rule-celement" + languages: + - "python" + message: | + The application was found using the `xml.etree` package for processing XML. + Pythons default xml processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `etree` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + category: "security" + shortDescription: "Improper restriction of XML external entity reference" + security-severity: "Medium" + pattern-either: + - patterns: + - pattern: "xml.etree.cElementTree.fromstring(...)" + - pattern-not: "xml.etree.cElementTree.fromstring(\"...\")" + - pattern: "xml.etree.cElementTree.parse(...)" + - pattern: "xml.etree.cElementTree.iterparse(...)" + - pattern: "xml.etree.cElementTree.XMLParser(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-element.py b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-element.py new file mode 100644 index 0000000..69cdb25 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-element.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/xml_etree_elementtree.py +# hash: 8eee173 + +import xml.etree.ElementTree as badET +import defusedxml.ElementTree as goodET + +xmlString = "\nTove\nJani\nReminder\nDon't forget me this weekend!\n" + +# unsafe +tree = badET.fromstring(xmlString) +print(tree) +# ruleid: python_xml_rule-element +badET.parse('filethatdoesntexist.xml') +# ruleid: python_xml_rule-element +badET.iterparse('filethatdoesntexist.xml') +# ruleid: python_xml_rule-element +a = badET.XMLParser() + +# safe +tree = goodET.fromstring(xmlString) +print(tree) +# ok: python_xml_rule-element +goodET.parse('filethatdoesntexist.xml') +# ok: python_xml_rule-element +goodET.iterparse('filethatdoesntexist.xml') +# ok: python_xml_rule-element +a = goodET.XMLParser() diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-element.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-element.yml new file mode 100644 index 0000000..0ceca8f --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-element.yml @@ -0,0 +1,59 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_xml_rule-element" + languages: + - "python" + message: | + The application was found using the `xml.etree` package for processing XML. + Pythons default xml processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `etree` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + category: "security" + shortDescription: "Improper restriction of XML external entity reference" + security-severity: "Medium" + pattern-either: + - patterns: + - pattern: "xml.etree.ElementTree.fromstring(...)" + - pattern-not: "xml.etree.ElementTree.fromstring(\"...\")" + - pattern: "xml.etree.ElementTree.parse(...)" + - pattern: "xml.etree.ElementTree.iterparse(...)" + - pattern: "xml.etree.ElementTree.XMLParser(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-etree.py b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-etree.py new file mode 100644 index 0000000..cef235c --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-etree.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/xml_lxml.py +# hash: 8eee173 + +import lxml.etree +import lxml +from lxml import etree +from defusedxml.lxml import fromstring +from defuxedxml import lxml as potato + +xmlString = "\nTove\nJani\nReminder\nDon't forget me this weekend!\n" +root = lxml.etree.fromstring(xmlString) +# ruleid: python_xml_rule-etree +lxml.etree.RestrictedElement() +# ruleid: python_xml_rule-etree +lxml.etree.GlobalParserTLS() +# ruleid: python_xml_rule-etree +lxml.etree.getDefaultParser() +# ruleid: python_xml_rule-etree +lxml.etree.check_docinfo() +root = fromstring(xmlString) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-etree.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-etree.yml new file mode 100644 index 0000000..13a9f93 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-etree.yml @@ -0,0 +1,61 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_xml_rule-etree" + languages: + - "python" + message: | + The application was found using the `lxml.etree` package for processing XML. + Python's default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `etree` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + category: "security" + shortDescription: "Improper restriction of XML external entity reference" + security-severity: "Medium" + pattern-either: + - pattern: "lxml.etree.parse(...)" + - patterns: + - pattern: "lxml.etree.fromstring(...)" + - pattern-not: "lxml.etree.fromstring(\"...\")" + - pattern: "lxml.etree.RestrictedElement(...)" + - pattern: "lxml.etree.GlobalParserTLS(...)" + - pattern: "lxml.etree.getDefaultParser(...)" + - pattern: "lxml.etree.check_docinfo(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatbuilder.py b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatbuilder.py new file mode 100644 index 0000000..a702cd2 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatbuilder.py @@ -0,0 +1,3 @@ +# License: MIT (c) GitLab Inc. +# TODO: Placeholder file; add example code. + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatbuilder.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatbuilder.yml new file mode 100644 index 0000000..1999d2b --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatbuilder.yml @@ -0,0 +1,58 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_xml_rule-expatbuilder" + languages: + - "python" + message: | + The application was found using the `xml.dom.expatbuilder` which calls the `xml.dom.minidom` + package for processing XML. Python's default XML processors suffer from various XML parsing + vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.dom.minidom` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + category: "security" + shortDescription: "Improper restriction of XML external entity reference" + security-severity: "Medium" + pattern-either: + - patterns: + - pattern: "xml.dom.expatbuilder.parse(...)" + - pattern-not: "xml.dom.expatbuilder.parse(\"...\")" + - pattern: "xml.dom.expatbuilder.parseString(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatreader.py b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatreader.py new file mode 100644 index 0000000..a702cd2 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatreader.py @@ -0,0 +1,3 @@ +# License: MIT (c) GitLab Inc. +# TODO: Placeholder file; add example code. + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatreader.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatreader.yml new file mode 100644 index 0000000..0704220 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-expatreader.yml @@ -0,0 +1,59 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_xml_rule-expatreader" + languages: + - "python" + message: | + The application was found using the `xml.sax.expatreader` package for processing XML. Python's + default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.sax` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + category: "security" + shortDescription: "Improper restriction of XML external entity reference" + security-severity: "Medium" + pattern-either: + - pattern: "xml.dom.expatreader.parse(...)" + - patterns: + - pattern: "xml.dom.expatreader.parseString(...)" + - pattern-not: "xml.dom.expatreader.parseString(\"...\")" + - pattern: "xml.dom.expatreader.parseString(...)" + - pattern: "xml.dom.expatreader.create_parser(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-minidom.py b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-minidom.py new file mode 100644 index 0000000..affc544 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-minidom.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/xml_minidom.py +# hash: 8eee173 + +from xml.dom.minidom import parseString as badParseString +from defusedxml.minidom import parseString as goodParseString + +from xml.dom.minidom import parse as badParse +from defusedxml.minidom import parse as goodParse + +def foo(str): + # ruleid: python_xml_rule-minidom + a = badParseString(str) + print(a) + # ok: python_xml_rule-minidom + b = goodParseString(str) + print(b) + + # ruleid: python_xml_rule-minidom + a = badParse(str) + print(a) + # ok: python_xml_rule-minidom + b = goodParse(str) + print(b) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-minidom.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-minidom.yml new file mode 100644 index 0000000..f9aadc5 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-minidom.yml @@ -0,0 +1,57 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_xml_rule-minidom" + languages: + - "python" + message: | + The application was found using the `xml.dom.minidom` package for processing XML. Python's + default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.dom.minidom` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + category: "security" + shortDescription: "Improper restriction of XML external entity reference" + security-severity: "Medium" + pattern-either: + - patterns: + - pattern: "xml.dom.minidom.parseString(...)" + - pattern-not: "xml.dom.minidom.parseString(\"...\")" + - pattern: "xml.dom.minidom.parse(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-pulldom.py b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-pulldom.py new file mode 100644 index 0000000..76d1ebe --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-pulldom.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# License: Apache 2.0 (c) PyCQA +# source: https://github.com/PyCQA/bandit/blob/master/examples/xml_minidom.py +# hash: 8eee173 + +from xml.dom.pulldom import parseString as badParseString +from defusedxml.pulldom import parseString as goodParseString + +from xml.dom.pulldom import parse as badParse +from defusedxml.pulldom import parse as goodParse + +def foo(str): + # ruleid: python_xml_rule-pulldom + a = badParseString(str) + print(a) + b = goodParseString(str) + print(b) + + # ruleid: python_xml_rule-pulldom + a = badParse(str) + print(a) + # ok: python_xml_rule-pulldom + b = goodParse(str) + print(b) diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-pulldom.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-pulldom.yml new file mode 100644 index 0000000..bdfa3da --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-pulldom.yml @@ -0,0 +1,57 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_xml_rule-pulldom" + languages: + - "python" + message: | + The application was found using the `xml.dom.pulldom` package for processing XML. Python's + default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.dom.pulldom` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + category: "security" + shortDescription: "Improper restriction of XML external entity reference" + security-severity: "Medium" + pattern-either: + - patterns: + - pattern: "xml.dom.pulldom.parseString(...)" + - pattern-not: "xml.dom.pulldom.parseString(\"...\")" + - pattern: "xml.dom.pulldom.parse(...)" + severity: "WARNING" diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-sax.py b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-sax.py new file mode 100644 index 0000000..a702cd2 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-sax.py @@ -0,0 +1,3 @@ +# License: MIT (c) GitLab Inc. +# TODO: Placeholder file; add example code. + diff --git a/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-sax.yml b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-sax.yml new file mode 100644 index 0000000..009fb29 --- /dev/null +++ b/compliance-agent/rules/vendor/gitlab/upstream/python/xml/rule-sax.yml @@ -0,0 +1,58 @@ +# yamllint disable +# License: MIT (c) GitLab Inc. +# yamllint enable +--- +rules: +- id: "python_xml_rule-sax" + languages: + - "python" + message: | + The application was found using the `xml.sax` package for processing XML. + Python's default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.sax` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: "CWE-611" + owasp: + - "A4:2017-XML External Entities (XXE)" + - "A05:2021-Security Misconfiguration" + - "A02:2025-Security Misconfiguration" + category: "security" + shortDescription: "Improper restriction of XML external entity reference" + security-severity: "Medium" + pattern-either: + - pattern: "xml.sax.parse(...)" + - patterns: + - pattern: "xml.sax.parseString(...)" + - pattern-not: "xml.sax.parseString(\"...\")" + - pattern: "xml.sax.make_parser(...)" + severity: "WARNING" diff --git a/compliance-agent/src/pipeline/dotnet/fixture_tests.rs b/compliance-agent/src/pipeline/dotnet/fixture_tests.rs index c7f39e4..825ff32 100644 --- a/compliance-agent/src/pipeline/dotnet/fixture_tests.rs +++ b/compliance-agent/src/pipeline/dotnet/fixture_tests.rs @@ -138,6 +138,8 @@ async fn the_csharp_rules_find_the_planted_weaknesses() { "cra-ai-15-csharp-cert-validation-disabled Plant.Web/OrderService.svc.cs:16", "cra-ai-20-csharp-sql-string Plant.Web/OrderService.svc.cs:21", "cra-ai-20-csharp-unsafe-deserialization Plant.Web/OrderService.svc.cs:27", + // The vendored GitLab C# rules (#492) agree on the SQL. + "gitlab-csharp_injection_rule-SQLInjection Plant.Web/OrderService.svc.cs:21", ] ); } diff --git a/compliance-agent/src/pipeline/finding_store.rs b/compliance-agent/src/pipeline/finding_store.rs index 56bcac4..10f2fd4 100644 --- a/compliance-agent/src/pipeline/finding_store.rs +++ b/compliance-agent/src/pipeline/finding_store.rs @@ -96,7 +96,9 @@ impl RunFindings { /// and label them with their app variant. Called before grouping too, so /// a group's list of places names each place's variant. pub fn label(&self, findings: &mut [Finding]) { - content_fingerprints(self.tree.as_deref(), findings); + if let Some(tree) = &self.tree { + content_fingerprints(tree, findings); + } self.variants.label(findings); } @@ -714,7 +716,7 @@ fn normalised(line: &str) -> String { /// row an earlier run stored. A finding without a file and line, a group /// (#464, keyed without places already), one already keyed, and one whose /// line is empty or gone keep the fingerprint they have. -fn content_fingerprints(tree: Option<&Path>, findings: &mut [Finding]) { +fn content_fingerprints(tree: &Path, findings: &mut [Finding]) { let mut files: HashMap>> = HashMap::new(); for finding in findings.iter_mut() { if !finding.occurrences.is_empty() || !finding.legacy_fingerprints.is_empty() { @@ -723,13 +725,8 @@ fn content_fingerprints(tree: Option<&Path>, findings: &mut [Finding]) { let (Some(path), Some(line)) = (finding.file_path.clone(), finding.line_number) else { continue; }; - // Without a tree (the PLC scan reads several), only a scanner's own - // content can key a finding. - if tree.is_none() && finding.fingerprint_content.is_none() { - continue; - } let lines = files.entry(path.clone()).or_insert_with(|| { - std::fs::read_to_string(tree?.join(&path)) + std::fs::read_to_string(tree.join(&path)) .ok() .map(|text| text.lines().map(normalised).collect()) }); @@ -965,7 +962,7 @@ mod tests { } fn keyed(tree: &Path, mut findings: Vec) -> Vec { - content_fingerprints(Some(tree), &mut findings); + content_fingerprints(tree, &mut findings); findings } diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 0d983ae..3e6d077 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -1214,15 +1214,40 @@ impl PipelineOrchestrator { "PLC control-logic analysis complete" ); - // Saved like the code scan's findings: keyed by content (#491), with a - // row stored under the line-based fingerprint taken over, moved lines - // followed, and newly computed control refs stored on earlier rows. - // A PLC finding is not closed when it is gone (not yet, #443). - let mut all_findings = all_findings; - let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id); - run_findings.label(&mut all_findings); - let new_count = run_findings.save_new(&self.db, &mut all_findings).await?; - run_findings.write_back(&self.db, &mut all_findings).await?; + let mut new_count = 0u32; + let mut refreshed_count = 0u32; + for mut finding in all_findings { + finding.scan_run_id = Some(scan_run_id.to_string()); + if self + .db + .findings() + .find_one(doc! { "fingerprint": &finding.fingerprint }) + .await? + .is_none() + { + self.db.findings().insert_one(&finding).await?; + new_count += 1; + } else if !finding.control_refs.is_empty() { + // Re-scan refresh: mirror run_pipeline — persist newly-computed + // control_refs onto a PLC finding first seen before the semantic + // pass ran. The insert path alone never would, so without this a + // PLC re-scan can only pick up mappings via a delete + re-add. + self.db + .findings() + .update_one( + doc! { "fingerprint": &finding.fingerprint }, + doc! { "$set": { "control_refs": finding.control_refs.clone() } }, + ) + .await?; + refreshed_count += 1; + } + } + if refreshed_count > 0 { + tracing::info!( + target_id, + "Refreshed control_refs on {refreshed_count} existing PLC findings" + ); + } if !all_sbom.is_empty() { if let Err(e) = self diff --git a/compliance-agent/src/pipeline/plc/mod.rs b/compliance-agent/src/pipeline/plc/mod.rs index d6b511f..e58e766 100644 --- a/compliance-agent/src/pipeline/plc/mod.rs +++ b/compliance-agent/src/pipeline/plc/mod.rs @@ -79,27 +79,7 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec { .to_string_lossy() .to_string(); for pou in &pous { - let mut hits = rules::analyze(pou); - hits.sort_by_key(|h| h.line); - // How often the same hit came before in this POU: the same flaw - // twice is two findings (#491). - let mut seen: std::collections::HashMap<(&'static str, String, String), usize> = - std::collections::HashMap::new(); - for hit in hits { - let occurrence = { - let count = seen - .entry((hit.rule_id, hit.title.clone(), hit.description.clone())) - .or_insert(0); - *count += 1; - *count - 1 - }; - // What identifies the hit without its line: the POU and what - // the rule says about it (variable and function names), as a - // PLCopen XML line is not a line of the file. - let content = format!( - "{}\u{1f}{}\u{1f}{}\u{1f}{occurrence}", - pou.name, hit.title, hit.description - ); + for hit in rules::analyze(pou) { let line_s = hit.line.to_string(); let fingerprint = dedup::compute_fingerprint(&[repo_id, &rel, hit.rule_id, &pou.name, &line_s]); @@ -117,7 +97,6 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec { f.rule_id = Some(hit.rule_id.to_string()); f.cwe = hit.cwe.map(String::from); f.remediation = Some(hit.remediation.to_string()); - f.fingerprint_content = Some(content); findings.push(f); } } @@ -138,31 +117,6 @@ mod tests { .join("examples/plc-demo") } - #[test] - fn plc_findings_are_keyed_by_what_they_flag_not_their_line() { - let source = std::fs::read_to_string(demo_dir().join("pump_station.st")).expect("demo"); - let keys = |text: &str| { - let dir = std::env::temp_dir().join(format!("cs-plcfp-{}", uuid::Uuid::new_v4())); - std::fs::create_dir_all(&dir).expect("mkdir"); - std::fs::write(dir.join("pump_station.st"), text).expect("write"); - let found = analyze_tree(&dir, "t"); - let _ = std::fs::remove_dir_all(&dir); - found - }; - let before = keys(&source); - let after = keys(&format!("(* a comment *)\n\n{source}")); - assert!(!before.is_empty()); - let content = |f: &Vec| -> Vec> { - f.iter().map(|x| x.fingerprint_content.clone()).collect() - }; - // The same content, though every line moved by two. - assert_eq!(content(&before), content(&after)); - assert_ne!(before[0].line_number, after[0].line_number); - // No two hits share their content: the same flaw twice is two findings. - let distinct: HashSet<_> = content(&before).into_iter().collect(); - assert_eq!(distinct.len(), before.len()); - } - #[test] fn scans_demo_project_end_to_end() { let findings = analyze_tree(&demo_dir(), "demo-target"); diff --git a/compliance-agent/src/pipeline/semgrep.rs b/compliance-agent/src/pipeline/semgrep.rs index 644eff6..af817f1 100644 --- a/compliance-agent/src/pipeline/semgrep.rs +++ b/compliance-agent/src/pipeline/semgrep.rs @@ -1,3 +1,4 @@ +use std::ffi::OsString; use std::path::{Path, PathBuf}; use compliance_core::models::{Finding, ScanType, Severity}; @@ -10,13 +11,21 @@ use crate::pipeline::source_text::{read_lines, relative_path}; /// What open-source semgrep writes in place of the matched code. const REDACTED_LINES: &str = "requires login"; -/// Our own CRA-control rules, bundled into the binary and staged to temp -/// files at scan time: every `rules/*.yaml` pack, one per language family -/// (a test keeps this list complete). They are the only rules semgrep runs: -/// the Semgrep registry rules (`--config=auto`, `p/...`) are licensed for -/// internal use only, not for a service offered to others, and `auto` cannot -/// run without sending metrics to Semgrep. Each rule id is keyed back to its -/// control by the `control-map` LUT. +/// The rules semgrep runs, bundled into the binary and staged to temp files at +/// scan time (a test keeps this list complete): +/// +/// - our own CRA-control rules, every `rules/*.yaml` pack, one per language +/// family, each rule id keyed back to its control by the `control-map` LUT; +/// - the vendored third-party packs, `rules/vendor//pack.yaml` (#492): +/// MIT-licensed rules only, ids prefixed by their source (`gitlab-`, +/// `0xdea-`, `elttam-`), matched to controls by CWE. Provenance, the pinned +/// upstream commit and the rules left out are in each pack's NOTICE; +/// `scripts/vendor-semgrep-rules.py` regenerates them. +/// +/// Nothing else: the Semgrep registry rules (`--config=auto`, `p/...`) are +/// licensed for internal use only, not for a service offered to others, and +/// `auto` cannot run without sending metrics to Semgrep ([`semgrep_args`] and +/// a test guard this). /// /// Each pack is staged under its own fixed name. semgrep prefixes a rule's /// check_id with the config's directory; [`bare_rule_id`] takes it off again @@ -39,8 +48,24 @@ const RULE_PACKS: &[(&str, &str)] = &[ "compliance-cra-semgrep-objc.yaml", include_str!("../../rules/cra_semgrep_objc.yaml"), ), + ( + "compliance-vendor-gitlab.yaml", + include_str!("../../rules/vendor/gitlab/pack.yaml"), + ), + ( + "compliance-vendor-0xdea.yaml", + include_str!("../../rules/vendor/0xdea/pack.yaml"), + ), + ( + "compliance-vendor-elttam.yaml", + include_str!("../../rules/vendor/elttam/pack.yaml"), + ), ]; +/// The vendored packs, by source: where they live under `rules/vendor/`. +#[cfg(test)] +const VENDOR_SOURCES: &[&str] = &["gitlab", "0xdea", "elttam"]; + /// What a finding's fingerprint hashes in front of our rule id. /// /// semgrep prefixes a rule's id with the directory of its config file, @@ -52,14 +77,15 @@ const RULE_PACKS: &[(&str, &str)] = &[ /// It is fixed here, no longer taken from wherever the temp directory is. const FINGERPRINT_RULE_PREFIX: &str = "tmp."; -/// The ids of the rules in our packs, as written after `- id:`. +/// The ids of the rules in our packs and the vendored ones, as written after +/// `- id:` (quotes taken off). pub fn bundled_rule_ids() -> &'static [&'static str] { static IDS: std::sync::LazyLock> = std::sync::LazyLock::new(|| { RULE_PACKS .iter() .flat_map(|(_, rules)| rules.lines()) .filter_map(|line| line.trim().strip_prefix("- id:")) - .map(str::trim) + .map(|id| id.trim().trim_matches(|c| c == '"' || c == '\'')) .collect() }); &IDS @@ -67,8 +93,9 @@ pub fn bundled_rule_ids() -> &'static [&'static str] { /// Our rule id without the path semgrep puts in front of it /// (`tmp.cra-ai-8-csharp-hardcoded-credential` → `cra-ai-8-csharp-hardcoded-credential`, -/// also the older `tmp.compliance-cra-semgrep.cra-ai-1-…` form). An id that is -/// not one of ours is returned unchanged. +/// also the older `tmp.compliance-cra-semgrep.cra-ai-1-…` form), the same for +/// a vendored rule (`tmp.gitlab-csharp_crypto_rule-WeakCipherMode`). An id that +/// is not bundled is returned unchanged. pub fn bare_rule_id(check_id: &str) -> &str { bundled_rule_ids() .iter() @@ -150,29 +177,9 @@ impl Scanner for SemgrepScanner { async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result { let rule_packs = stage_cra_rules().await?; // Empty environment + kill-on-drop: semgrep only needs to find itself - // and write temp files, and a timed-out run must actually die. No - // metrics and no version check: nothing about a customer's code leaves - // the scan. + // and write temp files, and a timed-out run must actually die. let mut command = crate::pipeline::tool_cmd::tool("semgrep", &[]); - for pack in &rule_packs { - command.arg(format!("--config={}", pack.display())); - } - command.args([ - "--metrics=off", - "--disable-version-check", - "--json", - "--quiet", - "--max-memory", - "500", - "--jobs", - "2", - ]); - // Anchored at the tree root: a bare `Drivers` would also skip a - // customer's own `app/Drivers/`. - for dir in &self.excluded { - command.arg("--exclude").arg(format!("/{dir}")); - } - command.arg(repo_path); + command.args(semgrep_args(&rule_packs, &self.excluded, repo_path)); let output = tokio::time::timeout(std::time::Duration::from_secs(600), command.output()) .await @@ -242,6 +249,37 @@ impl Scanner for SemgrepScanner { } } +/// The arguments of the one semgrep run: the staged packs as the only +/// configs, no metrics and no version check (nothing about a customer's code +/// leaves the scan), then the excluded directories and the tree. +fn semgrep_args(packs: &[PathBuf], excluded: &[String], repo_path: &Path) -> Vec { + let mut args: Vec = packs + .iter() + .map(|pack| format!("--config={}", pack.display()).into()) + .collect(); + args.extend( + [ + "--metrics=off", + "--disable-version-check", + "--json", + "--quiet", + "--max-memory", + "500", + "--jobs", + "2", + ] + .map(OsString::from), + ); + // Anchored at the tree root: a bare `Drivers` would also skip a + // customer's own `app/Drivers/`. + for dir in excluded { + args.push("--exclude".into()); + args.push(format!("/{dir}").into()); + } + args.push(repo_path.into()); + args +} + #[derive(serde::Deserialize)] struct SemgrepOutput { results: Vec, @@ -357,23 +395,35 @@ mod tests { #[test] fn every_rule_file_is_bundled() { - // A pack added to rules/ but not to RULE_PACKS would never run. + // A pack added to rules/ (or a vendored source) but not to RULE_PACKS + // would never run. let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("rules"); - let mut on_disk: Vec = std::fs::read_dir(&dir) + let mut on_disk: Vec = std::fs::read_dir(&dir) .unwrap_or_else(|e| panic!("{}: {e}", dir.display())) .filter_map(Result::ok) - .map(|e| e.file_name().to_string_lossy().to_string()) - .filter(|n| n.ends_with(".yaml") || n.ends_with(".yml")) + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "yaml" || x == "yml")) .collect(); + let vendor = dir.join("vendor"); + let mut sources: Vec = std::fs::read_dir(&vendor) + .unwrap_or_else(|e| panic!("{}: {e}", vendor.display())) + .filter_map(Result::ok) + .filter(|e| e.path().is_dir()) + .map(|e| e.file_name().to_string_lossy().to_string()) + .collect(); + sources.sort(); + let mut expected: Vec<&str> = VENDOR_SOURCES.to_vec(); + expected.sort_unstable(); + assert_eq!(sources, expected, "rules/vendor/ and VENDOR_SOURCES differ"); + on_disk.extend(sources.iter().map(|s| vendor.join(s).join("pack.yaml"))); on_disk.sort(); - let mut bundled: Vec = RULE_PACKS + let mut bundled: Vec = RULE_PACKS .iter() .map(|(_, rules)| { - std::fs::read_dir(&dir) - .unwrap_or_else(|e| panic!("{e}")) - .filter_map(Result::ok) - .find(|e| std::fs::read_to_string(e.path()).is_ok_and(|t| t == *rules)) - .map(|e| e.file_name().to_string_lossy().to_string()) + on_disk + .iter() + .find(|p| std::fs::read_to_string(p).is_ok_and(|t| t == *rules)) + .cloned() .unwrap_or_default() }) .collect(); @@ -381,6 +431,230 @@ mod tests { assert_eq!(on_disk, bundled); } + /// One vendored rule as `rules/vendor//rules.json` lists it. + #[derive(serde::Deserialize)] + struct VendoredRule { + id: String, + languages: Vec, + cwe: Option, + } + + fn vendored_rules(source: &str) -> Vec { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("rules/vendor") + .join(source) + .join("rules.json"); + let text = + std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())) + } + + #[test] + fn vendored_rules_are_namespaced_by_source() { + let bundled = bundled_rule_ids(); + let mut seen = std::collections::HashSet::new(); + for source in VENDOR_SOURCES { + let rules = vendored_rules(source); + assert!(!rules.is_empty(), "{source}: no rules"); + for rule in &rules { + assert!( + rule.id.starts_with(&format!("{source}-")), + "{}: not prefixed with {source}-", + rule.id + ); + assert!( + bundled.contains(&rule.id.as_str()), + "{} is not bundled", + rule.id + ); + assert!(seen.insert(rule.id.clone()), "{} twice", rule.id); + // What semgrep reports, wherever the pack was staged. + assert_eq!(bare_rule_id(&format!("tmp.{}", rule.id)), rule.id); + assert_eq!(bare_rule_id(&format!("var.tmp.{}", rule.id)), rule.id); + } + } + // The index lists exactly the vendored rules in the packs. + let in_packs = bundled.iter().filter(|id| { + VENDOR_SOURCES + .iter() + .any(|s| id.starts_with(&format!("{s}-"))) + }); + assert_eq!(in_packs.count(), seen.len()); + // Our own ids never collide with a source prefix. + assert!(bundled + .iter() + .all(|id| id.starts_with("cra-ai-") || seen.contains(*id))); + } + + #[test] + fn every_vendored_rule_maps_to_a_control_for_its_languages() { + // A vendored rule must count for a control (by its CWE, or by its id + // where it has none), and a binding that claims the rule's languages, + // or the CRA status would report a finding without a control. + let map = control_map::ControlMap::cra().unwrap_or_else(|e| panic!("map: {e}")); + for source in VENDOR_SOURCES { + for rule in vendored_rules(source) { + let bindings: Vec<_> = map + .controls + .iter() + .flat_map(|c| c.scans.iter().map(move |b| (c, b))) + .filter(|(_, b)| b.tool == "semgrep") + .filter(|(_, b)| { + rule.cwe.as_ref().is_some_and(|w| b.cwe.contains(w)) + || b.rules.contains(&rule.id) + }) + .collect(); + assert!( + !bindings.is_empty(), + "{} ({:?}) maps to no control", + rule.id, + rule.cwe + ); + assert!( + bindings + .iter() + .any(|(_, b)| rule.languages.iter().all(|l| b.languages.contains(l))), + "{}: no binding of {:?} claims {:?}", + rule.id, + bindings.iter().map(|(c, _)| &c.control).collect::>(), + rule.languages + ); + // The agent finds them the same way. + assert!(!map + .controls_for_finding("semgrep", rule.cwe.as_deref(), Some(&rule.id)) + .is_empty()); + } + } + } + + #[test] + fn semgrep_only_ever_runs_the_staged_packs() { + // The registry rules must never come back (#492): their licence allows + // internal use only, and `auto` sends metrics. Every --config is one of + // our staged files, and nothing points semgrep at the registry. + let packs: Vec = RULE_PACKS + .iter() + .map(|(name, _)| std::env::temp_dir().join(name)) + .collect(); + let args = semgrep_args( + &packs, + &["vendor".to_string(), "p/".to_string()], + Path::new("/work/r/repo"), + ); + let args: Vec = args + .iter() + .map(|a| a.to_string_lossy().into_owned()) + .collect(); + let configs: Vec<&str> = args + .iter() + .filter_map(|a| a.strip_prefix("--config=")) + .collect(); + assert_eq!(configs.len(), RULE_PACKS.len()); + for (config, (name, _)) in configs.iter().zip(RULE_PACKS) { + assert_eq!(*config, std::env::temp_dir().join(name).to_string_lossy()); + assert_no_registry_config(config); + } + // No other way to name a config. + assert!(!args + .iter() + .any(|a| a == "--config" || a == "-c" || a.starts_with("-c="))); + assert!(args.contains(&"--metrics=off".to_string())); + assert!(args.contains(&"--disable-version-check".to_string())); + } + + /// Fails for a semgrep config that is the registry: `auto`, a `p/` pack, + /// an `r/` rule, a snippet id or any URL. + fn assert_no_registry_config(config: &str) { + let lower = config.to_ascii_lowercase(); + assert_ne!(lower, "auto", "--config=auto"); + for prefix in ["p/", "r/", "s/", "c/", "tests/", "policy", "supply-chain"] { + assert!(!lower.starts_with(prefix), "registry config {config}"); + } + assert!(!lower.contains("://"), "config from a URL: {config}"); + assert!(!lower.contains("semgrep.dev"), "registry config {config}"); + assert!( + Path::new(config).is_absolute(), + "not a local file: {config}" + ); + } + + #[test] + fn the_registry_guard_catches_registry_configs() { + for config in [ + "auto", + "p/default", + "p/0xdea", + "r/python.lang.security.audit.exec-detected", + "https://semgrep.dev/c/p/ci", + "http://example.com/rules.yaml", + ] { + assert!( + std::panic::catch_unwind(|| assert_no_registry_config(config)).is_err(), + "{config} passed" + ); + } + assert_no_registry_config("/tmp/compliance-cra-semgrep.yaml"); + } + + #[test] + fn nothing_in_the_repository_points_semgrep_at_the_registry() { + // The agent's run is checked above; this catches a second invocation + // (a script, the Dockerfile, CI) that brings the registry back. + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap_or_else(|| panic!("workspace root")); + let registry = regex::Regex::new( + r#"(?i)--config[= ]+["']?(auto\b|p/|r/|https?://)|semgrep\.dev/(c|p|r)/|semgrep\s+(ci|scan)?\s*--config[= ]+["']?(auto|p/|r/)"#, + ) + .unwrap_or_else(|e| panic!("{e}")); + let mut hits = Vec::new(); + for dir in [ + "compliance-agent/src", + "compliance-core/src", + "docker", + "scripts", + ".gitea", + ] { + for entry in walkdir::WalkDir::new(root.join(dir)) + .into_iter() + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file()) + { + let path = entry.path(); + // This test names what it looks for. + if path.ends_with("pipeline/semgrep.rs") { + continue; + } + let Ok(text) = std::fs::read_to_string(path) else { + continue; + }; + for (n, line) in text.lines().enumerate() { + if registry.is_match(line) { + hits.push(format!("{}:{}: {line}", path.display(), n + 1)); + } + } + } + } + for file in ["Dockerfile.agent", "docker-compose.yml"] { + let text = std::fs::read_to_string(root.join(file)).unwrap_or_default(); + for (n, line) in text.lines().enumerate() { + if registry.is_match(line) { + hits.push(format!("{file}:{}: {line}", n + 1)); + } + } + } + assert!( + hits.is_empty(), + "semgrep registry configs:\n{}", + hits.join("\n") + ); + assert!(registry.is_match("semgrep --config=auto .")); + assert!(registry.is_match("semgrep --config p/default")); + assert!(registry.is_match("semgrep --config=r/python.lang.x")); + assert!(registry.is_match("semgrep --config https://semgrep.dev/c/p/ci")); + assert!(!registry.is_match("semgrep --config=/tmp/compliance-cra-semgrep.yaml")); + } + #[test] fn rule_ids_are_stored_without_the_staging_path() { for id in [ diff --git a/compliance-agent/tests/nightly.rs b/compliance-agent/tests/nightly.rs index 970d857..cc76619 100644 --- a/compliance-agent/tests/nightly.rs +++ b/compliance-agent/tests/nightly.rs @@ -17,7 +17,8 @@ //! - a blessed snapshot in `fixtures/nightly/baselines/.json`: //! - **exact**: scan status, skipped stages, SBOM components, and findings //! from deterministic scanners (PLC rules, secrets, patterns, lint, our own -//! `cra-ai-*` semgrep rules, the only ones semgrep runs); +//! `cra-ai-*` semgrep rules and the vendored `gitlab-`, `0xdea-` and +//! `elttam-` ones, #492); //! - **at least**: CVE and advisory ids, whose sources change daily; //! - **ignored**: LLM code review and triage. Control refs, which the LLM //! control judge stamps, are reported under "advisory" but do not gate. @@ -313,7 +314,8 @@ async fn seed_nightly( } /// A semgrep rule id is prefixed with the path of the config it came from; our -/// own rules are recognised by their `cra-ai-` id wherever it sits. +/// own rules are recognised by their `cra-ai-` id wherever it sits. (The agent +/// has stored bare ids since #473, the vendored ones included.) fn normalise_rule(scanner: &str, rule: &str) -> String { match rule.find("cra-ai-") { Some(i) if scanner == "semgrep" => rule[i..].to_string(), diff --git a/control-map/data/cra_control_map.json b/control-map/data/cra_control_map.json index 998e4af..e7ece1e 100644 --- a/control-map/data/cra_control_map.json +++ b/control-map/data/cra_control_map.json @@ -63,6 +63,33 @@ ], "check": "A committed executable or library must be built with the operating system's basic exploit mitigations on (ASLR/PIE, DEP/non-executable stack, RELRO); one without them is not secure by default. Defence-in-depth extras (CFG, SafeSEH, stack protector, FORTIFY, high-entropy ASLR) are reported but not bound here.", "attach_only": true + }, + { + "tool": "semgrep", + "scan_type": "sast", + "languages": [ + "csharp", + "generic", + "java", + "python" + ], + "cwe": [ + "CWE-942", + "CWE-732", + "CWE-1104", + "CWE-1327", + "CWE-554" + ], + "rules": [ + "elttam-default-properties-devmode", + "elttam-struts-xml-devmode", + "elttam-web-xml-devmode", + "elttam-struts-xml-action-dmi", + "elttam-struts-xml-dmi", + "elttam-taglib-action-dmi", + "elttam-struts-xml-always-select-full-namespace" + ], + "check": "Vendored rules (GitLab, elttam): the shipped configuration must be secure by default; a development mode left on (Struts devMode or dynamic method invocation), permissive CORS, world-writable file permissions, a service bound to all interfaces or a missing input-validation framework violates it." } ], "note": null, @@ -167,6 +194,22 @@ ], "rules": [], "check": "Passwords must be stored with a slow, salted password hash (bcrypt, scrypt, Argon2id, PBKDF2); a fast or unsalted hash (MD5, SHA-1, SHA-256) of a password violates it." + }, + { + "tool": "semgrep", + "scan_type": "sast", + "languages": [ + "csharp", + "java" + ], + "cwe": [ + "CWE-287", + "CWE-306", + "CWE-521", + "CWE-1390" + ], + "rules": [], + "check": "Vendored rules (GitLab): access must require strong authentication; an anonymous LDAP bind, an empty database password, missing password complexity or SAML comment handling that lets a signature be bypassed violates it." } ], "note": null, @@ -226,6 +269,19 @@ "cra-ai-8-csharp-hardcoded-credential" ], "check": "No password, key or secret may be written into the source; a real credential assigned to a password- or key-like name violates it." + }, + { + "tool": "semgrep", + "scan_type": "sast", + "languages": [ + "java" + ], + "cwe": [ + "CWE-259", + "CWE-798" + ], + "rules": [], + "check": "Vendored rules (GitLab): no password or key may be written into the source; a real credential assigned in code violates it. A placeholder or an empty value does not." } ], "note": null, @@ -312,6 +368,23 @@ "dotnet-config-insecure-cookies" ], "check": "Session and authentication cookies must be Secure and HttpOnly; httpCookies without requireSSL or httpOnlyCookies violates it." + }, + { + "tool": "semgrep", + "scan_type": "sast", + "languages": [ + "csharp", + "go", + "java" + ], + "cwe": [ + "CWE-352", + "CWE-614", + "CWE-1004", + "CWE-1275" + ], + "rules": [], + "check": "Vendored rules (GitLab, elttam): session state must be protected; cookies without Secure, HttpOnly or a safe SameSite value, and state-changing handlers without CSRF protection violate it." } ], "note": null, @@ -425,6 +498,26 @@ "cra-ai-13-csharp-ecb-mode" ], "check": "Sensitive data must be protected with current algorithms; MD5, SHA-1, DES, 3DES, RC2 or ECB mode used for it violates it." + }, + { + "tool": "semgrep", + "scan_type": "sast", + "languages": [ + "csharp", + "java", + "javascript", + "python" + ], + "cwe": [ + "CWE-208", + "CWE-326", + "CWE-327", + "CWE-780" + ], + "rules": [ + "elttam-gcm-static-iv" + ], + "check": "Vendored rules (GitLab, elttam): sensitive data must be protected with current algorithms; DES, RC4, MD5, SHA-1, ECB, RSA without padding, short keys, a static GCM nonce or a timing-unsafe comparison of secrets violates it. A non-security use (a cache key, a checksum of public data) does not." } ], "note": null, @@ -546,6 +639,25 @@ "dotnet-config-wcf-insecure-binding" ], "check": "Network traffic must be encrypted; a WCF binding with security mode None or TransportCredentialOnly, or a basicHttpBinding without transport security, violates it." + }, + { + "tool": "semgrep", + "scan_type": "sast", + "languages": [ + "csharp", + "go", + "java", + "python" + ], + "cwe": [ + "CWE-295", + "CWE-297", + "CWE-319", + "CWE-322", + "CWE-757" + ], + "rules": [], + "check": "Vendored rules (GitLab): network traffic must use TLS 1.2 or newer with certificate and host checking; disabled verification, plain-text protocols (HTTP, FTP, SMTP, telnet) for sensitive data or an old protocol version violates it." } ], "note": null, @@ -604,6 +716,26 @@ "secret-file-signing-key" ], "check": "Keys must not be committed to the source: a private-key store (.pfx, .p12, .jks, .keystore) or strong-name key pair (.snk) in the repository violates it." + }, + { + "tool": "semgrep", + "scan_type": "sast", + "languages": [ + "c", + "cpp", + "csharp", + "java", + "javascript", + "python", + "typescript" + ], + "cwe": [ + "CWE-321", + "CWE-330", + "CWE-338" + ], + "rules": [], + "check": "Vendored rules (GitLab, 0xdea): keys, tokens and nonces need a cryptographically secure random generator; rand(), java.util.Random, Math.random or the random module for them violates it." } ], "note": null, @@ -728,6 +860,88 @@ "cra-ai-20-csharp-path-traversal" ], "check": "Input from outside must not reach SQL, the command line, a type-resolving deserializer, an XML parser with external entities, or a file path unchecked; such a flow in C# code violates it." + }, + { + "tool": "semgrep", + "scan_type": "sast", + "languages": [ + "c", + "cpp", + "csharp", + "generic", + "go", + "java", + "javascript", + "python", + "typescript" + ], + "cwe": [ + "CWE-15", + "CWE-20", + "CWE-22", + "CWE-77", + "CWE-78", + "CWE-79", + "CWE-88", + "CWE-89", + "CWE-90", + "CWE-91", + "CWE-94", + "CWE-95", + "CWE-113", + "CWE-116", + "CWE-125", + "CWE-131", + "CWE-134", + "CWE-155", + "CWE-158", + "CWE-170", + "CWE-180", + "CWE-182", + "CWE-185", + "CWE-190", + "CWE-193", + "CWE-200", + "CWE-209", + "CWE-242", + "CWE-252", + "CWE-362", + "CWE-364", + "CWE-367", + "CWE-377", + "CWE-415", + "CWE-416", + "CWE-467", + "CWE-502", + "CWE-552", + "CWE-562", + "CWE-590", + "CWE-601", + "CWE-611", + "CWE-643", + "CWE-676", + "CWE-683", + "CWE-686", + "CWE-696", + "CWE-697", + "CWE-704", + "CWE-762", + "CWE-770", + "CWE-787", + "CWE-806", + "CWE-839", + "CWE-917", + "CWE-918", + "CWE-1260", + "CWE-1333" + ], + "rules": [ + "elttam-potential-symlink-takeover-with-os-executable", + "elttam-sprintf-unescaped-control-characters", + "elttam-non-atomic-use-of-converted-uintptr", + "elttam-UnsafeHttpInvokerServiceExporter-XML" + ], + "check": "Vendored rules (GitLab, 0xdea, elttam): untrusted input must not reach an interpreter, the file system, a deserialiser or a fixed-size buffer unchecked; injection (SQL, OS command, LDAP, XPath, XSS, template), path traversal, unsafe deserialisation, XXE, SSRF, open redirects, and memory errors (unbounded copies, off-by-one, use after free, double free, integer wraparound) violate it." } ], "note": null, diff --git a/docs/features/control-mapping.md b/docs/features/control-mapping.md index a7a7830..0e56b24 100644 --- a/docs/features/control-mapping.md +++ b/docs/features/control-mapping.md @@ -22,11 +22,12 @@ Every control lands in one of three buckets, recorded in the `control-map` LUT ( | `needs_tooling` | Code-checkable, but no off-the-shelf tool digs it out — we author a detector or use the grounded surface check | | `not_code_checkable` | A design/process property — out of static-scan scope | -For the **CRA** framework (40 controls) the split is **21 covered · 0 needs_tooling · 19 not_code_checkable**. Every semgrep binding names our own rules only: the Semgrep registry rules are not run (their licence allows internal use only, not a service for others), so a binding covers exactly the languages its rules are written for. The originally uncovered controls were resolved as a hybrid: +For the **CRA** framework (40 controls) the split is **21 covered · 0 needs_tooling · 19 not_code_checkable**. The Semgrep registry rules are not run (their licence allows internal use only, not a service for others): every semgrep binding names our own rules or, since #492, the vendored MIT packs (GitLab, 0xdea, elttam), so a binding covers exactly the languages its rules are written for. The originally uncovered controls were resolved as a hybrid: - **Custom semgrep detectors**, shipped in the binary and matched back to controls **by rule id** so a broad CWE can't over-attribute: - for Python and JavaScript/TypeScript: `cra-ai-1`, `7`, `10`, `14` (secure-by-default, weak password hashing, insecure session cookies, weak data-at-rest ciphers), `cra-ai-20` (shell commands and SQL built from variables, request input echoed into a response), `cra-ai-8` (hard-coded credentials, Python) and `cra-ai-15` (plain `http://` requests); - for C and C++ firmware: `cra-ai-8`, `13`, `16`, `20` (hard-coded credentials including `#define` macros, broken hash/cipher, `rand()`, unbounded string functions and non-literal format strings), next to cppcheck for memory safety. +- **Vendored semgrep packs** (GitLab, 0xdea, elttam; #492), bound **by CWE** like off-the-shelf tools, on a semgrep binding of their own per control whose `languages` are exactly those of the vendored rules under those CWEs (a test checks every vendored rule maps to a control that claims its languages). The few elttam rules without a CWE are bound by rule id. Because these bindings are `semgrep` bindings, a CWE they list also attaches our own semgrep findings with that CWE to the control. - **mobsfscan** for Android and iOS apps, bound **by CWE** (a mobsfscan binding only ever attaches mobsfscan findings): `cra-ai-1` (debuggable, exported components, outdated `minSdkVersion`), `7`, `8`, `9`, `13`, `14`, `15` (cleartext, TLS, App Transport Security), `16` and `20`. Each binding lists only the languages mobsfscan has rules for under those CWEs, so `cra-ai-1` covers Java and Kotlin (its manifest checks) but not Swift. - **8 grounded surface checks** (`cra-ai-6`, `11`, `12`, `24`, `27`, `28`, `29`, `30`): the absence-based controls (no rate limiting, no security logging, no update-signature check…) that have no syntactic pattern. - **Marked not_code_checkable** (`cra-ai-2`, `3`, `4`, `5`, among the 19): minimal attack surface, secure architecture, least privilege, tamper protection. diff --git a/docs/reference/tools.md b/docs/reference/tools.md index d1bbe23..9804427 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -6,7 +6,8 @@ Prüfwerk uses a combination of open-source scanners and AI-powered analysis to [Semgrep](https://semgrep.dev/) is an open-source static analysis engine (LGPL-2.1) that finds vulnerabilities by matching patterns in source code. -Prüfwerk runs the engine with **its own CRA rules only**: +Prüfwerk runs the engine with **its own CRA rules** and **three vendored, +MIT-licensed community rule packs**. Its own rules: - Python and JavaScript/TypeScript: secure defaults, weak password hashing, insecure session cookies, weak ciphers for data at rest, shell commands and @@ -19,13 +20,32 @@ Prüfwerk runs the engine with **its own CRA rules only**: Keychain. The Objective-C rule is a text pattern, as Semgrep cannot parse Objective-C. +The vendored packs (#492), each pinned to an upstream commit and shipped +in the agent with its licence and a NOTICE (`compliance-agent/rules/vendor/`): + +| Source | Licence | Rules | Languages | +|---|---|---|---| +| [GitLab SAST rules](https://gitlab.com/gitlab-org/security-products/sast-rules) v2.10.1 | MIT (only files with GitLab's MIT header) | 148 | C#, Java, JavaScript/TypeScript, Python, one Go rule | +| [0xdea semgrep-rules](https://github.com/0xdea/semgrep-rules) | MIT | 35 | C, C++ | +| [elttam semgrep-rules](https://github.com/elttam/semgrep-rules) | MIT | 34 | Java, Go, Struts/Spring XML | + +Their rule ids carry the source as a prefix (`gitlab-…`, `0xdea-…`, +`elttam-…`), and they count for the CRA controls by CWE. Rules that match a +Semgrep registry rule, review hints and rules that flood real firmware and +library code with false positives (measured on FreeRTOS, lwIP and the nightly +fixtures) are left out; each pack's NOTICE lists them with the reason. Not +vendored at all: GitLab's C rules (GPL-2.0, generated from flawfinder), its +gosec-derived Go rules (Apache-2.0) and its LGPL/Commons Clause/EE +directories, and elttam's Kubernetes rules (derived from registry rules). + The rules of the Semgrep registry (`--config=auto`, `p/...`) are not used: their licence (Semgrep Rules License v1.0) allows internal use only, not a service offered to others, and `auto` cannot run without sending metrics to -Semgrep. Semgrep runs with `--metrics=off` and no version check, so nothing -about your code leaves the scan. Code in other languages gets no Semgrep -findings; the CRA view says so (*Keine Prüfregel für den gefundenen Code*) -instead of reporting it as clean. +Semgrep. A test fails if the agent's semgrep run, a script or the CI ever +names a registry config. Semgrep runs with `--metrics=off` and no version +check, so nothing about your code leaves the scan. Code in a language no rule +covers gets no Semgrep findings; the CRA view says so (*Keine Prüfregel für +den gefundenen Code*) instead of reporting it as clean. Semgrep produces **Codeanalyse (SAST)** findings with file paths, line numbers, and rule descriptions. diff --git a/docs/release/staging-test-plan-after-v0.4.5.md b/docs/release/staging-test-plan-after-v0.4.5.md index fae6ca7..e2a10fa 100644 --- a/docs/release/staging-test-plan-after-v0.4.5.md +++ b/docs/release/staging-test-plan-after-v0.4.5.md @@ -20,6 +20,7 @@ together on stage in one pass before the next prod promotion. | #467 (follow-up) | npm and Maven licenses from their public registries | | #491 | Findings keyed by the code they flag, not its line number | | #491 (PLC) | PLC findings keyed the same way | +| #492 | Vendored MIT semgrep packs (GitLab, 0xdea, elttam); guard against registry rules | | #495 | Binary depth: PE/ELF hardening, signatures, .NET references, CPE/purl candidates, Intel HEX checks | | #498 (1/4) | VEX status on CVE alerts, OpenVEX and CycloneDX VEX, a valid CycloneDX SBOM | @@ -451,6 +452,29 @@ alerts (e.g. the log4j/gson target of check 19). validates (before, vulnerabilities sat inside the components); the evidence pack gains the two VEX files. +### 23. #492 Vendored semgrep packs + +- **Do:** upload `fixtures/nightly/firmware/c-sensor-node` and + `fixtures/dotnet/framework48` as **Archiv**, and a small Java or Python tree + with an obvious weakness (e.g. `Cipher.getInstance("DES")`, + `yaml.load(data)` or `requests.get(url, verify=False)`). +- **Expect:** besides the `cra-ai-*` findings, Codeanalyse findings with the + tool `semgrep` and rule ids `gitlab-…` (Java/Python/C#, e.g. + `gitlab-csharp_injection_rule-SQLInjection` in `OrderService.svc.cs`) and + `0xdea-raptor-…` (C, e.g. `0xdea-raptor-insecure-api-strcpy-strcat`, + `0xdea-raptor-unchecked-ret-malloc` in the sensor node), each with a CWE and + a CRA control (cra-ai-13/15/16/20 …). The Java/Python tree's CRA view now + shows those controls as checked instead of *Keine Prüfregel für den + gefundenen Code*. No rule id contains `tmp.` or a path. +- **Expect:** the SAST stage still completes on a large tree (the Android + public sample from the nightly), no `sast` skip. +- **Log:** nothing new; `Semgrep failed` must not appear. +- **[visible]** on the next prod rescan: Java, Python, C#, JavaScript and C/C++ + targets get new Codeanalyse findings from the vendored rules, and controls + for Java/Go code move from "no rule for the languages found" to assessed. + In managed repositories new High findings go through LLM triage and open + tracker issues on that first rescan (#451). + ## After the pass - The nightly job on `main` is green with the new mobile targets. diff --git a/scripts/vendor-semgrep-rules.py b/scripts/vendor-semgrep-rules.py new file mode 100755 index 0000000..ec1e19b --- /dev/null +++ b/scripts/vendor-semgrep-rules.py @@ -0,0 +1,351 @@ +#!/usr/bin/env python3 +"""Vendor the permissively licensed third-party semgrep rule packs (#492). + +For each source below this script + +1. checks out the upstream repository at its pinned commit, +2. copies the selected rule files and their semgrep test files *verbatim* to + ``compliance-agent/rules/vendor//upstream/`` (``semgrep --test`` + runs on them), together with the upstream LICENSE, +3. writes the pack the agent runs, ``compliance-agent/rules/vendor//pack.yaml``: + every kept rule with its id prefixed by the source (``gitlab-``, ``0xdea-``, + ``elttam-``) and its ``languages`` in flow style, +4. writes ``rules.json``, the index of the pack (id, languages, first CWE) the + control-map test reads, and +5. writes ``NOTICE`` (provenance, licence, what was left out and why) and + ``UPSTREAM`` (repository and pinned commit). + +Licence is the hard rule, as Prüfwerk is a service offered to others: only +MIT-licensed rules are vendored. Never the Semgrep registry / semgrep-rules +(Semgrep Rules License), opengrep-rules (Commons Clause) or Trail of Bits +(AGPL). GitLab's repository mixes licences per directory *and* per file, so +every GitLab rule file must carry its ``License: MIT`` header. + +Usage:: + + scripts/vendor-semgrep-rules.py # clone at the pins + scripts/vendor-semgrep-rules.py --upstream DIR # DIR/ are clones + +Requires PyYAML. The output is deterministic: running it again at the same +pins changes nothing. +""" + +from __future__ import annotations + +import argparse +import fnmatch +import json +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile + +import yaml + +ROOT = pathlib.Path(__file__).resolve().parent.parent +VENDOR = ROOT / "compliance-agent" / "rules" / "vendor" + +# Rules whose text matches a rule of the Semgrep registry (semgrep/semgrep-rules, +# Semgrep Rules License v1.0): the same message or the same patterns. They may +# have been ported independently from the same origin (bandit), but a copy +# cannot be ruled out, so they are not vendored at all. +REGISTRY_LOOKALIKE = "matches a Semgrep registry rule (provenance spot-check); not vendored" + +# Rules that fire far more often than they find anything on the nightly +# fixtures and public samples (noise budget, #492), or that only enumerate code +# for a manual audit. Their files are vendored (the licence allows it), the +# pack leaves them out. +SOURCES = { + "gitlab": { + "name": "GitLab SAST rules", + "url": "https://gitlab.com/gitlab-org/security-products/sast-rules", + "commit": "53bf5cf6df3c51b6c02110f5a638b5e6213666cd", + "version": "v2.10.1 (2026-09-21)", + "licence": "MIT (per-file header `License: MIT (c) GitLab Inc.`)", + "copyright": "Copyright (c) 2011-present GitLab Inc.", + # Only these, and every rule file in them must say MIT. + "not_selected": [ + "c/: every file is GPL-2.0 (generated from flawfinder), not MIT", + "go/ except crypto/rule-tlsversion: Apache-2.0 ports of gosec, not MIT", + "scala/: MIT, but no Scala in the products we scan", + "rules/lgpl/: LGPL-3.0 (njsscan/mobsfscan); mobsfscan runs separately", + "rules/lgpl-cc/: LGPL with Commons Clause", + "rules/gitlab/: GitLab EE licence", + ], + "include": [ + "csharp/**", + "java/**", + "javascript/**", + "python/**", + "go/crypto/rule-tlsversion.*", + ], + "require_header": "License: MIT (c) GitLab Inc.", + "exclude": { + "javascript/xss/rule-mustache-escape": REGISTRY_LOOKALIKE, + "python/exec/rule-start-process-with-no-shell": REGISTRY_LOOKALIKE, + "python/exec/rule-subprocess-popen-shell-true": REGISTRY_LOOKALIKE, + "python/ssh/rule-ssh-nohost-key-verification": REGISTRY_LOOKALIKE, + "python/flask/rule-app-debug": REGISTRY_LOOKALIKE, + "python/deserialization/rule-marshal": REGISTRY_LOOKALIKE, + "python/deserialization/rule-dill": REGISTRY_LOOKALIKE, + "python/crypto/rule-crypto-encrypt-ec": REGISTRY_LOOKALIKE, + }, + "drop": { + "gitlab-python_assert_rule-assert-used": "16 hits in psf/requests, all in tests; a plain `assert` is not a weakness in our customers' Python", + }, + }, + "0xdea": { + "name": "0xdea semgrep-rules (C/C++)", + "url": "https://github.com/0xdea/semgrep-rules", + "commit": "dae50da6e6e629750f1daec73a01ef9206a372ab", + "version": "v2.0.0 + 20 commits (2026-09-25)", + "licence": "MIT", + "copyright": "Copyright (c) 2022 raptor (Marco Ivaldi)", + "not_selected": [ + "rules/noisy/: upstream marks these unsuitable for general use", + ], + "include": ["rules/c/**"], + "require_header": None, + "exclude": {}, + "drop": { + "0xdea-raptor-missing-return": "FP storm: 1514 hits in FreeRTOS-Kernel (port macros); a review hint by upstream's own description (code quality / audit aid), not a weakness", + "0xdea-raptor-typos": "FP storm: 989 hits in FreeRTOS-Kernel and lwIP; a review hint by upstream's own description (code quality / audit aid), not a weakness", + "0xdea-raptor-interesting-api-calls": "FP storm: 718 hits in lwIP; lists every call of an \"interesting\" API for a manual audit", + "0xdea-raptor-signed-unsigned-conversion": "FP storm: 221 hits in FreeRTOS-Kernel and lwIP, nearly all benign casts", + "0xdea-raptor-suspicious-assert": "FP storm: 176 hits in FreeRTOS-Kernel and lwIP (configASSERT/LWIP_ASSERT on sizes)", + "0xdea-raptor-format-string-bugs": "FP storm: 61 hits in lwIP, all literal formats joined with a macro (\"%s\"NEWLINE); our cra-ai-20-c-non-literal-format-string covers the real case", + "0xdea-raptor-argv-envp-access": "43 hits on every argv/getenv read; an audit aid, not a weakness", + "0xdea-raptor-mismatched-memory-management": "36 hits in lwIP, sampled hits are plain matching malloc/free pairs", + "0xdea-raptor-write-into-stack-buffer": "27 hits on every write into a stack array; an audit aid, not a weakness", + "0xdea-raptor-integer-truncation": "23 hits in lwIP, sampled hits assign small constants (`x = 1`)", + "0xdea-raptor-missing-default-in-switch": "22 hits; a review hint by upstream's own description (code quality / audit aid), not a weakness", + "0xdea-raptor-missing-break-in-switch": "intended fallthrough in FreeRTOS-Kernel and lwIP; a review hint by upstream's own description (code quality / audit aid), not a weakness", + "0xdea-raptor-pointer-subtraction": "16 hits in lwIP, all `len = end - start` length arithmetic", + "0xdea-raptor-high-entropy-assignment": "14 hits, sampled hits are base64 tables and exception-name strings; gitleaks covers committed secrets", + }, + }, + "elttam": { + "name": "elttam semgrep-rules", + "url": "https://github.com/elttam/semgrep-rules", + "commit": "244268562cc92d33f54b8a60a187df5520f91b26", + "version": "main (2026-08-03, no tags)", + "licence": "MIT (LICENSE names 'Copyright (c) 2020 Semgrep': the MIT text of " + "the repository template the first commit came from)", + "copyright": "Copyright (c) 2020 Semgrep; rules by elttam", + "include": [ + "rules/generic/**", + "rules/go/**", + "rules/java/**", + "rules/php/**", + "rules/yaml/**", + "rules-audit/**", + ], + "not_selected": [], + "require_header": None, + "exclude": { + # Not vendored at all. + "rules/generic/*": "a `mode: join` rule (experimental semgrep join mode, " + "no single-file semantics); not vendored", + "rules/yaml/kubernetes/*": "derived from Semgrep registry rules " + "(same paths and wording, 'Upstream PR 2630'); not vendored", + "rules/yaml/github-actions/*": "CI workflow hygiene, not product code; not vendored", + "rules-audit/**/entrypoints/*": "enumerates every controller/route for a manual " + "audit, not a weakness; not vendored", + "rules/java/spring/security/audit/remoting/UnsafeHttpInvokerServiceExporter": "one " + "of its rules does not parse in semgrep 1.177, which fails the file's test; " + "not vendored (the XML variant is)", + "rules/php/php-filter-chain-read-from-oracle": "fails its own upstream test in " + "semgrep 1.177 (a false positive on a line marked ok); not vendored", + "rules-audit/javascript/rand-token": "fails its own upstream test in semgrep " + "1.177 (misses a line marked ruleid); not vendored", + "rules-audit/**/orm-leak/*": "ORM-leak review hints whose upstream tests name " + "rules that do not exist (`semgrep --test` fails); not vendored", + "rules-audit/c/lang/security/audit/exec*": "enumerates every process start for a " + "manual audit, not a weakness; not vendored", + "rules-audit/java/lang/security/audit/processbuilder*": "enumerates every " + "ProcessBuilder for a manual audit, not a weakness; not vendored", + }, + "drop": {}, + }, +} + +# What goes into the pack from a rule, in this order; the rest follows sorted. +ID_PREFIX = {"gitlab": "gitlab-", "0xdea": "0xdea-", "elttam": "elttam-"} +RULE_EXT = (".yml", ".yaml") + + +def run(*args: str, cwd: pathlib.Path | None = None) -> str: + return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout + + +def checkout(source: str, spec: dict, upstream: pathlib.Path | None, tmp: pathlib.Path) -> pathlib.Path: + if upstream is not None: + repo = upstream / source + head = run("git", "rev-parse", "HEAD", cwd=repo).strip() + if head != spec["commit"]: + sys.exit(f"{repo} is at {head}, the pin is {spec['commit']}") + return repo + repo = tmp / source + run("git", "clone", "--quiet", spec["url"] + ".git", str(repo)) + run("git", "checkout", "--quiet", spec["commit"], cwd=repo) + return repo + + +def matches(rel: str, globs) -> bool: + return any(fnmatch.fnmatch(rel, g) for g in globs) + + +def excluded(rel: str, spec: dict) -> str | None: + """The reason a file is not vendored, by its stem (``dir/rule-x`` covers + ``dir/rule-x.yml``, its test ``dir/rule-x.py`` and a test dir ``dir/rule-x/``).""" + for pattern, reason in spec["exclude"].items(): + stem = pattern + if rel == stem or rel.startswith(stem + ".") or rel.startswith(stem + "/"): + return reason + if fnmatch.fnmatch(rel, pattern) or fnmatch.fnmatch(rel, pattern + "/*"): + return reason + return None + + +def is_test_only(path: pathlib.Path) -> bool: + return ".test." in path.name or ".fixed." in path.name + + +def namespaced(source: str, rule_id: str) -> str: + # No dots: semgrep puts the config's path in front of a rule id with dots, + # and the agent strips that prefix at the last id it knows. + return ID_PREFIX[source] + re.sub(r"[^A-Za-z0-9_-]", "-", rule_id) + + +def first_cwe(rule: dict) -> str | None: + cwe = (rule.get("metadata") or {}).get("cwe") + if isinstance(cwe, list): + cwe = cwe[0] if cwe else None + found = re.match(r"\s*(CWE-\d+)", str(cwe)) if cwe else None + return found.group(1) if found else None + + +def flow_list(values) -> str: + return "[" + ", ".join(str(v) for v in values) + "]" + + +def emit_rule(rule: dict, new_id: str) -> str: + rest = {k: v for k, v in rule.items() if k not in ("id", "languages")} + body = yaml.safe_dump( + rest, sort_keys=False, allow_unicode=True, width=100, default_flow_style=False + ) + lines = [f" - id: {new_id}", f" languages: {flow_list(rule['languages'])}"] + lines += [" " + line if line else "" for line in body.rstrip("\n").split("\n")] + return "\n".join(lines) + "\n" + + +def vendor(source: str, spec: dict, repo: pathlib.Path) -> dict: + out = VENDOR / source + if out.exists(): + shutil.rmtree(out) + (out / "upstream").mkdir(parents=True) + shutil.copyfile(repo / "LICENSE", out / "LICENSE") + + kept, left_out, files = [], [], [] + for path in sorted(p for p in repo.rglob("*") if p.is_file() and ".git" not in p.parts): + rel = path.relative_to(repo).as_posix() + if not matches(rel, spec["include"]): + continue + reason = excluded(rel, spec) + if reason: + if path.suffix in RULE_EXT and not is_test_only(path): + for rule in yaml.safe_load(path.read_text())["rules"]: + left_out.append((namespaced(source, rule["id"]), rel, reason)) + continue + dest = out / "upstream" / rel + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, dest) + if path.suffix in RULE_EXT and not is_test_only(path): + text = path.read_text() + if spec["require_header"] and spec["require_header"] not in text.split("---")[0]: + sys.exit(f"{source}: {rel} does not carry '{spec['require_header']}'") + files.append(rel) + for rule in yaml.safe_load(text)["rules"]: + new_id = namespaced(source, rule["id"]) + if new_id in spec["drop"]: + left_out.append((new_id, rel, spec["drop"][new_id])) + else: + kept.append((new_id, rel, rule)) + + unknown = set(spec["drop"]) - {r[0] for r in left_out} + if unknown: + sys.exit(f"{source}: drop list names rules that do not exist: {sorted(unknown)}") + ids = [k[0] for k in kept] + if len(ids) != len(set(ids)): + sys.exit(f"{source}: duplicate rule ids after namespacing") + + pack = [ + f"# {spec['name']}, vendored by scripts/vendor-semgrep-rules.py; do not edit.", + f"# Upstream: {spec['url']} at {spec['commit']}", + f"# Licence: {spec['licence']}; see LICENSE and NOTICE next to this file.", + f"# Changed from upstream: ids prefixed with '{ID_PREFIX[source]}', rules", + "# left out as listed in NOTICE, rules re-serialised into one file.", + "rules:", + ] + text = "\n".join(pack) + "\n" + "".join(emit_rule(rule, new_id) for new_id, _, rule in kept) + # The agent reads ids and languages line by line: each rule must have + # exactly one `- id:` line, and no other line may look like one. + id_lines = [l for l in text.splitlines() if l.strip().startswith("- id:")] + if len(id_lines) != len(kept): + sys.exit(f"{source}: a rule body contains a line starting with '- id:'") + (out / "pack.yaml").write_text(text) + # The index the control-map test reads (the agent has no YAML parser): + # each rule's id, languages and first CWE id. + index = [ + {"id": new_id, "languages": rule["languages"], "cwe": first_cwe(rule)} + for new_id, _, rule in kept + ] + (out / "rules.json").write_text(json.dumps(index, indent=1) + "\n") + + notice = [ + f"{spec['name']}", + "=" * len(spec["name"]), + "", + f"Upstream: {spec['url']}", + f"Commit: {spec['commit']}", + f"Version: {spec['version']}", + f"Licence: {spec['licence']}", + f"Copyright: {spec['copyright']}", + "", + "Prüfwerk runs these rules with its own semgrep invocation (--metrics=off,", + "local files only). upstream/ holds the selected files unchanged, with", + "their semgrep tests. pack.yaml is what the agent runs: the same rules with", + f"ids prefixed by '{ID_PREFIX[source]}', re-serialised into one file, without", + "the rules listed below. Both are produced by scripts/vendor-semgrep-rules.py.", + "", + f"Selected from upstream: {', '.join(spec['include'])}", + f"Rules in the pack: {len(kept)} (from {len(files)} files)", + "", + *(["Not selected:", *[f"- {n}" for n in spec["not_selected"]], ""] if spec["not_selected"] else []), + "Left out", + "--------", + "", + ] + if not left_out: + notice.append("Nothing.") + for rule_id, rel, reason in sorted(left_out): + notice.append(f"- {rule_id} ({rel}): {reason}") + (out / "NOTICE").write_text("\n".join(notice) + "\n") + (out / "UPSTREAM").write_text(f"{spec['url']} {spec['commit']}\n") + return {"kept": len(kept), "left_out": len(left_out), "files": len(files)} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--upstream", type=pathlib.Path, help="directory with clones named by source") + args = parser.parse_args() + with tempfile.TemporaryDirectory() as tmp: + for source, spec in SOURCES.items(): + repo = checkout(source, spec, args.upstream, pathlib.Path(tmp)) + print(source, vendor(source, spec, repo)) + + +if __name__ == "__main__": + main()