From f0e97b4f31b9abde8608a456d48c3d3b8b5e4137 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Mon, 11 Dec 2023 15:02:54 +0100 Subject: [PATCH 01/39] add workflow to update embedded AppSec rules (#15) The workflow simply runs `_tools/rule-pdate/update.sh` and creates a PR with the result. --- .github/workflows/test.yml | 23 ++++++++---- .github/workflows/update-rules.yml | 57 ++++++++++++++++++++++++++++++ README.md | 17 +++++++++ _tools/rules-updater/Dockerfile | 17 ++++++--- _tools/rules-updater/update.sh | 5 +-- appsec/embed.go | 4 +-- 6 files changed, 108 insertions(+), 15 deletions(-) create mode 100644 .github/workflows/update-rules.yml create mode 100644 README.md diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3a8531f..ea36c5c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,13 +11,12 @@ env: DD_APPSEC_WAF_TIMEOUT: 5s jobs: native: + name: Native ${{ matrix.runs-on }} (Go ${{ matrix.go-version }}, CGO_ENABLED=${{ matrix.cgo_enabled }}) strategy: matrix: runs-on: [ macos-13, macos-12, macos-11, ubuntu-22.04, ubuntu-20.04, windows-latest ] go-version: [ "1.21", "1.20", "1.19" ] - cgo_enabled: # test it compiles with and without cgo - - 0 - - 1 + cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo fail-fast: false runs-on: ${{ matrix.runs-on }} steps: @@ -44,6 +43,7 @@ jobs: # Same tests but on the official golang container for linux golang-linux-container: + name: Docker golang:${{ matrix.go-version }}-${{ matrix.distribution }} (CGO_ENABLED=${{ matrix.cgo_enabled }}) runs-on: ubuntu-latest container: image: golang:${{ matrix.go-version }}-${{ matrix.distribution }} @@ -77,12 +77,11 @@ jobs: env CGO_ENABLED=${{ matrix.cgo_enabled }} ./gotestsum -- -v ./... || true linux-arm64: + name: Linux ARM64 (CGO_ENABLED=${{ matrix.cgo_enabled }}) runs-on: ubuntu-latest strategy: matrix: - cgo_enabled: # test it compiles with and without the cgo - - 0 - - 1 + cgo_enabled: [ "0", "1" ] # test it compiles with and without the cgo fail-fast: false steps: - uses: actions/checkout@v3 @@ -97,4 +96,14 @@ jobs: with: platforms: arm64 - run: docker run --platform=linux/arm64 -v $PWD:$PWD -w $PWD -eCGO_ENABLED=${{ matrix.cgo_enabled }} -eDD_APPSEC_WAF_TIMEOUT=$DD_APPSEC_WAF_TIMEOUT golang go test -v ./... - + + everything: + name: All Tests + needs: + - native + - golang-linux-container + - linux-arm64 + runs-on: ubuntu-latest + steps: + - name: Completed + run: echo "All tests completed!" diff --git a/.github/workflows/update-rules.yml b/.github/workflows/update-rules.yml new file mode 100644 index 0000000..9f8679e --- /dev/null +++ b/.github/workflows/update-rules.yml @@ -0,0 +1,57 @@ +name: Update AppSec Rules +on: + workflow_dispatch: # manually + schedule: + - cron: "0 6 * * 1" # every Monday at 06:00 UTC + +jobs: + update: + runs-on: ubuntu-latest + outputs: + mutation_happened: ${{ steps.detect.outputs.mutation_happened }} + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v3 + - name: Upgrade AppSec Rules + run: ./_tools/rules-updater/update.sh latest + - name: Detect Udpated Coded + id: detect + run: |- + git add . + git diff --staged --patch --exit-code > ${{ runner.temp }}/repo.patch || echo "mutation_happened=true" >> $GITHUB_OUTPUT + - name: Upload Patch + if: steps.detect.outputs.mutation_happened + uses: actions/upload-artifact@v3 + with: + name: repo.patch + path: ${{ runner.temp }}/repo.patch + + create-pr: + needs: update + runs-on: ubuntu-latest + permissions: + contents: write + if: needs.update.outputs.mutation_happened + steps: + - uses: actions/checkout@v3 + - name: Download Patch + uses: actions/upload-artifact@v3 + with: + name: repo.patch + path: ${{ runner.temp }} + - name: Apply Patch + run: git apply ${{ runner.temp }}/repo.patch + - name: Configure git identity + run: |- + git config user.name "github-actions[bot] on behalf of ${{ github.actor }}" + git config user.email "${{ github.actor }}@users.noreply.github.com" + - name: Push Changes + run: |- + git add . + git commit -m "Update embedded AppSec Rules" + git push --force-with-lease origin HEAD:automation/update-appsec-rules + - name: Create Pull Request + run: |- + gh pr create --fill --base "main" --head "automation/update-appsec-rules" --reviewer "@DataDog/asm-go" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/README.md b/README.md new file mode 100644 index 0000000..d6d3c93 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# `github.com/DataDog/appsec-internal-go` + +This repository hosts a go module that provides shared implementations for +internal details of various DataDog libraries and agents. This module is not +intended to be used directly by end-users. + +## Updating embedded Rules + +Embedded rules (at `appsec/rules.json`) are updated by the +`_tools/rules-updater/update.sh` script. A GitHub Workflow named +`Update AppSec Rules` can be used to perform this task entirely from the GitHub +Web UI. + +The GitHub Workflow runs automatically on a weekly basis (relatively early on +Monday morning), so manual intervention (beyond reviewing and merging the PR +created by the scheduled execution) should not be needed unless rules need to be +updated without waiting for the next Monday. diff --git a/_tools/rules-updater/Dockerfile b/_tools/rules-updater/Dockerfile index 234126f..4f96ab4 100644 --- a/_tools/rules-updater/Dockerfile +++ b/_tools/rules-updater/Dockerfile @@ -1,10 +1,19 @@ FROM golang:1.21 as go-format -ARG version -ENV VERSION=$version -ADD https://raw.githubusercontent.com/DataDog/appsec-event-rules/$version/build/recommended.json /home/rules.json + +RUN apt update && apt install -y jq curl COPY writer/ /home/ WORKDIR /home/ -RUN go run writer.go ${VERSION} > embed.go + +ARG version + +RUN if [ "${version}" = "latest" ]; then \ + curl -s 'https://api.github.com/repos/DataDog/appsec-event-rules/releases/latest' | jq -r '.tag_name' > .version; \ + else \ + echo "${version}" > .version; \ + fi + +RUN curl -fSsL "https://raw.githubusercontent.com/DataDog/appsec-event-rules/$(cat .version)/build/recommended.json" -o /home/rules.json +RUN go run writer.go $(cat .version) > embed.go FROM scratch COPY --from=go-format /home/embed.go embed.go diff --git a/_tools/rules-updater/update.sh b/_tools/rules-updater/update.sh index 14a6b31..9bc0913 100755 --- a/_tools/rules-updater/update.sh +++ b/_tools/rules-updater/update.sh @@ -10,6 +10,8 @@ # Usage: ./update.sh # Example: ./update.sh 1.2.5 # +# When the tag specified is "latest", the latest version of the rules file is +# determined using the GitHub API. set -eu @@ -26,6 +28,5 @@ trap "rm -r $tmpDir" EXIT DOCKER_BUILDKIT=1 docker build -o type=local,dest="$tmpDir" --build-arg version="$1" --no-cache "$scriptDir" echo "================ Done ================" -cp -v $tmpDir/embed.go "$destDir" -cp -v $tmpDir/rules.json "$destDir" +cp -v $tmpDir/embed.go $tmpDir/rules.json "$destDir" echo "Output written to $destDir" diff --git a/appsec/embed.go b/appsec/embed.go index 2262840..b8f3b3d 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.8.0) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.8.0/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.9.0) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.9.0/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string From d7b1b64ff5f3ec7c3c1c151171f3ccb1d045a554 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Mon, 11 Dec 2023 15:32:40 +0100 Subject: [PATCH 02/39] Fix minor issues with auto-update workflow (#17) --- .github/workflows/update-rules.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/update-rules.yml b/.github/workflows/update-rules.yml index 9f8679e..4f6258e 100644 --- a/.github/workflows/update-rules.yml +++ b/.github/workflows/update-rules.yml @@ -14,7 +14,7 @@ jobs: - uses: actions/setup-go@v3 - name: Upgrade AppSec Rules run: ./_tools/rules-updater/update.sh latest - - name: Detect Udpated Coded + - name: Detect Udpated Code id: detect run: |- git add . @@ -35,7 +35,7 @@ jobs: steps: - uses: actions/checkout@v3 - name: Download Patch - uses: actions/upload-artifact@v3 + uses: actions/download-artifact@v3 with: name: repo.patch path: ${{ runner.temp }} From 9174ef994306293273df18a1420bdf2e8a8e6d76 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Mon, 11 Dec 2023 15:40:37 +0100 Subject: [PATCH 03/39] Improve PR auto-creation --- .github/workflows/update-rules.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/update-rules.yml b/.github/workflows/update-rules.yml index 4f6258e..45a8c06 100644 --- a/.github/workflows/update-rules.yml +++ b/.github/workflows/update-rules.yml @@ -40,7 +40,10 @@ jobs: name: repo.patch path: ${{ runner.temp }} - name: Apply Patch - run: git apply ${{ runner.temp }}/repo.patch + id: apply + run: |- + git apply ${{ runner.temp }}/repo.patch + echo "version=$(jq -r '.metadata.rules_version' < ./appsec/rules.json)" >> $GITHUB_OUTPUT - name: Configure git identity run: |- git config user.name "github-actions[bot] on behalf of ${{ github.actor }}" @@ -52,6 +55,9 @@ jobs: git push --force-with-lease origin HEAD:automation/update-appsec-rules - name: Create Pull Request run: |- - gh pr create --fill --base "main" --head "automation/update-appsec-rules" --reviewer "@DataDog/asm-go" + gh pr create --title "Update embedded AppSec Rules to ${{ steps.apply.outputs.version }}" \ + --body "Automatically created by [GitHub Actions](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})." \ + --base "main" --head "automation/update-appsec-rules" \ + --reviewer "@DataDog/asm-go" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From d422f0c4bba0e31d5a4926f7a9d0f7d9c8178158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Mazeau?= Date: Mon, 11 Dec 2023 16:04:54 +0100 Subject: [PATCH 04/39] config: export env vars and default values (#16) --- appsec/config.go | 70 +++++++++++++++++++++++++------------------ appsec/config_test.go | 58 +++++++++++++++++------------------ 2 files changed, 70 insertions(+), 58 deletions(-) diff --git a/appsec/config.go b/appsec/config.go index 7248e60..1d9c4e1 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -18,22 +18,34 @@ import ( // Configuration environment variables const ( - envAPISecEnabled = "DD_EXPERIMENTAL_API_SECURITY_ENABLED" - envAPISecSampleRate = "DD_API_SECURITY_REQUEST_SAMPLE_RATE" - envObfuscatorKey = "DD_APPSEC_OBFUSCATION_PARAMETER_KEY_REGEXP" - envObfuscatorValue = "DD_APPSEC_OBFUSCATION_PARAMETER_VALUE_REGEXP" - envWafTimeout = "DD_APPSEC_WAF_TIMEOUT" - envTraceRateLimit = "DD_APPSEC_TRACE_RATE_LIMIT" - envRules = "DD_APPSEC_RULES" + // EnvAPISecEnabled is the env var used to enable API Security + EnvAPISecEnabled = "DD_EXPERIMENTAL_API_SECURITY_ENABLED" + // EnvAPISecSampleRate is the env var used to set the sampling rate of API Security schema extraction + EnvAPISecSampleRate = "DD_API_SECURITY_REQUEST_SAMPLE_RATE" + // EnvObfuscatorKey is the env var used to provide the WAF key obfuscation regexp + EnvObfuscatorKey = "DD_APPSEC_OBFUSCATION_PARAMETER_KEY_REGEXP" + // EnvObfuscatorValue is the env var used to provide the WAF value obfuscation regexp + EnvObfuscatorValue = "DD_APPSEC_OBFUSCATION_PARAMETER_VALUE_REGEXP" + // EnvWAFTimeout is the env var used to specify the timeout value for a WAF run + EnvWAFTimeout = "DD_APPSEC_WAF_TIMEOUT" + // EnvTraceRateLimit is the env var used to set the ASM trace limiting rate + EnvTraceRateLimit = "DD_APPSEC_TRACE_RATE_LIMIT" + // EnvRules is the env var used to provide a path to a local security rule file + EnvRules = "DD_APPSEC_RULES" ) // Configuration constants and default values const ( - defaultAPISecSampleRate = .1 - defaultObfuscatorKeyRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:_?phrase)?|secret|(?:api_?|private_?|public_?)key)|token|consumer_?(?:id|key|secret)|sign(?:ed|ature)|bearer|authorization` - defaultObfuscatorValueRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:_?phrase)?|secret|(?:api_?|private_?|public_?|access_?|secret_?)key(?:_?id)?|token|consumer_?(?:id|key|secret)|sign(?:ed|ature)?|auth(?:entication|orization)?)(?:\s*=[^;]|"\s*:\s*"[^"]+")|bearer\s+[a-z0-9\._\-]+|token:[a-z0-9]{13}|gh[opsu]_[0-9a-zA-Z]{36}|ey[I-L][\w=-]+\.ey[I-L][\w=-]+(?:\.[\w.+\/=-]+)?|[\-]{5}BEGIN[a-z\s]+PRIVATE\sKEY[\-]{5}[^\-]+[\-]{5}END[a-z\s]+PRIVATE\sKEY|ssh-rsa\s*[a-z0-9\/\.+]{100,}` - defaultWAFTimeout = 4 * time.Millisecond - defaultTraceRate uint = 100 // up to 100 appsec traces/s + // DefaultAPISecSampleRate is the default rate at which API Security schemas are extracted from requests + DefaultAPISecSampleRate = .1 + // DefaultObfuscatorKeyRegex is the default regexp used to obfuscate keys + DefaultObfuscatorKeyRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:_?phrase)?|secret|(?:api_?|private_?|public_?)key)|token|consumer_?(?:id|key|secret)|sign(?:ed|ature)|bearer|authorization` + // DefaultObfuscatorValueRegex is the default regexp used to obfuscate values + DefaultObfuscatorValueRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:_?phrase)?|secret|(?:api_?|private_?|public_?|access_?|secret_?)key(?:_?id)?|token|consumer_?(?:id|key|secret)|sign(?:ed|ature)?|auth(?:entication|orization)?)(?:\s*=[^;]|"\s*:\s*"[^"]+")|bearer\s+[a-z0-9\._\-]+|token:[a-z0-9]{13}|gh[opsu]_[0-9a-zA-Z]{36}|ey[I-L][\w=-]+\.ey[I-L][\w=-]+(?:\.[\w.+\/=-]+)?|[\-]{5}BEGIN[a-z\s]+PRIVATE\sKEY[\-]{5}[^\-]+[\-]{5}END[a-z\s]+PRIVATE\sKEY|ssh-rsa\s*[a-z0-9\/\.+]{100,}` + // DefaultWAFTimeout is the default time limit (ms) past which a WAF run will timeout + DefaultWAFTimeout = 4 * time.Millisecond + // DefaultTraceRate is the default limit (trace/sec) past which ASM traces are sampled out + DefaultTraceRate uint = 100 // up to 100 appsec traces/s ) // APISecConfig holds the configuration for API Security schemas reporting @@ -59,16 +71,16 @@ func NewAPISecConfig() APISecConfig { } func apiSecurityEnabled() bool { - enabled, _ := strconv.ParseBool(os.Getenv(envAPISecEnabled)) + enabled, _ := strconv.ParseBool(os.Getenv(EnvAPISecEnabled)) return enabled } func readAPISecuritySampleRate() float64 { - value := os.Getenv(envAPISecSampleRate) + value := os.Getenv(EnvAPISecSampleRate) rate, err := strconv.ParseFloat(value, 64) if err != nil { - logEnvVarParsingError(envAPISecSampleRate, value, err, defaultAPISecSampleRate) - return defaultAPISecSampleRate + logEnvVarParsingError(EnvAPISecSampleRate, value, err, DefaultAPISecSampleRate) + return DefaultAPISecSampleRate } // Clamp the value so that 0.0 <= rate <= 1.0 if rate < 0. { @@ -81,8 +93,8 @@ func readAPISecuritySampleRate() float64 { // NewObfuscatorConfig creates and returns a new WAF obfuscator configuration by reading the env func NewObfuscatorConfig() ObfuscatorConfig { - keyRE := readObfuscatorConfigRegexp(envObfuscatorKey, defaultObfuscatorKeyRegex) - valueRE := readObfuscatorConfigRegexp(envObfuscatorValue, defaultObfuscatorValueRegex) + keyRE := readObfuscatorConfigRegexp(EnvObfuscatorKey, DefaultObfuscatorKeyRegex) + valueRE := readObfuscatorConfigRegexp(EnvObfuscatorValue, DefaultObfuscatorValueRegex) return ObfuscatorConfig{KeyRegex: keyRE, ValueRegex: valueRE} } @@ -101,10 +113,10 @@ func readObfuscatorConfigRegexp(name, defaultValue string) string { } // WAFTimeoutFromEnv reads and parses the WAF timeout value set through the env -// If not set, it defaults to `defaultWAFTimeout` +// If not set, it defaults to `DefaultWAFTimeout` func WAFTimeoutFromEnv() (timeout time.Duration) { - timeout = defaultWAFTimeout - value := os.Getenv(envWafTimeout) + timeout = DefaultWAFTimeout + value := os.Getenv(EnvWAFTimeout) if value == "" { return } @@ -118,31 +130,31 @@ func WAFTimeoutFromEnv() (timeout time.Duration) { parsed, err := time.ParseDuration(value) if err != nil { - logEnvVarParsingError(envWafTimeout, value, err, timeout) + logEnvVarParsingError(EnvWAFTimeout, value, err, timeout) return } if parsed <= 0 { - logUnexpectedEnvVarValue(envWafTimeout, parsed, "expecting a strictly positive duration", timeout) + logUnexpectedEnvVarValue(EnvWAFTimeout, parsed, "expecting a strictly positive duration", timeout) return } return parsed } // RateLimitFromEnv reads and parses the trace rate limit set through the env -// If not set, it defaults to `defaultTraceRate` +// If not set, it defaults to `DefaultTraceRate` func RateLimitFromEnv() (rate uint) { - rate = defaultTraceRate - value := os.Getenv(envTraceRateLimit) + rate = DefaultTraceRate + value := os.Getenv(EnvTraceRateLimit) if value == "" { return rate } parsed, err := strconv.ParseUint(value, 10, 0) if err != nil { - logEnvVarParsingError(envTraceRateLimit, value, err, rate) + logEnvVarParsingError(EnvTraceRateLimit, value, err, rate) return } if parsed == 0 { - logUnexpectedEnvVarValue(envTraceRateLimit, parsed, "expecting a value strictly greater than 0", rate) + logUnexpectedEnvVarValue(EnvTraceRateLimit, parsed, "expecting a value strictly greater than 0", rate) return } return uint(parsed) @@ -151,7 +163,7 @@ func RateLimitFromEnv() (rate uint) { // RulesFromEnv returns the security rules provided through the environment // If the env var is not set, the default recommended rules are returned instead func RulesFromEnv() ([]byte, error) { - filepath := os.Getenv(envRules) + filepath := os.Getenv(EnvRules) if filepath == "" { log.Debug("appsec: using the default built-in recommended security rules") return DefaultRuleset() diff --git a/appsec/config_test.go b/appsec/config_test.go index 7df561a..37e824e 100644 --- a/appsec/config_test.go +++ b/appsec/config_test.go @@ -23,34 +23,34 @@ func TestAPISecConfig(t *testing.T) { }{ { name: "disabled", - sampleRate: defaultAPISecSampleRate, + sampleRate: DefaultAPISecSampleRate, }, { name: "disabled", enabledVar: "false", - sampleRate: defaultAPISecSampleRate, + sampleRate: DefaultAPISecSampleRate, }, { name: "disabled", enabledVar: "0", - sampleRate: defaultAPISecSampleRate, + sampleRate: DefaultAPISecSampleRate, }, { name: "disabled", enabledVar: "weirdvalue", - sampleRate: defaultAPISecSampleRate, + sampleRate: DefaultAPISecSampleRate, }, { name: "enabled", enabledVar: "true", enabled: true, - sampleRate: defaultAPISecSampleRate, + sampleRate: DefaultAPISecSampleRate, }, { name: "enabled", enabledVar: "1", enabled: true, - sampleRate: defaultAPISecSampleRate, + sampleRate: DefaultAPISecSampleRate, }, { name: "sampleRate 1.0", @@ -75,8 +75,8 @@ func TestAPISecConfig(t *testing.T) { }, } { t.Run(tc.name, func(t *testing.T) { - t.Setenv(envAPISecEnabled, tc.enabledVar) - t.Setenv(envAPISecSampleRate, tc.sampleRateVar) + t.Setenv(EnvAPISecEnabled, tc.enabledVar) + t.Setenv(EnvAPISecSampleRate, tc.sampleRateVar) cfg := NewAPISecConfig() require.Equal(t, tc.enabled, cfg.Enabled) require.Equal(t, tc.sampleRate, cfg.SampleRate) @@ -86,25 +86,25 @@ func TestAPISecConfig(t *testing.T) { func TestObfuscatorConfig(t *testing.T) { defaultConfig := ObfuscatorConfig{ - KeyRegex: defaultObfuscatorKeyRegex, - ValueRegex: defaultObfuscatorValueRegex, + KeyRegex: DefaultObfuscatorKeyRegex, + ValueRegex: DefaultObfuscatorValueRegex, } t.Run("key/env-var-normal", func(t *testing.T) { expCfg := defaultConfig expCfg.KeyRegex = "test" - t.Setenv(envObfuscatorKey, "test") + t.Setenv(EnvObfuscatorKey, "test") cfg := NewObfuscatorConfig() require.Equal(t, expCfg, cfg) }) t.Run("key/env-var-empty", func(t *testing.T) { expCfg := defaultConfig expCfg.KeyRegex = "" - t.Setenv(envObfuscatorKey, "") + t.Setenv(EnvObfuscatorKey, "") cfg := NewObfuscatorConfig() require.Equal(t, expCfg, cfg) }) t.Run("key/compile-error", func(t *testing.T) { - t.Setenv(envObfuscatorKey, "+") + t.Setenv(EnvObfuscatorKey, "+") cfg := NewObfuscatorConfig() require.Equal(t, defaultConfig, cfg) }) @@ -112,19 +112,19 @@ func TestObfuscatorConfig(t *testing.T) { t.Run("value/env-var-normal", func(t *testing.T) { expCfg := defaultConfig expCfg.ValueRegex = "test" - t.Setenv(envObfuscatorValue, "test") + t.Setenv(EnvObfuscatorValue, "test") cfg := NewObfuscatorConfig() require.Equal(t, expCfg, cfg) }) t.Run("value/env-var-empty", func(t *testing.T) { expCfg := defaultConfig expCfg.ValueRegex = "" - t.Setenv(envObfuscatorValue, "") + t.Setenv(EnvObfuscatorValue, "") cfg := NewObfuscatorConfig() require.Equal(t, expCfg, cfg) }) t.Run("value/compile-error", func(t *testing.T) { - t.Setenv(envObfuscatorValue, "+") + t.Setenv(EnvObfuscatorValue, "+") cfg := NewObfuscatorConfig() require.Equal(t, defaultConfig, cfg) }) @@ -144,26 +144,26 @@ func TestTraceRateLimit(t *testing.T) { { name: "not-parsable", env: "not a uint", - expected: defaultTraceRate, + expected: DefaultTraceRate, }, { name: "negative", env: "-1", - expected: defaultTraceRate, + expected: DefaultTraceRate, }, { name: "zero", env: "0", - expected: defaultTraceRate, + expected: DefaultTraceRate, }, { name: "empty-string", env: "", - expected: defaultTraceRate, + expected: DefaultTraceRate, }, } { t.Run(tc.name, func(t *testing.T) { - t.Setenv(envTraceRateLimit, tc.env) + t.Setenv(EnvTraceRateLimit, tc.env) require.Equal(t, tc.expected, RateLimitFromEnv()) }) } @@ -188,26 +188,26 @@ func TestWAFTimeout(t *testing.T) { { name: "not-parsable", env: "not a duration string", - expected: defaultWAFTimeout, + expected: DefaultWAFTimeout, }, { name: "negative", env: "-1s", - expected: defaultWAFTimeout, + expected: DefaultWAFTimeout, }, { name: "zero", env: "0", - expected: defaultWAFTimeout, + expected: DefaultWAFTimeout, }, { name: "empty-string", env: "", - expected: defaultWAFTimeout, + expected: DefaultWAFTimeout, }, } { t.Run(tc.name, func(t *testing.T) { - t.Setenv(envWafTimeout, tc.env) + t.Setenv(EnvWAFTimeout, tc.env) require.Equal(t, tc.expected, WAFTimeoutFromEnv()) }) @@ -218,14 +218,14 @@ func TestRules(t *testing.T) { t.Run("empty-string", func(t *testing.T) { defaultRules, err := DefaultRuleset() require.NoError(t, err) - t.Setenv(envRules, "") + t.Setenv(EnvRules, "") rules, err := RulesFromEnv() require.NoError(t, err) require.Equal(t, defaultRules, rules) }) t.Run("file-not-found", func(t *testing.T) { - t.Setenv(envRules, "i do not exist") + t.Setenv(EnvRules, "i do not exist") rules, err := RulesFromEnv() require.Error(t, err) require.Nil(t, rules) @@ -240,7 +240,7 @@ func TestRules(t *testing.T) { }() _, err = file.WriteString(StaticRecommendedRules) require.NoError(t, err) - t.Setenv(envRules, file.Name()) + t.Setenv(EnvRules, file.Name()) rules, err := RulesFromEnv() require.NoError(t, err) require.Equal(t, StaticRecommendedRules, string(rules)) From d4085412801b6a101d64aa2df3e1364809ad3002 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Mon, 11 Dec 2023 16:18:50 +0100 Subject: [PATCH 05/39] Update embedded AppSec Rules to 1.10.0 (#18) Co-authored-by: github-actions[bot] on behalf of RomainMuller --- .github/workflows/test.yml | 5 +- appsec/embed.go | 4 +- appsec/rules.json | 1395 +++++++++++++++++++++++++++++++++++- 3 files changed, 1400 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ea36c5c..5765215 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,7 +3,10 @@ on: workflow_dispatch: # manually schedule: # nightly - cron: "0 0 * * *" - pull_request: # on pull requests touching appsec files + pull_request: {} + merge_group: + branches: + - main push: # on push to the main branch branches: - main diff --git a/appsec/embed.go b/appsec/embed.go index b8f3b3d..8d4d83d 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.9.0) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.9.0/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.10.0) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.10.0/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string diff --git a/appsec/rules.json b/appsec/rules.json index 172558f..d572c00 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.9.0" + "rules_version": "1.10.0" }, "rules": [ { @@ -118,6 +118,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "list": [ @@ -346,6 +349,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "list": [ @@ -1839,6 +1845,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "^(?i:file|ftps?)://.*?\\?+$", @@ -1881,6 +1890,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "list": [ @@ -2391,6 +2403,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "^\\(\\s*\\)\\s+{", @@ -2547,6 +2562,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "list": [ @@ -2608,6 +2626,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:HTTP_(?:ACCEPT(?:_(?:ENCODING|LANGUAGE|CHARSET))?|(?:X_FORWARDED_FO|REFERE)R|(?:USER_AGEN|HOS)T|CONNECTION|KEEP_ALIVE)|PATH_(?:TRANSLATED|INFO)|ORIG_PATH_INFO|QUERY_STRING|REQUEST_URI|AUTH_TYPE)", @@ -2650,6 +2671,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "php://(?:std(?:in|out|err)|(?:in|out)put|fd|memory|temp|filter)", @@ -2691,6 +2715,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "list": [ @@ -2775,6 +2802,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b(?:s(?:e(?:t(?:_(?:e(?:xception|rror)_handler|magic_quotes_runtime|include_path)|defaultstub)|ssion_s(?:et_save_handler|tart))|qlite_(?:(?:(?:unbuffered|single|array)_)?query|create_(?:aggregate|function)|p?open|exec)|tr(?:eam_(?:context_create|socket_client)|ipc?slashes|rev)|implexml_load_(?:string|file)|ocket_c(?:onnect|reate)|h(?:ow_sourc|a1_fil)e|pl_autoload_register|ystem)|p(?:r(?:eg_(?:replace(?:_callback(?:_array)?)?|match(?:_all)?|split)|oc_(?:(?:terminat|clos|nic)e|get_status|open)|int_r)|o(?:six_(?:get(?:(?:e[gu]|g)id|login|pwnam)|mk(?:fifo|nod)|ttyname|kill)|pen)|hp(?:_(?:strip_whitespac|unam)e|version|info)|g_(?:(?:execut|prepar)e|connect|query)|a(?:rse_(?:ini_file|str)|ssthru)|utenv)|r(?:unkit_(?:function_(?:re(?:defin|nam)e|copy|add)|method_(?:re(?:defin|nam)e|copy|add)|constant_(?:redefine|add))|e(?:(?:gister_(?:shutdown|tick)|name)_function|ad(?:(?:gz)?file|_exif_data|dir))|awurl(?:de|en)code)|i(?:mage(?:createfrom(?:(?:jpe|pn)g|x[bp]m|wbmp|gif)|(?:jpe|pn)g|g(?:d2?|if)|2?wbmp|xbm)|s_(?:(?:(?:execut|write?|read)ab|fi)le|dir)|ni_(?:get(?:_all)?|set)|terator_apply|ptcembed)|g(?:et(?:_(?:c(?:urrent_use|fg_va)r|meta_tags)|my(?:[gpu]id|inode)|(?:lastmo|cw)d|imagesize|env)|z(?:(?:(?:defla|wri)t|encod|fil)e|compress|open|read)|lob)|a(?:rray_(?:u(?:intersect(?:_u?assoc)?|diff(?:_u?assoc)?)|intersect_u(?:assoc|key)|diff_u(?:assoc|key)|filter|reduce|map)|ssert(?:_options)?|tob)|h(?:tml(?:specialchars(?:_decode)?|_entity_decode|entities)|(?:ash(?:_(?:update|hmac))?|ighlight)_file|e(?:ader_register_callback|x2bin))|f(?:i(?:le(?:(?:[acm]tim|inod)e|(?:_exist|perm)s|group)?|nfo_open)|tp_(?:nb_(?:ge|pu)|connec|ge|pu)t|(?:unction_exis|pu)ts|write|open)|o(?:b_(?:get_(?:c(?:ontents|lean)|flush)|end_(?:clean|flush)|clean|flush|start)|dbc_(?:result(?:_all)?|exec(?:ute)?|connect)|pendir)|m(?:b_(?:ereg(?:_(?:replace(?:_callback)?|match)|i(?:_replace)?)?|parse_str)|(?:ove_uploaded|d5)_file|ethod_exists|ysql_query|kdir)|e(?:x(?:if_(?:t(?:humbnail|agname)|imagetype|read_data)|ec)|scapeshell(?:arg|cmd)|rror_reporting|val)|c(?:url_(?:file_create|exec|init)|onvert_uuencode|reate_function|hr)|u(?:n(?:serialize|pack)|rl(?:de|en)code|[ak]?sort)|b(?:(?:son_(?:de|en)|ase64_en)code|zopen|toa)|(?:json_(?:de|en)cod|debug_backtrac|tmpfil)e|var_dump)(?:\\s|/\\*.*\\*/|//.*|#.*|\\\"|')*\\((?:(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:\\$\\w+|[A-Z\\d]\\w*|\\w+\\(.*\\)|\\\\?\"(?:[^\"]|\\\\\"|\"\"|\"\\+\")*\\\\?\"|\\\\?'(?:[^']|''|'\\+')*\\\\?')(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:(?:::|\\.|->)(?:\\s|/\\*.*\\*/|//.*|#.*)*\\w+(?:\\(.*\\))?)?,)*(?:(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:\\$\\w+|[A-Z\\d]\\w*|\\w+\\(.*\\)|\\\\?\"(?:[^\"]|\\\\\"|\"\"|\"\\+\")*\\\\?\"|\\\\?'(?:[^']|''|'\\+')*\\\\?')(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:(?:::|\\.|->)(?:\\s|/\\*.*\\*/|//.*|#.*)*\\w+(?:\\(.*\\))?)?)?\\)", @@ -2820,6 +2850,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "[oOcC]:\\d+:\\\".+?\\\":\\d+:{[\\W\\w]*}", @@ -2861,6 +2894,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:(?:bzip|ssh)2|z(?:lib|ip)|(?:ph|r)ar|expect|glob|ogg)://", @@ -2904,6 +2940,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b(?:(?:l(?:(?:utimes|chmod)(?:Sync)?|(?:stat|ink)Sync)|w(?:rite(?:(?:File|v)(?:Sync)?|Sync)|atchFile)|u(?:n(?:watchFile|linkSync)|times(?:Sync)?)|s(?:(?:ymlink|tat)Sync|pawn(?:File|Sync))|ex(?:ec(?:File(?:Sync)?|Sync)|istsSync)|a(?:ppendFile|ccess)(?:Sync)?|(?:Caveat|Inode)s|open(?:dir)?Sync|new\\s+Function|Availability|\\beval)\\s*\\(|m(?:ain(?:Module\\s*(?:\\W*\\s*(?:constructor|require)|\\[)|\\s*(?:\\W*\\s*(?:constructor|require)|\\[))|kd(?:temp(?:Sync)?|irSync)\\s*\\(|odule\\.exports\\s*=)|c(?:(?:(?:h(?:mod|own)|lose)Sync|reate(?:Write|Read)Stream|p(?:Sync)?)\\s*\\(|o(?:nstructor\\s*(?:\\W*\\s*_load|\\[)|pyFile(?:Sync)?\\s*\\())|f(?:(?:(?:s(?:(?:yncS)?|tatS)|datas(?:yncS)?)ync|ch(?:mod|own)(?:Sync)?)\\s*\\(|u(?:nction\\s*\\(\\s*\\)\\s*{|times(?:Sync)?\\s*\\())|r(?:e(?:(?:ad(?:(?:File|link|dir)?Sync|v(?:Sync)?)|nameSync)\\s*\\(|quire\\s*(?:\\W*\\s*main|\\[))|m(?:Sync)?\\s*\\()|process\\s*(?:\\W*\\s*(?:mainModule|binding)|\\[)|t(?:his\\.constructor|runcateSync\\s*\\()|_(?:\\$\\$ND_FUNC\\$\\$_|_js_function)|global\\s*(?:\\W*\\s*process|\\[)|String\\s*\\.\\s*fromCharCode|binding\\s*\\[)", @@ -2946,6 +2985,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b(?:w(?:atch|rite)|(?:spaw|ope)n|exists|close|fork|read)\\s*\\(", @@ -3000,6 +3042,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "]*>[\\s\\S]*?", @@ -3057,6 +3102,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\bon(?:d(?:r(?:ag(?:en(?:ter|d)|leave|start|over)?|op)|urationchange|blclick)|s(?:e(?:ek(?:ing|ed)|arch|lect)|u(?:spend|bmit)|talled|croll|how)|m(?:ouse(?:(?:lea|mo)ve|o(?:ver|ut)|enter|down|up)|essage)|p(?:a(?:ge(?:hide|show)|(?:st|us)e)|lay(?:ing)?|rogress|aste|ointer(?:cancel|down|enter|leave|move|out|over|rawupdate|up))|c(?:anplay(?:through)?|o(?:ntextmenu|py)|hange|lick|ut)|a(?:nimation(?:iteration|start|end)|(?:fterprin|bor)t|uxclick|fterscriptexecute)|t(?:o(?:uch(?:cancel|start|move|end)|ggle)|imeupdate)|f(?:ullscreen(?:change|error)|ocus(?:out|in)?|inish)|(?:(?:volume|hash)chang|o(?:ff|n)lin)e|b(?:efore(?:unload|print)|lur)|load(?:ed(?:meta)?data|start|end)?|r(?:es(?:ize|et)|atechange)|key(?:press|down|up)|w(?:aiting|heel)|in(?:valid|put)|e(?:nded|rror)|unload)[\\s\\x0B\\x09\\x0C\\x3B\\x2C\\x28\\x3B]*?=[^=]", @@ -3113,6 +3161,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "[a-z]+=(?:[^:=]+:.+;)*?[^:=]+:url\\(javascript", @@ -3169,6 +3220,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:\\W|^)(?:javascript:(?:[\\s\\S]+[=\\x5c\\(\\[\\.<]|[\\s\\S]*?(?:\\bname\\b|\\x5c[ux]\\d)))|@\\W*?i\\W*?m\\W*?p\\W*?o\\W*?r\\W*?t\\W*?(?:/\\*[\\s\\S]*?)?(?:[\\\"']|\\W*?u\\W*?r\\W*?l[\\s\\S]*?\\()|[^-]*?-\\W*?m\\W*?o\\W*?z\\W*?-\\W*?b\\W*?i\\W*?n\\W*?d\\W*?i\\W*?n\\W*?g[^:]*?:\\W*?u\\W*?r\\W*?l[\\s\\S]*?\\(", @@ -3212,6 +3266,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "list": [ @@ -3260,6 +3317,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i:<.*[:]?vmlframe.*?[\\s/+]*?src[\\s/+]*=)", @@ -3304,6 +3364,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i:(?:j|&#x?0*(?:74|4A|106|6A);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:a|&#x?0*(?:65|41|97|61);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:v|&#x?0*(?:86|56|118|76);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:a|&#x?0*(?:65|41|97|61);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:s|&#x?0*(?:83|53|115|73);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:c|&#x?0*(?:67|43|99|63);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:r|&#x?0*(?:82|52|114|72);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:i|&#x?0*(?:73|49|105|69);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:p|&#x?0*(?:80|50|112|70);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:t|&#x?0*(?:84|54|116|74);?)(?:\\t|\\n|\\r|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?::|&(?:#x?0*(?:58|3A);?|colon;)).)", @@ -3348,6 +3411,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i:(?:v|&#x?0*(?:86|56|118|76);?)(?:\\t|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:b|&#x?0*(?:66|42|98|62);?)(?:\\t|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:s|&#x?0*(?:83|53|115|73);?)(?:\\t|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:c|&#x?0*(?:67|43|99|63);?)(?:\\t|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:r|&#x?0*(?:82|52|114|72);?)(?:\\t|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:i|&#x?0*(?:73|49|105|69);?)(?:\\t|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:p|&#x?0*(?:80|50|112|70);?)(?:\\t|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?:t|&#x?0*(?:84|54|116|74);?)(?:\\t|&(?:#x?0*(?:9|13|10|A|D);?|tab;|newline;))*(?::|&(?:#x?0*(?:58|3A);?|colon;)).)", @@ -3392,6 +3458,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "]", @@ -3608,6 +3689,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": ")|<.*\\+AD4-", @@ -3692,6 +3779,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "![!+ ]\\[\\]", @@ -3734,6 +3824,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b(?i:eval|settimeout|setinterval|new\\s+Function|alert|prompt)[\\s+]*\\([^\\)]", @@ -3775,6 +3868,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ] }, @@ -3814,6 +3910,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i:sleep\\(\\s*?\\d*?\\s*?\\)|benchmark\\(.*?\\,.*?\\))", @@ -3856,6 +3955,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:[\\\"'`](?:;*?\\s*?waitfor\\s+(?:delay|time)\\s+[\\\"'`]|;.*?:\\s*?goto)|alter\\s*?\\w+.*?cha(?:racte)?r\\s+set\\s+\\w+)", @@ -3896,6 +3998,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i:merge.*?using\\s*?\\(|execute\\s*?immediate\\s*?[\\\"'`]|match\\s*?[\\w(?:),+-]+\\s*?against\\s*?\\()", @@ -3937,6 +4042,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "union.*?select.*?from", @@ -3978,6 +4086,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:;\\s*?shutdown\\s*?(?:[#;{]|\\/\\*|--)|waitfor\\s*?delay\\s?[\\\"'`]+\\s?\\d|select\\s*?pg_sleep)", @@ -4018,6 +4129,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i:(?:\\[?\\$(?:(?:s(?:lic|iz)|wher)e|e(?:lemMatch|xists|q)|n(?:o[rt]|in?|e)|l(?:ike|te?)|t(?:ext|ype)|a(?:ll|nd)|jsonSchema|between|regex|x?or|div|mod)\\]?)\\b)", @@ -4061,6 +4175,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:^[\\W\\d]+\\s*?(?:alter\\s*(?:a(?:(?:pplication\\s*rol|ggregat)e|s(?:ymmetric\\s*ke|sembl)y|u(?:thorization|dit)|vailability\\s*group)|c(?:r(?:yptographic\\s*provider|edential)|o(?:l(?:latio|um)|nversio)n|ertificate|luster)|s(?:e(?:rv(?:ice|er)|curity|quence|ssion|arch)|y(?:mmetric\\s*key|nonym)|togroup|chema)|m(?:a(?:s(?:ter\\s*key|k)|terialized)|e(?:ssage\\s*type|thod)|odule)|l(?:o(?:g(?:file\\s*group|in)|ckdown)|a(?:ngua|r)ge|ibrary)|t(?:(?:abl(?:espac)?|yp)e|r(?:igger|usted)|hreshold|ext)|p(?:a(?:rtition|ckage)|ro(?:cedur|fil)e|ermission)|d(?:i(?:mension|skgroup)|atabase|efault|omain)|r(?:o(?:l(?:lback|e)|ute)|e(?:sourc|mot)e)|f(?:u(?:lltext|nction)|lashback|oreign)|e(?:xte(?:nsion|rnal)|(?:ndpoi|ve)nt)|in(?:dex(?:type)?|memory|stance)|b(?:roker\\s*priority|ufferpool)|x(?:ml\\s*schema|srobject)|w(?:ork(?:load)?|rapper)|hi(?:erarchy|stogram)|o(?:perator|utline)|(?:nicknam|queu)e|us(?:age|er)|group|java|view)|union\\s*(?:(?:distin|sele)ct|all))\\b|\\b(?:(?:(?:trunc|cre|upd)at|renam)e|(?:inser|selec)t|de(?:lete|sc)|alter|load)\\s+(?:group_concat|load_file|char)\\b\\s*\\(?|[\\s(]load_file\\s*?\\(|[\\\"'`]\\s+regexp\\W)", @@ -4101,6 +4218,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i:/\\*[!+](?:[\\w\\s=_\\-(?:)]+)?\\*/)", @@ -4143,6 +4263,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i:\\.cookie\\b.*?;\\W*?(?:expires|domain)\\W*?=|\\bhttp-equiv\\W+set-cookie\\b)", @@ -4188,6 +4311,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "java\\.lang\\.(?:runtime|processbuilder)", @@ -4233,6 +4359,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:unmarshaller|base64data|java\\.).*(?:runtime|processbuilder)", @@ -4277,6 +4406,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "list": [ @@ -4312,6 +4444,7 @@ "java.lang.object", "java.lang.process", "java.lang.reflect", + "java.lang.runtime", "java.lang.string", "java.lang.stringbuilder", "java.lang.system", @@ -4362,6 +4495,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:class\\.module\\.classLoader\\.resources\\.context\\.parent\\.pipeline|springframework\\.context\\.support\\.FileSystemXmlApplicationContext)", @@ -4403,6 +4539,9 @@ { "address": "graphql.server.all_resolvers" }, + { + "address": "graphql.server.resolver" + }, { "address": "server.request.headers.no_cookies" } @@ -4448,6 +4587,9 @@ { "address": "graphql.server.all_resolvers" }, + { + "address": "graphql.server.resolver" + }, { "address": "server.request.headers.no_cookies" } @@ -4493,6 +4635,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "[@#]ognl", @@ -4639,6 +4784,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "#(?:set|foreach|macro|parse|if)\\(.*\\)|<#assign.*>" @@ -4680,6 +4828,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b(?:burpcollaborator\\.net|oastify\\.com)\\b" @@ -4721,6 +4872,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\bqualysperiscope\\.com\\b|\\.oscomm\\." @@ -4762,6 +4916,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\bprbly\\.win\\b" @@ -4802,6 +4959,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b(?:webhook\\.site|\\.canarytokens\\.com|vii\\.one|act1on3\\.ru|gdsburp\\.com|arcticwolf\\.net|oob\\.li|htbiw\\.com|h4\\.vc|mochan\\.cloud|imshopping\\.com|bootstrapnodejs\\.com|mooo-ng\\.com|securitytrails\\.com|canyouhackit\\.io|7bae\\.xyz)\\b" @@ -4842,6 +5002,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b(?:\\.ngrok\\.io|requestbin\\.com|requestbin\\.net)\\b" @@ -4883,6 +5046,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\bappspidered\\.rapid7\\." @@ -4924,6 +5090,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b(?:interact\\.sh|oast\\.(?:pro|live|site|online|fun|me)|indusfacefinder\\.in|where\\.land|syhunt\\.net|tssrt\\.de|boardofcyber\\.io|assetnote-callback\\.com|praetorianlabs\\.dev|netspi\\.sh)\\b" @@ -4965,6 +5134,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b(?:\\.|(?:\\\\|&#)(?:0*46|x0*2e);)?r87(?:\\.|(?:\\\\|&#)(?:0*46|x0*2e);)(?:me|com)\\b", @@ -5010,6 +5182,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\bwhsec(?:\\.|(?:\\\\|&#)(?:0*46|x0*2e);)us\\b", @@ -5055,6 +5230,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\b\\.nessus\\.org\\b", @@ -5100,6 +5278,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\bwatchtowr\\.com\\b", @@ -5145,6 +5326,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\bptst\\.io\\b", @@ -5186,6 +5370,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "^(?i:file|ftps?|https?).*/rfiinc\\.txt\\?+$", @@ -5230,6 +5417,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:(?:['\"\\x60({|;&]|(?:^|['\"\\x60({|;&])(?:cmd(?:\\.exe)?\\s+(?:/\\w(?::\\w+)?\\s+)*))(?:ping|curl|wget|telnet)|\\bnslookup)[\\s,]", @@ -5265,6 +5455,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?:<\\?xml[^>]*>.*)]+SYSTEM\\s+[^>]+>", @@ -5318,6 +5511,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "<(?:iframe|esi:include)(?:(?:\\s|/)*\\w+=[\"'\\w]+)*(?:\\s|/)*src(?:doc)?=[\"']?(?:data:|javascript:|http:|dns:|//)[^\\s'\"]+['\"]?", @@ -5364,6 +5560,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "https?:\\/\\/(?:.*\\.)?(?:bxss\\.(?:in|me)|xss\\.ht|js\\.rip)", @@ -5949,6 +6148,48 @@ ], "transformers": [] }, + { + "id": "nfd-000-010", + "name": "Detect failed attempts to find API documentation", + "tags": { + "type": "security_scanner", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "confidence": "0" + }, + "conditions": [ + { + "operator": "match_regex", + "parameters": { + "inputs": [ + { + "address": "server.response.status" + } + ], + "regex": "^404$", + "options": { + "case_sensitive": true + } + } + }, + { + "operator": "match_regex", + "parameters": { + "inputs": [ + { + "address": "server.request.uri.raw" + } + ], + "regex": "(?:/swagger\\b|/api[-/]docs?\\b)", + "options": { + "case_sensitive": false + } + } + } + ], + "transformers": [] + }, { "id": "sqr-000-001", "name": "SSRF: Try to access the credential manager of the main cloud services", @@ -5977,6 +6218,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i)^\\W*((http|ftp)s?://)?\\W*((::f{4}:)?(169|(0x)?0*a9|0+251)\\.?(254|(0x)?0*fe|0+376)[0-9a-fx\\.:]+|metadata\\.google\\.internal|metadata\\.goog)\\W*/", @@ -6018,6 +6262,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "require\\(['\"][\\w\\.]+['\"]\\)|process\\.\\w+\\([\\w\\.]*\\)|\\.toString\\(\\)", @@ -6063,6 +6310,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i)[&|]\\s*type\\s+%\\w+%\\\\+\\w+\\.ini\\s*[&|]" @@ -6103,6 +6353,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i)[&|]\\s*cat\\s*\\/etc\\/[\\w\\.\\/]*passwd\\s*[&|]" @@ -6145,6 +6398,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(?i)[&|]\\s*timeout\\s+/t\\s+\\d+\\s*[&|]" @@ -6182,6 +6438,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "http(s?):\\/\\/([A-Za-z0-9\\.\\-\\_]+|\\[[A-Fa-f0-9\\:]+\\]|):5986\\/wsman", @@ -6222,6 +6481,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "^(jar:)?(http|https):\\/\\/([0-9oq]{1,5}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|[0-9]{1,10})(:[0-9]{1,5})?(\\/[^:@]*)?$" @@ -6261,6 +6523,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "^(jar:)?(http|https):\\/\\/((\\[)?[:0-9a-f\\.x]{2,}(\\])?)(:[0-9]{1,5})?(\\/[^:@]*)?$" @@ -6303,6 +6568,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "(http|https):\\/\\/(?:.*\\.)?(?:burpcollaborator\\.net|localtest\\.me|mail\\.ebc\\.apple\\.com|bugbounty\\.dod\\.network|.*\\.[nx]ip\\.io|oastify\\.com|oast\\.(?:pro|live|site|online|fun|me)|sslip\\.io|requestbin\\.com|requestbin\\.net|hookbin\\.com|webhook\\.site|canarytokens\\.com|interact\\.sh|ngrok\\.io|bugbounty\\.click|prbly\\.win|qualysperiscope\\.com|vii\\.one|act1on3\\.ru)" @@ -6343,6 +6611,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "^(jar:)?((file|netdoc):\\/\\/[\\\\\\/]+|(dict|gopher|ldap|sftp|tftp):\\/\\/.*:[0-9]{1,5})" @@ -6388,6 +6659,9 @@ }, { "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" } ], "regex": "\\${[^j]*j[^n]*n[^d]*d[^i]*i[^:]*:[^}]*}" @@ -7923,5 +8197,1124 @@ ], "transformers": [] } + ], + "processors": [ + { + "id": "extract-content", + "generator": "extract_schema", + "conditions": [ + { + "operator": "equals", + "parameters": { + "inputs": [ + { + "address": "waf.context.processor", + "key_path": [ + "extract-schema" + ] + } + ], + "type": "boolean", + "value": true + } + } + ], + "parameters": { + "mappings": [ + { + "inputs": [ + { + "address": "server.request.body" + } + ], + "output": "_dd.appsec.s.req.body" + }, + { + "inputs": [ + { + "address": "server.request.cookies" + } + ], + "output": "_dd.appsec.s.req.cookies" + }, + { + "inputs": [ + { + "address": "server.request.query" + } + ], + "output": "_dd.appsec.s.req.query" + }, + { + "inputs": [ + { + "address": "server.request.path_params" + } + ], + "output": "_dd.appsec.s.req.params" + }, + { + "inputs": [ + { + "address": "server.response.body" + } + ], + "output": "_dd.appsec.s.res.body" + }, + { + "inputs": [ + { + "address": "graphql.server.all_resolvers" + } + ], + "output": "_dd.appsec.s.graphql.all_resolvers" + }, + { + "inputs": [ + { + "address": "graphql.server.resolver" + } + ], + "output": "_dd.appsec.s.graphql.resolver" + } + ], + "scanners": [ + { + "tags": { + "category": "payment" + } + }, + { + "tags": { + "category": "pii" + } + } + ] + }, + "evaluate": false, + "output": true + }, + { + "id": "extract-headers", + "generator": "extract_schema", + "conditions": [ + { + "operator": "equals", + "parameters": { + "inputs": [ + { + "address": "waf.context.processor", + "key_path": [ + "extract-schema" + ] + } + ], + "type": "boolean", + "value": true + } + } + ], + "parameters": { + "mappings": [ + { + "inputs": [ + { + "address": "server.request.headers.no_cookies" + } + ], + "output": "_dd.appsec.s.req.headers" + }, + { + "inputs": [ + { + "address": "server.response.headers.no_cookies" + } + ], + "output": "_dd.appsec.s.res.headers" + } + ], + "scanners": [ + { + "tags": { + "category": "credentials" + } + }, + { + "tags": { + "category": "pii" + } + } + ] + }, + "evaluate": false, + "output": true + } + ], + "scanners": [ + { + "id": "JU1sRk3mSzqSUJn6GrVn7g", + "name": "American Express Card Scanner (4+4+4+3 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b3[47]\\d{2}(?:(?:\\s\\d{4}\\s\\d{4}\\s\\d{3})|(?:\\,\\d{4}\\,\\d{4}\\,\\d{3})|(?:-\\d{4}-\\d{4}-\\d{3})|(?:\\.\\d{4}\\.\\d{4}\\.\\d{3}))\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "amex", + "category": "payment" + } + }, + { + "id": "edmH513UTQWcRiQ9UnzHlw-mod", + "name": "American Express Card Scanner (4+6|5+5|6 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b3[47]\\d{2}(?:(?:\\s\\d{5,6}\\s\\d{5,6})|(?:\\.\\d{5,6}\\.\\d{5,6})|(?:-\\d{5,6}-\\d{5,6})|(?:,\\d{5,6},\\d{5,6}))\\b", + "options": { + "case_sensitive": false, + "min_length": 17 + } + } + }, + "tags": { + "type": "card", + "card_type": "amex", + "category": "payment" + } + }, + { + "id": "e6K4h_7qTLaMiAbaNXoSZA", + "name": "American Express Card Scanner (8+7 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b3[47]\\d{6}(?:(?:\\s\\d{7})|(?:\\,\\d{7})|(?:-\\d{7})|(?:\\.\\d{7}))\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "amex", + "category": "payment" + } + }, + { + "id": "K2rZflWzRhGM9HiTc6whyQ", + "name": "American Express Card Scanner (1x15 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b3[47]\\d{13}\\b", + "options": { + "case_sensitive": false, + "min_length": 15 + } + } + }, + "tags": { + "type": "card", + "card_type": "amex", + "category": "payment" + } + }, + { + "id": "9d7756e343cefa22a5c098e1092590f806eb5446", + "name": "Basic Authentication Scanner", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\bauthorization\\b", + "options": { + "case_sensitive": false, + "min_length": 13 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "^basic\\s+[A-Za-z0-9+/=]+", + "options": { + "case_sensitive": false, + "min_length": 7 + } + } + }, + "tags": { + "type": "basic_auth", + "category": "credentials" + } + }, + { + "id": "mZy8XjZLReC9smpERXWnnw", + "name": "Bearer Authentication Scanner", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\bauthorization\\b", + "options": { + "case_sensitive": false, + "min_length": 13 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "^bearer\\s+[-a-z0-9._~+/]{4,}", + "options": { + "case_sensitive": false, + "min_length": 11 + } + } + }, + "tags": { + "type": "bearer_token", + "category": "credentials" + } + }, + { + "id": "450239afc250a19799b6c03dc0e16fd6a4b2a1af", + "name": "Canadian Social Insurance Number Scanner", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:social[\\s_]?(?:insurance(?:\\s+number)?)?|SIN|Canadian[\\s_]?(?:social[\\s_]?(?:insurance)?|insurance[\\s_]?number)?)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b\\d{3}-\\d{3}-\\d{3}\\b", + "options": { + "case_sensitive": false, + "min_length": 11 + } + } + }, + "tags": { + "type": "canadian_sin", + "category": "pii" + } + }, + { + "id": "87a879ff33693b46c8a614d8211f5a2c289beca0", + "name": "Digest Authentication Scanner", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\bauthorization\\b", + "options": { + "case_sensitive": false, + "min_length": 13 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "^digest\\s+", + "options": { + "case_sensitive": false, + "min_length": 7 + } + } + }, + "tags": { + "type": "digest_auth", + "category": "credentials" + } + }, + { + "id": "qWumeP1GQUa_E4ffAnT-Yg", + "name": "American Express Card Scanner (1x14 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "(?:30[0-59]\\d|3[689]\\d{2})(?:\\d{10})", + "options": { + "case_sensitive": false, + "min_length": 14 + } + } + }, + "tags": { + "type": "card", + "card_type": "diners", + "category": "payment" + } + }, + { + "id": "NlTWWM5LS6W0GSqBLuvtRw", + "name": "Diners Card Scanner (4+4+4+2 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:30[0-59]\\d|3[689]\\d{2})(?:(?:\\s\\d{4}\\s\\d{4}\\s\\d{2})|(?:\\,\\d{4}\\,\\d{4}\\,\\d{2})|(?:-\\d{4}-\\d{4}-\\d{2})|(?:\\.\\d{4}\\.\\d{4}\\.\\d{2}))\\b", + "options": { + "case_sensitive": false, + "min_length": 17 + } + } + }, + "tags": { + "type": "card", + "card_type": "diners", + "category": "payment" + } + }, + { + "id": "Xr5VdbQSTXitYGGiTfxBpw", + "name": "Diners Card Scanner (4+6+4 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:30[0-59]\\d|3[689]\\d{2})(?:(?:\\s\\d{6}\\s\\d{4})|(?:\\.\\d{6}\\.\\d{4})|(?:-\\d{6}-\\d{4})|(?:,\\d{6},\\d{4}))\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "diners", + "category": "payment" + } + }, + { + "id": "gAbunN_WQNytxu54DjcbAA-mod", + "name": "Diners Card Scanner (8+6 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:30[0-59]\\d{5}|3[689]\\d{6})\\s?(?:(?:\\s\\d{6})|(?:\\,\\d{6})|(?:-\\d{6})|(?:\\.\\d{6}))\\b", + "options": { + "case_sensitive": false, + "min_length": 14 + } + } + }, + "tags": { + "type": "card", + "card_type": "diners", + "category": "payment" + } + }, + { + "id": "9cs4qCfEQBeX17U7AepOvQ", + "name": "MasterCard Scanner (2x8 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:6221(?:2[6-9]|[3-9][0-9])\\d{2}(?:,\\d{8}|\\s\\d{8}|-\\d{8}|\\.\\d{8})|6229(?:[01][0-9]|2[0-5])\\d{2}(?:,\\d{8}|\\s\\d{8}|-\\d{8}|\\.\\d{8})|(?:6011|65\\d{2}|64[4-9]\\d|622[2-8])\\d{4}(?:,\\d{8}|\\s\\d{8}|-\\d{8}|\\.\\d{8}))\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "discover", + "category": "payment" + } + }, + { + "id": "YBIDWJIvQWW_TFOyU0CGJg", + "name": "Discover Card Scanner (4x4 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:(?:(?:6221(?:2[6-9]|[3-9][0-9])\\d{2}(?:,\\d{4}){2})|(?:6221\\s(?:2[6-9]|[3-9][0-9])\\d{2}(?:\\s\\d{4}){2})|(?:6221\\.(?:2[6-9]|[3-9][0-9])\\d{2}(?:\\.\\d{4}){2})|(?:6221-(?:2[6-9]|[3-9][0-9])\\d{2}(?:-\\d{4}){2}))|(?:(?:6229(?:[01][0-9]|2[0-5])\\d{2}(?:,\\d{4}){2})|(?:6229\\s(?:[01][0-9]|2[0-5])\\d{2}(?:\\s\\d{4}){2})|(?:6229\\.(?:[01][0-9]|2[0-5])\\d{2}(?:\\.\\d{4}){2})|(?:6229-(?:[01][0-9]|2[0-5])\\d{2}(?:-\\d{4}){2}))|(?:(?:6011|65\\d{2}|64[4-9]\\d|622[2-8])(?:(?:\\s\\d{4}){3}|(?:\\.\\d{4}){3}|(?:-\\d{4}){3}|(?:,\\d{4}){3})))\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "discover", + "category": "payment" + } + }, + { + "id": "12cpbjtVTMaMutFhh9sojQ", + "name": "Discover Card Scanner (1x16 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:6221(?:2[6-9]|[3-9][0-9])\\d{10}|6229(?:[01][0-9]|2[0-5])\\d{10}|(?:6011|65\\d{2}|64[4-9]\\d|622[2-8])\\d{12})\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "discover", + "category": "payment" + } + }, + { + "id": "PuXiVTCkTHOtj0Yad1ppsw", + "name": "Standard E-mail Address", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:(?:e[-\\s]?)?mail|address|sender|\\bto\\b|from|recipient)\\b", + "options": { + "case_sensitive": false, + "min_length": 2 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*(%40|@)(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}\\b", + "options": { + "case_sensitive": false, + "min_length": 5 + } + } + }, + "tags": { + "type": "email", + "category": "pii" + } + }, + { + "id": "8VS2RKxzR8a_95L5fuwaXQ", + "name": "IBAN", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:iban|account|sender|receiver)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:NO\\d{2}(?:[ \\-]?\\d{4}){2}[ \\-]?\\d{3}|BE\\d{2}(?:[ \\-]?\\d{4}){3}|(?:DK|FO|FI|GL|SD)\\d{2}(?:[ \\-]?\\d{4}){3}[ \\-]?\\d{2}|NL\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?\\d{4}){2}[ \\-]?\\d{2}|MK\\d{2}[ \\-]?\\d{3}[A-Z0-9](?:[ \\-]?[A-Z0-9]{4}){2}[ \\-]?[A-Z0-9]\\d{2}|SI\\d{17}|(?:AT|BA|EE|LT|XK)\\d{18}|(?:LU|KZ|EE|LT)\\d{5}[A-Z0-9]{13}|LV\\d{2}[A-Z]{4}[A-Z0-9]{13}|(?:LI|CH)\\d{2}[ \\-]?\\d{4}[ \\-]?\\d[A-Z0-9]{3}(?:[ \\-]?[A-Z0-9]{4}){2}[ \\-]?[A-Z0-9]|HR\\d{2}(?:[ \\-]?\\d{4}){4}[ \\-]?\\d|GE\\d{2}[ \\-]?[A-Z0-9]{2}\\d{2}\\d{14}|VA\\d{20}|BG\\d{2}[A-Z]{4}\\d{6}[A-Z0-9]{8}|BH\\d{2}[A-Z]{4}[A-Z0-9]{14}|GB\\d{2}[A-Z]{4}(?:[ \\-]?\\d{4}){3}[ \\-]?\\d{2}|IE\\d{2}[ \\-]?[A-Z0-9]{4}(?:[ \\-]?\\d{4}){3}[ \\-]?\\d{2}|(?:CR|DE|ME|RS)\\d{2}(?:[ \\-]?\\d{4}){4}[ \\-]?\\d{2}|(?:AE|TL|IL)\\d{2}(?:[ \\-]?\\d{4}){4}[ \\-]?\\d{3}|GI\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?[A-Z0-9]{4}){3}[ \\-]?[A-Z0-9]{3}|IQ\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?\\d{4}){3}[ \\-]?\\d{3}|MD\\d{2}(?:[ \\-]?[A-Z0-9]{4}){5}|SA\\d{2}[ \\-]?\\d{2}[A-Z0-9]{2}(?:[ \\-]?[A-Z0-9]{4}){4}|RO\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?[A-Z0-9]{4}){4}|(?:PK|VG)\\d{2}[ \\-]?[A-Z0-9]{4}(?:[ \\-]?\\d{4}){4}|AD\\d{2}(?:[ \\-]?\\d{4}){2}(?:[ \\-]?[A-Z0-9]{4}){3}|(?:CZ|SK|ES|SE|TN)\\d{2}(?:[ \\-]?\\d{4}){5}|(?:LY|PT|ST)\\d{2}(?:[ \\-]?\\d{4}){5}[ \\-]?\\d|TR\\d{2}[ \\-]?\\d{4}[ \\-]?\\d[A-Z0-9]{3}(?:[ \\-]?[A-Z0-9]{4}){3}[ \\-]?[A-Z0-9]{2}|IS\\d{2}(?:[ \\-]?\\d{4}){5}[ \\-]?\\d{2}|(?:IT|SM)\\d{2}[ \\-]?[A-Z]\\d{3}[ \\-]?\\d{4}[ \\-]?\\d{3}[A-Z0-9](?:[ \\-]?[A-Z0-9]{4}){2}[ \\-]?[A-Z0-9]{3}|GR\\d{2}[ \\-]?\\d{4}[ \\-]?\\d{3}[A-Z0-9](?:[ \\-]?[A-Z0-9]{4}){3}[A-Z0-9]{3}|(?:FR|MC)\\d{2}(?:[ \\-]?\\d{4}){2}[ \\-]?\\d{2}[A-Z0-9]{2}(?:[ \\-]?[A-Z0-9]{4}){2}[ \\-]?[A-Z0-9]\\d{2}|MR\\d{2}(?:[ \\-]?\\d{4}){5}[ \\-]?\\d{3}|(?:SV|DO)\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?\\d{4}){5}|BY\\d{2}[ \\-]?[A-Z]{4}[ \\-]?\\d{4}(?:[ \\-]?[A-Z0-9]{4}){4}|GT\\d{2}(?:[ \\-]?[A-Z0-9]{4}){6}|AZ\\d{2}[ \\-]?[A-Z0-9]{4}(?:[ \\-]?\\d{5}){4}|LB\\d{2}[ \\-]?\\d{4}(?:[ \\-]?[A-Z0-9]{5}){4}|(?:AL|CY)\\d{2}(?:[ \\-]?\\d{4}){2}(?:[ \\-]?[A-Z0-9]{4}){4}|(?:HU|PL)\\d{2}(?:[ \\-]?\\d{4}){6}|QA\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?[A-Z0-9]{4}){5}[ \\-]?[A-Z0-9]|PS\\d{2}[ \\-]?[A-Z0-9]{4}(?:[ \\-]?\\d{4}){5}[ \\-]?\\d|UA\\d{2}[ \\-]?\\d{4}[ \\-]?\\d{2}[A-Z0-9]{2}(?:[ \\-]?[A-Z0-9]{4}){4}[ \\-]?[A-Z0-9]|BR\\d{2}(?:[ \\-]?\\d{4}){5}[ \\-]?\\d{3}[A-Z0-9][ \\-]?[A-Z0-9]|EG\\d{2}(?:[ \\-]?\\d{4}){6}\\d|MU\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?\\d{4}){4}\\d{3}[A-Z][ \\-]?[A-Z]{2}|(?:KW|JO)\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?[A-Z0-9]{4}){5}[ \\-]?[A-Z0-9]{2}|MT\\d{2}[ \\-]?[A-Z]{4}[ \\-]?\\d{4}[ \\-]?\\d[A-Z0-9]{3}(?:[ \\-]?[A-Z0-9]{3}){4}[ \\-]?[A-Z0-9]{3}|SC\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?\\d{4}){5}[ \\-]?[A-Z]{3}|LC\\d{2}[ \\-]?[A-Z]{4}(?:[ \\-]?[A-Z0-9]{4}){6})\\b", + "options": { + "case_sensitive": false, + "min_length": 15 + } + } + }, + "tags": { + "type": "iban", + "category": "payment" + } + }, + { + "id": "h6WJcecQTwqvN9KeEtwDvg", + "name": "JCB Card Scanner (1x16 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b35(?:2[89]|[3-9][0-9])(?:\\d{12})\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "jcb", + "category": "payment" + } + }, + { + "id": "gcEaMu_VSJ2-bGCEkgyC0w", + "name": "JCB Card Scanner (2x8 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b35(?:2[89]|[3-9][0-9])\\d{4}(?:(?:,\\d{8})|(?:-\\d{8})|(?:\\s\\d{8})|(?:\\.\\d{8}))\\b", + "options": { + "case_sensitive": false, + "min_length": 17 + } + } + }, + "tags": { + "type": "card", + "card_type": "jcb", + "category": "payment" + } + }, + { + "id": "imTliuhXT5GAeRNhqChXQQ", + "name": "JCB Card Scanner (4x4 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b35(?:2[89]|[3-9][0-9])(?:(?:\\s\\d{4}){3}|(?:\\.\\d{4}){3}|(?:-\\d{4}){3}|(?:,\\d{4}){3})\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "jcb", + "category": "payment" + } + }, + { + "id": "9osY3xc9Q7ONAV0zw9Uz4A", + "name": "JSON Web Token", + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\bey[I-L][\\w=-]+\\.ey[I-L][\\w=-]+(\\.[\\w.+\\/=-]+)?\\b", + "options": { + "case_sensitive": false, + "min_length": 20 + } + } + }, + "tags": { + "type": "json_web_token", + "category": "credentials" + } + }, + { + "id": "d1Q9D3YMRxuVKf6CZInJPw", + "name": "Maestro Card Scanner (1x16 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:5[06-9]\\d{2}|6\\d{3})(?:\\d{12})\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "maestro", + "category": "payment" + } + }, + { + "id": "M3YIQKKjRVmoeQuM3pjzrw", + "name": "Maestro Card Scanner (2x8 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:5[06-9]\\d{6}|6\\d{7})(?:\\s\\d{8}|\\.\\d{8}|-\\d{8}|,\\d{8})\\b", + "options": { + "case_sensitive": false, + "min_length": 17 + } + } + }, + "tags": { + "type": "card", + "card_type": "maestro", + "category": "payment" + } + }, + { + "id": "hRxiQBlSSVKcjh5U7LZYLA", + "name": "Maestro Card Scanner (4x4 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:5[06-9]\\d{2}|6\\d{3})(?:(?:\\s\\d{4}){3}|(?:\\.\\d{4}){3}|(?:-\\d{4}){3}|(?:,\\d{4}){3})\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "maestro", + "category": "payment" + } + }, + { + "id": "NwhIYNS4STqZys37WlaIKA", + "name": "MasterCard Scanner (2x8 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:(?:5[1-5]\\d{2})|(?:222[1-9])|(?:22[3-9]\\d)|(?:2[3-6]\\d{2})|(?:27[0-1]\\d)|(?:2720))(?:(?:\\d{4}(?:(?:,\\d{8})|(?:-\\d{8})|(?:\\s\\d{8})|(?:\\.\\d{8}))))\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "mastercard", + "category": "payment" + } + }, + { + "id": "axxJkyjhRTOuhjwlsA35Vw", + "name": "MasterCard Scanner (4x4 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:(?:5[1-5]\\d{2})|(?:222[1-9])|(?:22[3-9]\\d)|(?:2[3-6]\\d{2})|(?:27[0-1]\\d)|(?:2720))(?:(?:\\s\\d{4}){3}|(?:\\.\\d{4}){3}|(?:-\\d{4}){3}|(?:,\\d{4}){3})\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "mastercard", + "category": "payment" + } + }, + { + "id": "76EhmoK3TPqJcpM-fK0pLw", + "name": "MasterCard Scanner (1x16 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:(?:5[1-5]\\d{2})|(?:222[1-9])|(?:22[3-9]\\d)|(?:2[3-6]\\d{2})|(?:27[0-1]\\d)|(?:2720))(?:\\d{12})\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "mastercard", + "category": "payment" + } + }, + { + "id": "de0899e0cbaaa812bb624cf04c912071012f616d-mod", + "name": "UK National Insurance Number Scanner", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "^nin$|\\binsurance\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b[A-Z]{2}[\\s-]?\\d{6}[\\s-]?[A-Z]?\\b", + "options": { + "case_sensitive": false, + "min_length": 8 + } + } + }, + "tags": { + "type": "uk_nin", + "category": "pii" + } + }, + { + "id": "d962f7ddb3f55041e39195a60ff79d4814a7c331", + "name": "US Passport Scanner", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\bpassport\\b", + "options": { + "case_sensitive": false, + "min_length": 8 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b[0-9A-Z]{9}\\b|\\b[0-9]{6}[A-Z][0-9]{2}\\b", + "options": { + "case_sensitive": false, + "min_length": 8 + } + } + }, + "tags": { + "type": "passport_number", + "category": "pii" + } + }, + { + "id": "7771fc3b-b205-4b93-bcef-28608c5c1b54", + "name": "United States Social Security Number Scanner", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:SSN|(?:(?:social)?[\\s_]?(?:security)?[\\s_]?(?:number)?)?)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b\\d{3}[-\\s\\.]{1}\\d{2}[-\\s\\.]{1}\\d{4}\\b", + "options": { + "case_sensitive": false, + "min_length": 11 + } + } + }, + "tags": { + "type": "us_ssn", + "category": "pii" + } + }, + { + "id": "ac6d683cbac77f6e399a14990793dd8fd0fca333", + "name": "US Vehicle Identification Number Scanner", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:vehicle[_\\s-]*identification[_\\s-]*number|vin)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b[A-HJ-NPR-Z0-9]{17}\\b", + "options": { + "case_sensitive": false, + "min_length": 17 + } + } + }, + "tags": { + "type": "vin", + "category": "pii" + } + }, + { + "id": "wJIgOygRQhKkR69b_9XbRQ", + "name": "Visa Card Scanner (2x8 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b4\\d{3}(?:(?:\\d{4}(?:(?:,\\d{8})|(?:-\\d{8})|(?:\\s\\d{8})|(?:\\.\\d{8}))))\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "visa", + "category": "payment" + } + }, + { + "id": "0o71SJxXQNK7Q6gMbBesFQ", + "name": "Visa Card Scanner (4x4 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "\\b4\\d{3}(?:(?:,\\d{4}){3}|(?:\\s\\d{4}){3}|(?:\\.\\d{4}){3}|(?:-\\d{4}){3})\\b", + "options": { + "case_sensitive": false, + "min_length": 16 + } + } + }, + "tags": { + "type": "card", + "card_type": "visa", + "category": "payment" + } + }, + { + "id": "QrHD6AfgQm6z-j0wStxTvA", + "name": "Visa Card Scanner (1x15 & 1x16 & 1x19 digits)", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:card|cc|credit|debit|payment|amex|visa|mastercard|maestro|discover|jcb|diner)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "4[0-9]{12}(?:[0-9]{3})?", + "options": { + "case_sensitive": false, + "min_length": 13 + } + } + }, + "tags": { + "type": "card", + "card_type": "visa", + "category": "payment" + } + } ] } \ No newline at end of file From 241dc584b66b4ac24422cd044455f237f78fec49 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Wed, 20 Dec 2023 10:10:07 +0100 Subject: [PATCH 06/39] chore: make update workflow authenticate (#19) Since the DataDog/appsec-event-rules repository has been made internal, it is now necessary to authenticate in order to be able to access releases, etc... --- .github/workflows/update-rules.yml | 6 ++++-- _tools/rules-updater/Dockerfile | 13 +++++++++++-- _tools/rules-updater/update.sh | 8 +++++++- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/.github/workflows/update-rules.yml b/.github/workflows/update-rules.yml index 45a8c06..9ea3917 100644 --- a/.github/workflows/update-rules.yml +++ b/.github/workflows/update-rules.yml @@ -14,7 +14,9 @@ jobs: - uses: actions/setup-go@v3 - name: Upgrade AppSec Rules run: ./_tools/rules-updater/update.sh latest - - name: Detect Udpated Code + env: + GITHUB_TOKEN: ${{ secrets.UPDATE_RULES_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + - name: Detect Updated Code id: detect run: |- git add . @@ -60,4 +62,4 @@ jobs: --base "main" --head "automation/update-appsec-rules" \ --reviewer "@DataDog/asm-go" env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.MUTATOR_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} diff --git a/_tools/rules-updater/Dockerfile b/_tools/rules-updater/Dockerfile index 4f96ab4..43f7e14 100644 --- a/_tools/rules-updater/Dockerfile +++ b/_tools/rules-updater/Dockerfile @@ -5,14 +5,23 @@ COPY writer/ /home/ WORKDIR /home/ ARG version +ARG GITHUB_TOKEN RUN if [ "${version}" = "latest" ]; then \ - curl -s 'https://api.github.com/repos/DataDog/appsec-event-rules/releases/latest' | jq -r '.tag_name' > .version; \ + curl \ + --header "Authorization: Bearer ${GITHUB_TOKEN}" \ + --header "X-Github-Api-Version: 2022-11-28" \ + -fSsL 'https://api.github.com/repos/DataDog/appsec-event-rules/releases/latest' \ + | jq -r '.tag_name' > .version; \ else \ echo "${version}" > .version; \ fi -RUN curl -fSsL "https://raw.githubusercontent.com/DataDog/appsec-event-rules/$(cat .version)/build/recommended.json" -o /home/rules.json +RUN curl \ + --header "Authorization: Bearer ${GITHUB_TOKEN}" \ + --header "X-Github-Api-Version: 2022-11-28" \ + -fSsL "https://raw.githubusercontent.com/DataDog/appsec-event-rules/$(cat .version)/build/recommended.json" \ + -o /home/rules.json RUN go run writer.go $(cat .version) > embed.go FROM scratch diff --git a/_tools/rules-updater/update.sh b/_tools/rules-updater/update.sh index 9bc0913..34701b2 100755 --- a/_tools/rules-updater/update.sh +++ b/_tools/rules-updater/update.sh @@ -17,6 +17,12 @@ set -eu [ $# -ne 1 ] && echo "Usage: $0 \"version\"" >&2 && exit 1 +if [ -z ${GITHUB_TOKEN:-} ]; then + echo "The GITHUB_TOKEN environmnent variable must be set to a valid GitHub" + echo "token with read access to the DataDog/appsec-event-rules repository." + exit 1 +fi + echo "================ Minifying ================" tmpDir="$(mktemp -d /tmp/rule-update-XXXXXXXXX)" @@ -26,7 +32,7 @@ destDir="$(readlink -f "$scriptDir/../../appsec/")" trap "rm -r $tmpDir" EXIT -DOCKER_BUILDKIT=1 docker build -o type=local,dest="$tmpDir" --build-arg version="$1" --no-cache "$scriptDir" +DOCKER_BUILDKIT=1 docker build -o type=local,dest="$tmpDir" --build-arg version="$1" --build-arg GITHUB_TOKEN="${GITHUB_TOKEN}" --no-cache "$scriptDir" echo "================ Done ================" cp -v $tmpDir/embed.go $tmpDir/rules.json "$destDir" echo "Output written to $destDir" From 61c65c4322f49e189ddf8160fa9f15400c6371fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Mazeau?= Date: Thu, 1 Feb 2024 09:18:46 +0100 Subject: [PATCH 07/39] feat(config): enable APISec by default (#20) ## Content - Rename `DD_EXPERIMENTAL_API_SECURITY_ENABLED` to `DD_API_SECURITY_ENABLED` - If `DD_API_SECURITY_ENABLED` is not set, API Security is enabled. Otherwise the parsed value is used to enabled API Security (or not) ## Motivation This is to align the behaviour with the latest RFC edit --------- Co-authored-by: Julio Guerra --- appsec/config.go | 12 ++++++++++-- appsec/config_test.go | 16 ++++++++-------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/appsec/config.go b/appsec/config.go index 1d9c4e1..8abff4d 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -19,7 +19,7 @@ import ( // Configuration environment variables const ( // EnvAPISecEnabled is the env var used to enable API Security - EnvAPISecEnabled = "DD_EXPERIMENTAL_API_SECURITY_ENABLED" + EnvAPISecEnabled = "DD_API_SECURITY_ENABLED" // EnvAPISecSampleRate is the env var used to set the sampling rate of API Security schema extraction EnvAPISecSampleRate = "DD_API_SECURITY_REQUEST_SAMPLE_RATE" // EnvObfuscatorKey is the env var used to provide the WAF key obfuscation regexp @@ -71,7 +71,15 @@ func NewAPISecConfig() APISecConfig { } func apiSecurityEnabled() bool { - enabled, _ := strconv.ParseBool(os.Getenv(EnvAPISecEnabled)) + enabled := true + str, set := os.LookupEnv(EnvAPISecEnabled) + if set { + var err error + enabled, err = strconv.ParseBool(str) + if err != nil { + logEnvVarParsingError(EnvAPISecEnabled, str, err, enabled) + } + } return enabled } diff --git a/appsec/config_test.go b/appsec/config_test.go index 37e824e..3f93c7b 100644 --- a/appsec/config_test.go +++ b/appsec/config_test.go @@ -21,10 +21,6 @@ func TestAPISecConfig(t *testing.T) { enabled bool sampleRate float64 }{ - { - name: "disabled", - sampleRate: DefaultAPISecSampleRate, - }, { name: "disabled", enabledVar: "false", @@ -40,6 +36,11 @@ func TestAPISecConfig(t *testing.T) { enabledVar: "weirdvalue", sampleRate: DefaultAPISecSampleRate, }, + { + name: "enabled", + enabled: true, + sampleRate: DefaultAPISecSampleRate, + }, { name: "enabled", enabledVar: "true", @@ -54,28 +55,27 @@ func TestAPISecConfig(t *testing.T) { }, { name: "sampleRate 1.0", - enabledVar: "true", sampleRateVar: "1.0", enabled: true, sampleRate: 1., }, { name: "sampleRate 50.0", - enabledVar: "true", sampleRateVar: "50.0", enabled: true, sampleRate: 1., }, { name: "sampleRate -50.0", - enabledVar: "true", sampleRateVar: "-50.0", enabled: true, sampleRate: 0., }, } { t.Run(tc.name, func(t *testing.T) { - t.Setenv(EnvAPISecEnabled, tc.enabledVar) + if len(tc.enabledVar) > 0 { + t.Setenv(EnvAPISecEnabled, tc.enabledVar) + } t.Setenv(EnvAPISecSampleRate, tc.sampleRateVar) cfg := NewAPISecConfig() require.Equal(t, tc.enabled, cfg.Enabled) From baec4beee27a38c1fd143db5bf8b110fc9ad9dd5 Mon Sep 17 00:00:00 2001 From: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> Date: Tue, 13 Feb 2024 09:14:30 +0100 Subject: [PATCH 08/39] chore: remove inet.af (#21) the domain name `inet.af` became unavailable for polical reasons. But we don't need it anymore since it was integrated as `net/netip` Signed-off-by: Eliott Bouhana --- go.mod | 5 +---- go.sum | 32 -------------------------------- netip/{ip_go119.go => ip.go} | 3 --- netip/ip_default.go | 32 -------------------------------- 4 files changed, 1 insertion(+), 71 deletions(-) rename netip/{ip_go119.go => ip.go} (96%) delete mode 100644 netip/ip_default.go diff --git a/go.mod b/go.mod index 9d34c29..897b715 100644 --- a/go.mod +++ b/go.mod @@ -1,17 +1,14 @@ module github.com/DataDog/appsec-internal-go -go 1.18 +go 1.19 require ( github.com/stretchr/testify v1.8.4 go.uber.org/atomic v1.11.0 - inet.af/netaddr v0.0.0-20230525184311-b8eac61e914a ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - go4.org/intern v0.0.0-20230525184215-6c62f75575cb // indirect - go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 1a031ca..9fc0841 100644 --- a/go.sum +++ b/go.sum @@ -1,44 +1,12 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dvyukov/go-fuzz v0.0.0-20210103155950-6a8e9d1f2415/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go4.org/intern v0.0.0-20211027215823-ae77deb06f29/go.mod h1:cS2ma+47FKrLPdXFpr7CuxiTW3eyJbWew4qx0qtQWDA= -go4.org/intern v0.0.0-20230525184215-6c62f75575cb h1:ae7kzL5Cfdmcecbh22ll7lYP3iuUdnfnhiPcSaDgH/8= -go4.org/intern v0.0.0-20230525184215-6c62f75575cb/go.mod h1:Ycrt6raEcnF5FTsLiLKkhBTO6DPX3RCUCUVnks3gFJU= -go4.org/unsafe/assume-no-moving-gc v0.0.0-20211027215541-db492cf91b37/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= -go4.org/unsafe/assume-no-moving-gc v0.0.0-20230525183740-e7c30c78aeb2/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= -go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6 h1:lGdhQUN/cnWdSH3291CUuxSEqc+AsGTiDxPP3r2J0l4= -go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -inet.af/netaddr v0.0.0-20230525184311-b8eac61e914a h1:1XCVEdxrvL6c0TGOhecLuB7U9zYNdxZEjvOqJreKZiM= -inet.af/netaddr v0.0.0-20230525184311-b8eac61e914a/go.mod h1:e83i32mAQOW1LAqEIweALsuK2Uw4mhQadA5r7b0Wobo= diff --git a/netip/ip_go119.go b/netip/ip.go similarity index 96% rename from netip/ip_go119.go rename to netip/ip.go index 2c185de..99e1e62 100644 --- a/netip/ip_go119.go +++ b/netip/ip.go @@ -3,9 +3,6 @@ // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2022 Datadog, Inc. -//go:build go1.19 -// +build go1.19 - package netip import "net/netip" diff --git a/netip/ip_default.go b/netip/ip_default.go deleted file mode 100644 index f2906a0..0000000 --- a/netip/ip_default.go +++ /dev/null @@ -1,32 +0,0 @@ -// Unless explicitly stated otherwise all files in this repository are licensed -// under the Apache License Version 2.0. -// This product includes software developed at Datadog (https://www.datadoghq.com/). -// Copyright 2022 Datadog, Inc. - -//go:build !go1.19 -// +build !go1.19 - -package netip - -import "inet.af/netaddr" - -// Addr wraps an netaddr.IP value -type Addr = netaddr.IP - -// Prefix wraps an netaddr.IPPrefix value -type Prefix = netaddr.IPPrefix - -var ( - // ParseAddr wraps the netaddr.ParseIP function - ParseAddr = netaddr.ParseIP - // ParsePrefix wraps the netaddr.ParseIPPrefix function - ParsePrefix = netaddr.ParseIPPrefix - // MustParsePrefix wraps the netaddr.MustParseIPPrefix function - MustParsePrefix = netaddr.MustParseIPPrefix - // MustParseAddr wraps the netaddr.MustParseIP function - MustParseAddr = netaddr.MustParseIP - // IPv4 wraps the netaddr.IPv4 function - IPv4 = netaddr.IPv4 - // AddrFrom16 wraps the netaddr.IPv6Raw function - AddrFrom16 = netaddr.IPv6Raw -) From 674e6485ef73e9327f7868a9a234847eff46483a Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Wed, 21 Feb 2024 13:57:05 +0100 Subject: [PATCH 09/39] fix: possible goroutine leak in `limiter.TokenTicker` (in tests only) (#22) --- go.mod | 3 +- go.sum | 10 ++- limiter/limiter.go | 50 ++++++++------- limiter/limiter_test.go | 131 +++++++++++++++++++++++++++------------- 4 files changed, 127 insertions(+), 67 deletions(-) diff --git a/go.mod b/go.mod index 897b715..971552b 100644 --- a/go.mod +++ b/go.mod @@ -4,11 +4,12 @@ go 1.19 require ( github.com/stretchr/testify v1.8.4 - go.uber.org/atomic v1.11.0 + go.uber.org/goleak v1.3.0 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect + github.com/kr/text v0.2.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 9fc0841..5f88626 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,16 @@ +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/limiter/limiter.go b/limiter/limiter.go index c14f772..f1f16d3 100644 --- a/limiter/limiter.go +++ b/limiter/limiter.go @@ -3,12 +3,13 @@ // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2022-present Datadog, Inc. +// Package limiter provides simple rate limiting primitives, and an implementation of a token bucket rate limiter. package limiter import ( "time" - "go.uber.org/atomic" + "sync/atomic" ) // Limiter is used to abstract the rate limiter implementation to only expose the needed function for rate limiting. @@ -25,35 +26,43 @@ type Limiter interface { // TokenTicker.Allow() and TokenTicker.Stop() *must* be called once done using. Note that calling TokenTicker.Allow() // before TokenTicker.Start() is valid, but it means the bucket won't be refilling until the call to TokenTicker.Start() is made type TokenTicker struct { - tokens atomic.Int64 - maxTokens int64 - ticker *time.Ticker - stopChan chan struct{} + tokens atomic.Int64 // The amount of tokens currently available + maxTokens int64 // The maximum amount of tokens the bucket can hold + ticker *time.Ticker // The ticker used to update the bucket (nil if not started yet) + stopChan chan struct{} // The channel to stop the ticker updater (nil if not started yet) } // NewTokenTicker is a utility function that allocates a token ticker, initializes necessary fields and returns it func NewTokenTicker(tokens, maxTokens int64) *TokenTicker { - return &TokenTicker{ - tokens: *atomic.NewInt64(tokens), + t := &TokenTicker{ maxTokens: maxTokens, } + t.tokens.Store(tokens) + return t } // updateBucket performs a select loop to update the token amount in the bucket. // Used in a goroutine by the rate limiter. -func (t *TokenTicker) updateBucket(ticksChan <-chan time.Time, startTime time.Time, syncChan chan struct{}) { +func (t *TokenTicker) updateBucket(startTime time.Time, ticksChan <-chan time.Time, stopChan <-chan struct{}, syncChan chan<- struct{}) { nsPerToken := time.Second.Nanoseconds() / t.maxTokens elapsedNs := int64(0) prevStamp := startTime for { select { - case <-t.stopChan: + case <-stopChan: if syncChan != nil { close(syncChan) } return - case stamp := <-ticksChan: + case stamp, ok := <-ticksChan: + if !ok { + // The ticker has been closed, stamp is a zero-value, we ignore that. We nil-out the + // ticksChan so we don't get stuck endlessly reading from this closed channel again. + ticksChan = nil + continue + } + // Compute the time in nanoseconds that passed between the previous timestamp and this one // This will be used to know how many tokens can be added into the bucket depending on the limiter rate elapsedNs += stamp.Sub(prevStamp).Nanoseconds() @@ -96,22 +105,17 @@ func (t *TokenTicker) updateBucket(ticksChan <-chan time.Time, startTime time.Ti func (t *TokenTicker) Start() { timeNow := time.Now() t.ticker = time.NewTicker(500 * time.Microsecond) - t.start(t.ticker.C, timeNow, false) + t.start(timeNow, t.ticker.C, nil) } // start is used for internal testing. Controlling the ticker means being able to test per-tick -// rather than per-duration, which is more reliable if the app is under a lot of stress. -// sync is used to decide whether the limiter should create a channel for synchronization with the testing app after a -// bucket update. The limiter is in charge of closing the channel in this case. -func (t *TokenTicker) start(ticksChan <-chan time.Time, startTime time.Time, sync bool) <-chan struct{} { +// rather than per-duration, which is more reliable if the app is under a lot of stress. The +// syncChan, if non-nil, will receive one message after each tick from the ticksChan has been +// processed, providing a strong synchronization primitive. The limiter will close the syncChan when +// it is stopped, signaling that no further ticks will be processed. +func (t *TokenTicker) start(startTime time.Time, ticksChan <-chan time.Time, syncChan chan<- struct{}) { t.stopChan = make(chan struct{}) - var syncChan chan struct{} - - if sync { - syncChan = make(chan struct{}) - } - go t.updateBucket(ticksChan, startTime, syncChan) - return syncChan + go t.updateBucket(startTime, ticksChan, t.stopChan, syncChan) } // Stop shuts down the rate limiter, taking care stopping the ticker and closing all channels @@ -119,11 +123,13 @@ func (t *TokenTicker) Stop() { // Stop the ticker only if it has been instantiated (not the case when testing by calling start() directly) if t.ticker != nil { t.ticker.Stop() + t.ticker = nil // Ensure stop can be called multiple times idempotently. } // Close the stop channel only if it has been created. This covers the case where Stop() is called without any prior // call to Start() if t.stopChan != nil { close(t.stopChan) + t.stopChan = nil // Ensure stop can be called multiple times idempotently. } } diff --git a/limiter/limiter_test.go b/limiter/limiter_test.go index 18f1a03..6eaa3b3 100644 --- a/limiter/limiter_test.go +++ b/limiter/limiter_test.go @@ -9,18 +9,22 @@ import ( "fmt" "math" "sync" + "sync/atomic" "testing" "time" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.uber.org/atomic" + "go.uber.org/goleak" ) func TestLimiterUnit(t *testing.T) { startTime := time.Now() t.Run("no-ticks-1", func(t *testing.T) { - l := NewTestTicker(1, 100) + defer goleak.VerifyNone(t) + + l := newTestTicker(1, 100) l.start(startTime) defer l.stop() // No ticks between the requests @@ -29,7 +33,9 @@ func TestLimiterUnit(t *testing.T) { }) t.Run("no-ticks-2", func(t *testing.T) { - l := NewTestTicker(100, 100) + defer goleak.VerifyNone(t) + + l := newTestTicker(100, 100) l.start(startTime) defer l.stop() // No ticks between the requests @@ -40,89 +46,102 @@ func TestLimiterUnit(t *testing.T) { }) t.Run("10ms-ticks", func(t *testing.T) { - l := NewTestTicker(1, 100) + defer goleak.VerifyNone(t) + + l := newTestTicker(1, 100) l.start(startTime) defer l.stop() require.True(t, l.Allow(), "First call to limiter.Allow() should return True") require.False(t, l.Allow(), "Second call to limiter.Allow() should return false") - l.tick(startTime.Add(10 * time.Millisecond)) + l.tick(10 * time.Millisecond) require.True(t, l.Allow(), "Third call to limiter.Allow() after 10ms should return True") }) t.Run("9ms-ticks", func(t *testing.T) { - l := NewTestTicker(1, 100) + defer goleak.VerifyNone(t) + + l := newTestTicker(1, 100) l.start(startTime) defer l.stop() require.True(t, l.Allow(), "First call to limiter.Allow() should return True") - l.tick(startTime.Add(9 * time.Millisecond)) + l.tick(9 * time.Millisecond) require.False(t, l.Allow(), "Second call to limiter.Allow() after 9ms should return False") - l.tick(startTime.Add(10 * time.Millisecond)) + l.tick(10 * time.Millisecond) require.True(t, l.Allow(), "Third call to limiter.Allow() after 10ms should return True") }) t.Run("1s-rate", func(t *testing.T) { - l := NewTestTicker(1, 1) + defer goleak.VerifyNone(t) + + l := newTestTicker(1, 1) l.start(startTime) defer l.stop() require.True(t, l.Allow(), "First call to limiter.Allow() should return True with 1s per token") - l.tick(startTime.Add(500 * time.Millisecond)) + l.tick(500 * time.Millisecond) require.False(t, l.Allow(), "Second call to limiter.Allow() should return False with 1s per Token") - l.tick(startTime.Add(1000 * time.Millisecond)) + l.tick(1000 * time.Millisecond) require.True(t, l.Allow(), "Third call to limiter.Allow() should return True with 1s per Token") }) t.Run("100-requests-burst", func(t *testing.T) { - l := NewTestTicker(100, 100) + defer goleak.VerifyNone(t) + + l := newTestTicker(100, 100) l.start(startTime) defer l.stop() for i := 0; i < 100; i++ { require.Truef(t, l.Allow(), "Burst call %d to limiter.Allow() should return True with 100 initial tokens", i) - startTime = startTime.Add(50 * time.Microsecond) - l.tick(startTime) + l.tick(50 * time.Millisecond) } }) t.Run("101-requests-burst", func(t *testing.T) { - l := NewTestTicker(100, 100) + defer goleak.VerifyNone(t) + + l := newTestTicker(100, 100) l.start(startTime) defer l.stop() for i := 0; i < 100; i++ { require.Truef(t, l.Allow(), "Burst call %d to limiter.Allow() should return True with 100 initial tokens", i) startTime = startTime.Add(50 * time.Microsecond) - l.tick(startTime) + l.tick(0) } require.False(t, l.Allow(), "Burst call 101 to limiter.Allow() should return False with 100 initial tokens") }) t.Run("bucket-refill-short", func(t *testing.T) { - l := NewTestTicker(100, 100) + defer goleak.VerifyNone(t) + + l := newTestTicker(100, 100) l.start(startTime) defer l.stop() for i := 0; i < 1000; i++ { - startTime = startTime.Add(time.Millisecond) - l.tick(startTime) + l.tick(time.Millisecond) require.Equalf(t, int64(100), l.t.tokens.Load(), "Bucket should have exactly 100 tokens") } }) t.Run("bucket-refill-long", func(t *testing.T) { - l := NewTestTicker(100, 100) + defer goleak.VerifyNone(t) + + l := newTestTicker(100, 100) l.start(startTime) defer l.stop() for i := 0; i < 1000; i++ { - startTime = startTime.Add(3 * time.Second) - l.tick(startTime) + l.tick(3 * time.Second) } require.Equalf(t, int64(100), l.t.tokens.Load(), "Bucket should have exactly 100 tokens") }) t.Run("allow-after-stop", func(t *testing.T) { - l := NewTestTicker(3, 3) + defer goleak.VerifyNone(t) + + l := newTestTicker(3, 3) l.start(startTime) require.True(t, l.Allow()) l.stop() @@ -133,7 +152,9 @@ func TestLimiterUnit(t *testing.T) { }) t.Run("allow-before-start", func(t *testing.T) { - l := NewTestTicker(2, 100) + defer goleak.VerifyNone(t) + + l := newTestTicker(2, 100) // The limiter keeps allowing until there's no more tokens require.True(t, l.Allow()) require.True(t, l.Allow()) @@ -141,7 +162,7 @@ func TestLimiterUnit(t *testing.T) { l.start(startTime) // The limiter has used all its tokens and the bucket is not getting refilled yet require.False(t, l.Allow()) - l.tick(startTime.Add(10 * time.Millisecond)) + l.tick(10 * time.Millisecond) // The limiter has started refilling its tokens require.True(t, l.Allow()) l.stop() @@ -154,6 +175,8 @@ func TestLimiter(t *testing.T) { // Each goroutine will continuously call the rate limiter for 1 second for nbUsers := 1; nbUsers <= 10; nbUsers *= 10 { t.Run(fmt.Sprintf("continuous-requests-%d-users", nbUsers), func(t *testing.T) { + defer goleak.VerifyNone(t) + var startBarrier, stopBarrier sync.WaitGroup // Create a start barrier to synchronize every goroutine's launch and // increase the chances of parallel accesses @@ -170,9 +193,9 @@ func TestLimiter(t *testing.T) { for tStart := time.Now(); time.Since(tStart) < 1*time.Second; { if !l.Allow() { - skipped.Inc() + skipped.Add(1) } else { - kept.Inc() + kept.Add(1) } } }(l, &kept, &skipped) @@ -197,9 +220,11 @@ func TestLimiter(t *testing.T) { // Simulate sporadic bursts during up to 1 minute for burstAmount := 1; burstAmount <= 10; burstAmount++ { t.Run(fmt.Sprintf("requests-bursts-%d-iterations", burstAmount), func(t *testing.T) { + defer goleak.VerifyNone(t) + skipped := 0 kept := 0 - l := NewTestTicker(100, 100) + l := newTestTicker(100, 100) l.start(startTime) defer l.stop() @@ -212,8 +237,7 @@ func TestLimiter(t *testing.T) { } } // Schedule next burst 1sec later - startTime = startTime.Add(burstFreq) - l.tick(startTime) + l.tick(burstFreq) } expectedSkipped := (burstSize - 100) * burstAmount @@ -230,12 +254,16 @@ func TestLimiter(t *testing.T) { } func BenchmarkLimiter(b *testing.B) { + defer goleak.VerifyNone(b, goleak.IgnoreCurrent()) + for nbUsers := 1; nbUsers <= 1000; nbUsers *= 10 { b.Run(fmt.Sprintf("%d-users", nbUsers), func(b *testing.B) { var skipped, kept atomic.Uint64 limiter := NewTokenTicker(0, 100) limiter.Start() defer limiter.Stop() + + b.StopTimer() b.ResetTimer() for n := 0; n < b.N; n++ { @@ -251,18 +279,25 @@ func BenchmarkLimiter(b *testing.B) { startBarrier.Wait() // Sync the starts of the goroutines defer stopBarrier.Done() // Signal we are done when returning + b.StartTimer() // Ensure the timer is started now... + for i := 0; i < 100; i++ { if !l.Allow() { - skipped.Inc() + skipped.Add(1) } else { - kept.Inc() + kept.Add(1) } } }(limiter, &kept, &skipped) } + startBarrier.Done() // Unblock the user goroutines stopBarrier.Wait() // Wait for the user goroutines to be done + b.StopTimer() } + + assert.NotEqual(b, 0, kept.Load(), "expected to have accepted at least 1") + assert.NotEqual(b, 0, skipped.Load(), "expected to have skipped at least 1") }) } } @@ -270,30 +305,44 @@ func BenchmarkLimiter(b *testing.B) { // TestTicker is a utility struct used to send hand-crafted ticks to the rate limiter for controlled testing // It also makes sure to give time to the bucket update goroutine by using the optional sync channel type TestTicker struct { - C chan time.Time - syncChan <-chan struct{} - t *TokenTicker + C chan time.Time + syncChan <-chan struct{} + t *TokenTicker + timestamp time.Time } -func NewTestTicker(tokens, maxTokens int64) *TestTicker { +func newTestTicker(tokens, maxTokens int64) *TestTicker { return &TestTicker{ C: make(chan time.Time), t: NewTokenTicker(tokens, maxTokens), } } -func (t *TestTicker) start(timeStamp time.Time) { - t.syncChan = t.t.start(t.C, timeStamp, true) +func (t *TestTicker) start(timestamp time.Time) { + syncChan := make(chan struct{}, 1) + t.syncChan = syncChan + t.timestamp = timestamp + t.t.start(timestamp, t.C, syncChan) } func (t *TestTicker) stop() { t.t.Stop() close(t.C) - // syncChan is closed by the token ticker when sure that nothing else will be sent on it + // syncChan is closed by the token ticker when sure that nothing else will be sent on it. + for _, ok := <-t.syncChan; ok; _, ok = <-t.syncChan { + // Drain the channel. + } + t.syncChan = nil + t.timestamp = time.Time{} } -func (t *TestTicker) tick(timeStamp time.Time) { - t.C <- timeStamp +// tick advances the `TestTicker`'s internal clock by the provided duration, and sends a tick to the +// underlying `TokenTicker`. It then waits for the `TokenTicker` to be done processing that tick, so +// the caller can assume the tocken bucket has been appropriately updated. +func (t *TestTicker) tick(delta time.Duration) { + t.timestamp = t.timestamp.Add(delta) + + t.C <- t.timestamp <-t.syncChan } From 8c3da8ca2606d177af06f8fcc97ab94bb3e282da Mon Sep 17 00:00:00 2001 From: Julio Guerra Date: Fri, 1 Mar 2024 10:00:35 +0100 Subject: [PATCH 10/39] appsec/config: 1 ms default WAF timeout (#23) --- appsec/config.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appsec/config.go b/appsec/config.go index 8abff4d..d672370 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -42,8 +42,8 @@ const ( DefaultObfuscatorKeyRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:_?phrase)?|secret|(?:api_?|private_?|public_?)key)|token|consumer_?(?:id|key|secret)|sign(?:ed|ature)|bearer|authorization` // DefaultObfuscatorValueRegex is the default regexp used to obfuscate values DefaultObfuscatorValueRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:_?phrase)?|secret|(?:api_?|private_?|public_?|access_?|secret_?)key(?:_?id)?|token|consumer_?(?:id|key|secret)|sign(?:ed|ature)?|auth(?:entication|orization)?)(?:\s*=[^;]|"\s*:\s*"[^"]+")|bearer\s+[a-z0-9\._\-]+|token:[a-z0-9]{13}|gh[opsu]_[0-9a-zA-Z]{36}|ey[I-L][\w=-]+\.ey[I-L][\w=-]+(?:\.[\w.+\/=-]+)?|[\-]{5}BEGIN[a-z\s]+PRIVATE\sKEY[\-]{5}[^\-]+[\-]{5}END[a-z\s]+PRIVATE\sKEY|ssh-rsa\s*[a-z0-9\/\.+]{100,}` - // DefaultWAFTimeout is the default time limit (ms) past which a WAF run will timeout - DefaultWAFTimeout = 4 * time.Millisecond + // DefaultWAFTimeout is the default time limit past which a WAF run will timeout + DefaultWAFTimeout = time.Millisecond // DefaultTraceRate is the default limit (trace/sec) past which ASM traces are sampled out DefaultTraceRate uint = 100 // up to 100 appsec traces/s ) From a0d07db7762555d22cf383f9716906ee23521032 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Mon, 4 Mar 2024 10:39:05 +0100 Subject: [PATCH 11/39] Update embedded AppSec Rules to 1.11.0 (#24) Co-authored-by: github-actions[bot] on behalf of RomainMuller --- appsec/embed.go | 4 +- appsec/rules.json | 94 +++++++++++++++++++++++++++++++++-------------- 2 files changed, 69 insertions(+), 29 deletions(-) diff --git a/appsec/embed.go b/appsec/embed.go index 8d4d83d..9617fb3 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.10.0) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.10.0/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.11.0) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.11.0/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string diff --git a/appsec/rules.json b/appsec/rules.json index d572c00..7912743 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.10.0" + "rules_version": "1.11.0" }, "rules": [ { @@ -141,7 +141,10 @@ "appscan_fingerprint", "w00tw00t.at.isc.sans.dfind", "w00tw00t.at.blackhats.romanian.anti-sec" - ] + ], + "options": { + "enforce_word_boundary": true + } }, "operator": "phrase_match" } @@ -1778,7 +1781,10 @@ "windows\\win.ini", "default\\ntuser.dat", "/var/run/secrets/kubernetes.io/serviceaccount" - ] + ], + "options": { + "enforce_word_boundary": true + } }, "operator": "phrase_match" } @@ -1895,6 +1901,9 @@ "address": "graphql.server.resolver" } ], + "options": { + "enforce_word_boundary": true + }, "list": [ "${cdpath}", "${dirstack}", @@ -2471,7 +2480,10 @@ "settings.local.php", "local.xml", ".env" - ] + ], + "options": { + "enforce_word_boundary": true + } }, "operator": "phrase_match" } @@ -2567,6 +2579,9 @@ "address": "graphql.server.resolver" } ], + "options": { + "enforce_word_boundary": true + }, "list": [ "$globals", "$_cookie", @@ -2765,7 +2780,10 @@ "wp_safe_remote_post", "wp_safe_remote_request", "zlib_decode" - ] + ], + "options": { + "enforce_word_boundary": true + } }, "operator": "phrase_match" } @@ -2980,9 +2998,6 @@ { "address": "server.request.path_params" }, - { - "address": "grpc.server.request.message" - }, { "address": "graphql.server.all_resolvers" }, @@ -3037,9 +3052,6 @@ { "address": "server.request.path_params" }, - { - "address": "grpc.server.request.message" - }, { "address": "graphql.server.all_resolvers" }, @@ -3271,6 +3283,9 @@ "address": "graphql.server.resolver" } ], + "options": { + "enforce_word_boundary": true + }, "list": [ "document.cookie", "document.write", @@ -3546,9 +3561,6 @@ { "address": "server.request.path_params" }, - { - "address": "grpc.server.request.message" - }, { "address": "graphql.server.all_resolvers" }, @@ -3863,9 +3875,6 @@ { "address": "server.request.path_params" }, - { - "address": "grpc.server.request.message" - }, { "address": "graphql.server.all_resolvers" }, @@ -4454,7 +4463,10 @@ "org.apache.struts2", "org.omg.corba", "java.beans.xmldecode" - ] + ], + "options": { + "enforce_word_boundary": true + } }, "operator": "phrase_match" } @@ -4581,9 +4593,6 @@ { "address": "server.request.path_params" }, - { - "address": "grpc.server.request.message" - }, { "address": "graphql.server.all_resolvers" }, @@ -5342,6 +5351,40 @@ ], "transformers": [] }, + { + "id": "dog-920-001", + "name": "JWT authentication bypass", + "tags": { + "type": "http_protocol_violation", + "category": "attack_attempt", + "cwe": "287", + "capec": "1000/225/115", + "confidence": "0" + }, + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.cookies" + }, + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "authorization" + ] + } + ], + "regex": "^(?:Bearer )?ey[A-Za-z0-9+_\\-/]*([QY][UW]x[Hn]Ij([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gOiAi[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]Ij([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]IDogI[km]5[Pv][Tb][km][U-X]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]IiA6ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]IDoi[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]Ij([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gOiAi[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciOiAi[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*IDogI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]IDogI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yIgO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciIDoi[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*IDogI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yIgOiJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]IDoi[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]IDogI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yI6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yI6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]IiA6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*IDogI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yIgO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]Ij([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciOiJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*IDoi[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gOiJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yIgOiAi[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]IDoi[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]IjogI[km]5[Pv][Tb][km][U-X]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]IiA6I[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6I[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yI6I[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yI6ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciIDogI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[QY][UW]x[Hn]IiA6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]IiA6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*IDoi[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ciO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6I[km]5[Pv][Tb][km][U-X]|[QY][UW]x[Hn]IiA6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yI6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yIgO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gOiJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ID([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gI[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yIgO([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[\\x2b\\x2f-9A-Za-z]ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*ICJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]I([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*IDoi[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]A6I[km]5[Pv][Tb][km][U-X]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]y([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gOiJ[Ou][Tb][02]5[Fl]|[QY][UW]x[Hn]Ijoi[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z]{2}[159BFJNRVZdhlptx][Bh][Tb][EG]ci([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[048AEIMQUYcgkosw]gOiAi[Tb][km]9[Ou][RZ][Q-Za-f]|[\\x2b\\x2f-9A-Za-z][02EGUWkm]F[Ms][RZ]yI6([048ACEIMQSUYcgikoswy]|[\\x2b\\x2f-9A-Za-z]I)*[CSiy]Ai[Tb][km]9[Ou][RZ][Q-Za-f])[A-Za-z0-9+-/]*\\.[A-Za-z0-9+_\\-/]+\\.(?:[A-Za-z0-9+_\\-/]+)?$", + "options": { + "case_sensitive": true + } + }, + "operator": "match_regex" + } + ], + "transformers": [] + }, { "id": "dog-931-001", "name": "RFI: URL Payload to well known RFI target", @@ -5603,6 +5646,9 @@ { "operator": "phrase_match", "parameters": { + "options": { + "enforce_word_boundary": true + }, "inputs": [ { "address": "server.request.uri.raw" @@ -6606,9 +6652,6 @@ { "address": "server.request.headers.no_cookies" }, - { - "address": "grpc.server.request.message" - }, { "address": "graphql.server.all_resolvers" }, @@ -6654,9 +6697,6 @@ { "address": "server.request.headers.no_cookies" }, - { - "address": "grpc.server.request.message" - }, { "address": "graphql.server.all_resolvers" }, From 601f3d1c4d1c078fa763d18590480bb19d78a1aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Mazeau?= Date: Thu, 21 Mar 2024 10:58:24 +0100 Subject: [PATCH 12/39] chore: add CODEOWNER file (#25) --- CODEOWNERS | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 CODEOWNERS diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..2e4d479 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,2 @@ +# default owner +* @DataDog/asm-go From 68bbdedaff3fca251ac577300c32cb09c7f273b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Mazeau?= Date: Tue, 28 May 2024 13:27:17 +0200 Subject: [PATCH 13/39] feat: add RASP enablement to config (#26) --- appsec/config.go | 37 ++++++++++++++++++++++--------------- appsec/config_test.go | 19 +++++++++++++++++++ 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/appsec/config.go b/appsec/config.go index d672370..74a4739 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -32,6 +32,8 @@ const ( EnvTraceRateLimit = "DD_APPSEC_TRACE_RATE_LIMIT" // EnvRules is the env var used to provide a path to a local security rule file EnvRules = "DD_APPSEC_RULES" + // EnvRASPEnabled is the env var used to enable/disable RASP functionalities for ASM + EnvRASPEnabled = "DD_APPSEC_RASP_ENABLED" ) // Configuration constants and default values @@ -65,24 +67,10 @@ type ObfuscatorConfig struct { // NewAPISecConfig creates and returns a new API Security configuration by reading the env func NewAPISecConfig() APISecConfig { return APISecConfig{ - Enabled: apiSecurityEnabled(), + Enabled: boolEnv(EnvAPISecEnabled, true), SampleRate: readAPISecuritySampleRate(), } } - -func apiSecurityEnabled() bool { - enabled := true - str, set := os.LookupEnv(EnvAPISecEnabled) - if set { - var err error - enabled, err = strconv.ParseBool(str) - if err != nil { - logEnvVarParsingError(EnvAPISecEnabled, str, err, enabled) - } - } - return enabled -} - func readAPISecuritySampleRate() float64 { value := os.Getenv(EnvAPISecSampleRate) rate, err := strconv.ParseFloat(value, 64) @@ -99,6 +87,12 @@ func readAPISecuritySampleRate() float64 { return rate } +// RASPEnabled returns true if RASP functionalities are enabled through the env, or if DD_APPSEC_RASP_ENABLED +// is not set +func RASPEnabled() bool { + return boolEnv(EnvRASPEnabled, true) +} + // NewObfuscatorConfig creates and returns a new WAF obfuscator configuration by reading the env func NewObfuscatorConfig() ObfuscatorConfig { keyRE := readObfuscatorConfigRegexp(EnvObfuscatorKey, DefaultObfuscatorKeyRegex) @@ -194,3 +188,16 @@ func logEnvVarParsingError(name, value string, err error, defaultValue any) { func logUnexpectedEnvVarValue(name string, value any, reason string, defaultValue any) { log.Debug("appsec: unexpected configuration value of %s=%v: %s. Using default value %v.", name, value, reason, defaultValue) } + +func boolEnv(key string, def bool) bool { + strVal, ok := os.LookupEnv(key) + if !ok { + return def + } + v, err := strconv.ParseBool(strVal) + if err != nil { + logEnvVarParsingError(key, strVal, err, def) + return def + } + return v +} diff --git a/appsec/config_test.go b/appsec/config_test.go index 3f93c7b..c3c56c0 100644 --- a/appsec/config_test.go +++ b/appsec/config_test.go @@ -246,3 +246,22 @@ func TestRules(t *testing.T) { require.Equal(t, StaticRecommendedRules, string(rules)) }) } + +func TestRASPEnablement(t *testing.T) { + t.Run("enabled", func(t *testing.T) { + t.Setenv(EnvRASPEnabled, "true") + require.True(t, RASPEnabled()) + }) + + t.Run("disabled", func(t *testing.T) { + t.Setenv(EnvRASPEnabled, "false") + require.False(t, RASPEnabled()) + }) + + t.Run("unset", func(t *testing.T) { + // t.Setenv first to restore the original value at the end of the test + t.Setenv(EnvRASPEnabled, "") + os.Unsetenv(EnvRASPEnabled) + require.True(t, RASPEnabled()) + }) +} From 1cf8118ca785aebe493e168e1b76881921d335a9 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Wed, 19 Jun 2024 09:03:34 +0200 Subject: [PATCH 14/39] Update embedded AppSec Rules to 1.12.0 (#27) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Automatically created by [GitHub Actions](https://github.com/DataDog/appsec-internal-go/actions/runs/9542753491). --------- Co-authored-by: github-actions[bot] on behalf of RomainMuller Co-authored-by: François Mazeau --- appsec/config_test.go | 11 ++- appsec/embed.go | 4 +- appsec/rules.json | 211 +++++++++++++++++++++++++++++++++++++++++- 3 files changed, 216 insertions(+), 10 deletions(-) diff --git a/appsec/config_test.go b/appsec/config_test.go index c3c56c0..660508e 100644 --- a/appsec/config_test.go +++ b/appsec/config_test.go @@ -31,11 +31,6 @@ func TestAPISecConfig(t *testing.T) { enabledVar: "0", sampleRate: DefaultAPISecSampleRate, }, - { - name: "disabled", - enabledVar: "weirdvalue", - sampleRate: DefaultAPISecSampleRate, - }, { name: "enabled", enabled: true, @@ -53,6 +48,12 @@ func TestAPISecConfig(t *testing.T) { enabled: true, sampleRate: DefaultAPISecSampleRate, }, + { + name: "enabled", + enabledVar: "weirdvalue", + enabled: true, + sampleRate: DefaultAPISecSampleRate, + }, { name: "sampleRate 1.0", sampleRateVar: "1.0", diff --git a/appsec/embed.go b/appsec/embed.go index 9617fb3..e7cf7c7 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.11.0) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.11.0/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.12.0) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.12.0/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string diff --git a/appsec/rules.json b/appsec/rules.json index 7912743..0b25be9 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.11.0" + "rules_version": "1.12.0" }, "rules": [ { @@ -1921,7 +1921,6 @@ "$ifs", "$oldpwd", "$ostype", - "$path", "$pwd", "dev/fd/", "dev/null", @@ -5849,7 +5848,8 @@ "/website.php", "/stats.php", "/assets/plugins/mp3_id/mp3_id.php", - "/siteminderagent/forms/smpwservices.fcc" + "/siteminderagent/forms/smpwservices.fcc", + "/eval-stdin.php" ] } } @@ -6236,6 +6236,155 @@ ], "transformers": [] }, + { + "id": "rasp-930-100", + "name": "Local file inclusion exploit", + "enabled": false, + "tags": { + "type": "lfi", + "category": "vulnerability_trigger", + "cwe": "22", + "capec": "1000/255/153/126", + "confidence": "0", + "module": "rasp" + }, + "conditions": [ + { + "parameters": { + "resource": [ + { + "address": "server.io.fs.file" + } + ], + "params": [ + { + "address": "server.request.query" + }, + { + "address": "server.request.body" + }, + { + "address": "server.request.path_params" + }, + { + "address": "grpc.server.request.message" + }, + { + "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" + } + ] + }, + "operator": "lfi_detector" + } + ], + "transformers": [], + "on_match": [ + "stack_trace" + ] + }, + { + "id": "rasp-934-100", + "name": "Server-side request forgery exploit", + "enabled": false, + "tags": { + "type": "ssrf", + "category": "vulnerability_trigger", + "cwe": "918", + "capec": "1000/225/115/664", + "confidence": "0", + "module": "rasp" + }, + "conditions": [ + { + "parameters": { + "resource": [ + { + "address": "server.io.net.url" + } + ], + "params": [ + { + "address": "server.request.query" + }, + { + "address": "server.request.body" + }, + { + "address": "server.request.path_params" + }, + { + "address": "grpc.server.request.message" + }, + { + "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" + } + ] + }, + "operator": "ssrf_detector" + } + ], + "transformers": [], + "on_match": [ + "stack_trace" + ] + }, + { + "id": "rasp-942-100", + "name": "SQL injection exploit", + "enabled": false, + "tags": { + "type": "sql_injection", + "category": "vulnerability_trigger", + "cwe": "89", + "capec": "1000/152/248/66", + "confidence": "0", + "module": "rasp" + }, + "conditions": [ + { + "parameters": { + "resource": [ + { + "address": "server.db.statement" + } + ], + "params": [ + { + "address": "server.request.query" + }, + { + "address": "server.request.body" + }, + { + "address": "server.request.path_params" + }, + { + "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" + } + ], + "db_type": [ + { + "address": "server.db.system" + } + ] + }, + "operator": "sqli_detector" + } + ], + "transformers": [], + "on_match": [ + "stack_trace" + ] + }, { "id": "sqr-000-001", "name": "SSRF: Try to access the credential manager of the main cloud services", @@ -8391,6 +8540,34 @@ } ], "scanners": [ + { + "id": "406f8606-52c4-4663-8db9-df70f9e8766c", + "name": "ZIP Code", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\b(?:zip|postal)\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "^[0-9]{5}(?:-[0-9]{4})?$", + "options": { + "case_sensitive": true, + "min_length": 5 + } + } + }, + "tags": { + "type": "zipcode", + "category": "address" + } + }, { "id": "JU1sRk3mSzqSUJn6GrVn7g", "name": "American Express Card Scanner (4+4+4+3 digits)", @@ -9157,6 +9334,34 @@ "category": "payment" } }, + { + "id": "18b608bd7a764bff5b2344c0", + "name": "Phone number", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\bphone|number|mobile\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "value": { + "operator": "match_regex", + "parameters": { + "regex": "^(?:\\(\\+\\d{1,3}\\)|\\+\\d{1,3}|00\\d{1,3})?[-\\s\\.]?(?:\\(\\d{3}\\)[-\\s\\.]?)?(?:\\d[-\\s\\.]?){6,10}$", + "options": { + "case_sensitive": false, + "min_length": 6 + } + } + }, + "tags": { + "type": "phone", + "category": "pii" + } + }, { "id": "de0899e0cbaaa812bb624cf04c912071012f616d-mod", "name": "UK National Insurance Number Scanner", From 1439246c18bb29d33d2f6c9ccbb8672bd18354d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Mazeau?= Date: Thu, 20 Jun 2024 16:13:50 +0200 Subject: [PATCH 15/39] refactor: remove external rules processors (#29) We used to add rules processors manually because they were not part of the default ruleset. Now that they are, this step is not needed and we get rid of this extra step. Draft for now, this needs to be tested against dd-trace-go --- _tools/rules-updater/writer/template.txt | 6 - appsec/embed.go | 6 - appsec/processors.json | 208 ----------------------- appsec/rules.go | 7 - 4 files changed, 227 deletions(-) delete mode 100644 appsec/processors.json diff --git a/_tools/rules-updater/writer/template.txt b/_tools/rules-updater/writer/template.txt index c0a02f5..173a04e 100644 --- a/_tools/rules-updater/writer/template.txt +++ b/_tools/rules-updater/writer/template.txt @@ -12,9 +12,3 @@ import _ "embed" // Blank import comment for golint compliance // //go:embed rules.json var StaticRecommendedRules string - -// StaticProcessors holds the default processors and scanners used for API Security -// Not part of the recommended security rules -// -//go:embed processors.json -var StaticProcessors string diff --git a/appsec/embed.go b/appsec/embed.go index e7cf7c7..cfa0a5d 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -12,9 +12,3 @@ import _ "embed" // Blank import comment for golint compliance // //go:embed rules.json var StaticRecommendedRules string - -// StaticProcessors holds the default processors and scanners used for API Security -// Not part of the recommended security rules -// -//go:embed processors.json -var StaticProcessors string diff --git a/appsec/processors.json b/appsec/processors.json deleted file mode 100644 index 968c53d..0000000 --- a/appsec/processors.json +++ /dev/null @@ -1,208 +0,0 @@ -{ - "processors": [ - { - "id": "processor-001", - "generator": "extract_schema", - "conditions": [ - { - "operator": "equals", - "parameters": { - "inputs": [ - { - "address": "waf.context.processor", - "key_path": [ - "extract-schema" - ] - } - ], - "type": "boolean", - "value": true - } - } - ], - "parameters": { - "mappings": [ - { - "inputs": [ - { - "address": "server.request.body" - } - ], - "output": "_dd.appsec.s.req.body" - }, - { - "inputs": [ - { - "address": "server.request.headers.no_cookies" - } - ], - "output": "_dd.appsec.s.req.headers" - }, - { - "inputs": [ - { - "address": "server.request.query" - } - ], - "output": "_dd.appsec.s.req.query" - }, - { - "inputs": [ - { - "address": "server.request.path_params" - } - ], - "output": "_dd.appsec.s.req.params" - }, - { - "inputs": [ - { - "address": "server.request.cookies" - } - ], - "output": "_dd.appsec.s.req.cookies" - }, - { - "inputs": [ - { - "address": "server.response.headers.no_cookies" - } - ], - "output": "_dd.appsec.s.res.headers" - }, - { - "inputs": [ - { - "address": "server.response.body" - } - ], - "output": "_dd.appsec.s.res.body" - } - ], - "scanners": [ - { - "tags": { - "category": "pii" - } - } - ] - }, - "evaluate": false, - "output": true - } - ], - "scanners": [ - { - "id": "d962f7ddb3f55041e39195a60ff79d4814a7c331", - "name": "US Passport Scanner", - "key": { - "operator": "match_regex", - "parameters": { - "regex": "passport", - "options": { - "case_sensitive": false, - "min_length": 8 - } - } - }, - "value": { - "operator": "match_regex", - "parameters": { - "regex": "\\b[0-9A-Z]{9}\\b|\\b[0-9]{6}[A-Z][0-9]{2}\\b", - "options": { - "case_sensitive": false, - "min_length": 8 - } - } - }, - "tags": { - "type": "passport_number", - "category": "pii" - } - }, - { - "id": "ac6d683cbac77f6e399a14990793dd8fd0fca333", - "name": "US Vehicle Identification Number Scanner", - "key": { - "operator": "match_regex", - "parameters": { - "regex": "vehicle[_\\s-]*identification[_\\s-]*number|vin", - "options": { - "case_sensitive": false, - "min_length": 3 - } - } - }, - "value": { - "operator": "match_regex", - "parameters": { - "regex": "\\b[A-HJ-NPR-Z0-9]{17}\\b", - "options": { - "case_sensitive": false, - "min_length": 17 - } - } - }, - "tags": { - "type": "vin", - "category": "pii" - } - }, - { - "id": "de0899e0cbaaa812bb624cf04c912071012f616d", - "name": "UK National Insurance Number Scanner", - "key": { - "operator": "match_regex", - "parameters": { - "regex": "national[\\s_]?(?:insurance(?:\\s+number)?)?|NIN|NI[\\s_]?number|insurance[\\s_]?number", - "options": { - "case_sensitive": false, - "min_length": 3 - } - } - }, - "value": { - "operator": "match_regex", - "parameters": { - "regex": "\\b[A-Z]{2}\\d{6}[A-Z]?\\b", - "options": { - "case_sensitive": false, - "min_length": 8 - } - } - }, - "tags": { - "type": "uk_nin", - "category": "pii" - } - }, - { - "id": "450239afc250a19799b6c03dc0e16fd6a4b2a1af", - "name": "Canadian Social Insurance Number Scanner", - "key": { - "operator": "match_regex", - "parameters": { - "regex": "social[\\s_]?(?:insurance(?:\\s+number)?)?|SIN|Canadian[\\s_]?(?:social[\\s_]?(?:insurance)?|insurance[\\s_]?number)?", - "options": { - "case_sensitive": false, - "min_length": 3 - } - } - }, - "value": { - "operator": "match_regex", - "parameters": { - "regex": "\\b\\d{3}-\\d{3}-\\d{3}\\b", - "options": { - "case_sensitive": false, - "min_length": 11 - } - } - }, - "tags": { - "type": "canadian_sin", - "category": "pii" - } - } - ] -} \ No newline at end of file diff --git a/appsec/rules.go b/appsec/rules.go index d2d672a..29a46bf 100644 --- a/appsec/rules.go +++ b/appsec/rules.go @@ -18,16 +18,9 @@ func DefaultRuleset() ([]byte, error) { // DefaultRulesetMap returns the unmarshaled default recommended security rules for AppSec func DefaultRulesetMap() (map[string]any, error) { var rules map[string]any - var processors map[string]any if err := json.Unmarshal([]byte(StaticRecommendedRules), &rules); err != nil { return nil, err } - if err := json.Unmarshal([]byte(StaticProcessors), &processors); err != nil { - return nil, err - } - for k, v := range processors { - rules[k] = v - } return rules, nil } From d26bbec527fa7f1e1028c7f385eb6af9b663cfdb Mon Sep 17 00:00:00 2001 From: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> Date: Thu, 20 Jun 2024 16:14:19 +0200 Subject: [PATCH 16/39] ci: rollout macos-11 in favor of macos-14 (#30) GitHub is deprecating macos-11 runners so we need to swap them out Signed-off-by: Eliott Bouhana --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5765215..ec5035c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -17,7 +17,7 @@ jobs: name: Native ${{ matrix.runs-on }} (Go ${{ matrix.go-version }}, CGO_ENABLED=${{ matrix.cgo_enabled }}) strategy: matrix: - runs-on: [ macos-13, macos-12, macos-11, ubuntu-22.04, ubuntu-20.04, windows-latest ] + runs-on: [ macos-14, macos-13, macos-12, ubuntu-22.04, ubuntu-20.04, windows-latest ] go-version: [ "1.21", "1.20", "1.19" ] cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo fail-fast: false From c629936193d6f9e9f89269a5c742b47a43fc184d Mon Sep 17 00:00:00 2001 From: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> Date: Wed, 10 Jul 2024 17:37:25 +0200 Subject: [PATCH 17/39] chore: deprecate go 1.20 & upgrade obfuscation regexps (#31) - [x] Upgrade the go.mod and run `go mod tidy` - [x] Remove go 1.20 from the CI - [x] Replace Obfuscation Key & Value Regexprs withe better ones Signed-off-by: Eliott Bouhana --- .github/workflows/test.yml | 9 +++------ appsec/config.go | 4 ++-- go.mod | 2 +- go.sum | 2 ++ 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ec5035c..7c9b8fc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,7 @@ jobs: strategy: matrix: runs-on: [ macos-14, macos-13, macos-12, ubuntu-22.04, ubuntu-20.04, windows-latest ] - go-version: [ "1.21", "1.20", "1.19" ] + go-version: [ "1.22", "1.21" ] cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo fail-fast: false runs-on: ${{ matrix.runs-on }} @@ -52,12 +52,9 @@ jobs: image: golang:${{ matrix.go-version }}-${{ matrix.distribution }} strategy: matrix: - go-version: [ "1.21", "1.20", "1.19" ] - distribution: [ bookworm, bullseye, buster, alpine ] + go-version: [ "1.22", "1.21" ] + distribution: [ bookworm, bullseye, alpine ] cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo - exclude: - - go-version: 1.21 - distribution: buster fail-fast: false steps: - uses: actions/checkout@v3 diff --git a/appsec/config.go b/appsec/config.go index 74a4739..3cfed5b 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -41,9 +41,9 @@ const ( // DefaultAPISecSampleRate is the default rate at which API Security schemas are extracted from requests DefaultAPISecSampleRate = .1 // DefaultObfuscatorKeyRegex is the default regexp used to obfuscate keys - DefaultObfuscatorKeyRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:_?phrase)?|secret|(?:api_?|private_?|public_?)key)|token|consumer_?(?:id|key|secret)|sign(?:ed|ature)|bearer|authorization` + DefaultObfuscatorKeyRegex = `(?i)pass|pw(?:or)?d|secret|(?:api|private|public|access)[_-]?key|token|consumer[_-]?(?:id|key|secret)|sign(?:ed|ature)|bearer|authorization|jsessionid|phpsessid|asp\.net[_-]sessionid|sid|jwt` // DefaultObfuscatorValueRegex is the default regexp used to obfuscate values - DefaultObfuscatorValueRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:_?phrase)?|secret|(?:api_?|private_?|public_?|access_?|secret_?)key(?:_?id)?|token|consumer_?(?:id|key|secret)|sign(?:ed|ature)?|auth(?:entication|orization)?)(?:\s*=[^;]|"\s*:\s*"[^"]+")|bearer\s+[a-z0-9\._\-]+|token:[a-z0-9]{13}|gh[opsu]_[0-9a-zA-Z]{36}|ey[I-L][\w=-]+\.ey[I-L][\w=-]+(?:\.[\w.+\/=-]+)?|[\-]{5}BEGIN[a-z\s]+PRIVATE\sKEY[\-]{5}[^\-]+[\-]{5}END[a-z\s]+PRIVATE\sKEY|ssh-rsa\s*[a-z0-9\/\.+]{100,}` + DefaultObfuscatorValueRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:[_-]?phrase)?|secret(?:[_-]?key)?|(?:(?:api|private|public|access)[_-]?)key(?:[_-]?id)?|(?:(?:auth|access|id|refresh)[_-]?)?token|consumer[_-]?(?:id|key|secret)|sign(?:ed|ature)?|auth(?:entication|orization)?|jsessionid|phpsessid|asp\.net(?:[_-]|-)sessionid|sid|jwt)(?:\s*=[^;]|"\s*:\s*"[^"]+")|bearer\s+[a-z0-9\._\-]+|token:[a-z0-9]{13}|gh[opsu]_[0-9a-zA-Z]{36}|ey[I-L][\w=-]+\.ey[I-L][\w=-]+(?:\.[\w.+\/=-]+)?|[\-]{5}BEGIN[a-z\s]+PRIVATE\sKEY[\-]{5}[^\-]+[\-]{5}END[a-z\s]+PRIVATE\sKEY|ssh-rsa\s*[a-z0-9\/\.+]{100,}` // DefaultWAFTimeout is the default time limit past which a WAF run will timeout DefaultWAFTimeout = time.Millisecond // DefaultTraceRate is the default limit (trace/sec) past which ASM traces are sampled out diff --git a/go.mod b/go.mod index 971552b..6e9e17c 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/DataDog/appsec-internal-go -go 1.19 +go 1.21 require ( github.com/stretchr/testify v1.8.4 diff --git a/go.sum b/go.sum index 5f88626..b641b0c 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,7 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -12,5 +13,6 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From 405608c9ec4c5eda6f8d4380ec90e647d4d499f3 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Mon, 29 Jul 2024 11:45:43 +0200 Subject: [PATCH 18/39] Update embedded AppSec Rules to 1.13.0 (#32) Automatically created by [GitHub Actions](https://github.com/DataDog/appsec-internal-go/actions/runs/10138997675). Co-authored-by: github-actions[bot] on behalf of RomainMuller --- appsec/embed.go | 4 +- appsec/rules.json | 220 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 221 insertions(+), 3 deletions(-) diff --git a/appsec/embed.go b/appsec/embed.go index cfa0a5d..9c28884 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.12.0) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.12.0/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.13.0) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.13.0/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string diff --git a/appsec/rules.json b/appsec/rules.json index 0b25be9..f181703 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.12.0" + "rules_version": "1.13.0" }, "rules": [ { @@ -6285,6 +6285,55 @@ "stack_trace" ] }, + { + "id": "rasp-932-100", + "name": "Shell injection exploit", + "enabled": false, + "tags": { + "type": "command_injection", + "category": "vulnerability_trigger", + "cwe": "77", + "capec": "1000/152/248/88", + "confidence": "0", + "module": "rasp" + }, + "conditions": [ + { + "parameters": { + "resource": [ + { + "address": "server.sys.shell.cmd" + } + ], + "params": [ + { + "address": "server.request.query" + }, + { + "address": "server.request.body" + }, + { + "address": "server.request.path_params" + }, + { + "address": "grpc.server.request.message" + }, + { + "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" + } + ] + }, + "operator": "shi_detector" + } + ], + "transformers": [], + "on_match": [ + "stack_trace" + ] + }, { "id": "rasp-934-100", "name": "Server-side request forgery exploit", @@ -8388,6 +8437,57 @@ } ], "processors": [ + { + "id": "http-endpoint-fingerprint", + "generator": "http_endpoint_fingerprint", + "conditions": [ + { + "operator": "exists", + "parameters": { + "inputs": [ + { + "address": "waf.context.event" + }, + { + "address": "server.business_logic.users.login.failure" + }, + { + "address": "server.business_logic.users.login.success" + } + ] + } + } + ], + "parameters": { + "mappings": [ + { + "method": [ + { + "address": "server.request.method" + } + ], + "uri_raw": [ + { + "address": "server.request.uri.raw" + } + ], + "body": [ + { + "address": "server.request.body" + } + ], + "query": [ + { + "address": "server.request.query" + } + ], + "output": "_dd.appsec.fp.http.endpoint" + } + ] + }, + "evaluate": false, + "output": true + }, { "id": "extract-content", "generator": "extract_schema", @@ -8537,6 +8637,124 @@ }, "evaluate": false, "output": true + }, + { + "id": "http-header-fingerprint", + "generator": "http_header_fingerprint", + "conditions": [ + { + "operator": "exists", + "parameters": { + "inputs": [ + { + "address": "waf.context.event" + }, + { + "address": "server.business_logic.users.login.failure" + }, + { + "address": "server.business_logic.users.login.success" + } + ] + } + } + ], + "parameters": { + "mappings": [ + { + "headers": [ + { + "address": "server.request.headers.no_cookies" + } + ], + "output": "_dd.appsec.fp.http.header" + } + ] + }, + "evaluate": false, + "output": true + }, + { + "id": "http-network-fingerprint", + "generator": "http_network_fingerprint", + "conditions": [ + { + "operator": "exists", + "parameters": { + "inputs": [ + { + "address": "waf.context.event" + }, + { + "address": "server.business_logic.users.login.failure" + }, + { + "address": "server.business_logic.users.login.success" + } + ] + } + } + ], + "parameters": { + "mappings": [ + { + "headers": [ + { + "address": "server.request.headers.no_cookies" + } + ], + "output": "_dd.appsec.fp.http.network" + } + ] + }, + "evaluate": false, + "output": true + }, + { + "id": "session-fingerprint", + "generator": "session_fingerprint", + "conditions": [ + { + "operator": "exists", + "parameters": { + "inputs": [ + { + "address": "waf.context.event" + }, + { + "address": "server.business_logic.users.login.failure" + }, + { + "address": "server.business_logic.users.login.success" + } + ] + } + } + ], + "parameters": { + "mappings": [ + { + "cookies": [ + { + "address": "server.request.cookies" + } + ], + "session_id": [ + { + "address": "usr.session_id" + } + ], + "user_id": [ + { + "address": "usr.id" + } + ], + "output": "_dd.appsec.fp.session" + } + ] + }, + "evaluate": false, + "output": true } ], "scanners": [ From d56489371866ef611464824c973e80116380dfbc Mon Sep 17 00:00:00 2001 From: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> Date: Mon, 30 Sep 2024 14:04:31 +0200 Subject: [PATCH 19/39] chore: upgrade ruleset 1.13.0 -> 1.13.1 (#33) Signed-off-by: Eliott Bouhana --- appsec/rules.json | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/appsec/rules.json b/appsec/rules.json index f181703..d05b1e6 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.13.0" + "rules_version": "1.13.1" }, "rules": [ { @@ -6239,7 +6239,6 @@ { "id": "rasp-930-100", "name": "Local file inclusion exploit", - "enabled": false, "tags": { "type": "lfi", "category": "vulnerability_trigger", @@ -6288,7 +6287,6 @@ { "id": "rasp-932-100", "name": "Shell injection exploit", - "enabled": false, "tags": { "type": "command_injection", "category": "vulnerability_trigger", @@ -6337,7 +6335,6 @@ { "id": "rasp-934-100", "name": "Server-side request forgery exploit", - "enabled": false, "tags": { "type": "ssrf", "category": "vulnerability_trigger", @@ -6386,7 +6383,6 @@ { "id": "rasp-942-100", "name": "SQL injection exploit", - "enabled": false, "tags": { "type": "sql_injection", "category": "vulnerability_trigger", @@ -9780,4 +9776,4 @@ } } ] -} \ No newline at end of file +} From 31eced2491e9adf3af53fb066af8eeb268f5c842 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Fri, 18 Oct 2024 12:14:51 +0200 Subject: [PATCH 20/39] feat: ruleset v1.13.1 (#34) Additionally, update `Dockerfile` to use the relatively new secrets feature to pass the `GITHUB_TOKEN`, in order to adhere to best practices. --- _tools/rules-updater/Dockerfile | 10 ++++++---- _tools/rules-updater/update.sh | 2 +- appsec/embed.go | 4 ++-- appsec/rules.json | 6 ++++-- 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/_tools/rules-updater/Dockerfile b/_tools/rules-updater/Dockerfile index 43f7e14..53b4760 100644 --- a/_tools/rules-updater/Dockerfile +++ b/_tools/rules-updater/Dockerfile @@ -1,13 +1,14 @@ -FROM golang:1.21 as go-format +# syntax=docker/dockerfile:1 +FROM golang:1.21 AS go-format RUN apt update && apt install -y jq curl COPY writer/ /home/ WORKDIR /home/ ARG version -ARG GITHUB_TOKEN -RUN if [ "${version}" = "latest" ]; then \ +RUN --mount=type=secret,id=GITHUB_TOKEN,env=GITHUB_TOKEN \ + if [ "${version}" = "latest" ]; then \ curl \ --header "Authorization: Bearer ${GITHUB_TOKEN}" \ --header "X-Github-Api-Version: 2022-11-28" \ @@ -17,7 +18,8 @@ RUN if [ "${version}" = "latest" ]; then \ echo "${version}" > .version; \ fi -RUN curl \ +RUN --mount=type=secret,id=GITHUB_TOKEN,env=GITHUB_TOKEN \ + curl \ --header "Authorization: Bearer ${GITHUB_TOKEN}" \ --header "X-Github-Api-Version: 2022-11-28" \ -fSsL "https://raw.githubusercontent.com/DataDog/appsec-event-rules/$(cat .version)/build/recommended.json" \ diff --git a/_tools/rules-updater/update.sh b/_tools/rules-updater/update.sh index 34701b2..465c03d 100755 --- a/_tools/rules-updater/update.sh +++ b/_tools/rules-updater/update.sh @@ -32,7 +32,7 @@ destDir="$(readlink -f "$scriptDir/../../appsec/")" trap "rm -r $tmpDir" EXIT -DOCKER_BUILDKIT=1 docker build -o type=local,dest="$tmpDir" --build-arg version="$1" --build-arg GITHUB_TOKEN="${GITHUB_TOKEN}" --no-cache "$scriptDir" +DOCKER_BUILDKIT=1 docker build -o type=local,dest="$tmpDir" --build-arg version="$1" --secret "id=GITHUB_TOKEN,env=GITHUB_TOKEN" --no-cache "$scriptDir" echo "================ Done ================" cp -v $tmpDir/embed.go $tmpDir/rules.json "$destDir" echo "Output written to $destDir" diff --git a/appsec/embed.go b/appsec/embed.go index 9c28884..e8e17b9 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.13.0) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.13.0/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.13.1) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.13.1/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string diff --git a/appsec/rules.json b/appsec/rules.json index d05b1e6..a2a52ac 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -6286,7 +6286,7 @@ }, { "id": "rasp-932-100", - "name": "Shell injection exploit", + "name": "Command injection exploit", "tags": { "type": "command_injection", "category": "vulnerability_trigger", @@ -6335,6 +6335,7 @@ { "id": "rasp-934-100", "name": "Server-side request forgery exploit", + "enabled": false, "tags": { "type": "ssrf", "category": "vulnerability_trigger", @@ -6383,6 +6384,7 @@ { "id": "rasp-942-100", "name": "SQL injection exploit", + "enabled": false, "tags": { "type": "sql_injection", "category": "vulnerability_trigger", @@ -9776,4 +9778,4 @@ } } ] -} +} \ No newline at end of file From d58768f1f6421bd704f1872295d5b3e6c997c52f Mon Sep 17 00:00:00 2001 From: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> Date: Tue, 29 Oct 2024 13:09:56 +0100 Subject: [PATCH 21/39] chore: upgrade static rules 1.13.1 -> 1.13.2 (#36) Signed-off-by: Eliott Bouhana --- appsec/embed.go | 4 ++-- appsec/rules.json | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/appsec/embed.go b/appsec/embed.go index e8e17b9..2d6da7d 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.13.1) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.13.1/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.13.2) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.13.2/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string diff --git a/appsec/rules.json b/appsec/rules.json index a2a52ac..d0e486c 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.13.1" + "rules_version": "1.13.2" }, "rules": [ { @@ -6335,7 +6335,6 @@ { "id": "rasp-934-100", "name": "Server-side request forgery exploit", - "enabled": false, "tags": { "type": "ssrf", "category": "vulnerability_trigger", @@ -6384,7 +6383,6 @@ { "id": "rasp-942-100", "name": "SQL injection exploit", - "enabled": false, "tags": { "type": "sql_injection", "category": "vulnerability_trigger", @@ -6424,7 +6422,7 @@ } ] }, - "operator": "sqli_detector" + "operator": "sqli_detector@v2" } ], "transformers": [], From 2da4f26da82e5f5d914fee8413ba39231e32183f Mon Sep 17 00:00:00 2001 From: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> Date: Mon, 4 Nov 2024 09:57:32 +0100 Subject: [PATCH 22/39] chore: upgrade go versions and CI runners (#35) --- .github/workflows/test.yml | 28 +++------------------------- _tools/rules-updater/Dockerfile | 2 +- go.mod | 2 +- 3 files changed, 5 insertions(+), 27 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7c9b8fc..c002b4a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -17,8 +17,8 @@ jobs: name: Native ${{ matrix.runs-on }} (Go ${{ matrix.go-version }}, CGO_ENABLED=${{ matrix.cgo_enabled }}) strategy: matrix: - runs-on: [ macos-14, macos-13, macos-12, ubuntu-22.04, ubuntu-20.04, windows-latest ] - go-version: [ "1.22", "1.21" ] + runs-on: [ macos-15, macos-14, macos-13, ubuntu-22.04, ubuntu-20.04, windows-latest, arm-4core-linux ] + go-version: [ "1.23", "1.22" ] cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo fail-fast: false runs-on: ${{ matrix.runs-on }} @@ -52,7 +52,7 @@ jobs: image: golang:${{ matrix.go-version }}-${{ matrix.distribution }} strategy: matrix: - go-version: [ "1.22", "1.21" ] + go-version: [ "1.23", "1.22" ] distribution: [ bookworm, bullseye, alpine ] cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo fail-fast: false @@ -76,33 +76,11 @@ jobs: # Run the tests with gotestsum env CGO_ENABLED=${{ matrix.cgo_enabled }} ./gotestsum -- -v ./... || true - linux-arm64: - name: Linux ARM64 (CGO_ENABLED=${{ matrix.cgo_enabled }}) - runs-on: ubuntu-latest - strategy: - matrix: - cgo_enabled: [ "0", "1" ] # test it compiles with and without the cgo - fail-fast: false - steps: - - uses: actions/checkout@v3 - - name: Go modules cache - uses: actions/cache@v3 - with: - path: ~/go/pkg/mod - key: go-pkg-mod-${{ hashFiles('**/go.sum') }} - restore-keys: go-pkg-mod- - - name: Set up QEMU - uses: docker/setup-qemu-action@v2 - with: - platforms: arm64 - - run: docker run --platform=linux/arm64 -v $PWD:$PWD -w $PWD -eCGO_ENABLED=${{ matrix.cgo_enabled }} -eDD_APPSEC_WAF_TIMEOUT=$DD_APPSEC_WAF_TIMEOUT golang go test -v ./... - everything: name: All Tests needs: - native - golang-linux-container - - linux-arm64 runs-on: ubuntu-latest steps: - name: Completed diff --git a/_tools/rules-updater/Dockerfile b/_tools/rules-updater/Dockerfile index 53b4760..9655655 100644 --- a/_tools/rules-updater/Dockerfile +++ b/_tools/rules-updater/Dockerfile @@ -1,5 +1,5 @@ # syntax=docker/dockerfile:1 -FROM golang:1.21 AS go-format +FROM golang:latest AS go-format RUN apt update && apt install -y jq curl COPY writer/ /home/ diff --git a/go.mod b/go.mod index 6e9e17c..a6a8845 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/DataDog/appsec-internal-go -go 1.21 +go 1.22 require ( github.com/stretchr/testify v1.8.4 From afa49a73ed8fb15f7adb067116c1d8b79ffa5fb4 Mon Sep 17 00:00:00 2001 From: Benjamin De Bernardi Date: Tue, 4 Feb 2025 10:25:39 +0100 Subject: [PATCH 23/39] Update third party actions (#38) `upload-artifact` and `download-artifact` were outdated and causing [job failures](https://github.com/DataDog/appsec-internal-go/actions/runs/13115825664) - `checkout` `upload-artifact` and `download-artifact` to v4 - `setup-go` to v5 - all pinned to specific releases --- .github/workflows/test.yml | 14 ++++++-------- .github/workflows/update-rules.yml | 10 +++++----- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c002b4a..974c1ac 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,9 +1,7 @@ name: Test on: workflow_dispatch: # manually - schedule: # nightly - - cron: "0 0 * * *" - pull_request: {} + pull_request: # default behaviour opened, reopened, synchronize, edited, ready_for_review merge_group: branches: - main @@ -23,14 +21,14 @@ jobs: fail-fast: false runs-on: ${{ matrix.runs-on }} steps: - - uses: actions/checkout@v3 - - uses: actions/setup-go@v3 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - uses: actions/setup-go@f111f3307d8850f501ac008e886eec1fd1932a34 # v5.3.0 with: go-version: ${{ matrix.go-version }} cache: true - name: Go modules cache - uses: actions/cache@v3 + uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: ~/go/pkg/mod key: go-pkg-mod-${{ hashFiles('**/go.sum') }} @@ -57,13 +55,13 @@ jobs: cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo fail-fast: false steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 # Install gcc and the libc headers on alpine images - if: ${{ matrix.distribution == 'alpine' }} run: apk add gcc musl-dev libc6-compat git - name: Go modules cache - uses: actions/cache@v3 + uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: ~/go/pkg/mod key: go-pkg-mod-${{ hashFiles('**/go.sum') }} diff --git a/.github/workflows/update-rules.yml b/.github/workflows/update-rules.yml index 9ea3917..c24c442 100644 --- a/.github/workflows/update-rules.yml +++ b/.github/workflows/update-rules.yml @@ -10,8 +10,8 @@ jobs: outputs: mutation_happened: ${{ steps.detect.outputs.mutation_happened }} steps: - - uses: actions/checkout@v3 - - uses: actions/setup-go@v3 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - uses: actions/setup-go@f111f3307d8850f501ac008e886eec1fd1932a34 # v5.3.0 - name: Upgrade AppSec Rules run: ./_tools/rules-updater/update.sh latest env: @@ -23,7 +23,7 @@ jobs: git diff --staged --patch --exit-code > ${{ runner.temp }}/repo.patch || echo "mutation_happened=true" >> $GITHUB_OUTPUT - name: Upload Patch if: steps.detect.outputs.mutation_happened - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 with: name: repo.patch path: ${{ runner.temp }}/repo.patch @@ -35,9 +35,9 @@ jobs: contents: write if: needs.update.outputs.mutation_happened steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Download Patch - uses: actions/download-artifact@v3 + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 with: name: repo.patch path: ${{ runner.temp }} From c8b8550b38e65fa1f7bcebb1e8b7d609712177e7 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Tue, 4 Feb 2025 10:31:50 +0100 Subject: [PATCH 24/39] Update embedded AppSec Rules to 1.13.3 (#37) Automatically created by [GitHub Actions](https://github.com/DataDog/appsec-internal-go/actions/runs/13116094580). Co-authored-by: github-actions[bot] on behalf of genesor --- appsec/embed.go | 4 +- appsec/rules.json | 508 ++++++++++++++++++++++++++++++++-------------- 2 files changed, 355 insertions(+), 157 deletions(-) diff --git a/appsec/embed.go b/appsec/embed.go index 2d6da7d..97b129c 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.13.2) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.13.2/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.13.3) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.13.3/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string diff --git a/appsec/rules.json b/appsec/rules.json index d0e486c..2f53276 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.13.2" + "rules_version": "1.13.3" }, "rules": [ { @@ -9,7 +9,8 @@ "name": "Block IP Addresses", "tags": { "type": "block_ip", - "category": "security_response" + "category": "security_response", + "module": "network-acl" }, "conditions": [ { @@ -34,7 +35,8 @@ "name": "Block User Addresses", "tags": { "type": "block_user", - "category": "security_response" + "category": "security_response", + "module": "authentication-acl" }, "conditions": [ { @@ -64,7 +66,8 @@ "tool_name": "Acunetix", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -98,7 +101,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -162,7 +166,8 @@ "category": "attack_attempt", "cwe": "176", "capec": "1000/255/153/267/71", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -191,7 +196,8 @@ "crs_id": "921110", "category": "attack_attempt", "cwe": "444", - "capec": "1000/210/272/220/33" + "capec": "1000/210/272/220/33", + "module": "waf" }, "conditions": [ { @@ -228,7 +234,8 @@ "crs_id": "921160", "category": "attack_attempt", "cwe": "113", - "capec": "1000/210/272/220/105" + "capec": "1000/210/272/220/105", + "module": "waf" }, "conditions": [ { @@ -263,7 +270,8 @@ "category": "attack_attempt", "cwe": "22", "capec": "1000/255/153/126", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -297,7 +305,8 @@ "category": "attack_attempt", "cwe": "22", "capec": "1000/255/153/126", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -1803,7 +1812,8 @@ "category": "attack_attempt", "cwe": "98", "capec": "1000/152/175/253/193", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -1831,7 +1841,8 @@ "crs_id": "931120", "category": "attack_attempt", "cwe": "98", - "capec": "1000/152/175/253/193" + "capec": "1000/152/175/253/193", + "module": "waf" }, "conditions": [ { @@ -1876,7 +1887,8 @@ "category": "attack_attempt", "cwe": "77", "capec": "1000/152/248/88", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -2388,7 +2400,8 @@ "category": "attack_attempt", "cwe": "77", "capec": "1000/152/248/88", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -2436,7 +2449,8 @@ "category": "attack_attempt", "cwe": "706", "capec": "1000/225/122/17/177", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -2500,7 +2514,8 @@ "category": "attack_attempt", "cwe": "434", "capec": "1000/225/122/17/650", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -2553,7 +2568,8 @@ "category": "attack_attempt", "cwe": "94", "capec": "1000/225/122/17/650", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -2620,7 +2636,8 @@ "crs_id": "933131", "category": "attack_attempt", "cwe": "94", - "capec": "1000/225/122/17/650" + "capec": "1000/225/122/17/650", + "module": "waf" }, "conditions": [ { @@ -2665,7 +2682,8 @@ "category": "attack_attempt", "cwe": "94", "capec": "1000/225/122/17/650", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -2709,7 +2727,8 @@ "category": "attack_attempt", "cwe": "94", "capec": "1000/225/122/17/650", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -2799,7 +2818,8 @@ "crs_id": "933160", "category": "attack_attempt", "cwe": "94", - "capec": "1000/225/122/17/650" + "capec": "1000/225/122/17/650", + "module": "waf" }, "conditions": [ { @@ -2824,7 +2844,7 @@ "address": "graphql.server.resolver" } ], - "regex": "\\b(?:s(?:e(?:t(?:_(?:e(?:xception|rror)_handler|magic_quotes_runtime|include_path)|defaultstub)|ssion_s(?:et_save_handler|tart))|qlite_(?:(?:(?:unbuffered|single|array)_)?query|create_(?:aggregate|function)|p?open|exec)|tr(?:eam_(?:context_create|socket_client)|ipc?slashes|rev)|implexml_load_(?:string|file)|ocket_c(?:onnect|reate)|h(?:ow_sourc|a1_fil)e|pl_autoload_register|ystem)|p(?:r(?:eg_(?:replace(?:_callback(?:_array)?)?|match(?:_all)?|split)|oc_(?:(?:terminat|clos|nic)e|get_status|open)|int_r)|o(?:six_(?:get(?:(?:e[gu]|g)id|login|pwnam)|mk(?:fifo|nod)|ttyname|kill)|pen)|hp(?:_(?:strip_whitespac|unam)e|version|info)|g_(?:(?:execut|prepar)e|connect|query)|a(?:rse_(?:ini_file|str)|ssthru)|utenv)|r(?:unkit_(?:function_(?:re(?:defin|nam)e|copy|add)|method_(?:re(?:defin|nam)e|copy|add)|constant_(?:redefine|add))|e(?:(?:gister_(?:shutdown|tick)|name)_function|ad(?:(?:gz)?file|_exif_data|dir))|awurl(?:de|en)code)|i(?:mage(?:createfrom(?:(?:jpe|pn)g|x[bp]m|wbmp|gif)|(?:jpe|pn)g|g(?:d2?|if)|2?wbmp|xbm)|s_(?:(?:(?:execut|write?|read)ab|fi)le|dir)|ni_(?:get(?:_all)?|set)|terator_apply|ptcembed)|g(?:et(?:_(?:c(?:urrent_use|fg_va)r|meta_tags)|my(?:[gpu]id|inode)|(?:lastmo|cw)d|imagesize|env)|z(?:(?:(?:defla|wri)t|encod|fil)e|compress|open|read)|lob)|a(?:rray_(?:u(?:intersect(?:_u?assoc)?|diff(?:_u?assoc)?)|intersect_u(?:assoc|key)|diff_u(?:assoc|key)|filter|reduce|map)|ssert(?:_options)?|tob)|h(?:tml(?:specialchars(?:_decode)?|_entity_decode|entities)|(?:ash(?:_(?:update|hmac))?|ighlight)_file|e(?:ader_register_callback|x2bin))|f(?:i(?:le(?:(?:[acm]tim|inod)e|(?:_exist|perm)s|group)?|nfo_open)|tp_(?:nb_(?:ge|pu)|connec|ge|pu)t|(?:unction_exis|pu)ts|write|open)|o(?:b_(?:get_(?:c(?:ontents|lean)|flush)|end_(?:clean|flush)|clean|flush|start)|dbc_(?:result(?:_all)?|exec(?:ute)?|connect)|pendir)|m(?:b_(?:ereg(?:_(?:replace(?:_callback)?|match)|i(?:_replace)?)?|parse_str)|(?:ove_uploaded|d5)_file|ethod_exists|ysql_query|kdir)|e(?:x(?:if_(?:t(?:humbnail|agname)|imagetype|read_data)|ec)|scapeshell(?:arg|cmd)|rror_reporting|val)|c(?:url_(?:file_create|exec|init)|onvert_uuencode|reate_function|hr)|u(?:n(?:serialize|pack)|rl(?:de|en)code|[ak]?sort)|b(?:(?:son_(?:de|en)|ase64_en)code|zopen|toa)|(?:json_(?:de|en)cod|debug_backtrac|tmpfil)e|var_dump)(?:\\s|/\\*.*\\*/|//.*|#.*|\\\"|')*\\((?:(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:\\$\\w+|[A-Z\\d]\\w*|\\w+\\(.*\\)|\\\\?\"(?:[^\"]|\\\\\"|\"\"|\"\\+\")*\\\\?\"|\\\\?'(?:[^']|''|'\\+')*\\\\?')(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:(?:::|\\.|->)(?:\\s|/\\*.*\\*/|//.*|#.*)*\\w+(?:\\(.*\\))?)?,)*(?:(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:\\$\\w+|[A-Z\\d]\\w*|\\w+\\(.*\\)|\\\\?\"(?:[^\"]|\\\\\"|\"\"|\"\\+\")*\\\\?\"|\\\\?'(?:[^']|''|'\\+')*\\\\?')(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:(?:::|\\.|->)(?:\\s|/\\*.*\\*/|//.*|#.*)*\\w+(?:\\(.*\\))?)?)?\\)", + "regex": "\\b(?:s(?:e(?:t(?:_(?:e(?:xception|rror)_handler|magic_quotes_runtime|include_path)|defaultstub)|ssion_s(?:et_save_handler|tart))|qlite_(?:(?:(?:unbuffered|single|array)_)?query|create_(?:aggregate|function)|p?open|exec)|tr(?:eam_(?:context_create|socket_client)|ipc?slashes|rev)|implexml_load_(?:string|file)|ocket_c(?:onnect|reate)|h(?:ow_sourc|a1_fil)e|pl_autoload_register|ystem)|p(?:r(?:eg_(?:replace(?:_callback(?:_array)?)?|match(?:_all)?|split)|oc_(?:(?:terminat|clos|nic)e|get_status|open)|int_r)|o(?:six_(?:get(?:(?:e[gu]|g)id|login|pwnam)|mk(?:fifo|nod)|ttyname|kill)|pen)|hp(?:_(?:strip_whitespac|unam)e|version|info)|g_(?:(?:execut|prepar)e|connect|query)|a(?:rse_(?:ini_file|str)|ssthru)|utenv)|r(?:unkit_(?:function_(?:re(?:defin|nam)e|copy|add)|method_(?:re(?:defin|nam)e|copy|add)|constant_(?:redefine|add))|e(?:(?:gister_(?:shutdown|tick)|name)_function|ad(?:(?:gz)?file|_exif_data|dir))|awurl(?:de|en)code)|i(?:mage(?:createfrom(?:(?:jpe|pn)g|x[bp]m|wbmp|gif)|(?:jpe|pn)g|g(?:d2?|if)|2?wbmp|xbm)|s_(?:(?:(?:execut|write?|read)ab|fi)le|dir)|ni_(?:get(?:_all)?|set)|terator_apply|ptcembed)|g(?:et(?:_(?:c(?:urrent_use|fg_va)r|meta_tags)|my(?:[gpu]id|inode)|(?:lastmo|cw)d|imagesize|env)|z(?:(?:(?:defla|wri)t|encod|fil)e|compress|open|read)|lob)|a(?:rray_(?:u(?:intersect(?:_u?assoc)?|diff(?:_u?assoc)?)|intersect_u(?:assoc|key)|diff_u(?:assoc|key)|filter|reduce|map)|ssert(?:_options)?|tob)|h(?:tml(?:specialchars(?:_decode)?|_entity_decode|entities)|(?:ash(?:_(?:update|hmac))?|ighlight)_file|e(?:ader_register_callback|x2bin))|f(?:i(?:le(?:(?:[acm]tim|inod)e|(?:_exist|perm)s|group)?|nfo_open)|tp_(?:nb_(?:ge|pu)|connec|ge|pu)t|(?:unction_exis|pu)ts|write|open)|o(?:b_(?:get_(?:c(?:ontents|lean)|flush)|end_(?:clean|flush)|clean|flush|start)|dbc_(?:result(?:_all)?|exec(?:ute)?|connect)|pendir)|m(?:b_(?:ereg(?:_(?:replace(?:_callback)?|match)|i(?:_replace)?)?|parse_str)|(?:ove_uploaded|d5)_file|ethod_exists|ysql_query|kdir)|e(?:x(?:if_(?:t(?:humbnail|agname)|imagetype|read_data)|ec)|scapeshell(?:arg|cmd)|rror_reporting|val)|c(?:url_(?:file_create|exec|init)|onvert_uuencode|reate_function|hr)|u(?:n(?:serialize|pack)|rl(?:de|en)code|[ak]?sort)|b(?:(?:son_(?:de|en)|ase64_en)code|zopen|toa)|(?:json_(?:de|en)cod|debug_backtrac|tmpfil)e|var_dump)(?:\\s|/\\*.*\\*/|//.*|#.*|\\\"|')*\\((?:(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:\\$\\w+|[A-Z\\d]\\w*|\\w+\\(.*\\)|\\\\?\"(?:[^\"]|\\\\\"|\"\"|\"\\+\")*\\\\?\"|\\\\?'(?:[^']|''|'\\+')*\\\\?')(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:(?:::|\\.|->)(?:\\s|/\\*.*\\*/|//.*|#.*)*\\w+(?:\\(.*\\))?)?,)*(?:(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:\\$\\w+|[A-Z\\d]\\w*|\\w+\\(.*\\)|\\\\?\"(?:[^\"]|\\\\\"|\"\"|\"\\+\")*\\\\?\"|\\\\?'(?:[^']|''|'\\+')*\\\\?')(?:\\s|/\\*.*\\*/|//.*|#.*)*(?:(?:::|\\.|->)(?:\\s|/\\*.*\\*/|//.*|#.*)*\\w+(?:\\(.*\\))?)?)?\\)\\s*(?:[;\\.)}\\]|\\\\]|\\?>|%>|$)", "options": { "case_sensitive": true, "min_length": 5 @@ -2844,7 +2864,8 @@ "category": "attack_attempt", "cwe": "502", "capec": "1000/152/586", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -2891,7 +2912,8 @@ "crs_id": "933200", "category": "attack_attempt", "cwe": "502", - "capec": "1000/152/586" + "capec": "1000/152/586", + "module": "waf" }, "conditions": [ { @@ -2937,7 +2959,8 @@ "crs_id": "934100", "category": "attack_attempt", "cwe": "94", - "capec": "1000/152/242" + "capec": "1000/152/242", + "module": "waf" }, "conditions": [ { @@ -2982,7 +3005,8 @@ "category": "attack_attempt", "confidence": "1", "cwe": "94", - "capec": "1000/152/242" + "capec": "1000/152/242", + "module": "waf" }, "conditions": [ { @@ -3024,7 +3048,8 @@ "category": "attack_attempt", "cwe": "80", "capec": "1000/152/242/63/591", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3081,7 +3106,8 @@ "category": "attack_attempt", "cwe": "83", "capec": "1000/152/242/63/591/243", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3140,7 +3166,8 @@ "category": "attack_attempt", "cwe": "84", "capec": "1000/152/242/63/591/244", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3199,7 +3226,8 @@ "category": "attack_attempt", "cwe": "83", "capec": "1000/152/242/63/591/243", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3257,7 +3285,8 @@ "crs_id": "941180", "category": "attack_attempt", "cwe": "79", - "capec": "1000/152/242/63/591" + "capec": "1000/152/242/63/591", + "module": "waf" }, "conditions": [ { @@ -3311,7 +3340,8 @@ "category": "attack_attempt", "cwe": "80", "capec": "1000/152/242/63/591", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3358,7 +3388,8 @@ "category": "attack_attempt", "cwe": "80", "capec": "1000/152/242/63/591", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3405,7 +3436,8 @@ "category": "attack_attempt", "cwe": "80", "capec": "1000/152/242/63/591", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3452,7 +3484,8 @@ "category": "attack_attempt", "cwe": "83", "capec": "1000/152/242/63/591/243", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3498,7 +3531,8 @@ "category": "attack_attempt", "cwe": "83", "capec": "1000/152/242/63/591/243", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3545,7 +3579,8 @@ "crs_id": "941270", "category": "attack_attempt", "cwe": "83", - "capec": "1000/152/242/63/591/243" + "capec": "1000/152/242/63/591/243", + "module": "waf" }, "conditions": [ { @@ -3588,7 +3623,8 @@ "category": "attack_attempt", "cwe": "83", "capec": "1000/152/242/63/591/243", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3634,7 +3670,8 @@ "category": "attack_attempt", "cwe": "83", "capec": "1000/152/242/63/591/243", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3680,7 +3717,8 @@ "category": "attack_attempt", "cwe": "83", "capec": "1000/152/242/63/591/243", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3726,7 +3764,8 @@ "category": "attack_attempt", "cwe": "87", "capec": "1000/152/242/63/591/199", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3770,7 +3809,8 @@ "crs_id": "941360", "category": "attack_attempt", "cwe": "87", - "capec": "1000/152/242/63/591/199" + "capec": "1000/152/242/63/591/199", + "module": "waf" }, "conditions": [ { @@ -3815,7 +3855,8 @@ "category": "attack_attempt", "confidence": "1", "cwe": "79", - "capec": "1000/152/242/63/591" + "capec": "1000/152/242/63/591", + "module": "waf" }, "conditions": [ { @@ -3859,7 +3900,8 @@ "crs_id": "942100", "category": "attack_attempt", "cwe": "89", - "capec": "1000/152/248/66" + "capec": "1000/152/248/66", + "module": "waf" }, "conditions": [ { @@ -3898,7 +3940,8 @@ "category": "attack_attempt", "cwe": "89", "capec": "1000/152/248/66/7", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3943,7 +3986,8 @@ "category": "attack_attempt", "cwe": "89", "capec": "1000/152/248/66/7", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -3986,7 +4030,8 @@ "crs_id": "942250", "category": "attack_attempt", "cwe": "89", - "capec": "1000/152/248/66" + "capec": "1000/152/248/66", + "module": "waf" }, "conditions": [ { @@ -4030,7 +4075,8 @@ "crs_id": "942270", "category": "attack_attempt", "cwe": "89", - "capec": "1000/152/248/66" + "capec": "1000/152/248/66", + "module": "waf" }, "conditions": [ { @@ -4074,7 +4120,8 @@ "category": "attack_attempt", "cwe": "89", "capec": "1000/152/248/66/7", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -4117,7 +4164,8 @@ "crs_id": "942290", "category": "attack_attempt", "cwe": "943", - "capec": "1000/152/248/676" + "capec": "1000/152/248/676", + "module": "waf" }, "conditions": [ { @@ -4163,7 +4211,8 @@ "crs_id": "942360", "category": "attack_attempt", "cwe": "89", - "capec": "1000/152/248/66/470" + "capec": "1000/152/248/66/470", + "module": "waf" }, "conditions": [ { @@ -4206,7 +4255,8 @@ "crs_id": "942500", "category": "attack_attempt", "cwe": "89", - "capec": "1000/152/248/66" + "capec": "1000/152/248/66", + "module": "waf" }, "conditions": [ { @@ -4251,7 +4301,8 @@ "category": "attack_attempt", "cwe": "384", "capec": "1000/225/21/593/61", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -4296,7 +4347,8 @@ "category": "attack_attempt", "cwe": "94", "capec": "1000/152/242", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -4344,7 +4396,8 @@ "type": "java_code_injection", "category": "attack_attempt", "cwe": "94", - "capec": "1000/152/242" + "capec": "1000/152/242", + "module": "waf" }, "conditions": [ { @@ -4391,7 +4444,8 @@ "crs_id": "944130", "category": "attack_attempt", "cwe": "94", - "capec": "1000/152/242" + "capec": "1000/152/242", + "module": "waf" }, "conditions": [ { @@ -4529,7 +4583,8 @@ "type": "nosql_injection", "category": "attack_attempt", "cwe": "943", - "capec": "1000/152/248/676" + "capec": "1000/152/248/676", + "module": "waf" }, "conditions": [ { @@ -4573,7 +4628,8 @@ "type": "java_code_injection", "category": "attack_attempt", "cwe": "94", - "capec": "1000/152/242" + "capec": "1000/152/242", + "module": "waf" }, "conditions": [ { @@ -4619,7 +4675,8 @@ "category": "attack_attempt", "cwe": "94", "capec": "1000/152/242", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -4695,7 +4752,8 @@ "category": "attack_attempt", "cwe": "1321", "capec": "1000/152/242", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -4725,7 +4783,8 @@ "category": "attack_attempt", "cwe": "1321", "capec": "1000/152/242", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -4769,7 +4828,8 @@ "category": "attack_attempt", "cwe": "1336", "capec": "1000/152/242/19", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -4813,7 +4873,8 @@ "tool_name": "BurpCollaborator", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -4857,7 +4918,8 @@ "tool_name": "Qualys", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -4901,7 +4963,8 @@ "tool_name": "Probely", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -4944,7 +5007,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -4987,7 +5051,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -5031,7 +5096,8 @@ "tool_name": "Rapid7", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -5075,7 +5141,8 @@ "tool_name": "interact.sh", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -5119,7 +5186,8 @@ "tool_name": "Netsparker", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -5167,7 +5235,8 @@ "tool_name": "WhiteHatSecurity", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -5215,7 +5284,8 @@ "tool_name": "Nessus", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -5263,7 +5333,8 @@ "tool_name": "Watchtowr", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -5311,7 +5382,8 @@ "tool_name": "AppCheckNG", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -5358,7 +5430,8 @@ "category": "attack_attempt", "cwe": "287", "capec": "1000/225/115", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -5392,7 +5465,8 @@ "category": "attack_attempt", "cwe": "98", "capec": "1000/152/175/253/193", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -5436,7 +5510,8 @@ "category": "attack_attempt", "cwe": "77", "capec": "1000/152/248/88", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -5483,7 +5558,8 @@ "category": "attack_attempt", "cwe": "91", "capec": "1000/152/248/250", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -5521,7 +5597,8 @@ "category": "attack_attempt", "cwe": "83", "capec": "1000/152/242/63/591/243", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -5579,7 +5656,8 @@ "category": "attack_attempt", "cwe": "83", "capec": "1000/152/242/63/591/243", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -5866,7 +5944,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -5908,7 +5987,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -5950,7 +6030,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -5992,7 +6073,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6034,7 +6116,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6059,7 +6142,7 @@ "address": "server.request.uri.raw" } ], - "regex": "\\.(cgi|bat|dll|exe|key|cert|crt|pem|der|pkcs|pkcs|pkcs[0-9]*|nsf|jsa|war|java|class|vb|vba|so|git|svn|hg|cvs)([^a-zA-Z0-9_]|$)", + "regex": "\\.(cgi|bat|dll|exe|key|cert|crt|pem|der|pkcs|pkcs|pkcs[0-9]*|nsf|jsa|war|java|class|vb|vba|so|git|svn|hg|cvs)([?#&/]|$)", "options": { "case_sensitive": false } @@ -6076,7 +6159,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6118,7 +6202,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6160,7 +6245,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6202,7 +6288,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -6276,7 +6363,7 @@ } ] }, - "operator": "lfi_detector" + "operator": "lfi_detector@v2" } ], "transformers": [], @@ -6286,7 +6373,7 @@ }, { "id": "rasp-932-100", - "name": "Command injection exploit", + "name": "Shell command injection exploit", "tags": { "type": "command_injection", "category": "vulnerability_trigger", @@ -6332,6 +6419,54 @@ "stack_trace" ] }, + { + "id": "rasp-932-110", + "name": "OS command injection exploit", + "tags": { + "type": "command_injection", + "category": "vulnerability_trigger", + "cwe": "77", + "capec": "1000/152/248/88", + "confidence": "0", + "module": "rasp" + }, + "conditions": [ + { + "parameters": { + "resource": [ + { + "address": "server.sys.exec.cmd" + } + ], + "params": [ + { + "address": "server.request.query" + }, + { + "address": "server.request.body" + }, + { + "address": "server.request.path_params" + }, + { + "address": "grpc.server.request.message" + }, + { + "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" + } + ] + }, + "operator": "cmdi_detector" + } + ], + "transformers": [], + "on_match": [ + "stack_trace" + ] + }, { "id": "rasp-934-100", "name": "Server-side request forgery exploit", @@ -6438,7 +6573,8 @@ "category": "attack_attempt", "cwe": "918", "capec": "1000/225/115/664", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6482,7 +6618,8 @@ "type": "js_code_injection", "category": "attack_attempt", "cwe": "94", - "capec": "1000/152/242" + "capec": "1000/152/242", + "module": "waf" }, "conditions": [ { @@ -6527,7 +6664,8 @@ "category": "attack_attempt", "cwe": "78", "capec": "1000/152/248/88", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6570,7 +6708,8 @@ "category": "attack_attempt", "cwe": "78", "capec": "1000/152/248/88", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6615,7 +6754,8 @@ "category": "attack_attempt", "cwe": "78", "capec": "1000/152/248/88", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6658,7 +6798,8 @@ "category": "attack_attempt", "cwe": "918", "capec": "1000/225/115/664", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6701,7 +6842,8 @@ "category": "attack_attempt", "cwe": "918", "capec": "1000/225/115/664", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -6743,7 +6885,8 @@ "category": "attack_attempt", "cwe": "918", "capec": "1000/225/115/664", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -6785,7 +6928,8 @@ "category": "attack_attempt", "cwe": "918", "capec": "1000/225/115/664", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6828,7 +6972,8 @@ "category": "attack_attempt", "cwe": "918", "capec": "1000/225/115/664", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -6870,7 +7015,8 @@ "category": "attack_attempt", "cwe": "94", "capec": "1000/152/242", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6916,7 +7062,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Joomla exploitation tool", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6945,7 +7092,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Nessus", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -6974,7 +7122,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Arachni", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7003,7 +7152,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Jorgee", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7032,7 +7182,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Probely", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -7061,7 +7212,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Metis", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7090,7 +7242,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "SQLPowerInjector", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7119,7 +7272,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "N-Stealth", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7148,7 +7302,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Brutus", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7176,7 +7331,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7205,7 +7361,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Netsparker", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -7234,7 +7391,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "JAASCois", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7263,7 +7421,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Nsauditor", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7292,7 +7451,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Paros", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7321,7 +7481,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "DirBuster", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7350,7 +7511,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Pangolin", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7379,7 +7541,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Qualys", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -7408,7 +7571,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "SQLNinja", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7437,7 +7601,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Nikto", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7466,7 +7631,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "BlackWidow", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7495,7 +7661,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Grendel-Scan", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7524,7 +7691,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Havij", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7553,7 +7721,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "w3af", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7582,7 +7751,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Nmap", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7611,7 +7781,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Nessus", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7640,7 +7811,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "EvilScanner", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7669,7 +7841,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "WebFuck", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7698,7 +7871,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "OpenVAS", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7727,7 +7901,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Spider-Pig", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7756,7 +7931,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Zgrab", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7785,7 +7961,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Zmeu", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7814,7 +7991,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "GoogleSecurityScanner", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -7843,7 +8021,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Commix", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7872,7 +8051,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Gobuster", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7901,7 +8081,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "CGIchk", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7930,7 +8111,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "FFUF", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7959,7 +8141,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Nuclei", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -7988,7 +8171,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Tsunami", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8017,7 +8201,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Nimbostratus", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8046,7 +8231,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Datadog Canary Test", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8081,7 +8267,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Datadog Canary Test", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8119,7 +8306,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "AlertLogic", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -8148,7 +8336,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "wfuzz", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8177,7 +8366,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Detectify", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -8206,7 +8396,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "BSQLBF", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8235,7 +8426,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "masscan", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8264,7 +8456,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "WPScan", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8293,7 +8486,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Aon", - "confidence": "0" + "confidence": "0", + "module": "waf" }, "conditions": [ { @@ -8322,7 +8516,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "feroxbuster", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8350,7 +8545,8 @@ "category": "attack_attempt", "cwe": "200", "capec": "1000/118/169", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8382,7 +8578,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "SQLmap", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { @@ -8411,7 +8608,8 @@ "cwe": "200", "capec": "1000/118/169", "tool_name": "Skipfish", - "confidence": "1" + "confidence": "1", + "module": "waf" }, "conditions": [ { From 5688dad2ce843628dedc97142419f7e0f065cf67 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Wed, 2 Apr 2025 11:01:40 +0200 Subject: [PATCH 25/39] apisec: new sampler implementation (#39) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implementation for a new API Security sampler that aimes at providing better information as the sampling decision is made per endpoint (method plus route) and response status code; instead of being made across all. This implementation is based on an open addressing hash table using copy-update-replace semantics, so that it is able to operate completely lock-less. This is described by [RFC-1021](https://docs.google.com/document/d/1U0PeFZ83hGFUSBKDFLzpl1xNVQL1881ry95WzSB9a-Q/edit?tab=t.0#heading=h.banlidxrzyc9). Here is the result of running the benchmark on my machine with `1,000,000,000` operations distributed over `concurrency * 10` goroutines for each configuration: ``` goos: darwin goarch: arm64 pkg: github.com/DataDog/appsec-internal-go/apisec cpu: Apple M1 Max │ 1 │ 1000 │ │ sec/op │ sec/op vs base │ Sampler/keySpaceSize=2048/interval=1s-10 76.27n ± 2% 88.40n ± 1% +15.91% (p=0.000 n=10) Sampler/keySpaceSize=8192/interval=1s-10 77.77n ± 26% 119.85n ± 25% +54.11% (p=0.000 n=10) geomean 77.01n 102.9n +33.65% │ 1 │ 1000 │ │ keep% │ keep% vs base │ Sampler/keySpaceSize=2048/interval=1s-10 15.77m ± 1% 18.23m ± 3% +15.60% (p=0.000 n=10) Sampler/keySpaceSize=8192/interval=1s-10 1314.5m ± 26% 204.4m ± 38% -84.45% (p=0.000 n=10) geomean 144.0m 61.04m -57.60% │ 1 │ 1000 │ │ B/op │ B/op vs base │ Sampler/keySpaceSize=2048/interval=1s-10 0.000 ± 0% 0.000 ± 0% ~ (p=1.000 n=10) ¹ Sampler/keySpaceSize=8192/interval=1s-10 1.000 ± 0% 0.000 ± 0% -100.00% (p=0.000 n=10) geomean ² ? ² ³ ¹ all samples are equal ² summaries must be >0 to compute geomean ³ ratios must be >0 to compute geomean │ 1 │ 1000 │ │ allocs/op │ allocs/op vs base │ Sampler/keySpaceSize=2048/interval=1s-10 0.000 ± 0% 0.000 ± 0% ~ (p=1.000 n=10) ¹ Sampler/keySpaceSize=8192/interval=1s-10 0.000 ± 0% 0.000 ± 0% ~ (p=1.000 n=10) ¹ geomean ² +0.00% ² ¹ all samples are equal ² summaries must be >0 to compute geomean ``` --------- Co-authored-by: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> --- apisec/internal/config/const.go | 16 + apisec/internal/timed/clock.go | 42 + apisec/internal/timed/set.go | 208 ++++ apisec/internal/timed/set_test.go | 109 +++ apisec/internal/timed/table.go | 181 ++++ apisec/internal/timed/table_test.go | 37 + apisec/sampler.go | 77 ++ apisec/sampler_test.go | 1384 +++++++++++++++++++++++++++ appsec/config.go | 45 +- appsec/config_test.go | 38 +- go.mod | 4 +- go.sum | 4 +- 12 files changed, 2084 insertions(+), 61 deletions(-) create mode 100644 apisec/internal/config/const.go create mode 100644 apisec/internal/timed/clock.go create mode 100644 apisec/internal/timed/set.go create mode 100644 apisec/internal/timed/set_test.go create mode 100644 apisec/internal/timed/table.go create mode 100644 apisec/internal/timed/table_test.go create mode 100644 apisec/sampler.go create mode 100644 apisec/sampler_test.go diff --git a/apisec/internal/config/const.go b/apisec/internal/config/const.go new file mode 100644 index 0000000..5c5f532 --- /dev/null +++ b/apisec/internal/config/const.go @@ -0,0 +1,16 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2023-present Datadog, Inc. + +package config + +import "time" + +const ( + // MaxItemCount is the maximum amount of items to keep in a timed set. + MaxItemCount = 4_096 + + // Interval is the interval between two samples being taken. + Interval = 30 * time.Second +) diff --git a/apisec/internal/timed/clock.go b/apisec/internal/timed/clock.go new file mode 100644 index 0000000..da0fa7f --- /dev/null +++ b/apisec/internal/timed/clock.go @@ -0,0 +1,42 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2023-present Datadog, Inc. + +package timed + +import "time" + +type ( + ClockFunc = func() int64 + + // biasedClock is a specialized clock implementation used to ensure we can get + // 32-bit wide timestamps without having to worry about wraparound. + biasedClock struct { + // clock is the underlying clock, returning a timestamp in seconds. + clock ClockFunc + // bias is effectively the time at which the biasedClock was initialized. + bias int64 + } +) + +// newBiasedClock creates a new [biasedClock] with the given clock function and +// horizon. +func newBiasedClock(clock ClockFunc, horizon uint32) biasedClock { + return biasedClock{ + clock: clock, + bias: clock() - int64(horizon), + } +} + +// Now returns the current timestamp, relative to this [biasedClock]. +func (c *biasedClock) Now() uint32 { + // We clamp it to [0,) to be absolutely safe... + return uint32(max(0, c.clock()-c.bias)) +} + +// UnixTime is a [ClockFunc] that returns the current Unix time (seconds since +// the Unix epoch). +func UnixTime() int64 { + return time.Now().Unix() +} diff --git a/apisec/internal/timed/set.go b/apisec/internal/timed/set.go new file mode 100644 index 0000000..b558b52 --- /dev/null +++ b/apisec/internal/timed/set.go @@ -0,0 +1,208 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2023-present Datadog, Inc. + +package timed + +import ( + "fmt" + "math/rand" + "sync/atomic" + "time" + + "github.com/DataDog/appsec-internal-go/apisec/internal/config" +) + +// capacity is the maximum number of items that may be temporarily present in a +// [LRU]. An eviction triggers once [config.MaxItemCount] is reached, however the +// implementation is based on Copy-Update-Replace semantics, so during a table +// rebuild, the old table may contrinue to receive items for a short while. +const capacity = 2 * config.MaxItemCount + +// LRU is a specialized open-addressing-hash-table-based implementation of a +// specialized LRU cache, using Copy-Update-Replace semantics to operate in a +// completely lock-less manner. +type LRU struct { + // table is the pointer to the current backing hash table + table atomic.Pointer[table] + // clock is used to determine the current timestamp when making + // changes + clock biasedClock + // intervalSeconds is the amount of time in seconds that an entry is + // considered live for. + intervalSeconds uint32 + // zeroKey is a key that is used to replace 0 in the set. This key and 0 are + // effectively the same item. This allows us to gracefully handle 0 in our + // use-case without having to half the hash-space (to 63 bits) so we can use + // one bit as an empty discriminator. The value is chosen at random when the + // set is created, so that different instances will merge 0 with a different + // key. + zeroKey uint64 + // rebuilding is a flag to indicate whether the table is being rebuilt as + // part of an eviction request. + rebuilding atomic.Bool +} + +// NewSet initializes a new, empty [LRU] with the given interval and clock +// function. The provided interval must be at least 1 second, and may not exceed +// [config.Interval]. +// +// Note: timestamps are stored at second resolution, so the interval will be +// rounded down to the nearest second. +func NewSet(interval time.Duration, clock ClockFunc) *LRU { + if interval < time.Second { + panic(fmt.Errorf("NewSet: interval must be at least 1s, got %v", interval)) + } + if interval > config.Interval { + panic(fmt.Errorf("NewSet: interval must not exceed %s, got %v", config.Interval, interval)) + } + + intervalSeconds := uint32(interval.Seconds()) + set := &LRU{ + clock: newBiasedClock(clock, intervalSeconds), + intervalSeconds: intervalSeconds, + zeroKey: rand.Uint64(), + } + + // That value cannot be zero... + for set.zeroKey == 0 { + set.zeroKey = rand.Uint64() + } + + set.table.Store(&table{}) + + return set +} + +// Hit determines whether the given key should be kept or dropped based on the +// last time it was sampled. If the table grows larger than [config.MaxItemCount], the +// [LRU.rebuild] method is called in a separate goroutine to begin the +// eviction process. Until this has completed, all updates to the [LRU] are +// effectively dropped, as they happen on the soon-to-be-replaced table. +// +// Note: in order to run completely lock-less, [LRU] cannot store the 0 key in +// the table, as a 0 key is used as a sentinel value to identify free entries. +// To avoid this pitfall, [LRU.zeroKey] is used as a substitute for 0, meaning +// 0 and [LRU.zeroKey] are treated as the same key. This is not an issue in +// common use, as given a uniform distribution of keys this only happens 1 in +// 2^64-1 times. +func (m *LRU) Hit(key uint64) bool { + if key == 0 { + // The 0 key is used as a way to imply a slot is empty; so we cannot store + // it in the table. To address this, when passed a 0 key, we will use the + // [Set.zeroKey] as a substitute. + key = m.zeroKey + } + + now := m.clock.Now() + threshold := now - m.intervalSeconds + + var ( + table = m.table.Load() + entry *entry + ) + for { + var exists bool + entry, exists = table.FindEntry(key) + if exists { + // The entry already exists, so we can proceed... + break + } + + // We're adding a new entry to the table, so we need to: + // 1. Ensure we have capacity (possibly trigger an eviction rebuild) + // 2. Claim the slot (or look for another slot if it's already claimed) + newCount := table.count.Add(1) + if newCount > config.MaxItemCount && m.rebuilding.CompareAndSwap(false, true) { + // We're already holding the maximium number of items, so we will rebuild + // in order to perform an eviction pass. Updates made in the meantime will + // be lost. + go m.rebuild(table, threshold) + } + if newCount > capacity { + // We don't have space to add any new item, so we'll ignore this and + // decide to DROP it (we may otherwise cause a surge of inconditional + // keep decisions, that is not desirable). This only happens in the most + // dire of circumstances (a table rebuild did not complete fast enough + // to make up free space). + table.count.Add(-1) + return false + } + + if entry.Key.CompareAndSwap(0, key) { + // We have successfully claimed the slot, so now we can proceed to set it + // up. If we fail to swap, another goroutine has sampled this slot just + // before this one, so we can DROP the sample. + return entry.Data.CompareAndSwap(0, newEntryData(now, now)) + } + + if entry.Key.Load() == key { + // Another goroutine has concurrently claimed this slot for this key, and + // since very little time has passed since then, so we can DROP this + // sample... This is extremely unlikely to happen (and nearly impossible + // to reliably cover in unit tests). + return false + } + + // Another goroutine has concurrently claimed this slot for another key... + // We will try to find another slot then... + table.count.Add(-1) + } + + // We have found an existing entry, so we can proceed to update it... + curData := entry.Data.Load() + if curData.SampleTime() <= threshold { + // We sampled this a while back (or this is the first time), so we may keep + // this sample! + + // Store the value ahead of the for loop so we don't have to do the bit + // shifts over and over again (even though they're cheap to do). + nowEntryData := newEntryData(now, now) + for !entry.Data.CompareAndSwap(curData, nowEntryData) { + // Another goroutine has already changed it... + curData = entry.Data.Load() + if curData.LastAccessKept() { + // The concurrent update was a KEEP (as is indicated by the fact its + // atime and stime are equal), so this one is necessarily a DROP. + return false + } + + if curData.SampleTime() >= now { + // The concurrent update was made in our future, and it somehow was not + // a KEEP, so we'll make a KEEP decision here, but avoid rolling back + // the [entryData.AccessTime] back. + return true + } + + // The concurrent update was a DROP, and our clock is ahead of theirs, so + // we'll try again... + } + + // We successfully swapped at this point, so we have our KEEP decision! + return true + } + + newData := curData.WithAccessTime(now) + for curData.AccessTime() < now { + if entry.Data.CompareAndSwap(curData, newData) { + // We are done here! + break + } + // Another goroutine has updated the access time... We'll try again... + curData = entry.Data.Load() + } + return false +} + +// rebuild runs in a separate goroutine, and creates a pruned copy of the +// provided [table] with old and expired entries removed. It will keep at most +// [config.MaxItemCount]*2/3 items in the new table. Once the rebuild is complete, it +// replaces the [LRU.table] with the copy. +func (m *LRU) rebuild(oldTable *table, threshold uint32) { + // Since Go has a GC, we can "just" replace the current [Set.table] with a + // trimmed down copy, and let the GC take care of reclaiming the old one, once + // it is no longer in use by any reader. + m.table.Store(oldTable.PrunedCopy(threshold)) + m.rebuilding.Store(false) +} diff --git a/apisec/internal/timed/set_test.go b/apisec/internal/timed/set_test.go new file mode 100644 index 0000000..f81e994 --- /dev/null +++ b/apisec/internal/timed/set_test.go @@ -0,0 +1,109 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2023-present Datadog, Inc. + +package timed + +import ( + "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/DataDog/appsec-internal-go/apisec/internal/config" + "github.com/stretchr/testify/require" +) + +func TestSet(t *testing.T) { + t.Run("New", func(t *testing.T) { + require.PanicsWithError(t, "NewSet: interval must be at least 1s, got 0s", func() { NewSet(0, UnixTime) }) + require.PanicsWithError(t, "NewSet: interval must be at least 1s, got 10ms", func() { NewSet(10*time.Millisecond, UnixTime) }) + require.PanicsWithError(t, "NewSet: interval must not exceed 30s, got 1m0s", func() { NewSet(time.Minute, UnixTime) }) + }) + + t.Run("Hit", func(t *testing.T) { + fakeTime := time.Now().Unix() + fakeClock := func() int64 { return fakeTime } + + subject := NewSet(config.Interval, fakeClock) + + require.True(t, subject.Hit(1337)) + for range config.Interval / time.Second { + require.False(t, subject.Hit(1337)) + fakeTime++ + } + require.True(t, subject.Hit(1337)) + + t.Run("zero", func(t *testing.T) { + require.True(t, subject.Hit(0)) + + // Keys are slotted via [% capacity], so if we don't properly encode + // 0-values, the new slot will inherit the previously set sample time, and + // the assertion will fail as a result. + zeroSlot := uint64(capacity) + if zeroSlot == subject.zeroKey { + // There is a very small chance that the zero key has been set to + // [capacity], in which case we'll just double it to escape the + // collision and get a fresh new hit. + zeroSlot *= 2 + } + require.True(t, subject.Hit(zeroSlot)) + }) + }) + + t.Run("rebuild", func(t *testing.T) { + var fakeTime atomic.Int64 + fakeTime.Store(time.Now().Unix()) + fakeClock := func() int64 { return fakeTime.Load() } + + subject := NewSet(config.Interval, fakeClock) + + var ( + goCount = runtime.GOMAXPROCS(0) * 10 + startBarrier sync.WaitGroup + finishBarrier sync.WaitGroup + ) + startBarrier.Add(goCount + 1) + finishBarrier.Add(goCount) + for g := range goCount { + go func() { + defer finishBarrier.Done() + startBarrier.Done() + startBarrier.Wait() + + for key := range uint64(config.MaxItemCount * 4) { + _ = subject.Hit(key) + if g == 0 { + fakeTime.Add(1) + } + } + }() + } + + startBarrier.Done() + finishBarrier.Wait() + + // Wiat for an in-progress rebuild to finish... + for subject.rebuilding.Load() { + runtime.Gosched() + } + + // Check the final table has a reasonable content... + table := subject.table.Load() + count := 0 + for i := range table.entries { + entry := &table.entries[i] + if entry.Key.Load() == 0 { + continue + } + // Since we ran through the keys sequentially, we should not have kept any + // of the first [config.MaxItemCount] keys in any case. + require.Less(t, uint64(config.MaxItemCount), entry.Key.Load()) + count++ + } + // We shoudl not have more than [maxItemCount] items left in the map... + require.LessOrEqual(t, count, config.MaxItemCount) + }) +} diff --git a/apisec/internal/timed/table.go b/apisec/internal/timed/table.go new file mode 100644 index 0000000..641bd7c --- /dev/null +++ b/apisec/internal/timed/table.go @@ -0,0 +1,181 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2023-present Datadog, Inc. + +package timed + +import ( + "slices" + "sync/atomic" + + "github.com/DataDog/appsec-internal-go/apisec/internal/config" +) + +type ( + // table is a simple open-addressing hash table implementation that uses a + // fixed array of items. + table struct { + // entries is the set of items contained in the table. The last entry is + // reserved for cases where all slots are taken before a rebuild is + // complete (it saves us from having to write code to deal with the + // impossibility to find an empty slot, as we always have a slot to return. + // We could return a throw-away slot but this would incur a heap allocation, + // which we can spare by doing this). + entries [capacity + 1]entry + // count is the number of items currently stored in the table. + count atomic.Int32 + } + + // entry is a single item in the open-addressing hash table. + entry struct { + // Key is the Key of the entry. A zero Key indicates that the entry is + // currently free. + Key atomic.Uint64 + // Data is the Data associated with the entry. + Data atomicEntryData + } + + // atomicEntryData is an atomic version of [entryData]. + atomicEntryData atomic.Uint64 + // entryData is a 64-bit value that represents the last time an entry was + // accessed paired together with the last time this value was sampled. + entryData uint64 + + // copiableEntry is a copy-able version of entryData, which is used for + // sorting entries by recency using a heap when re-building the table. + copiableEntry struct { + // Key is the Key of the entry. + Key uint64 + // Data is the Data associated with the entry. + Data entryData + } +) + +// FindEntry locates the correct entry for use in the table. If an entry already +// exists for the given key, it is returned with true. If not, the first blank +// entry is returned with false. +func (t *table) FindEntry(key uint64) (*entry, bool) { + origIdx := key % capacity + idx := origIdx + + for { + entry := &t.entries[idx] + if curKey := entry.Key.Load(); curKey == 0 || curKey == key { + // This is either the entry we're looking for, or an empty slot we can + // claim for this key. + return entry, curKey == key + } + idx = (idx + 1) % capacity + if idx == origIdx { + // We are back at the original index, meaning the map is full. + break + } + } + // We have gone full circle without finding a blank slot, so we give up and + // return our last resort slot that is reserved for this situation. + return &t.entries[capacity], true +} + +// PrunedCopy creates a copy of this table with expired items removed, retaining +// up to the [config.MaxItemCount]*2/3 most recent items from the original. +func (t *table) PrunedCopy(threshold uint32) *table { + // Sort the existing entries (most recent at the top) + newEntries := make([]copiableEntry, 0, capacity) + for i := range capacity { + if t.entries[i].BlankOrExpired(threshold) { + continue + } + newEntries = append(newEntries, t.entries[i].Copyable()) + } + slices.SortFunc(newEntries, copiableEntry.Compare) + + // Insert up to [config.MaxItemCount]*2/3 items into the new table + t = new(table) + count := min(int32(config.MaxItemCount*2/3), int32(len(newEntries))) + for _, entry := range newEntries[:count] { + slot, _ := t.FindEntry(entry.Key) + slot.Key.Store(entry.Key) + slot.Data.Store(entry.Data) + } + t.count.Store(count) + + return t +} + +// BlankOrExpired returns true if the receiver is blank or has expired already. +func (e *entry) BlankOrExpired(threshold uint32) bool { + return e.Key.Load() == 0 || e.Data.Load().SampleTime() < threshold +} + +// Copyable returns a [copyableEntry] version of this entry. +func (e *entry) Copyable() copiableEntry { + return copiableEntry{ + Key: e.Key.Load(), + Data: e.Data.Load(), + } +} + +// Load returns the current value held by this atomic. +func (d *atomicEntryData) Load() entryData { + return entryData((*atomic.Uint64)(d).Load()) +} + +// CompareAndSwap atomically compares the current value held by this atomic with +// the old value, and if they match replaes it with the new value. Returns true +// if the swap happened. +func (d *atomicEntryData) CompareAndSwap(old entryData, new entryData) (swapped bool) { + return (*atomic.Uint64)(d).CompareAndSwap(uint64(old), uint64(new)) +} + +// Store atomically stores the given value in this atomic. +func (d *atomicEntryData) Store(new entryData) { + (*atomic.Uint64)(d).Store(uint64(new)) +} + +// newEntryData creates a new [entryData] value from the given access and sample +// times. +func newEntryData(atime uint32, stime uint32) entryData { + return entryData(uint64(atime)<<32 | uint64(stime)) +} + +// AccessTime is the access time part of the [entryData]. +func (d entryData) AccessTime() uint32 { + return uint32(d >> 32) +} + +// SampleTime is the sample time part of the [entryData]. +func (d entryData) SampleTime() uint32 { + return uint32(d) +} + +// LastAccessKept returns true if the last access to this entry resulted in a +// decision to keep the sample. This is true of the access time is not 0 and is +// equal to the sample time. +func (d entryData) LastAccessKept() bool { + return d.AccessTime() != 0 && d.AccessTime() == d.SampleTime() +} + +// WithAccessTime returns a new [entryData] by copying the receiver and +// replacing the access time portion with the specified value. +func (d entryData) WithAccessTime(atime uint32) entryData { + return (d & 0x00000000_FFFFFFFF) | (entryData(atime) << 32) +} + +// Compare performs a comparison between the receiver and another entry; such +// that most recently sampled entries come first. Two entries with the same +// sample time are considered equal. +func (e copiableEntry) Compare(other copiableEntry) int { + tst := e.Data.SampleTime() + ost := other.Data.SampleTime() + if tst > ost { + // Receiver was sampled more recently (sorts higher) + return 1 + } + if tst < ost { + // Receiver was sampled less recently (sorts lower) + return -1 + } + // Both have the same sample time, so we consider them equal. + return 0 +} diff --git a/apisec/internal/timed/table_test.go b/apisec/internal/timed/table_test.go new file mode 100644 index 0000000..abd9305 --- /dev/null +++ b/apisec/internal/timed/table_test.go @@ -0,0 +1,37 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2023-present Datadog, Inc. + +package timed + +import ( + "math/rand/v2" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestEntryData(t *testing.T) { + t.Run("zero", func(t *testing.T) { + var subject entryData + + require.EqualValues(t, 0, subject.AccessTime()) + require.EqualValues(t, 0, subject.SampleTime()) + }) + + t.Run("newEntryData", func(t *testing.T) { + atime := rand.Uint32() + stime := rand.Uint32() + subject := newEntryData(atime, stime) + + require.Equal(t, atime, subject.AccessTime()) + require.Equal(t, stime, subject.SampleTime()) + + t.Run("WithAccessTime", func(t *testing.T) { + subject = subject.WithAccessTime(atime + 1) + require.Equal(t, atime+1, subject.AccessTime()) + require.Equal(t, stime, subject.SampleTime()) // Unchanged + }) + }) +} diff --git a/apisec/sampler.go b/apisec/sampler.go new file mode 100644 index 0000000..2bf6365 --- /dev/null +++ b/apisec/sampler.go @@ -0,0 +1,77 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2023-present Datadog, Inc. + +package apisec + +import ( + "encoding/binary" + "hash/fnv" + "time" + + "github.com/DataDog/appsec-internal-go/apisec/internal/config" + "github.com/DataDog/appsec-internal-go/apisec/internal/timed" +) + +type ( + Sampler interface { + DecisionFor(SamplingKey) bool + } + + timedSetSampler timed.LRU + + SamplingKey struct { + // Method is the value of the http.method span tag + Method string + // Route is the value of the http.route span tag + Route string + // StatusCode is the value of the http.status_code span tag + StatusCode int + } + + clockFunc = func() int64 +) + +// NewSampler returns a new [*Sampler] with the default clock function based on +// [time.Now]. +func NewSampler() Sampler { + return NewSamplerWithInterval(config.Interval) +} + +// NewSamplerWithInterval returns a new [*Sampler] with the specified interval +// instead of the default of 30 seconds. +func NewSamplerWithInterval(interval time.Duration) Sampler { + return newSampler(interval, timed.UnixTime) +} + +// newSampler allows creating a new [*Sampler] with custom clock function, +// which is useful for testing. +func newSampler(interval time.Duration, clock clockFunc) Sampler { + return (*timedSetSampler)(timed.NewSet(interval, clock)) +} + +// DecisionFor makes a sampling decision for the provided [SamplingKey]. If it +// returns true, the request has been "sampled in" and the caller should proceed +// with the necessary actions. If it returns false, the request has been +// dropped, and the caller should short-circuit without extending further +// effort. +func (s *timedSetSampler) DecisionFor(key SamplingKey) bool { + keyHash := key.hash() + return (*timed.LRU)(s).Hit(keyHash) +} + +// hash returns a hash of the key. Given the same seed, it always produces the +// same output. If the seed changes, the output is likely to change as well. +func (k SamplingKey) hash() uint64 { + fnv := fnv.New64() + + _, _ = fnv.Write([]byte(k.Method)) + _, _ = fnv.Write([]byte(k.Route)) + + var bytes [2]byte + binary.NativeEndian.PutUint16(bytes[:], uint16(k.StatusCode)) + _, _ = fnv.Write(bytes[:]) + + return fnv.Sum64() +} diff --git a/apisec/sampler_test.go b/apisec/sampler_test.go new file mode 100644 index 0000000..53d2762 --- /dev/null +++ b/apisec/sampler_test.go @@ -0,0 +1,1384 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2023-present Datadog, Inc. + +package apisec + +import ( + "context" + "fmt" + "math/rand" + "net/http" + "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/DataDog/appsec-internal-go/apisec/internal/config" + "github.com/stretchr/testify/assert" +) + +func TestSampler(t *testing.T) { + initTestVector() + + ctx := context.Background() + if deadline, ok := t.Deadline(); ok { + var cancel context.CancelFunc + ctx, cancel = context.WithDeadline(ctx, deadline) + defer cancel() + } + + const samplesToTake = config.MaxItemCount << 10 + + type testCase struct { + // KeySpace is the set of keys to randomly draw from when sampling. + KeySpace []SamplingKey + // SimulatedTPS is the number of samples per second to simulate. + SimulatedTPS int + // ExpectedKeepRate is the expected rate of samples being kept [0;1] + ExpectedKeepRate float64 + // AllowedDelta is the allowed delta for the keep rate. + AllowedDelta float64 + } + testCases := map[string]testCase{ + "small": { + KeySpace: testVector[:config.MaxItemCount/32], + SimulatedTPS: 10, + ExpectedKeepRate: .0415, + AllowedDelta: .0001, + }, + "medium": { + KeySpace: testVector[:config.MaxItemCount/16], + SimulatedTPS: 20, + ExpectedKeepRate: .0415, + AllowedDelta: .0001, + }, + "high": { + KeySpace: testVector[:config.MaxItemCount*2/3], + SimulatedTPS: 1000, + ExpectedKeepRate: .0091, + AllowedDelta: .0001, + }, + "large": { + KeySpace: testVector[:config.MaxItemCount], + SimulatedTPS: 1000, + ExpectedKeepRate: .01, + AllowedDelta: .005, // Small chance of collision here... so a bit more wiggle room... + }, + "extreme": { // Not actually realistic usage... Evictions galore! + KeySpace: testVector[:2*config.MaxItemCount], + SimulatedTPS: 10000, + ExpectedKeepRate: .21, + AllowedDelta: .05, // Very random evictions, so keep rate can be pretty off... + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + assert.Positive(t, tc.SimulatedTPS) + assert.GreaterOrEqual(t, tc.ExpectedKeepRate, 0.0) + assert.GreaterOrEqual(t, 1.0, tc.ExpectedKeepRate) + + var ( + goroutineCount = max(2, runtime.GOMAXPROCS(0)) + clock = newFakeClock(ctx, t, goroutineCount) + subject = newSampler(30*time.Second, clock.Unix) + sb sync.WaitGroup // Start barrier + wg sync.WaitGroup // Completion barrier + kept atomic.Uint64 + dropped atomic.Uint64 + ) + sb.Add(1 + goroutineCount) // All child goroutines + this one... + wg.Add(goroutineCount) + for range goroutineCount { + go func() { + defer wg.Done() + + sb.Done() // We're ready for business, signal to the start barrier... + sb.Wait() // Wait for all the goroutines to have started... + + for i := range samplesToTake { + if subject.DecisionFor(randomOne(tc.KeySpace)) { + kept.Add(1) + } else { + dropped.Add(1) + } + // The clock ticks every 10 samples (model a server processing 10 TPS) + if i%tc.SimulatedTPS == 0 { + clock.WaitForTick() + } + } + }() + } + + sb.Done() + wg.Wait() + + samplesTaken := kept.Load() + dropped.Load() + + keepRate := float64(kept.Load()) / float64(samplesTaken) + assert.InDelta(t, tc.ExpectedKeepRate, keepRate, tc.AllowedDelta, "expected keep rate around %.2f±%.2f%%, was %.2f%%", 100*tc.ExpectedKeepRate, 100*tc.AllowedDelta, 100*keepRate) + }) + } +} + +func TestSamplingKeyHash(t *testing.T) { + initTestVector() + + t.Run("collisions-are-infrequent", func(t *testing.T) { + hashes := make(map[uint64]struct{}, len(testVector)) + for _, key := range testVector { + hashes[key.hash()] = struct{}{} + } + + // Validates that the hash function results in less than 1% collisions. This + // is a little arbitrary, but should ensure the function as at least + // somewhat fit for purpose here. + assert.GreaterOrEqual(t, float64(len(hashes))/float64(len(testVector)), .99, + "the hash function should have less than 10% collisions") + }) + + t.Run("distribution-is-uniform-on-buckets", func(t *testing.T) { + buckets := make(map[int]struct{}, len(testVector)) + for _, key := range testVector { + buckets[int(key.hash()%config.MaxItemCount)] = struct{}{} + } + + // Validates that the hash function results in hitting at least 80% of the + // buckets. This is arbitrary, and may feel a little low, but our sample + // count is quite close to the bucket count, so this is actually solid. + assert.GreaterOrEqual(t, float64(len(buckets))/float64(config.MaxItemCount), .80, + "the hash function should slot into 50% of the buckets at least") + }) +} + +func BenchmarkSampler(b *testing.B) { + initTestVector() + + for _, keySpaceSize := range []int{config.MaxItemCount / 2, config.MaxItemCount * 2} { + keySpace := testVector[:keySpaceSize] + b.Run(fmt.Sprintf("keySpaceSize=%d", keySpaceSize), func(b *testing.B) { + for _, parallelism := range []int{1, 1000} { + b.Run(fmt.Sprintf("parallelism=%d/interval=1s", parallelism), func(b *testing.B) { + var ( + subject = NewSamplerWithInterval(time.Second) + kept atomic.Uint64 + dropped atomic.Uint64 + ) + + // We'll synchronize the start of all of our goroutines to ensure contention happens early. + b.StopTimer() + b.SetParallelism(parallelism) + var ( + wg sync.WaitGroup + barrier = make(chan struct{}) + ) + wg.Add(parallelism * runtime.GOMAXPROCS(0)) + + go func() { + wg.Wait() + b.StartTimer() + close(barrier) // Un-block all the goroutines; we're in business! + }() + + b.RunParallel(func(pb *testing.PB) { + wg.Done() + <-barrier + + for i := 0; pb.Next(); i = (i + 1) % keySpaceSize { + if subject.DecisionFor(keySpace[i]) { + kept.Add(1) + } else { + dropped.Add(1) + } + } + }) + + fkept := float64(kept.Load()) + b.ReportMetric(100*fkept/(fkept+float64(dropped.Load())), "keep%") + }) + } + }) + } +} + +type fakeClock struct { + t testing.TB + goCount int + now int64 + needTick atomic.Bool + wg sync.WaitGroup + cnd sync.Cond +} + +func newFakeClock(ctx context.Context, t testing.TB, goroutineCount int) *fakeClock { + res := &fakeClock{ + t: t, + goCount: goroutineCount, + now: time.Now().Unix(), + cnd: *sync.NewCond(&sync.Mutex{}), + } + res.wg.Add(goroutineCount) + go res.tick(ctx) + return res +} + +func (c *fakeClock) Unix() int64 { + return c.now +} + +func (c *fakeClock) WaitForTick() { + c.cnd.L.Lock() + + c.needTick.CompareAndSwap(false, true) + curTime := c.now + + c.wg.Done() + for curTime == c.now && c.now > 0 { + c.cnd.Wait() + } + c.cnd.L.Unlock() +} + +func (c *fakeClock) tick(ctx context.Context) { + c.t.Log("Start ticker!") + for { + select { + case <-ctx.Done(): + // Context is cancelled, stop the ticker... + c.cnd.L.Lock() + c.now = 0 + c.cnd.L.Unlock() + c.t.Log("Stop ticker!") + return + default: + if !c.needTick.Load() { + continue + } + c.wg.Wait() + c.cnd.L.Lock() + c.now++ + c.needTick.Store(false) + c.cnd.Broadcast() + c.wg.Add(c.goCount) + c.cnd.L.Unlock() + } + } +} + +func randomOne[T any](list []T) T { + return list[rand.Intn(len(list))] +} + +var ( + httpMethods = []string{ + http.MethodGet, + http.MethodHead, + http.MethodPost, + http.MethodPut, + http.MethodPatch, + http.MethodDelete, + http.MethodConnect, + http.MethodOptions, + http.MethodTrace, + } + httpStatusCodes = []int{ + http.StatusContinue, + http.StatusSwitchingProtocols, + http.StatusProcessing, + http.StatusEarlyHints, + http.StatusOK, + http.StatusCreated, + http.StatusAccepted, + http.StatusNonAuthoritativeInfo, + http.StatusNoContent, + http.StatusResetContent, + http.StatusPartialContent, + http.StatusMultiStatus, + http.StatusAlreadyReported, + http.StatusIMUsed, + http.StatusMultipleChoices, + http.StatusMovedPermanently, + http.StatusFound, + http.StatusSeeOther, + http.StatusNotModified, + http.StatusUseProxy, + http.StatusTemporaryRedirect, + http.StatusPermanentRedirect, + http.StatusBadRequest, + http.StatusUnauthorized, + http.StatusPaymentRequired, + http.StatusForbidden, + http.StatusNotFound, + http.StatusMethodNotAllowed, + http.StatusNotAcceptable, + http.StatusProxyAuthRequired, + http.StatusRequestTimeout, + http.StatusConflict, + http.StatusGone, + http.StatusLengthRequired, + http.StatusPreconditionFailed, + http.StatusRequestEntityTooLarge, + http.StatusRequestURITooLong, + http.StatusUnsupportedMediaType, + http.StatusRequestedRangeNotSatisfiable, + http.StatusExpectationFailed, + http.StatusTeapot, + http.StatusMisdirectedRequest, + http.StatusUnprocessableEntity, + http.StatusLocked, + http.StatusFailedDependency, + http.StatusTooEarly, + http.StatusUpgradeRequired, + http.StatusPreconditionRequired, + http.StatusTooManyRequests, + http.StatusRequestHeaderFieldsTooLarge, + http.StatusUnavailableForLegalReasons, + http.StatusInternalServerError, + http.StatusNotImplemented, + http.StatusBadGateway, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout, + http.StatusHTTPVersionNotSupported, + http.StatusVariantAlsoNegotiates, + http.StatusInsufficientStorage, + http.StatusLoopDetected, + http.StatusNotExtended, + http.StatusNetworkAuthenticationRequired, + } + httpRoute = []string{ + "/{namespace}/{repository}/@{snapshot}/*", + "/api/ui/query/timeseries", + "/api/v1/synthetics/private-locations/tests", + "/api/ui/frontend_telemetry/metrics", + "/api/ui/query/rapid-scalar", + "/api/v1/validate", + "/config", + "/v8/artifacts/{id}", + "/api/ui/feature-flags/get-active-feature-flags", + "/api/v1/synthetics/private-locations/tests/{publicID}/results", + "/api/v1/distribution_points", + "/api//logs-analytics/", + "/internal/snapshot/pull", + "/*", + "/api/unstable/apm/entities", + "/v2/", + "/dashboard/shared_widget_update/{id}/{widget_id}", + "/authn", + "/api/v1/synthetics/tests/updates/", + "/authz", + "/v3/elements/search", + "/api/ui/event-platform/logs/facets", + "/vault/agent/", + "/internal/snapshot/push", + "/api/v2/dashboard/presence/{resourceId}", + "/api/v1/snapshot", + "/api/v1/query", + "/api/v1/series", + "/v8/artifacts/events", + "/api/v1/monitor/", + "/series/batch_query", + "/orgs/{orgId}/analytics/requests", + "/api/v0.1/status", + "/api/v1/synthetics/private-locations/tests//results", + "/api/ui/error-tracking/issues/searches", + "/api/intake/ci/custom_spans", + "/internal/error-tracking/search", + "/v2/{name:(?:(?:(?:[a-zA-Z0-9]", + "/api/v0.1/configurations", + "/api/v2/apm/service_inference", + "/api/v2/git/repository/search_commits", + "/jobs/", + "/api/v2/libraries/tests/services/setting", + "/api/ui/data_streams/map", + "/readiness", + "/api/ui/apm/latency_breakdowns", + "/api/v2/discussions/dashboard/{dashboardID}", + "^dump-request$", + "/api/v2/watchdog/insights/search/", + "/api/ui/apm/versions", + "/probe", + "/api/v2/watchdog/insights/search", + "/api/ui/orchestration/facets/v2", + "/account/login", + "/-/readiness", + "/api/ui/apm/resources", + "/-/liveness", + "/monitor/evaluation_graph", + "/{namespace}/{repository}/@{snapshot}/simple/{project}", + "/watchdoginsights/outliers_query", + "/health/readiness", + "/health/liveness", + "/api/v2/on-prem-management-service/workflow-tasks/dequeue", + "/api/v2/users", + "/api/ui/slack-app/event", + "/token", + "/v2/{name:(?:(?:(?:[a-zA-Z0-9]", + "/watchdoginsights/outliers_resume", + "/_health", + "/api/unstable/coscreen", + "/internal/v0/3rd-party-software-info/query", + "/api/v2/org_configs/", + "/health", + "/watchdoginsights/watchdog_stories_query", + "/api//logs-analytics//", + "/api/intake/llm-obs/v1/trace/spans", + "/internal/ciem/enablementRequirements/{orgId}", + "/api/v2/ddsql/table", + "/monitor/search", + "/api/v2/cases/count", + "/api/ui/apm/live-search", + "/api/ui/orchestration/entities", + "/api/ui/experiments/get-all-experiments", + "/api/ui/event-platform/trace/facets", + "/api/v1/settings/favorite/list", + "/api/ui/team", + "/api/v1/dashboard/", + "/api/v2/query/timeseries", + "/api//watchdog/stories", + "/orgs/{orgId}/analytics/requests/{requestId}", + "/api/v2/team", + "/api/unstable/apm/entities/graph", + "/api/v2/incidents/search", + "/api/ui/support/authenticate", + "/dequeue_job", + "/api/ui/apm/breakdown", + "/static/*", + "/api/unstable/change-stories", + "/v2/{name:(?:(?:(?:[a-zA-Z0-9]", + "/api/v1/logs/views", + "/api/v2/ci/libraries/tests", + "/api/v2/notebook/presence/{resourceId}", + "/api/unstable/restriction_policy/relations/bulk", + "/orgs/{orgId}/scopes", + "/api/v1/security_analytics/activation", + "/api/v2/cases", + "/api/ui/api-monitoring/endpoint", + "/watchdoginsights/log_anomalies_query", + "/api/v1/slo//history", + "/api/ui/api-monitoring/endpoints", + "/api/v1/logs/indexes", + "/orgs/{orgId}/security_analytics/activation", + "/lock", + "/v2/{repo:(?:(?:(?:[a-zA-Z0-9]", + "/api/ui/apm/web/metadata", + "/metric/hosts_and_tags", + "/api/v1/monitor", + "/api/ui/event-platform/rum/facets", + "/favicon.ico", + "/api/ui/event-platform/feed/facets", + "/api/v2/workflows/{workflowId}/instances", + "/watchdoginsights/profiling_query", + "/api/v2/case/presence/{resourceId}", + "/api/v1/metrics/", + "/api//watchdog/story_facets", + "/v1/applications/{appId}", + "/snapshot/view////", + "/fabric-proxy-healthcheck", + "/api/v2/users/", + "/api/v2/current_user/user_team_fave", + "/dashboard/*", + "/api/v1/monitor//validate", + "/api/ui/query/scalar", + "/api/v2/static-analysis/rulesets/{RulesetName}", + "/api/ui/data_streams/info", + "/api/v2/event-platform/profile/activity", + "/metric/flat_tags_for_metric", + "/api/v2/services/definitions/", + "/api/unstable/databases/hosts", + "^$", + "api/usage/v1/hourly-usage.{ext}", + "/internal/api/v2/devflow/run-workflow", + "/api/ui/apm/host_groups", + "/api/v2/ci/tests/skippable", + "/api/v2/restriction_policy/", + "/status/index", + "/api/v1/logs/default-views", + "/api/v2/cases/aggregate", + "/dash/set_preference", + "/internal/catalog/v1/namespaces/*", + "/computeMetadata/v1/instance/service-accounts/{serviceAccount:[^/]+}/token", + "/metric/metric_metadata", + "/orgs/{orgId}/security_analytics/activation/{product}/pricing_model", + "/api/unstable/databases/recommendations/aggregated", + "/api/ui/event-platform/audit/facets", + "/api/v1/restriction_policy/{resourceID}", + "/api/ui/event-platform/query/field", + "/api/v1/monitor/validate", + "/metric/contexts_for_metrics", + "/graphql", + "/{version}/meta-data/iam/security-credentials/{role:.+}", + "/orgs/{orgId}/indexes", + "/api/v2/workflows//instances/", + "/api/v1/monitor//search_groups", + "/v1/applications/{appId}/streaming", + "/check//contexts", + "/api/v2/process/summary", + "/{version}/meta-data/iam/security-credentials/", + "/api/ui/flows/scalar", + "/api/v2/catalog/entity", + "/api/ui/integration/jira/webhook/{org_uuid}", + "/api/v1/apps/:app/inputs", + "/internal/dashboards/search/_index", + "/api/v1/apps/:app/inputs/:inputId", + "/api/v2/services/definitions", + "/api/v2/embed_query/timeseries", + "/api/ui/orchestration/manifest_history", + "/api/ui/monitor/search_all_counts", + "/api/ui/apm/latest_deployments", + "/", + "/internal/compliance/frameworks/{orgId}", + "/api/v2/ci/pipeline/tags", + "/api/unstable/public_dashboard_widget_query", + "/api/v2/logs/events/search", + "/api/unstable/datasets", + "/internal/event-platform/query/composite", + "/api/ui/trace/{traceID}", + "/api/unstable/accupath/entities/graph/{entityType}/*", + "^click$", + "/api/v1/monitor/groups/search", + "/api/v2/static-analysis/config/client", + "/api/v2/incidents-incident/presence/{resourceId}", + "/api/v2/metrics//volumes", + "/api/v1/dashboard_search", + "/api//hosts", + "/v2/{repo:(?:(?:(?:[a-zA-Z0-9]", + "/api/v2/roles", + "/api/ui/event-platform/{track}/standard-attributes/rules", + "/api/v2/ci/pipeline/metrics", + "/api/v2/host_map/nodes_by_group", + "/api//databases/hosts", + "/api/ui/apm/widget_stats_histogram", + "/api//logs-queries/list", + "/api/ui/dashboards//payload_version_history", + "/api/unstable/on-call/teams", + "/api/v1/tags/hosts/", + "/api/ui/security/asm/services", + "/api/v2/synthetics/tests//results", + "/api/ui/data_streams/alerts", + "/api/v2/workflows/{workflowId}/instances/{instanceId}", + "/api/v2/incident/presence/{resourceId}", + "/mail/sendgrid_incoming", + "/v2/{name:(?:(?:(?:[a-zA-Z0-9]", + "/api/v1/legacy_current_user", + "/unauthenticated_probe", + "/api/ui/services/catalog", + "/v3/elements/update", + "/api/unstable/obs-pipelines/quotas/{pipelineId}/buckets", + "/api/v2/services/catalog/product_areas", + "/computeMetadata/v1/instance/service-accounts/{serviceAccount:[^/]+}/", + "/api/v2/apm/services/stats", + "/api/v1/intake_monitoring", + "/series/proc_key_query", + "/api/v2/incidents-timeline/presence/{resourceId}", + "/lock/", + "/api/ui/apm/service/graph_real_time", + "/api/ui/error-tracking/issues/field-translations", + "/internal/security-graph/shards/{orgID}", + "/api//events/", + "/autoscaling/recommendation", + "/api/ui/event-platform/databasequery/facets", + "/api/unstable/databases/monitors", + "/api/unstable/apm/entities/ranked_entity_id_tags", + "/api/unstable/cost/tags", + "/api/intake/aws/securitylake", + "/tile/validate", + "/api/unstable/datasets/", + "/api/ui/monitor/search_all", + "/api/v1/synthetics/tests/uptimes", + "/api/ui/metric/search", + "/api/v2/notebook/multiplayer/{resourceId}", + "/api/v2/ci/pipeline", + "/api/v1/notebooks/", + "/api/v2/host_map/filters_and_groups", + "/monitor/validate_text", + "/api/ui/apm/has_traces", + "/api/ui/apm/dependency_stats_tree", + "/api/v1/rum/projects", + "/api/unstable/databases/recommendations", + "/api/v1/check_run", + "/api/v2/scorecard/grouped-outcomes", + "/integration/slack/inbound-event", + "/api/v2/intake_monitoring", + "/api/unstable/on-call/pages", + "/api/ui/event-platform/{track}/livetail/token", + "/api/ui/app_installations", + "/internal/event-platform/query/composite/resume", + "/api/v2/services/integrations/pagerduty", + "/api/v1/monitor/search", + "/v1/applications", + "/api/ui/api-monitoring/endpoints/count", + "/liveness", + "/dashboard/template-variables/values", + "/v1/version", + "/api/v2/workflows", + "/api/v1/notebooks", + "/metric/tag_keys_for_metric", + "/api/unstable/security/appsec/vm/activation", + "/computeMetadata/v1/project/project-id", + "/api/v1/synthetics/tests//locations", + "/api/ui/slo/correction_windows", + "/files/{ref}/{filename}", + "/api/unstable/datasets/{datasetUUID}", + "/api/v1/integration/webhooks/configuration/webhooks/", + "/process/tags/v2", + "/api/v2/monitor//downtime_matches", + "/apm/*", + "/api/v2/security_monitoring/rules", + `/sb/{string_1:[^/?()[\]]+}`, + "^basic-auth$", + "/v3/elements", + "/utils/healthcheck", + "/api/v2/scorecard/outcomes/batch", + "/metadata/identity/oauth2/token", + "/api/ui/apm/web/metadata/{serviceName}", + "/api/v1/synthetics/tests/search", + "/api/v1/logs/rate_limited_indexes", + "/api//node_map/nodes_by_group", + "/api/unstable/symdb-api/scopes/search", + "/api/v2/catalog/relation", + "/monitor/search_counts", + "/api/unstable/stegadography/cache", + "/query", + "/api/ui/event-platform/signal/facets", + "/api/beta/sketches", + "^simple-variable$", + "/internal/api/repository/{owner}/{repository}/history", + "/api/v2/current_user", + "/connectors/{connector}/status", + "/v1/health", + "/api/ui/error-tracking/issues/field-values", + "/api/unstable/symdb-api/services/metadata", + "/api/ui/span_links/{traceID}", + "/internal/domains/{DomainName}/routegroups/{RouteGroupName}", + "/v1/orgs/{orgId}/logs-queries/list", + "/api/v2/permissions", + "/api/v2/workflows//instances", + "/api/ui/watchdog/explains/influential-tags/ff", + "/apm/home", + "/cost/tags/pod/{namespace}/{pod_name}", + "/api/v2/integration/salesforce_marketing_cloud/event", + "/api/ui/cost/settings", + "^click-trap$", + "/api/v2/watchdog-story/presence/{resourceId}", + "/api/v2/reporting/schedule//", + "/api/v2/static-analysis/default-rulesets/{Language}", + "/indicators", + "/api/ui/cost/multisource", + "/internal/api/v2/spark_jobs/{spark_job_id}", + "/api/v2/scorecard/rules", + "/api/v2/roles/{roleUuid}", + "/internal/ci/gitlab/pipeline/*", + "/api/v2/security_monitoring/configuration/notification_rules", + "/api/ui/event-platform/query/field-value", + "/api/v2/synthetics/private-locations/config", + "/api/v2/test/libraries/test-management/tests", + "/api/v1/slo", + "/cluster_configuration/", + "/api/v1/slo/search", + "/api/ui/error-tracking/config", + "/api/ui/event-platform/profile/facets", + "/internal/api/v2/concurrency_locks", + "/api/v2/rum/funnel", + "/api/v0/synthetics/tests//status", + "/catalog/v1/namespaces", + "/api/unstable/restriction_policy/principal/", + "/api/v2/services/integrations/pagerduty/oncalls", + "/api/v1/synthetics/tests", + "/api/v1/monitor/tags", + "/internal/notebooks/search/_index", + "/orgs/{orgId}/cloud_security_management/resource_filters", + "/api/v1/integration", + "^cors-protected-resource$", + "/connectors/{connector}", + "/api/unstable/ui/trace/{traceID}", + "/alert/query_value/", + "/api/v2/query/scalar", + "/metric/histogram", + "/api/ui/resource_catalog/list", + "/v2/orgs/{orgId}/{trackType}/events/search", + "/api/ui/remote_config/*", + "/api/v2/security_monitoring/rules/{ruleId}", + "/api/v2/api_keys/", + "^status$", + "/api/v2/source-code-integration/enrich-stack-trace", + "/monitor/validate_param", + "/orgs/{orgId}/v2/security_analytics/rules", + "/api/v2/on-prem-management-service/runner/health-check", + "/api/v2/security_monitoring/signals/", + "/event/distrib", + "/internal/ciem/enabledIntegrations/{orgId}", + "/jobs", + "/internal/core/v2/prefixes/{id}", + "/api/v2/apicatalog/endpoints", + "/v2/orgs/{orgId}/vm", + "^sigv4$", + "/oauth2/v1/token", + "/api/v1/synthetics/tests/browser/", + "/api/v1/dashboard/public/", + "^simple-iframe$", + "/api//host_map/node_values", + "/api/v2/services/integrations/pagerduty/incidents", + "/v2/orgs/{orgId}/security_monitoring/configuration/notification_rules", + "/internal/intake/developer-telemetry/count", + "/api/v2/org_connections", + "/api/v1/synthetics/browser/tests//results//steps//screenshot", + "/api/ui/security_monitoring/content_packs", + "/api/unstable/on-call/escalation-policies/{policyUUID}/steps/{policyStepUUID}/escalations", + "/orgs/{orgId}/security_analytics/signals/get_metadata", + "/api/ui/container_images/facets", + "/api/ui/on-call/shifts", + "/api/v2/services/integrations/opsgenie", + "/monitors/*", + "/api/v2/services/integrations/opsgenie/incidents", + "/api//logs/analytics/aggregate", + "/orgs/{orgId}/analytics/requests/validate-search", + "/.well-known/jwks.json", + "/api/v2/events", + "/api/v1/slo/", + "/api/v1/monitor//unmute", + "/*id", + "/api/v1/rum/replay/sessions//views//segments", + "/api/v2/infrastructure/devices", + "/probe_smart_edge", + "/api/ui/event-platform/profilemetrics/facets", + "/api/ui/data_streams/apm_streaming_services", + "/api/v2/ucap/annotations/search-by-file", + "/api/v2/processes", + "/healthz/liveness", + "/api/v2/reporting/schedule/list", + "/catalog/v1/namespaces/{namespace}/tables/{table}/metrics", + "/watchdoginsights/synthetics_search_tests", + "/v2/models/{model_name}/versions/{model_version}/ready", + "/security/*", + "/v1/task/{taskId}", + "/api/v0.1/org", + "/clusters", + "/watchdoginsights/outliers_cancel", + "/logs", + "/api/v1/dashboard/lists", + "/v3/elements/aggregate", + "/api/v1/notebook//comments", + "/api/unstable/apm/tracer_agent_latest_versions", + "/api/ui/event-platform/{track}/org/state", + "/orgs/{orgId}/facets-with-reserved-fields", + "/event/icon/", + "/profiling/api/v1/aggregate", + "/api/ui/event-platform/netflow/facets", + "/api/v2/ci/my-commits", + "/v2/orgs/{orgId}/{trackType}/analytics/aggregate", + "/api/v1/synthetics/tests/", + "/api/v1/synthetics/ci/batch/", + "/api/v1/security_analytics/rules/facet_info", + "/orgs/{orgId}/state", + "/api/ui/apm/live-search/keys", + "/api/v1/events", + "/api/v1/synthetics/tests/poll_results", + "/api/v2/monitor/recommended", + "/api/v2/ucap/annotations/search", + "/api/v2/scorecard/outcomes", + "/internal/csm/onboarding/steps", + "/api/unstable/obs-pipelines/quotas/batch", + "/api/v2/incidents//relationships/integrations", + "/api/ui/notebooks//payload_version_history", + "/api/v2/team//memberships", + "/api/v2/security_monitoring/configuration/security_filters", + "/api/v2/internal/*", + "/api/ui/remote_config/products/live_debugging/probes", + "/series/embed_batch_query", + "/api/ui/error-tracking/issues/facets", + "/api/v2/services/definitions/{service:.*}", + "/api/v1/integrations/tiles/list", + "/api/v2/services/catalog", + "/healthz", + "/api/v1/metadata", + "/api/v2/logs/events", + "/api/v2/bits-ai-investigation/presence/{resourceId}", + "/status", + "/-/health", + "/api/v2/api_keys", + "/api/v2/metrics", + "/api/v1/synthetics/settings", + "/internal/api/ui/prr-survey-relay/surveys/{ServiceName}", + "/v1/info/state", + "/internal/disruptioncrons", + "/internal/hypothesis", + "/api/ui/error-tracking/issues/{issueID}", + "/series/proc_container_query", + "/api/v2/slo/{sloID}/status", + "/v3/entities", + "/account/change_subdomain/", + "^headers$", + "/rum/*", + "/api/:version/jobs/request", + "/api//apm/config/retention-filters", + "/api/v2/monitor/policy", + "/api/v1/role/{roleUuid}/user/{userHandle}", + "/api/ui/billing/vat_required", + "/api/ui/apm/resource", + "/api/v0/synthetics/tests/", + "/api/v2/product_trial_summary", + "/account/oauth2", + "/api/v1/restriction_policy/principal/{principalID}", + "/proc/query", + "/api/v1/insights", + "/intake", + "/profiling/api/v1/profiles//breakdown", + "/api/ui/error-tracking/issues/searches/{searchID}", + "/eee-intake/prod/gitlab", + "/internal/reporting/job/dequeue", + "/api/v2/incidents/", + "/api/v2/users//permissions", + "/api/unstable/security_monitoring/csm_features", + "/api/v2/bits-ai/config/global", + "/api/v2/powerpacks", + "/api/v1/lineage", + "/api/ui/public_dashboard/", + "/account/plan/plan_details", + "/v1/memory", + "/api/v2/incidents//timeline", + "/api/v2/metrics//all-tags", + "/api/unstable/on-call/pages/{pageIdentifier}", + "/v1/task/{taskId}/status", + "/monitor/notifications", + "/api/v2/workflow_instance_sources//instances", + "/account/integration", + "/api/ui/usage/billable/overall", + "/catalog/v1/config", + "/api/v2/security_monitoring/livetail", + "/api//events", + "/api//node_map/node_values", + "/api/v2/application_keys", + "/api/unstable/slo/search/group_by_tag", + "/api/ui/event-platform/appsecspan/facets", + "/api/ui/monitor//evaluation_graph", + "/api/v2/rum/analytics/aggregate", + "/api/v2/rum/applications", + "/api//node_map/filters_and_groups", + "/api/v2/static-analysis-sca/dependencies", + "/api/v1/hosts/totals", + "/api/ui/notebooks/lfg", + "/metrics", + "api/usage/v1/status", + "/api/v2/workflow_instance_sources/{id}/instances", + "/api/ui/ms-teams-app/bot/activity", + "/api/v0.2/stats", + "/internal/api/v2/spark_jobs", + "^scroll$", + "/api/v1/audit/config", + "/api/ui/flows/timeseries", + "/v1/status", + "/healthcheck", + "/monitors/manage", + "/api/unstable/catalog/definition", + "/orgs/{orgId}/security_analytics/rules/{ruleId}", + "/internal/dashboards/search/_bulkindex", + "/api/ui/trace/related_dashboards", + "/api/v2/source-code-integration/code-snippet", + "/synthetics/*", + "/agent_stats/report_failure", + "/api/v1/synthetics/_multilocator/updates", + "/account/saml/assertion", + "/api/v2/notebooks/search", + "/v1/task/{taskId}/results/{bufferId}/{token}", + "/api/v2/rum/resource", + "/api/v2/rum/events", + "/api/v2/events/search", + "/api/ui/event-platform/citest/facets", + "/api/ui/cost/aws_accounts", + "/api/v2/incidents", + "/api/ui/debugger/probe-statuses", + "/api/ui/event-platform/cipipeline/facets", + "/api/v2/synthetics/tests//results/", + "/api/v1/security_analytics/rules/facets", + "/screen/setup_notify_change", + "/api/v2/metrics/{metricName}/assets", + "/orgs/{orgId}/security_analytics/rules/facet_info", + "^assert-element-content$", + "^user-agent$", + "/api/v2/saml_configurations/", + "/signup/process", + "/api/ui/metrics/summary/list", + "/api/v2/integration/gcp/accounts", + "/api/v2/logs/config/custom-destinations/", + "/api/v2/embed_query/scalar", + "/api/v2/dora/settings", + "/api/v2/apicatalog/tags", + "/api/v1/logs/views/", + "/api/v2/host_map/node_names", + "/v1/announcement/{node_id}", + "/api/unstable/llm-obs/v2/clusters", + "/v1/service/{type}/{pool}", + "^input$", + "/internal/intake/developer-telemetry/distribution", + "/api/v2/dora/deployment", + "/api/unstable/monitor/on_missing_data_default_details", + "/api/v2/rum/replay/sessions/{sessionID}/watchers", + "^authenticated$", + "/functions", + "^assert-text-nowhere$", + "^iframeception$", + "^small-device$", + "/api/v2/{trackType}", + "/v2/_scanning/", + "^assert-text-present$", + "^iframe-in-popup$", + "/api/v1/synthetics/config", + "^prototype$", + "^cors$", + "/api/v1/security_analytics/rules/{ruleId}", + "/api/v1/synthetics/tests/api/", + "/gomod/{ref}/*", + "^hover$", + "^redirect-auth$", + "/api/v1/synthetics/variables", + "/v2/_scanning/{name:(?:(?:(?:[a-zA-Z0-9]", + "/v2/orgs/{orgId}/security_monitoring/configuration/security_filters", + "/process/get_token", + "/v1/statement/executing/{queryId}/{slug}/{token}", + "^select-option$", + "/api/v2/pets/{petID}", + "/monitors/{int_1:[0-9]+}/edit", + "/api/unstable/ddsql/custom_output", + "/api/v2/spreadsheets/{spreadsheetID}", + "/*repository_path/git-upload-pack", + "/notebook/*", + "/api/unstable/trace/{traceID}", + "/api/ui/app_listings", + "/api/ui/remote_config/management/org_config", + "/api/v1/security_analytics/rules/tags", + "/api/v1/rum/projects/", + "/account/saml/assertion/id/", + "/api/unstable/on-call/teams/{teamUUID}/on-call", + "/api/v2/apm/services", + "/internal/core/v2/routetables/{id}", + "/api/ui/container_images", + "/api/ui/security/appsec/flaggedips/{from}/{to}", + "/api/v2/incidents/config/rules", + "/orgs/{orgId}/facets", + "/api/v2/flamegraph", + "/api/v2/oauth2/.well-known/sites", + "/orgs/{orgId}/v2/security_analytics/livetail", + "/api//logs/config/archives/", + "/internal/security-graph/shards/mappings", + "/api/ui/team-list", + "fakecdnoutage", + "/api/:version/jobs/:id", + "/api/ui/cost/lite", + "/api/v2/internal/admin/org_access_request_meta/", + "/api/unstable/integration/aws/accounts", + "/internal/core/v2/pools/{id}/summary", + "/api/v2/metrics//tags", + "/monitor/bulk_delete", + "/orgs/{orgId}/security_analytics/rules", + "/v1/task/{taskId}/results/{bufferId}/{token}/acknowledge", + "^upload-file$", + "/api/ui/event-platform/cpfinding/facets", + "/account/forgot_password", + "/api/v2/rum/replay/playlists/{playlistID}", + "/internal/catalog/v1/namespaces", + "/integration/github/private-apps/hostnames", + "/api/v2/rum/resource/token", + "/api/v1/synthetics/tests/browser//results", + "/api/v1/synthetics/tests//results", + `/orchestration/{string_1:[^/?()[\]]+}/{string_2:[^/?()[\]]+}`, + "/api//observability_pipelines/v2/graphql", + "/api/v1/monitor//related_dashboards", + `/monitors/create/{string_1:[^/?()[\]]+}`, + "/xds/validate-config", + "/api/ui/data_streams/clusters", + "/v2/orgs/{orgId}/logs/config/custom-destination/{customDestinationId}", + "/api/ui/remote_config/products/asm/waf/exclusion_filters", + "/api/v2/py/pets/{pet_id}", + "/api/v2/security_monitoring/configuration/suppressions/{suppressionId}", + "/api/v2/rum/events/search", + "/api/unstable/smoke-test-go-classic-http/five", + "/api/unstable/smoke-test-go-classic-http/gzip", + "/api/unstable/smoke-test-go-classic-http/vault/secret", + "/api/unstable/smoke-test-go-classic-http/consul/value", + "/api/unstable/smoke-test-go-classic-http/experiment/status", + "/api/unstable/smoke-test-go-classic-http/panic", + "/metric/explorer", + "/api/unstable/smoke-test-go-classic-http/four", + "/api/unstable/smoke-test-go-classic-http/tap", + "/api/v1/security_analytics/resource_type_mapping", + "/api/ui/flows/list", + "/orgs/{orgId}/security_analytics/activation/{product}/enabled_log_sources", + "/api/v2/rum/replay/sessions//retention", + "/api/ui/resource_catalog/facet_resources", + "/v2/orgs/{orgId}/security_monitoring/cloud_workload_security/agent_rules/csm_features", + "/api/v1/notebooks//cells/", + "/api//tag_keys", + "/api/v2/apm/primary_tags/list", + "/api/ui/billing/accessible_features", + "/api/ui/ip-lookup/get-info", + "/api/v2/rum/replay/sessions/{sessionID}/watches", + "/api/v2/spans/events", + "/api/v2/app-builder/apps/{appId}", + "/error-tracking", + "/api/v2/team/{team_id}/memberships", + "/api/v2/ci/pipelines/events/search", + "/locks", + "/api/v1/org", + "/api/v2/connection/connections", + "/orgs/{orgId}/security_analytics/rules/tags", + "/api/v2/ddsql/user/table", + "/api/v1/integration/azure", + "/api/ui/event-platform/llmobs/facets", + "/logs/", + "/api/ui/remote_config/products/live_debugging/probes/log/{probeID}", + "/api/v1/check_github", + "/security/appsec/*", + "/api/ui/metrics/summary/facet_info", + "/api/v2/internal/admin/get_support_org_list", + "/api/ui/event-platform/ccm/facets", + "/api/v1/org/", + "/api/v1/widget/share", + "/v1/statement/queued/{queryId}/{slug}/{token}", + "/api/ui/remote_config/products/fleet/agents/count", + "/api/ui/resource-catalog-api/resources", + "/api/v2/reference-tables/{TableName}/rows", + "/api/v1/monitor/can_delete", + "/api/v2/spreadsheets", + "/debug/vars", + "/api/:version/jobs/:id/artifacts", + "/api/v2/infrastructure/facets", + "/api//event-platform//processors/samples", + "/api/v1/downtime", + "/api/v1/integration/gcp", + "/api/v1/slo/correction/", + "/profiling/api/v1/profiles//timeline", + "/api/ui/flows/map", + "/api/v1/service_dependencies/*", + "/api/v1/timeline", + "/api/unstable/error-tracking-codegen/*", + "/api/v2/git/repository/packfile", + "/api/v2/actions-datastores/{datastoreId}/items", + "/api/v2/integration/aws/accounts/{aws_account_config_id}", + "/oauth2/v1/keys", + "/api/ui/error-tracking/issues/field-values/{fieldValuesID}", + "/api/ui/remote_config/products/asm/waf/policies", + "/api/v2/agentless_scanning/accounts/azure", + "/api/ui/security_monitoring/rules/dependents", + "/api//node_map/node_names", + "/account/saml/metadata.xml", + "/metric/distribution/summary_aggr", + "/api/v2/current_user/application_keys", + "/api/v1/synthetics/private-locations/tests/files", + "/api/ui/usage/relevant-summary", + "/api/ui/error-tracking/issues/{issueID}/suspect-commit", + "/api/v2/incidents/config/user-defined-roles", + "/api/v2/incidents/{IncidentUUID}/rule-execution-states", + "/java-bazel/{ref}/{name}/{filename}", + "/api/v2/saml_configurations", + "/intake/", + "/account/saml/config//sp_metadata.xml", + "/api/ui/usage/ddm-summary", + "/api/v2/ide/product-availability", + "/api/v2/logs/historical_indexes", + "/api/unstable/on-call/schedules/{scheduleUUID}/on-call", + "/api/v1/integration/pagerduty/configuration/services/", + "api/usage/v1/relevant-usage.json", + "/api/ui/usage/relevant-trends", + "/api/ui/usage/summary", + "/api/ui/usage/trends", + "/api/v2/users//memberships", + "/orgs/{orgId}/security_analytics/rules/dependents", + "/api/ui/error-tracking/issues/{issueID}/activity-timeline", + "/oauth2/v1/.well-known/openid-configuration", + "/api/v2/org", + "/api/:version/jobs/:id/trace", + "/api/unstable/sensitive-data-scanner/groups", + "/api/v2/saml_configurations/idp_metadata", + "/api/unstable/cost/tag_keys", + "/v2/orgs/{orgId}/external-archives", + "/api/unstable/metric//tag_cardinalities", + "/internal/api/v2/concurrency_locks/{concurrency_lock_definition_id}/{workflow_id}", + "/api/ui/monitor/evaluation_preview", + "/api/v1/synthetics/private-locations", + "/api/v2/static-analysis/analysis/diff-aware", + "/api/unstable/error-tracking-codegen/ai-suggestions", + "/api/ui/app_listings/", + "/api/v1/breakdown", + "/api/ui/remote_config/products/live_debugging/probes/log", + "/api/v1/dashboard", + "/api/v2/incidents/config/types", + "/graph/embed", + "/orgs/{orgId}/security_analytics/rules/facets", + "/api/ui/orchestration/manifest_content", + "/api/v2/consul/value", + "/api/v2/ide/services/search", + "/api/v2/vault/secret", + "/account/login/by_email", + "/api/ui/usage/ddm-trends", + "/api/v2/exception", + "/api/unstable/remote_config/products/asm/activation", + "/api/v2/experiment/status", + "/v2/_dd/operations/replicate", + "/api/v1/correlations/", + "/internal/trino-ui/{cluster}/cluster_details_json", + "/api/unstable/profiles/list", + "/api/v2/app-builder/apps", + "/api/v2/agentless_scanning/setup_feedback/accounts/aws", + "/api/v2/identity_providers", + "/api/v2/cloud_security_management/resource_filters", + "/api/ui/event-platform/synthetics/facets", + "/api/v2/hamr", + "/api/v2/agentless_scanning/accounts/aws", + "/api/ui/event-platform/query/composite-list", + "/api/v2/users//orgs", + "/api/ui/security_monitoring/configuration/suppressions/rules/{ruleId}", + "/internal/api/v2/spark_jobs/{spark_job_id}/{retry_attempt}/state", + "/api/v2/quality-gates/evaluate", + "/source/list", + "/api/ui/siem-historical-detections/jobs/facet_info", + "/api/v1/trial", + "/overview/system_tiles", + "/api/v1/screen/integration/", + "/api/v1/downtime/search", + "/security", + "/internal/error-tracking/incoming", + "/v2/orgs/{orgId}/logs/config/archives/{externalId}", + "/api/unstable/team", + "/api/v2/internal/admin/switch_handle_post", + "/notebook", + "/v3/orgs/{orgId}/{trackType}/pipelines", + "/api/ui/data_streams/schemas", + "/integration/slack/configuration", + "/api/ui/security/appsec/responses/entities", + "/metric/distribution/list_summaries", + "/api/v1/downtime/cancel/by_scope", + "/api/unstable/stegadography/cache/{id}", + "/account/login/id/", + "/api/v1/health", + "/api/v2/spreadsheets/{spreadsheetID}/table-sheets/{sheetID}", + "/api/v2/static-analysis/repositories/counts/analysis", + "/api/v2/reference-tables", + "/api/v2/roles/{roleUuid}/permissions", + "/api/v1/synthetics/browser/tests/", + "/api/v2/incidents/config/org/settings/", + "/api/v2/roles/{roleUuid}/users", + "/api/v2/downtime", + "/api/v2/rum/replay/playlists", + "/api/v2/incidents/config/user-defined-fields", + "/api/v2/incidents//responders", + "/api/ui/twilio/voice/events", + "api/usage/v1/active-usage-types.json", + "/api/v2/audit/events", + "/api/v2/identity_providers//users", + "/api/v1/graph/embed", + "/api/v2/incidents/config/integrations//workflows", + "/api/v2/logs/views/mark-as-viewed", + "/api/ui/billing/last-updated", + "/signup_corp", + "/integration/github/private-apps/enrich-link", + "None", + "/api/v2/connection/integrations", + "/internal/doggo/search", + "/api/v2/source-code-integration/repositories-v2", + "/api/ui/billing/org/is-super", + "/api/v2/cases/projects", + "/api/v2/source-code-integration/code-owners", + "/api/v2/spans/events/search", + "/.well-known/apollo/server-health", + "/api/v2/on_prem_runners", + "/get_org_billing_data", + "/api/ui/product-catalog/be/ddm/product", + "/api/ui/product-catalog/bp/billing-dimension", + "/api/ui/product-catalog/rq/usage_attribution", + "/api/ui/product-catalog/be/billing-dimension", + "/api/ui/product-catalog/be/category", + "/api/ui/product-catalog/bp/percent-based", + "/api/v1/synthetics/browser/subtests//parents", + "/api/v2/authn_mappings/", + "/api/v2/on-call/presence/{resourceId}", + "/locks/delete", + "/api/v2/metrics//estimate", + "/api/v1/dashboard/recommendations_load_event//", + "/api/:version/runners/verify", + "/api/ui/integration/aws/integrationissues/account", + "/api/unstable/csm/onboarding/agents/count", + "/api/unstable/csm/onboarding/agents", + "/api/unstable/csm/onboarding/agents/facets", + "/api/v1/synthetics/browser/tests//results//artifacts", + "/api/v2/workflow_actions", + "/api/v2/apicatalog/facet/{facet}", + "/api/ui/csm/onboarding/agents/count", + "/api/ui/resource-catalog-api/distinct", + "/organization-settings/*", + "/api/v2/rum/replay/sessions//metadata", + "/api/ui/spans/custom-metrics", + "/services", + "/api/ui/obs-pipelines/pipelines/{pipelineId}", + "/api/v1/compliance_monitoring/findings/rule_based_view", + "/api/v2/static-analysis/repositories/products-enabled", + "/internal/cit/pr-comment", + "/v1/statement", + "/api/ui/integration/aws/integrationissues/status", + "/api/v2/py/pets", + "/process/agent_hosts", + "/api/unstable/smoke-test-go-classic-http/smoketest/grpc", + "/-/healthy", + "/api/unstable/smoke-test-go-classic-http-dest/smoketest/grpc", + "/api/unstable/smoke-test-go-classic-http/paginated/number-size", + "/api/unstable/smoke-test-go-classic-http/paginated/cursor", + "/internal/slack/event", + "/startup", + "/api/ui/data_streams/lag_metrics", + "/api/unstable/smoke-test-go-classic-http/paginated/offset-limit", + "/api/v1/synthetics/settings/default_locations", + "/api/v2/pets", + "/v2/orgs/{orgId}/security_monitoring/configuration/suppressions/rules/{ruleId}", + "/api/v2/actions-datastores/{datastoreId}", + "/api/unstable/on-prem-management-service/workflow-tasks/dequeue", + "/api/v1/search", + "/api/:version/job", + "/reports/v2/agents", + "/api/ui/ide/profiles/analytics", + "/api/ui/metrics/summary/export", + "/api/v2/paginated/cursor_limit", + "/api/v2/paginated/offset_limit", + "/api/ui/obs-pipelines/pipelines/{pipelineId}/relationships/draft", + "/api/v2/cloud_security_management/iac_remediation/code_location/finding", + "/api/v2/response_test/five", + "/api/v1/metrics", + "/api/v2/response_test/four", + "/api/v1/slo//corrections", + "/api/v2/paginated/number_size", + "/api/unstable/databases/recommendations/tags", + "/api/v2/services/integrations/opsgenie/oncalls", + "/api/v2/integration/aws/accounts", + "/u", + "/api/ui/security/appsec/responses/integrations", + "/api/v1/synthetics/tests/trigger/ci", + "/internal/reporting/job/heartbeat", + "/api/v1/integration/aws", + "/api/v2/incidents/incident_roles/reserved_roles", + "/downtime/monitors/match", + "/-/ready", + "/api/v1/security_analytics/rules", + "/v1/bundles/general", + "/api/ui/integrations//accounts", + "/api/ui/slo/summary_widget_query", + "/api/ui/workflows/", + "/api/unstable/data_security/summary", + "/api/v2/change-tracking/service_edges", + "/internal/v1/events", + "/api/ui/event-platform/secruntime/facets", + "/ticino/agent/", + "/api/unstable/cost/tag_keys/", + "/api/ui/apm/default_env_setting", + "/api/ui/security/appsec/responses/safeguards", + "/internal/gitlab/*", + "/api/intake/llm-obs/v1/eval-metric", + "/api/ui/remote_config/products/asm/waf/rules", + "/api/v2/workflow_actions/", + "^email_ses$", + "/api/v1/notebooks//cells", + "/api/v1/slo/saved_view/search", + "/jobs/spark_config", + "/api/ui/csm/onboarding/agents/heartbeats", + "/api/ui/remote_config/products/fleet/agents", + "/gateway/backend/all", + "/v1/task/{taskId}/results/{bufferId}", + "/api//apm/pipelines", + "/api/v2/rum/sankey", + "/api/unstable/cost/tag_groups", + "/api/v2/users/{user_id}/memberships", + "/api/v2/logs/config/custom-destinations", + "/api/v1/settings/favorite", + "/api/v2/event-correlation/rules", + "/api/v1/graph/snapshot", + "/api/v2/ddsql/user/csv", + "/api/v2/source-code-integration/get-file-link", + "/api/unstable/on-call/pages/facets", + "/api/ui/ide/profiles/flamegraph", + "/api/v2/metrics//active-configurations", + "/api/ui/data_streams/service_summary", + "/api/v1/inventories/taxonomy", + "/_internal/health", + "/api/v2/containers", + "/ready", + "/api/ui/apm/operation_names", + "/api/v1/logs/configuration/indexes", + "/orgs/{orgId}/integrations", + "/v1/issuer/sycamore/token", + "/api/v2/notifications/handles", + "/api/v2/workflow_templates", + "/api/v1/slo/preview_history", + "/event/explorer", + "/api/v1/service_dependencies", + "/infrastructure", + "/api/v2/static-analysis/secrets/rules", + "/v2/_scanning/{name:(?:(?:(?:[a-zA-Z0-9]", + "/orgs/{orgId}/security_analytics/default_rules", + "/api/ui/apm/host_group_keys", + "/api/ui/resource_catalog/list/group", + "/api/v1/downtime/", + "/api/v2/audit/events/search", + "/internal/v2/telemetry-archive/api/orgs/{orgID}/analytics/requests", + "/api/v1/dash/integration/", + "/gateway", + "/account/not_my_account", + "/api/v2/source-code-integration/repo-ids/search", + "/api/v2/tags/enrichment/{rulesetId}", + "/api//watchdog/stories/", + "/api/ui/integration/aws/metric_streams_config/{aws_account_config_id}", + "/api/ui/apps/categories", + "/api/ui/slo/search/tag_keys", + "/api/ui/workflows/{workflowId}", + "/api/unstable/data_security/resources/csv", + "/account/login/recaptcha", + "/api/ui/signup/event", + "/api/unstable/data_security/resources", + "/api/unstable/query-prediction/predict", + "/api/v1/synthetics/tests/fast", + "/api/v2/series", + "/process", + "/api//usage/hourly-attribution", + "/api/unstable/databases/datamodels/query", + "/kubernetes_jobs/", + "/v2/orgs/{orgId}/historical-indexes", + "/api/:version/projects/:id", + "/api/v2/security_monitoring/signals/search", + "/api/v1/logs/filters", + "/internal/csm/onboarding/capabilities", + "^create-element-with-user-provided-id$", + "/api/ui/reporting/recurrence/list", + "/specs//trigger", + } +) + +var ( + once sync.Once + testVector []SamplingKey +) + +func initTestVector() { + once.Do(func() { + testVector = make([]SamplingKey, len(httpMethods)*len(httpRoute)*len(httpStatusCodes)) + var mi, ri, si int + for i := range testVector { + testVector[i] = SamplingKey{ + Method: httpMethods[mi], + Route: httpRoute[ri], + StatusCode: httpStatusCodes[si], + } + if si = (si + 1) % len(httpStatusCodes); si == 0 { + if ri = (ri + 1) % len(httpRoute); ri == 0 { + mi++ + } + } + } + + // Shuffle the order of the key space so it's random, but use a constant-seed RNG so that all + // runs are equal (useful in benchmarks). + rand := rand.New(rand.NewSource(1337)) + rand.Shuffle(len(testVector), func(i int, j int) { testVector[i], testVector[j] = testVector[j], testVector[i] }) + }) +} diff --git a/appsec/config.go b/appsec/config.go index 3cfed5b..9810d27 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -13,6 +13,7 @@ import ( "unicode" "unicode/utf8" + "github.com/DataDog/appsec-internal-go/apisec" "github.com/DataDog/appsec-internal-go/log" ) @@ -20,8 +21,6 @@ import ( const ( // EnvAPISecEnabled is the env var used to enable API Security EnvAPISecEnabled = "DD_API_SECURITY_ENABLED" - // EnvAPISecSampleRate is the env var used to set the sampling rate of API Security schema extraction - EnvAPISecSampleRate = "DD_API_SECURITY_REQUEST_SAMPLE_RATE" // EnvObfuscatorKey is the env var used to provide the WAF key obfuscation regexp EnvObfuscatorKey = "DD_APPSEC_OBFUSCATION_PARAMETER_KEY_REGEXP" // EnvObfuscatorValue is the env var used to provide the WAF value obfuscation regexp @@ -50,12 +49,11 @@ const ( DefaultTraceRate uint = 100 // up to 100 appsec traces/s ) -// APISecConfig holds the configuration for API Security schemas reporting -// It is used to enabled/disable the feature as well as to configure the rate -// at which schemas get reported, +// APISecConfig holds the configuration for API Security schemas reporting. +// It is used to enabled/disable the feature. type APISecConfig struct { - Enabled bool - SampleRate float64 + Enabled bool + Sampler apisec.Sampler } // ObfuscatorConfig wraps the key and value regexp to be passed to the WAF to perform obfuscation. @@ -64,27 +62,26 @@ type ObfuscatorConfig struct { ValueRegex string } +type APISecOption func(*APISecConfig) + // NewAPISecConfig creates and returns a new API Security configuration by reading the env -func NewAPISecConfig() APISecConfig { - return APISecConfig{ - Enabled: boolEnv(EnvAPISecEnabled, true), - SampleRate: readAPISecuritySampleRate(), +func NewAPISecConfig(opts ...APISecOption) APISecConfig { + cfg := APISecConfig{ + Enabled: boolEnv(EnvAPISecEnabled, true), + Sampler: apisec.NewSampler(), } + for _, opt := range opts { + opt(&cfg) + } + return cfg } -func readAPISecuritySampleRate() float64 { - value := os.Getenv(EnvAPISecSampleRate) - rate, err := strconv.ParseFloat(value, 64) - if err != nil { - logEnvVarParsingError(EnvAPISecSampleRate, value, err, DefaultAPISecSampleRate) - return DefaultAPISecSampleRate + +// WithAPISecSampler sets the sampler for the API Security configuration. This is useful for testing +// purposes. +func WithAPISecSampler(sampler apisec.Sampler) APISecOption { + return func(c *APISecConfig) { + c.Sampler = sampler } - // Clamp the value so that 0.0 <= rate <= 1.0 - if rate < 0. { - rate = 0. - } else if rate > 1. { - rate = 1. - } - return rate } // RASPEnabled returns true if RASP functionalities are enabled through the env, or if DD_APPSEC_RASP_ENABLED diff --git a/appsec/config_test.go b/appsec/config_test.go index 660508e..76490eb 100644 --- a/appsec/config_test.go +++ b/appsec/config_test.go @@ -15,72 +15,44 @@ import ( func TestAPISecConfig(t *testing.T) { for _, tc := range []struct { - name string - enabledVar string - sampleRateVar string - enabled bool - sampleRate float64 + name string + enabledVar string + enabled bool }{ { name: "disabled", enabledVar: "false", - sampleRate: DefaultAPISecSampleRate, }, { name: "disabled", enabledVar: "0", - sampleRate: DefaultAPISecSampleRate, }, { - name: "enabled", - enabled: true, - sampleRate: DefaultAPISecSampleRate, + name: "enabled", + enabled: true, }, { name: "enabled", enabledVar: "true", enabled: true, - sampleRate: DefaultAPISecSampleRate, }, { name: "enabled", enabledVar: "1", enabled: true, - sampleRate: DefaultAPISecSampleRate, }, { name: "enabled", enabledVar: "weirdvalue", enabled: true, - sampleRate: DefaultAPISecSampleRate, - }, - { - name: "sampleRate 1.0", - sampleRateVar: "1.0", - enabled: true, - sampleRate: 1., - }, - { - name: "sampleRate 50.0", - sampleRateVar: "50.0", - enabled: true, - sampleRate: 1., - }, - { - name: "sampleRate -50.0", - sampleRateVar: "-50.0", - enabled: true, - sampleRate: 0., }, } { t.Run(tc.name, func(t *testing.T) { if len(tc.enabledVar) > 0 { t.Setenv(EnvAPISecEnabled, tc.enabledVar) } - t.Setenv(EnvAPISecSampleRate, tc.sampleRateVar) cfg := NewAPISecConfig() require.Equal(t, tc.enabled, cfg.Enabled) - require.Equal(t, tc.sampleRate, cfg.SampleRate) }) } } diff --git a/go.mod b/go.mod index a6a8845..0660d22 100644 --- a/go.mod +++ b/go.mod @@ -1,9 +1,9 @@ module github.com/DataDog/appsec-internal-go -go 1.22 +go 1.23.0 require ( - github.com/stretchr/testify v1.8.4 + github.com/stretchr/testify v1.10.0 go.uber.org/goleak v1.3.0 ) diff --git a/go.sum b/go.sum index b641b0c..7dbe38a 100644 --- a/go.sum +++ b/go.sum @@ -7,8 +7,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From e5b7e3f2b1ae33be678446251617072e0b999287 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Wed, 2 Apr 2025 11:52:29 +0200 Subject: [PATCH 26/39] fix: un-do breaking changes from v1.10.0 (#40) --- appsec/config.go | 32 +++++++++++++++++++++++++++++--- go.mod | 2 ++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/appsec/config.go b/appsec/config.go index 9810d27..2f0ac56 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -21,6 +21,9 @@ import ( const ( // EnvAPISecEnabled is the env var used to enable API Security EnvAPISecEnabled = "DD_API_SECURITY_ENABLED" + // EnvAPISecSampleRate is the env var used to set the sampling rate of API Security schema extraction. + // Deprecated: a new [APISecConfig.Sampler] is now used instead of this. + EnvAPISecSampleRate = "DD_API_SECURITY_REQUEST_SAMPLE_RATE" // EnvObfuscatorKey is the env var used to provide the WAF key obfuscation regexp EnvObfuscatorKey = "DD_APPSEC_OBFUSCATION_PARAMETER_KEY_REGEXP" // EnvObfuscatorValue is the env var used to provide the WAF value obfuscation regexp @@ -52,8 +55,10 @@ const ( // APISecConfig holds the configuration for API Security schemas reporting. // It is used to enabled/disable the feature. type APISecConfig struct { - Enabled bool Sampler apisec.Sampler + Enabled bool + // Deprecated: use the new [APISecConfig.Sampler] instead. + SampleRate float64 } // ObfuscatorConfig wraps the key and value regexp to be passed to the WAF to perform obfuscation. @@ -67,8 +72,9 @@ type APISecOption func(*APISecConfig) // NewAPISecConfig creates and returns a new API Security configuration by reading the env func NewAPISecConfig(opts ...APISecOption) APISecConfig { cfg := APISecConfig{ - Enabled: boolEnv(EnvAPISecEnabled, true), - Sampler: apisec.NewSampler(), + Enabled: boolEnv(EnvAPISecEnabled, true), + Sampler: apisec.NewSampler(), + SampleRate: readAPISecuritySampleRate(), } for _, opt := range opts { opt(&cfg) @@ -76,6 +82,26 @@ func NewAPISecConfig(opts ...APISecOption) APISecConfig { return cfg } +func readAPISecuritySampleRate() float64 { + value := os.Getenv(EnvAPISecSampleRate) + if value == "" { + return DefaultAPISecSampleRate + } + + rate, err := strconv.ParseFloat(value, 64) + if err != nil { + logEnvVarParsingError(EnvAPISecSampleRate, value, err, DefaultAPISecSampleRate) + return DefaultAPISecSampleRate + } + // Clamp the value so that 0.0 <= rate <= 1.0 + if rate < 0. { + rate = 0. + } else if rate > 1. { + rate = 1. + } + return rate +} + // WithAPISecSampler sets the sampler for the API Security configuration. This is useful for testing // purposes. func WithAPISecSampler(sampler apisec.Sampler) APISecOption { diff --git a/go.mod b/go.mod index 0660d22..9aa23ba 100644 --- a/go.mod +++ b/go.mod @@ -13,3 +13,5 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) + +retract v1.10.0 // This version includes unintended breaking changes. From 4b58d57608079aa0f18a17a0a2f181961b9b1d45 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Wed, 2 Apr 2025 12:27:28 +0200 Subject: [PATCH 27/39] feat: upgrade built-in rules to v1.14.1 (#42) --- appsec/embed.go | 4 +- appsec/rules.json | 336 ++++++++++++++++++++++++++++++++++------------ 2 files changed, 254 insertions(+), 86 deletions(-) diff --git a/appsec/embed.go b/appsec/embed.go index 97b129c..f2a6298 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.13.3) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.13.3/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.14.1) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.14.1/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string diff --git a/appsec/rules.json b/appsec/rules.json index 2f53276..ca182bf 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.13.3" + "rules_version": "1.14.1" }, "rules": [ { @@ -4864,6 +4864,36 @@ ], "transformers": [] }, + { + "id": "ua0-600-68x", + "name": "xorbot", + "tags": { + "type": "attack_tool", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "tool_name": "xorbot", + "confidence": "0", + "module": "waf" + }, + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "user-agent" + ] + } + ], + "regex": "\\bmasjesu\\b" + }, + "operator": "match_regex" + } + ], + "transformers": [] + }, { "id": "dog-913-001", "name": "BurpCollaborator OOB domain", @@ -5422,6 +5452,78 @@ ], "transformers": [] }, + { + "id": "dog-913-013", + "name": "Public PoC for CVE-2025-24813", + "tags": { + "type": "attack_tool", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "confidence": "1", + "module": "waf" + }, + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.uri.raw" + } + ], + "regex": "/iSee857/session", + "options": { + "case_sensitive": false, + "min_length": 16 + } + }, + "operator": "match_regex" + } + ], + "transformers": [] + }, + { + "id": "dog-913-014", + "name": "Exploit attempt for Next.js Middleware Exploit (CVE-2025-29927)", + "tags": { + "type": "security_scanner", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "confidence": "0", + "module": "waf" + }, + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "x-middleware-subrequest" + ] + } + ] + }, + "operator": "exists" + }, + { + "parameters": { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "x-middleware-subrequest" + ] + } + ], + "regex": "[0-9a-fA-F]{40}|\\[\\w+\\]" + }, + "operator": "!match_regex" + } + ], + "transformers": [] + }, { "id": "dog-920-001", "name": "JWT authentication bypass", @@ -6314,7 +6416,7 @@ "address": "server.request.uri.raw" } ], - "regex": "(?:/swagger\\b|/api[-/]docs?\\b)", + "regex": "(?:^|/)(?:swagger|api[-/]?docs?|openapi)\\b", "options": { "case_sensitive": false } @@ -6331,7 +6433,7 @@ "category": "vulnerability_trigger", "cwe": "22", "capec": "1000/255/153/126", - "confidence": "0", + "confidence": "1", "module": "rasp" }, "conditions": [ @@ -6379,7 +6481,7 @@ "category": "vulnerability_trigger", "cwe": "77", "capec": "1000/152/248/88", - "confidence": "0", + "confidence": "1", "module": "rasp" }, "conditions": [ @@ -6427,7 +6529,7 @@ "category": "vulnerability_trigger", "cwe": "77", "capec": "1000/152/248/88", - "confidence": "0", + "confidence": "1", "module": "rasp" }, "conditions": [ @@ -6479,6 +6581,20 @@ "module": "rasp" }, "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.io.net.url" + } + ], + "regex": "^(jar:)?https?:\\/\\/\\W*([0-9oq]{1,5}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|[0-9]{1,10}|(\\[)?[:0-9a-f\\.x]{2,}(\\])?|metadata\\.google\\.internal|(?:[a-z0-9:@\\.\\-]*\\.)?(?:burpcollaborator\\.net|localtest\\.me|mail\\.ebc\\.apple\\.com|bugbounty\\.dod\\.network|.*\\.[nx]ip\\.io|oastify\\.com|oast\\.(?:pro|live|site|online|fun|me)|sslip\\.io|requestbin\\.com|requestbin\\.net|hookbin\\.com|webhook\\.site|canarytokens\\.com|interact\\.sh|ngrok\\.io|bugbounty\\.click|prbly\\.win|qualysperiscope\\.com|vii\\.one|act1on3\\.ru|ifconfig\\.pro|dnslog\\.\\w+))(:[0-9]{1,5})?(\\/[^:@]*)?$", + "options": { + "case_sensitive": false + } + }, + "operator": "match_regex" + }, { "parameters": { "resource": [ @@ -6523,7 +6639,7 @@ "category": "vulnerability_trigger", "cwe": "89", "capec": "1000/152/248/66", - "confidence": "0", + "confidence": "1", "module": "rasp" }, "conditions": [ @@ -6957,7 +7073,7 @@ "address": "graphql.server.resolver" } ], - "regex": "(http|https):\\/\\/(?:.*\\.)?(?:burpcollaborator\\.net|localtest\\.me|mail\\.ebc\\.apple\\.com|bugbounty\\.dod\\.network|.*\\.[nx]ip\\.io|oastify\\.com|oast\\.(?:pro|live|site|online|fun|me)|sslip\\.io|requestbin\\.com|requestbin\\.net|hookbin\\.com|webhook\\.site|canarytokens\\.com|interact\\.sh|ngrok\\.io|bugbounty\\.click|prbly\\.win|qualysperiscope\\.com|vii\\.one|act1on3\\.ru)" + "regex": "(http|https):\\/\\/(?:.*\\.)?(?:burpcollaborator\\.net|localtest\\.me|mail\\.ebc\\.apple\\.com|bugbounty\\.dod\\.network|.*\\.[nx]ip\\.io|oastify\\.com|oast\\.(?:pro|live|site|online|fun|me)|sslip\\.io|requestbin\\.com|requestbin\\.net|hookbin\\.com|webhook\\.site|canarytokens\\.com|interact\\.sh|ngrok\\.io|bugbounty\\.click|prbly\\.win|qualysperiscope\\.com|vii\\.one|act1on3\\.ru|dnslog\\.\\w+)" }, "operator": "match_regex" } @@ -7765,7 +7881,7 @@ ] } ], - "regex": "nmap (nse|scripting engine)" + "regex": "nmap (nse|scripting engine|icap-client/)" }, "operator": "match_regex" } @@ -8537,6 +8653,126 @@ ], "transformers": [] }, + { + "id": "ua0-600-64x", + "name": "ddg_win", + "tags": { + "type": "attack_tool", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "tool_name": "ddg_win", + "confidence": "1", + "module": "waf" + }, + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "user-agent" + ] + } + ], + "regex": "\\bddg_win\\b" + }, + "operator": "match_regex" + } + ], + "transformers": [] + }, + { + "id": "ua0-600-65x", + "name": "ISS", + "tags": { + "type": "commercial_scanner", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "tool_name": "iss", + "confidence": "0", + "module": "waf" + }, + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "user-agent" + ] + } + ], + "regex": "\\bisscyberriskcrawler/\\d\\.\\d" + }, + "operator": "match_regex" + } + ], + "transformers": [] + }, + { + "id": "ua0-600-66x", + "name": "BountyBot", + "tags": { + "type": "attack_tool", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "tool_name": "bountybot", + "confidence": "1", + "module": "waf" + }, + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "user-agent" + ] + } + ], + "regex": "\\bbountybot\\b" + }, + "operator": "match_regex" + } + ], + "transformers": [] + }, + { + "id": "ua0-600-67x", + "name": "ZumBot", + "tags": { + "type": "attack_tool", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "tool_name": "zumbot", + "confidence": "1", + "module": "waf" + }, + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "user-agent" + ] + } + ], + "regex": "\\bzumbot\\b" + }, + "operator": "match_regex" + } + ], + "transformers": [] + }, { "id": "ua0-600-6xx", "name": "Stealthy scanner", @@ -8634,24 +8870,7 @@ { "id": "http-endpoint-fingerprint", "generator": "http_endpoint_fingerprint", - "conditions": [ - { - "operator": "exists", - "parameters": { - "inputs": [ - { - "address": "waf.context.event" - }, - { - "address": "server.business_logic.users.login.failure" - }, - { - "address": "server.business_logic.users.login.success" - } - ] - } - } - ], + "conditions": [], "parameters": { "mappings": [ { @@ -8679,7 +8898,7 @@ } ] }, - "evaluate": false, + "evaluate": true, "output": true }, { @@ -8835,24 +9054,7 @@ { "id": "http-header-fingerprint", "generator": "http_header_fingerprint", - "conditions": [ - { - "operator": "exists", - "parameters": { - "inputs": [ - { - "address": "waf.context.event" - }, - { - "address": "server.business_logic.users.login.failure" - }, - { - "address": "server.business_logic.users.login.success" - } - ] - } - } - ], + "conditions": [], "parameters": { "mappings": [ { @@ -8865,30 +9067,13 @@ } ] }, - "evaluate": false, + "evaluate": true, "output": true }, { "id": "http-network-fingerprint", "generator": "http_network_fingerprint", - "conditions": [ - { - "operator": "exists", - "parameters": { - "inputs": [ - { - "address": "waf.context.event" - }, - { - "address": "server.business_logic.users.login.failure" - }, - { - "address": "server.business_logic.users.login.success" - } - ] - } - } - ], + "conditions": [], "parameters": { "mappings": [ { @@ -8901,30 +9086,13 @@ } ] }, - "evaluate": false, + "evaluate": true, "output": true }, { "id": "session-fingerprint", "generator": "session_fingerprint", - "conditions": [ - { - "operator": "exists", - "parameters": { - "inputs": [ - { - "address": "waf.context.event" - }, - { - "address": "server.business_logic.users.login.failure" - }, - { - "address": "server.business_logic.users.login.success" - } - ] - } - } - ], + "conditions": [], "parameters": { "mappings": [ { @@ -8947,7 +9115,7 @@ } ] }, - "evaluate": false, + "evaluate": true, "output": true } ], From d1b4c20383e047ebbedfe378958983e40ccccc14 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Wed, 2 Apr 2025 14:38:09 +0200 Subject: [PATCH 28/39] chore: fix broken tests; remove `|| true` in CI (#41) --- .github/workflows/test.yml | 31 +++++-- apisec/internal/timed/{set.go => lru.go} | 0 .../timed/{set_test.go => lru_test.go} | 24 ++--- apisec/internal/timed/table.go | 4 +- apisec/internal/timed/testutil/fakeclock.go | 80 +++++++++++++++++ apisec/sampler_test.go | 88 +++---------------- 6 files changed, 132 insertions(+), 95 deletions(-) rename apisec/internal/timed/{set.go => lru.go} (100%) rename apisec/internal/timed/{set_test.go => lru_test.go} (87%) create mode 100644 apisec/internal/timed/testutil/fakeclock.go diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 974c1ac..867bde4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -16,13 +16,15 @@ jobs: strategy: matrix: runs-on: [ macos-15, macos-14, macos-13, ubuntu-22.04, ubuntu-20.04, windows-latest, arm-4core-linux ] - go-version: [ "1.23", "1.22" ] + go-version: [ "1.24", "1.23" ] cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo fail-fast: false runs-on: ${{ matrix.runs-on }} steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-go@f111f3307d8850f501ac008e886eec1fd1932a34 # v5.3.0 + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Setup Go + uses: actions/setup-go@f111f3307d8850f501ac008e886eec1fd1932a34 # v5.3.0 with: go-version: ${{ matrix.go-version }} cache: true @@ -34,13 +36,22 @@ jobs: key: go-pkg-mod-${{ hashFiles('**/go.sum') }} restore-keys: go-pkg-mod- + # Install build-essential on ARM linux runners if CGO is to be enabled + - name: Install build-essential (ARM linux) + if: matrix.runs-on == 'arm-4core-linux' && matrix.cgo_enabled == '1' + run: |- + sudo apt update + sudo apt install -y build-essential + - name: go test shell: bash run: | # Install gotestsum env GOBIN=$PWD go install gotest.tools/gotestsum@latest # Run the tests with gotestsum - env CGO_ENABLED=${{ matrix.cgo_enabled }} ./gotestsum -- -v ./... || true + ./gotestsum -- -v ${{ runner.os == 'Linux' && matrix.cgo_enabled == '1' && '-race' || '' }} ./... + env: + CGO_ENABLED: ${{ matrix.cgo_enabled }} # Same tests but on the official golang container for linux golang-linux-container: @@ -50,14 +61,16 @@ jobs: image: golang:${{ matrix.go-version }}-${{ matrix.distribution }} strategy: matrix: - go-version: [ "1.23", "1.22" ] + go-version: [ "1.24", "1.23" ] distribution: [ bookworm, bullseye, alpine ] cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo fail-fast: false steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 # Install gcc and the libc headers on alpine images - - if: ${{ matrix.distribution == 'alpine' }} + - if: matrix.distribution == 'alpine' + name: Install necessary packages (Alpine) run: apk add gcc musl-dev libc6-compat git - name: Go modules cache @@ -72,7 +85,9 @@ jobs: # Install gotestsum env GOBIN=$PWD go install gotest.tools/gotestsum@latest # Run the tests with gotestsum - env CGO_ENABLED=${{ matrix.cgo_enabled }} ./gotestsum -- -v ./... || true + ./gotestsum -- -v ${{ matrix.cgo_enabled == '1' && '-race' || '' }} ./... + env: + CGO_ENABLED: ${{ matrix.cgo_enabled }} everything: name: All Tests diff --git a/apisec/internal/timed/set.go b/apisec/internal/timed/lru.go similarity index 100% rename from apisec/internal/timed/set.go rename to apisec/internal/timed/lru.go diff --git a/apisec/internal/timed/set_test.go b/apisec/internal/timed/lru_test.go similarity index 87% rename from apisec/internal/timed/set_test.go rename to apisec/internal/timed/lru_test.go index f81e994..da6d88a 100644 --- a/apisec/internal/timed/set_test.go +++ b/apisec/internal/timed/lru_test.go @@ -6,17 +6,18 @@ package timed import ( + "context" "runtime" "sync" - "sync/atomic" "testing" "time" "github.com/DataDog/appsec-internal-go/apisec/internal/config" + "github.com/DataDog/appsec-internal-go/apisec/internal/timed/testutil" "github.com/stretchr/testify/require" ) -func TestSet(t *testing.T) { +func TestLRU(t *testing.T) { t.Run("New", func(t *testing.T) { require.PanicsWithError(t, "NewSet: interval must be at least 1s, got 0s", func() { NewSet(0, UnixTime) }) require.PanicsWithError(t, "NewSet: interval must be at least 1s, got 10ms", func() { NewSet(10*time.Millisecond, UnixTime) }) @@ -54,20 +55,23 @@ func TestSet(t *testing.T) { }) t.Run("rebuild", func(t *testing.T) { - var fakeTime atomic.Int64 - fakeTime.Store(time.Now().Unix()) - fakeClock := func() int64 { return fakeTime.Load() } + goCount := runtime.GOMAXPROCS(0) * 10 + ctx, cancel := context.WithCancel(context.Background()) + clock := testutil.NewFakeClock(ctx, t, goCount) + defer func() { + cancel() + clock.WaitUntilDone() + }() - subject := NewSet(config.Interval, fakeClock) + subject := NewSet(config.Interval, clock.Unix) var ( - goCount = runtime.GOMAXPROCS(0) * 10 startBarrier sync.WaitGroup finishBarrier sync.WaitGroup ) startBarrier.Add(goCount + 1) finishBarrier.Add(goCount) - for g := range goCount { + for range goCount { go func() { defer finishBarrier.Done() startBarrier.Done() @@ -75,9 +79,7 @@ func TestSet(t *testing.T) { for key := range uint64(config.MaxItemCount * 4) { _ = subject.Hit(key) - if g == 0 { - fakeTime.Add(1) - } + clock.WaitForTick() } }() } diff --git a/apisec/internal/timed/table.go b/apisec/internal/timed/table.go index 641bd7c..cfc1c4d 100644 --- a/apisec/internal/timed/table.go +++ b/apisec/internal/timed/table.go @@ -168,11 +168,11 @@ func (d entryData) WithAccessTime(atime uint32) entryData { func (e copiableEntry) Compare(other copiableEntry) int { tst := e.Data.SampleTime() ost := other.Data.SampleTime() - if tst > ost { + if tst < ost { // Receiver was sampled more recently (sorts higher) return 1 } - if tst < ost { + if tst > ost { // Receiver was sampled less recently (sorts lower) return -1 } diff --git a/apisec/internal/timed/testutil/fakeclock.go b/apisec/internal/timed/testutil/fakeclock.go new file mode 100644 index 0000000..7d4fc0b --- /dev/null +++ b/apisec/internal/timed/testutil/fakeclock.go @@ -0,0 +1,80 @@ +package testutil + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" +) + +type FakeClock struct { + t testing.TB + closed chan struct{} + goCount int + now int64 + needTick atomic.Bool + wg sync.WaitGroup + cnd sync.Cond +} + +func NewFakeClock(ctx context.Context, t testing.TB, goroutineCount int) *FakeClock { + res := &FakeClock{ + t: t, + closed: make(chan struct{}), + goCount: goroutineCount, + now: time.Now().Unix(), + cnd: *sync.NewCond(&sync.Mutex{}), + } + res.wg.Add(goroutineCount) + go res.tick(ctx) + return res +} + +func (c *FakeClock) Unix() int64 { + return c.now +} + +func (c *FakeClock) WaitForTick() { + c.cnd.L.Lock() + + c.needTick.CompareAndSwap(false, true) + curTime := c.now + + c.wg.Done() + for curTime == c.now && c.now > 0 { + c.cnd.Wait() + } + c.cnd.L.Unlock() +} + +func (c *FakeClock) WaitUntilDone() { + <-c.closed +} + +func (c *FakeClock) tick(ctx context.Context) { + c.t.Log("Start ticker!") + for { + select { + case <-ctx.Done(): + // Context is cancelled, stop the ticker... + c.cnd.L.Lock() + c.now = 0 + c.cnd.L.Unlock() + c.t.Log("Stop ticker!") + close(c.closed) + return + default: + if !c.needTick.Load() { + continue + } + c.wg.Wait() + c.cnd.L.Lock() + c.now++ + c.needTick.Store(false) + c.cnd.Broadcast() + c.wg.Add(c.goCount) + c.cnd.L.Unlock() + } + } +} diff --git a/apisec/sampler_test.go b/apisec/sampler_test.go index 53d2762..f502958 100644 --- a/apisec/sampler_test.go +++ b/apisec/sampler_test.go @@ -17,6 +17,7 @@ import ( "time" "github.com/DataDog/appsec-internal-go/apisec/internal/config" + "github.com/DataDog/appsec-internal-go/apisec/internal/timed/testutil" "github.com/stretchr/testify/assert" ) @@ -77,21 +78,24 @@ func TestSampler(t *testing.T) { for name, tc := range testCases { t.Run(name, func(t *testing.T) { - ctx, cancel := context.WithCancel(ctx) - defer cancel() - assert.Positive(t, tc.SimulatedTPS) assert.GreaterOrEqual(t, tc.ExpectedKeepRate, 0.0) assert.GreaterOrEqual(t, 1.0, tc.ExpectedKeepRate) + const goroutineCount = 10 // Fixed to ensure consistent keep rate... + ctx, cancel := context.WithCancel(ctx) + clock := testutil.NewFakeClock(ctx, t, goroutineCount) + defer func() { + cancel() + clock.WaitForTick() + }() + var ( - goroutineCount = max(2, runtime.GOMAXPROCS(0)) - clock = newFakeClock(ctx, t, goroutineCount) - subject = newSampler(30*time.Second, clock.Unix) - sb sync.WaitGroup // Start barrier - wg sync.WaitGroup // Completion barrier - kept atomic.Uint64 - dropped atomic.Uint64 + subject = newSampler(30*time.Second, clock.Unix) + sb sync.WaitGroup // Start barrier + wg sync.WaitGroup // Completion barrier + kept atomic.Uint64 + dropped atomic.Uint64 ) sb.Add(1 + goroutineCount) // All child goroutines + this one... wg.Add(goroutineCount) @@ -207,70 +211,6 @@ func BenchmarkSampler(b *testing.B) { } } -type fakeClock struct { - t testing.TB - goCount int - now int64 - needTick atomic.Bool - wg sync.WaitGroup - cnd sync.Cond -} - -func newFakeClock(ctx context.Context, t testing.TB, goroutineCount int) *fakeClock { - res := &fakeClock{ - t: t, - goCount: goroutineCount, - now: time.Now().Unix(), - cnd: *sync.NewCond(&sync.Mutex{}), - } - res.wg.Add(goroutineCount) - go res.tick(ctx) - return res -} - -func (c *fakeClock) Unix() int64 { - return c.now -} - -func (c *fakeClock) WaitForTick() { - c.cnd.L.Lock() - - c.needTick.CompareAndSwap(false, true) - curTime := c.now - - c.wg.Done() - for curTime == c.now && c.now > 0 { - c.cnd.Wait() - } - c.cnd.L.Unlock() -} - -func (c *fakeClock) tick(ctx context.Context) { - c.t.Log("Start ticker!") - for { - select { - case <-ctx.Done(): - // Context is cancelled, stop the ticker... - c.cnd.L.Lock() - c.now = 0 - c.cnd.L.Unlock() - c.t.Log("Stop ticker!") - return - default: - if !c.needTick.Load() { - continue - } - c.wg.Wait() - c.cnd.L.Lock() - c.now++ - c.needTick.Store(false) - c.cnd.Broadcast() - c.wg.Add(c.goCount) - c.cnd.L.Unlock() - } - } -} - func randomOne[T any](list []T) T { return list[rand.Intn(len(list))] } From 6e714c245f5d394c2af8ba2d7fa0b7ac2c445104 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Wed, 2 Apr 2025 14:39:08 +0200 Subject: [PATCH 29/39] feat: update embedded rules to v1.14.2 (#43) --- appsec/embed.go | 4 ++-- appsec/rules.json | 10 +++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/appsec/embed.go b/appsec/embed.go index f2a6298..ac8bea8 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -7,8 +7,8 @@ package appsec import _ "embed" // Blank import comment for golint compliance -// StaticRecommendedRules holds the recommended AppSec security rules (v1.14.1) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.14.1/build/recommended.json +// StaticRecommendedRules holds the recommended AppSec security rules (v1.14.2) +// Source: https://github.com/DataDog/appsec-event-rules/blob/1.14.2/build/recommended.json // //go:embed rules.json var StaticRecommendedRules string diff --git a/appsec/rules.json b/appsec/rules.json index ca182bf..e2216bb 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.14.1" + "rules_version": "1.14.2" }, "rules": [ { @@ -5503,9 +5503,13 @@ "x-middleware-subrequest" ] } - ] + ], + "regex": ".*", + "options": { + "min_length": 1 + } }, - "operator": "exists" + "operator": "match_regex" }, { "parameters": { From 24b05181e93c827727aa3ea0dee2c17d023c7a48 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Thu, 3 Apr 2025 12:15:48 +0200 Subject: [PATCH 30/39] fix: allow system tests to override API Security sampling interval (#44) Some system tests must override the sampling interval to 0 in order to be able to test schema extraction works as intended. This requires reading the default interval from an environment variable. --- apisec/internal/config/const.go | 5 ----- apisec/internal/timed/lru.go | 17 +++++++++------- apisec/internal/timed/lru_test.go | 14 ++++++------- apisec/sampler.go | 12 ++--------- appsec/config.go | 21 ++++++++++++++++++- appsec/config_test.go | 34 +++++++++++++++++++++++++++++++ 6 files changed, 73 insertions(+), 30 deletions(-) diff --git a/apisec/internal/config/const.go b/apisec/internal/config/const.go index 5c5f532..6483f28 100644 --- a/apisec/internal/config/const.go +++ b/apisec/internal/config/const.go @@ -5,12 +5,7 @@ package config -import "time" - const ( // MaxItemCount is the maximum amount of items to keep in a timed set. MaxItemCount = 4_096 - - // Interval is the interval between two samples being taken. - Interval = 30 * time.Second ) diff --git a/apisec/internal/timed/lru.go b/apisec/internal/timed/lru.go index b558b52..4a86f5d 100644 --- a/apisec/internal/timed/lru.go +++ b/apisec/internal/timed/lru.go @@ -7,11 +7,13 @@ package timed import ( "fmt" + "math" "math/rand" "sync/atomic" "time" "github.com/DataDog/appsec-internal-go/apisec/internal/config" + "github.com/DataDog/appsec-internal-go/log" ) // capacity is the maximum number of items that may be temporarily present in a @@ -44,18 +46,19 @@ type LRU struct { rebuilding atomic.Bool } -// NewSet initializes a new, empty [LRU] with the given interval and clock -// function. The provided interval must be at least 1 second, and may not exceed -// [config.Interval]. +// NewLRU initializes a new, empty [LRU] with the given interval and clock +// function. A warning will be logged if it is set below 1 second. Panics if +// the interval is more than [math.MaxUint32] seconds, as this value cannot be +// used internally. // // Note: timestamps are stored at second resolution, so the interval will be // rounded down to the nearest second. -func NewSet(interval time.Duration, clock ClockFunc) *LRU { +func NewLRU(interval time.Duration, clock ClockFunc) *LRU { if interval < time.Second { - panic(fmt.Errorf("NewSet: interval must be at least 1s, got %v", interval)) + log.Warn("NewLRU: interval is less than one second; this should not be attempted in production (value: %s)", interval) } - if interval > config.Interval { - panic(fmt.Errorf("NewSet: interval must not exceed %s, got %v", config.Interval, interval)) + if interval > time.Second*math.MaxUint32 { + panic(fmt.Errorf("NewLRU: interval must be <= %s, but was %s", time.Second*math.MaxUint32, interval)) } intervalSeconds := uint32(interval.Seconds()) diff --git a/apisec/internal/timed/lru_test.go b/apisec/internal/timed/lru_test.go index da6d88a..c18ad49 100644 --- a/apisec/internal/timed/lru_test.go +++ b/apisec/internal/timed/lru_test.go @@ -7,6 +7,7 @@ package timed import ( "context" + "math" "runtime" "sync" "testing" @@ -18,20 +19,19 @@ import ( ) func TestLRU(t *testing.T) { - t.Run("New", func(t *testing.T) { - require.PanicsWithError(t, "NewSet: interval must be at least 1s, got 0s", func() { NewSet(0, UnixTime) }) - require.PanicsWithError(t, "NewSet: interval must be at least 1s, got 10ms", func() { NewSet(10*time.Millisecond, UnixTime) }) - require.PanicsWithError(t, "NewSet: interval must not exceed 30s, got 1m0s", func() { NewSet(time.Minute, UnixTime) }) + t.Run("NewLRU", func(t *testing.T) { + require.PanicsWithError(t, "NewLRU: interval must be <= 1193046h28m15s, but was 1193046h28m16s", func() { NewLRU(time.Second*(math.MaxUint32+1), UnixTime) }) }) t.Run("Hit", func(t *testing.T) { fakeTime := time.Now().Unix() fakeClock := func() int64 { return fakeTime } - subject := NewSet(config.Interval, fakeClock) + const sampleIntervalSeconds = 30 + subject := NewLRU(sampleIntervalSeconds*time.Second, fakeClock) require.True(t, subject.Hit(1337)) - for range config.Interval / time.Second { + for range sampleIntervalSeconds { require.False(t, subject.Hit(1337)) fakeTime++ } @@ -63,7 +63,7 @@ func TestLRU(t *testing.T) { clock.WaitUntilDone() }() - subject := NewSet(config.Interval, clock.Unix) + subject := NewLRU(30*time.Second, clock.Unix) var ( startBarrier sync.WaitGroup diff --git a/apisec/sampler.go b/apisec/sampler.go index 2bf6365..97147e7 100644 --- a/apisec/sampler.go +++ b/apisec/sampler.go @@ -10,7 +10,6 @@ import ( "hash/fnv" "time" - "github.com/DataDog/appsec-internal-go/apisec/internal/config" "github.com/DataDog/appsec-internal-go/apisec/internal/timed" ) @@ -33,14 +32,7 @@ type ( clockFunc = func() int64 ) -// NewSampler returns a new [*Sampler] with the default clock function based on -// [time.Now]. -func NewSampler() Sampler { - return NewSamplerWithInterval(config.Interval) -} - -// NewSamplerWithInterval returns a new [*Sampler] with the specified interval -// instead of the default of 30 seconds. +// NewSamplerWithInterval returns a new [*Sampler] with the specified interval. func NewSamplerWithInterval(interval time.Duration) Sampler { return newSampler(interval, timed.UnixTime) } @@ -48,7 +40,7 @@ func NewSamplerWithInterval(interval time.Duration) Sampler { // newSampler allows creating a new [*Sampler] with custom clock function, // which is useful for testing. func newSampler(interval time.Duration, clock clockFunc) Sampler { - return (*timedSetSampler)(timed.NewSet(interval, clock)) + return (*timedSetSampler)(timed.NewLRU(interval, clock)) } // DecisionFor makes a sampling decision for the provided [SamplingKey]. If it diff --git a/appsec/config.go b/appsec/config.go index 2f0ac56..f24f0c3 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -36,12 +36,18 @@ const ( EnvRules = "DD_APPSEC_RULES" // EnvRASPEnabled is the env var used to enable/disable RASP functionalities for ASM EnvRASPEnabled = "DD_APPSEC_RASP_ENABLED" + + // envAPISecSampleDelay is the env var used to set the delay for the API Security sampler in system tests. + // It is not indended to be set by users. + envAPISecSampleDelay = "DD_API_SECURITY_SAMPLE_DELAY" ) // Configuration constants and default values const ( // DefaultAPISecSampleRate is the default rate at which API Security schemas are extracted from requests DefaultAPISecSampleRate = .1 + // DefaultAPISecSampleInterval is the default interval between two samples being taken. + DefaultAPISecSampleInterval = 30 * time.Second // DefaultObfuscatorKeyRegex is the default regexp used to obfuscate keys DefaultObfuscatorKeyRegex = `(?i)pass|pw(?:or)?d|secret|(?:api|private|public|access)[_-]?key|token|consumer[_-]?(?:id|key|secret)|sign(?:ed|ature)|bearer|authorization|jsessionid|phpsessid|asp\.net[_-]sessionid|sid|jwt` // DefaultObfuscatorValueRegex is the default regexp used to obfuscate values @@ -73,7 +79,7 @@ type APISecOption func(*APISecConfig) func NewAPISecConfig(opts ...APISecOption) APISecConfig { cfg := APISecConfig{ Enabled: boolEnv(EnvAPISecEnabled, true), - Sampler: apisec.NewSampler(), + Sampler: apisec.NewSamplerWithInterval(durationEnv(envAPISecSampleDelay, "s", DefaultAPISecSampleInterval)), SampleRate: readAPISecuritySampleRate(), } for _, opt := range opts { @@ -224,3 +230,16 @@ func boolEnv(key string, def bool) bool { } return v } + +func durationEnv(key string, unit string, def time.Duration) time.Duration { + strVal, ok := os.LookupEnv(key) + if !ok { + return def + } + val, err := time.ParseDuration(strVal + unit) + if err != nil { + logEnvVarParsingError(key, strVal, err, def) + return def + } + return val +} diff --git a/appsec/config_test.go b/appsec/config_test.go index 76490eb..c6cc762 100644 --- a/appsec/config_test.go +++ b/appsec/config_test.go @@ -238,3 +238,37 @@ func TestRASPEnablement(t *testing.T) { require.True(t, RASPEnabled()) }) } + +func TestDurationEnv(t *testing.T) { + const varName = "DD_TEST_VARIABLE_DURATION" + + type testCase struct { + EnvVal string + EnvUnit string + Expected time.Duration + } + testCases := map[string]testCase{ + "blank": { + EnvVal: "", + EnvUnit: "s", + Expected: 1337, + }, + "1m": { + EnvVal: "1", + EnvUnit: "m", + Expected: time.Minute, + }, + "invalid": { + EnvVal: "invalid", + EnvUnit: "s", + Expected: 1337, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + t.Setenv(varName, tc.EnvVal) + require.Equal(t, tc.Expected, durationEnv(varName, tc.EnvUnit, 1337)) + }) + } +} From fa998d63b4390f2ae70df95e28d17be32e5b3a6f Mon Sep 17 00:00:00 2001 From: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> Date: Mon, 19 May 2025 11:50:40 +0200 Subject: [PATCH 31/39] chore(ci): rollout ubuntu 20 in favor of ubuntu 24 (#48) Signed-off-by: Eliott Bouhana --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 867bde4..f40641e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,7 +15,7 @@ jobs: name: Native ${{ matrix.runs-on }} (Go ${{ matrix.go-version }}, CGO_ENABLED=${{ matrix.cgo_enabled }}) strategy: matrix: - runs-on: [ macos-15, macos-14, macos-13, ubuntu-22.04, ubuntu-20.04, windows-latest, arm-4core-linux ] + runs-on: [ macos-15, macos-14, macos-13, ubuntu-24.04, ubuntu-22.04, windows-latest, arm-4core-linux ] go-version: [ "1.24", "1.23" ] cgo_enabled: [ "0", "1" ] # test it compiles with and without cgo fail-fast: false From 8b944a534d45c8096dc190c1db71cf92d0559631 Mon Sep 17 00:00:00 2001 From: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> Date: Mon, 19 May 2025 12:39:02 +0200 Subject: [PATCH 32/39] feat(config): new default value obfuscation regex (#45) --- appsec/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appsec/config.go b/appsec/config.go index f24f0c3..a50e4e1 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -51,7 +51,7 @@ const ( // DefaultObfuscatorKeyRegex is the default regexp used to obfuscate keys DefaultObfuscatorKeyRegex = `(?i)pass|pw(?:or)?d|secret|(?:api|private|public|access)[_-]?key|token|consumer[_-]?(?:id|key|secret)|sign(?:ed|ature)|bearer|authorization|jsessionid|phpsessid|asp\.net[_-]sessionid|sid|jwt` // DefaultObfuscatorValueRegex is the default regexp used to obfuscate values - DefaultObfuscatorValueRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:[_-]?phrase)?|secret(?:[_-]?key)?|(?:(?:api|private|public|access)[_-]?)key(?:[_-]?id)?|(?:(?:auth|access|id|refresh)[_-]?)?token|consumer[_-]?(?:id|key|secret)|sign(?:ed|ature)?|auth(?:entication|orization)?|jsessionid|phpsessid|asp\.net(?:[_-]|-)sessionid|sid|jwt)(?:\s*=[^;]|"\s*:\s*"[^"]+")|bearer\s+[a-z0-9\._\-]+|token:[a-z0-9]{13}|gh[opsu]_[0-9a-zA-Z]{36}|ey[I-L][\w=-]+\.ey[I-L][\w=-]+(?:\.[\w.+\/=-]+)?|[\-]{5}BEGIN[a-z\s]+PRIVATE\sKEY[\-]{5}[^\-]+[\-]{5}END[a-z\s]+PRIVATE\sKEY|ssh-rsa\s*[a-z0-9\/\.+]{100,}` + DefaultObfuscatorValueRegex = `(?i)(?:p(?:ass)?w(?:or)?d|pass(?:[_-]?phrase)?|secret(?:[_-]?key)?|(?:(?:api|private|public|access)[_-]?)key(?:[_-]?id)?|(?:(?:auth|access|id|refresh)[_-]?)?token|consumer[_-]?(?:id|key|secret)|sign(?:ed|ature)?|auth(?:entication|orization)?|jsessionid|phpsessid|asp\.net(?:[_-]|-)sessionid|sid|jwt)(?:\s*=([^;&]+)|"\s*:\s*("[^"]+"|\d+))|bearer\s+([a-z0-9\._\-]+)|token\s*:\s*([a-z0-9]{13})|gh[opsu]_([0-9a-zA-Z]{36})|ey[I-L][\w=-]+\.(ey[I-L][\w=-]+(?:\.[\w.+\/=-]+)?)|[\-]{5}BEGIN[a-z\s]+PRIVATE\sKEY[\-]{5}([^\-]+)[\-]{5}END[a-z\s]+PRIVATE\sKEY|ssh-rsa\s*([a-z0-9\/\.+]{100,})` // DefaultWAFTimeout is the default time limit past which a WAF run will timeout DefaultWAFTimeout = time.Millisecond // DefaultTraceRate is the default limit (trace/sec) past which ASM traces are sampled out From 77e25f6a6a437e0440d4429efc3da65e76d211c1 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Mon, 19 May 2025 15:34:24 +0200 Subject: [PATCH 33/39] fix: make appsec.DefaultRuleset reutrn the ruleset as-is (#46) The `DefaultRuleset` function used to re-marshal a JSON document that was just parsed; as an artifact from times where the processors were merged into the ruleset separately. This has not been needed since a long time, as the default ruleset now includes the relevant processors already. This removes inefficiencies as we no longer have to parse, then format the data. The embedded object is also carried directly as a `[]byte` slice instead of a string, to remove the need for a string copy to happen all the time. Co-authored-by: Eliott Bouhana <47679741+eliottness@users.noreply.github.com> --- appsec/embed.go | 18 ++++++++++++------ appsec/rules.go | 9 +++------ appsec/rules_test.go | 24 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 12 deletions(-) create mode 100644 appsec/rules_test.go diff --git a/appsec/embed.go b/appsec/embed.go index ac8bea8..52cf177 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -5,10 +5,16 @@ package appsec -import _ "embed" // Blank import comment for golint compliance +import ( + _ "embed" // Blank import comment for golint compliance + "unsafe" +) -// StaticRecommendedRules holds the recommended AppSec security rules (v1.14.2) -// Source: https://github.com/DataDog/appsec-event-rules/blob/1.14.2/build/recommended.json -// -//go:embed rules.json -var StaticRecommendedRules string +var ( + //go:embed rules.json + staticRecommendedRules []byte + + // StaticRecommendedRules holds the recommended AppSec security rules (v1.14.2) + // Source: https://github.com/DataDog/appsec-event-rules/blob/1.14.2/build/recommended.json + StaticRecommendedRules = unsafe.String(&staticRecommendedRules[0], len(staticRecommendedRules)) +) diff --git a/appsec/rules.go b/appsec/rules.go index 29a46bf..50bc023 100644 --- a/appsec/rules.go +++ b/appsec/rules.go @@ -2,23 +2,20 @@ // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2023-present Datadog, Inc. + package appsec import "encoding/json" // DefaultRuleset returns the marshaled default recommended security rules for AppSec func DefaultRuleset() ([]byte, error) { - rules, err := DefaultRulesetMap() - if err != nil { - return nil, err - } - return json.Marshal(rules) + return staticRecommendedRules, nil } // DefaultRulesetMap returns the unmarshaled default recommended security rules for AppSec func DefaultRulesetMap() (map[string]any, error) { var rules map[string]any - if err := json.Unmarshal([]byte(StaticRecommendedRules), &rules); err != nil { + if err := json.Unmarshal(staticRecommendedRules, &rules); err != nil { return nil, err } diff --git a/appsec/rules_test.go b/appsec/rules_test.go new file mode 100644 index 0000000..f03545b --- /dev/null +++ b/appsec/rules_test.go @@ -0,0 +1,24 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2023-present Datadog, Inc. + +package appsec + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDefaultRuleset(t *testing.T) { + rules, err := DefaultRuleset() + require.NoError(t, err) + require.NotEmpty(t, rules) +} + +func TestDefaultRulesetMap(t *testing.T) { + rules, err := DefaultRulesetMap() + require.NoError(t, err) + require.NotEmpty(t, rules) +} From 1842076acee853d77d6d54cfad01dad6cdb6dc47 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Fri, 6 Jun 2025 16:04:11 +0200 Subject: [PATCH 34/39] chore: use GitHub App instead of PAT (#50) --- .github/workflows/update-rules.yml | 32 +++++++++++++++++++----- _tools/rules-updater/writer/template.txt | 18 ++++++++----- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/.github/workflows/update-rules.yml b/.github/workflows/update-rules.yml index c24c442..445b5f7 100644 --- a/.github/workflows/update-rules.yml +++ b/.github/workflows/update-rules.yml @@ -12,10 +12,19 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/setup-go@f111f3307d8850f501ac008e886eec1fd1932a34 # v5.3.0 + - name: Generate a GitHub token + id: generate-token + uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6 + with: + app-id: ${{ vars.DD_K9_LIBRARY_GO_APP_ID }} + private-key: ${{ secrets.DD_K9_LIBRARY_GO_APP_PRIVATE_KEY }} + owner: DataDog + repositories: appsec-event-rules + permission-contents: read - name: Upgrade AppSec Rules run: ./_tools/rules-updater/update.sh latest env: - GITHUB_TOKEN: ${{ secrets.UPDATE_RULES_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} - name: Detect Updated Code id: detect run: |- @@ -35,7 +44,16 @@ jobs: contents: write if: needs.update.outputs.mutation_happened steps: + - name: Generate a GitHub token + id: generate-token + uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6 + with: + app-id: ${{ vars.DD_K9_LIBRARY_GO_APP_ID }} + private-key: ${{ secrets.DD_K9_LIBRARY_GO_APP_PRIVATE_KEY }} - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + token: ${{ steps.generate-token.outputs.token }} + persist-credentials: true - name: Download Patch uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 with: @@ -48,8 +66,11 @@ jobs: echo "version=$(jq -r '.metadata.rules_version' < ./appsec/rules.json)" >> $GITHUB_OUTPUT - name: Configure git identity run: |- - git config user.name "github-actions[bot] on behalf of ${{ github.actor }}" - git config user.email "${{ github.actor }}@users.noreply.github.com" + git config user.name "${APP_SLUG}[bot]" + git config user.email "$(gh api "/users/${APP_SLUG}[bot]" | jq .id)+${APP_SLUG}[bot]@users.noreply.github.com" + env: + APP_SLUG: ${{ steps.generate-token.outputs.app-slug }} + GITHUB_TOKEN: ${{ github.token }} - name: Push Changes run: |- git add . @@ -59,7 +80,6 @@ jobs: run: |- gh pr create --title "Update embedded AppSec Rules to ${{ steps.apply.outputs.version }}" \ --body "Automatically created by [GitHub Actions](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})." \ - --base "main" --head "automation/update-appsec-rules" \ - --reviewer "@DataDog/asm-go" + --base "main" --head "automation/update-appsec-rules" env: - GITHUB_TOKEN: ${{ secrets.MUTATOR_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} diff --git a/_tools/rules-updater/writer/template.txt b/_tools/rules-updater/writer/template.txt index 173a04e..652f904 100644 --- a/_tools/rules-updater/writer/template.txt +++ b/_tools/rules-updater/writer/template.txt @@ -5,10 +5,16 @@ package appsec -import _ "embed" // Blank import comment for golint compliance +import ( + _ "embed" // Blank import comment for golint compliance + "unsafe" +) -// StaticRecommendedRules holds the recommended AppSec security rules (v{{.Version}}) -// Source: https://github.com/DataDog/appsec-event-rules/blob/{{.Version}}/build/recommended.json -// -//go:embed rules.json -var StaticRecommendedRules string +var ( + //go:embed rules.json + staticRecommendedRules []byte + + // StaticRecommendedRules holds the recommended AppSec security rules (v{{.Version}}) + // Source: https://github.com/DataDog/appsec-event-rules/blob/{{.Version}}/build/recommended.json + StaticRecommendedRules = unsafe.String(&staticRecommendedRules[0], len(staticRecommendedRules)) +) From 01322475864e3595183691411dab9b62d7dc6902 Mon Sep 17 00:00:00 2001 From: Flavien Darche <11708575+e-n-0@users.noreply.github.com> Date: Thu, 26 Jun 2025 16:17:39 +0200 Subject: [PATCH 35/39] feat: proxy sampler (#52) # Changes This PRs adds a new sampler for proxies environment. ([RFC](https://docs.google.com/document/d/1C9BmWYNM02_-T1EnHpAzziyytJJ1pBE6iCsQoQwVtyU/edit?pli=1&tab=t.0)) It also tweak the limiter to take interval. --- apisec/sampler.go | 29 +++++++++++++++++++++++++++ appsec/config.go | 40 ++++++++++++++++++++++++++++++++++++- limiter/limiter.go | 9 ++++++++- limiter/limiter_test.go | 44 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 120 insertions(+), 2 deletions(-) diff --git a/apisec/sampler.go b/apisec/sampler.go index 97147e7..76131f2 100644 --- a/apisec/sampler.go +++ b/apisec/sampler.go @@ -11,6 +11,7 @@ import ( "time" "github.com/DataDog/appsec-internal-go/apisec/internal/timed" + "github.com/DataDog/appsec-internal-go/limiter" ) type ( @@ -20,6 +21,12 @@ type ( timedSetSampler timed.LRU + proxySampler struct { + limiter limiter.Limiter + } + + nullSampler struct{} + SamplingKey struct { // Method is the value of the http.method span tag Method string @@ -32,6 +39,20 @@ type ( clockFunc = func() int64 ) +// NewProxySampler creates a new sampler suitable for proxy environments where the sampling decision +// is not based on the request's properties, but on a rate. +func NewProxySampler(rate int, interval time.Duration) Sampler { + if rate <= 0 { + return &nullSampler{} + } + r := int64(rate) + l := limiter.NewTokenTickerWithInterval(r, r, interval) + l.Start() + return &proxySampler{ + limiter: l, + } +} + // NewSamplerWithInterval returns a new [*Sampler] with the specified interval. func NewSamplerWithInterval(interval time.Duration) Sampler { return newSampler(interval, timed.UnixTime) @@ -53,6 +74,14 @@ func (s *timedSetSampler) DecisionFor(key SamplingKey) bool { return (*timed.LRU)(s).Hit(keyHash) } +func (s *proxySampler) DecisionFor(_ SamplingKey) bool { + return s.limiter.Allow() +} + +func (s *nullSampler) DecisionFor(_ SamplingKey) bool { + return false +} + // hash returns a hash of the key. Given the same seed, it always produces the // same output. If the seed changes, the output is likely to change as well. func (k SamplingKey) hash() uint64 { diff --git a/appsec/config.go b/appsec/config.go index a50e4e1..09cbbd4 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -24,6 +24,8 @@ const ( // EnvAPISecSampleRate is the env var used to set the sampling rate of API Security schema extraction. // Deprecated: a new [APISecConfig.Sampler] is now used instead of this. EnvAPISecSampleRate = "DD_API_SECURITY_REQUEST_SAMPLE_RATE" + // EnvAPISecProxySampleRate is the env var used to set the sampling rate of API Security schema extraction for proxies. + EnvAPISecProxySampleRate = "DD_API_SECURITY_PROXY_SAMPLE_RATE" // EnvObfuscatorKey is the env var used to provide the WAF key obfuscation regexp EnvObfuscatorKey = "DD_APPSEC_OBFUSCATION_PARAMETER_KEY_REGEXP" // EnvObfuscatorValue is the env var used to provide the WAF value obfuscation regexp @@ -48,6 +50,10 @@ const ( DefaultAPISecSampleRate = .1 // DefaultAPISecSampleInterval is the default interval between two samples being taken. DefaultAPISecSampleInterval = 30 * time.Second + // DefaultAPISecProxySampleRate is the default rate (schemas per minute) at which API Security schemas are extracted from requests + DefaultAPISecProxySampleRate = 300 + // DefaultAPISecProxySampleInterval is the default time window for the API Security proxy sampler rate limiter. + DefaultAPISecProxySampleInterval = time.Minute // DefaultObfuscatorKeyRegex is the default regexp used to obfuscate keys DefaultObfuscatorKeyRegex = `(?i)pass|pw(?:or)?d|secret|(?:api|private|public|access)[_-]?key|token|consumer[_-]?(?:id|key|secret)|sign(?:ed|ature)|bearer|authorization|jsessionid|phpsessid|asp\.net[_-]sessionid|sid|jwt` // DefaultObfuscatorValueRegex is the default regexp used to obfuscate values @@ -63,6 +69,7 @@ const ( type APISecConfig struct { Sampler apisec.Sampler Enabled bool + IsProxy bool // Deprecated: use the new [APISecConfig.Sampler] instead. SampleRate float64 } @@ -79,12 +86,23 @@ type APISecOption func(*APISecConfig) func NewAPISecConfig(opts ...APISecOption) APISecConfig { cfg := APISecConfig{ Enabled: boolEnv(EnvAPISecEnabled, true), - Sampler: apisec.NewSamplerWithInterval(durationEnv(envAPISecSampleDelay, "s", DefaultAPISecSampleInterval)), SampleRate: readAPISecuritySampleRate(), } for _, opt := range opts { opt(&cfg) } + + if cfg.Sampler != nil { + return cfg + } + + if cfg.IsProxy { + rate := intEnv(EnvAPISecProxySampleRate, DefaultAPISecProxySampleRate) + cfg.Sampler = apisec.NewProxySampler(rate, DefaultAPISecProxySampleInterval) + } else { + cfg.Sampler = apisec.NewSamplerWithInterval(durationEnv(envAPISecSampleDelay, "s", DefaultAPISecSampleInterval)) + } + return cfg } @@ -116,6 +134,13 @@ func WithAPISecSampler(sampler apisec.Sampler) APISecOption { } } +// WithProxy configures API Security for a proxy environment. +func WithProxy() APISecOption { + return func(c *APISecConfig) { + c.IsProxy = true + } +} + // RASPEnabled returns true if RASP functionalities are enabled through the env, or if DD_APPSEC_RASP_ENABLED // is not set func RASPEnabled() bool { @@ -243,3 +268,16 @@ func durationEnv(key string, unit string, def time.Duration) time.Duration { } return val } + +func intEnv(key string, def int) int { + strVal, ok := os.LookupEnv(key) + if !ok { + return def + } + val, err := strconv.Atoi(strVal) + if err != nil { + logEnvVarParsingError(key, strVal, err, def) + return def + } + return val +} diff --git a/limiter/limiter.go b/limiter/limiter.go index f1f16d3..fbe4f3e 100644 --- a/limiter/limiter.go +++ b/limiter/limiter.go @@ -28,14 +28,21 @@ type Limiter interface { type TokenTicker struct { tokens atomic.Int64 // The amount of tokens currently available maxTokens int64 // The maximum amount of tokens the bucket can hold + interval time.Duration // The interval at which the tokens are refilled ticker *time.Ticker // The ticker used to update the bucket (nil if not started yet) stopChan chan struct{} // The channel to stop the ticker updater (nil if not started yet) } // NewTokenTicker is a utility function that allocates a token ticker, initializes necessary fields and returns it func NewTokenTicker(tokens, maxTokens int64) *TokenTicker { + return NewTokenTickerWithInterval(tokens, maxTokens, time.Second) +} + +// NewTokenTickerWithInterval is a utility function that allocates a token ticker with a custom interval +func NewTokenTickerWithInterval(tokens, maxTokens int64, interval time.Duration) *TokenTicker { t := &TokenTicker{ maxTokens: maxTokens, + interval: interval, } t.tokens.Store(tokens) return t @@ -44,7 +51,7 @@ func NewTokenTicker(tokens, maxTokens int64) *TokenTicker { // updateBucket performs a select loop to update the token amount in the bucket. // Used in a goroutine by the rate limiter. func (t *TokenTicker) updateBucket(startTime time.Time, ticksChan <-chan time.Time, stopChan <-chan struct{}, syncChan chan<- struct{}) { - nsPerToken := time.Second.Nanoseconds() / t.maxTokens + nsPerToken := t.interval.Nanoseconds() / t.maxTokens elapsedNs := int64(0) prevStamp := startTime diff --git a/limiter/limiter_test.go b/limiter/limiter_test.go index 6eaa3b3..7d0467c 100644 --- a/limiter/limiter_test.go +++ b/limiter/limiter_test.go @@ -349,3 +349,47 @@ func (t *TestTicker) tick(delta time.Duration) { func (t *TestTicker) Allow() bool { return t.t.Allow() } + +func newTestTickerWithInterval(tokens, maxTokens int64, interval time.Duration) *TestTicker { + return &TestTicker{ + C: make(chan time.Time), + t: NewTokenTickerWithInterval(tokens, maxTokens, interval), + } +} + +func TestLimiterWithInterval(t *testing.T) { + startTime := time.Now() + t.Run("60-per-minute-rate", func(t *testing.T) { + defer goleak.VerifyNone(t) + + l := newTestTickerWithInterval(1, 60, time.Minute) // 60 tokens per minute, so 1 per second + l.start(startTime) + defer l.stop() + require.True(t, l.Allow(), "First call should be allowed") + require.False(t, l.Allow(), "Second call should be disallowed") + + l.tick(500 * time.Millisecond) + require.False(t, l.Allow(), "A call after 0.5s should be disallowed") + + l.tick(500 * time.Millisecond) // Total 1 second passed + require.True(t, l.Allow(), "A call after 1s should be allowed") + require.False(t, l.Allow(), "Another call should be disallowed") + }) + + t.Run("1-per-100ms-rate", func(t *testing.T) { + defer goleak.VerifyNone(t) + + l := newTestTickerWithInterval(1, 1, 100*time.Millisecond) // 1 token per 100ms + l.start(startTime) + defer l.stop() + require.True(t, l.Allow(), "First call should be allowed") + require.False(t, l.Allow(), "Second call should be disallowed") + + l.tick(50 * time.Millisecond) + require.False(t, l.Allow(), "A call after 50ms should be disallowed") + + l.tick(50 * time.Millisecond) // Total 100ms passed + require.True(t, l.Allow(), "A call after 100ms should be allowed") + require.False(t, l.Allow(), "Another call should be disallowed") + }) +} From 941568f726a5c6d01c70ed01d6c9b1802e2d7831 Mon Sep 17 00:00:00 2001 From: Flavien Darche <11708575+e-n-0@users.noreply.github.com> Date: Fri, 27 Jun 2025 16:20:10 +0200 Subject: [PATCH 36/39] Refine documentation for the proxy sample rate (#53) # Changes Related to the PR https://github.com/DataDog/dd-trace-go/pull/3698, the documentation of the proxy sample rate has been updated. --- appsec/config.go | 1 + 1 file changed, 1 insertion(+) diff --git a/appsec/config.go b/appsec/config.go index 09cbbd4..54cc54f 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -25,6 +25,7 @@ const ( // Deprecated: a new [APISecConfig.Sampler] is now used instead of this. EnvAPISecSampleRate = "DD_API_SECURITY_REQUEST_SAMPLE_RATE" // EnvAPISecProxySampleRate is the env var used to set the sampling rate of API Security schema extraction for proxies. + // The value represents the number of schemas extracted per minute (samples per minute). EnvAPISecProxySampleRate = "DD_API_SECURITY_PROXY_SAMPLE_RATE" // EnvObfuscatorKey is the env var used to provide the WAF key obfuscation regexp EnvObfuscatorKey = "DD_APPSEC_OBFUSCATION_PARAMETER_KEY_REGEXP" From 3f57bd23d1f8803a55d9ce09e2482730eb279c87 Mon Sep 17 00:00:00 2001 From: "dd-k9-library-go[bot]" <214463715+dd-k9-library-go[bot]@users.noreply.github.com> Date: Thu, 14 Aug 2025 13:53:20 +0000 Subject: [PATCH 37/39] Update embedded AppSec Rules to 1.15.1 (#55) Automatically created by [GitHub Actions](https://github.com/DataDog/appsec-internal-go/actions/runs/16872215336). Co-authored-by: dd-k9-library-go[bot] <214463715+dd-k9-library-go[bot]@users.noreply.github.com> --- appsec/embed.go | 4 +- appsec/rules.json | 363 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 361 insertions(+), 6 deletions(-) diff --git a/appsec/embed.go b/appsec/embed.go index 52cf177..125f298 100644 --- a/appsec/embed.go +++ b/appsec/embed.go @@ -14,7 +14,7 @@ var ( //go:embed rules.json staticRecommendedRules []byte - // StaticRecommendedRules holds the recommended AppSec security rules (v1.14.2) - // Source: https://github.com/DataDog/appsec-event-rules/blob/1.14.2/build/recommended.json + // StaticRecommendedRules holds the recommended AppSec security rules (v1.15.1) + // Source: https://github.com/DataDog/appsec-event-rules/blob/1.15.1/build/recommended.json StaticRecommendedRules = unsafe.String(&staticRecommendedRules[0], len(staticRecommendedRules)) ) diff --git a/appsec/rules.json b/appsec/rules.json index e2216bb..b39992a 100644 --- a/appsec/rules.json +++ b/appsec/rules.json @@ -1,7 +1,7 @@ { "version": "2.2", "metadata": { - "rules_version": "1.14.2" + "rules_version": "1.15.1" }, "rules": [ { @@ -2985,7 +2985,7 @@ "address": "graphql.server.resolver" } ], - "regex": "\\b(?:(?:l(?:(?:utimes|chmod)(?:Sync)?|(?:stat|ink)Sync)|w(?:rite(?:(?:File|v)(?:Sync)?|Sync)|atchFile)|u(?:n(?:watchFile|linkSync)|times(?:Sync)?)|s(?:(?:ymlink|tat)Sync|pawn(?:File|Sync))|ex(?:ec(?:File(?:Sync)?|Sync)|istsSync)|a(?:ppendFile|ccess)(?:Sync)?|(?:Caveat|Inode)s|open(?:dir)?Sync|new\\s+Function|Availability|\\beval)\\s*\\(|m(?:ain(?:Module\\s*(?:\\W*\\s*(?:constructor|require)|\\[)|\\s*(?:\\W*\\s*(?:constructor|require)|\\[))|kd(?:temp(?:Sync)?|irSync)\\s*\\(|odule\\.exports\\s*=)|c(?:(?:(?:h(?:mod|own)|lose)Sync|reate(?:Write|Read)Stream|p(?:Sync)?)\\s*\\(|o(?:nstructor\\s*(?:\\W*\\s*_load|\\[)|pyFile(?:Sync)?\\s*\\())|f(?:(?:(?:s(?:(?:yncS)?|tatS)|datas(?:yncS)?)ync|ch(?:mod|own)(?:Sync)?)\\s*\\(|u(?:nction\\s*\\(\\s*\\)\\s*{|times(?:Sync)?\\s*\\())|r(?:e(?:(?:ad(?:(?:File|link|dir)?Sync|v(?:Sync)?)|nameSync)\\s*\\(|quire\\s*(?:\\W*\\s*main|\\[))|m(?:Sync)?\\s*\\()|process\\s*(?:\\W*\\s*(?:mainModule|binding)|\\[)|t(?:his\\.constructor|runcateSync\\s*\\()|_(?:\\$\\$ND_FUNC\\$\\$_|_js_function)|global\\s*(?:\\W*\\s*process|\\[)|String\\s*\\.\\s*fromCharCode|binding\\s*\\[)", + "regex": "\\b(?:(?:l(?:(?:utimes|chmod)(?:Sync)?|(?:stat|ink)Sync)|w(?:rite(?:(?:File|v)(?:Sync)?|Sync)|atchFile)|u(?:n(?:watchFile|linkSync)|times(?:Sync)?)|s(?:(?:ymlink|tat)Sync|pawn(?:File|Sync))|ex(?:ec(?:File(?:Sync)?|Sync)|istsSync)|a(?:ppendFile|ccess)(?:Sync)?|(?:Caveat|Inode)s|open(?:dir)?Sync|new\\s+Function|Availability|\\beval)\\s*\\(|m(?:ain(?:Module\\s*(?:\\W*\\s*(?:constructor|require)|\\[)|\\s*(?:\\W*\\s*(?:constructor|require)|\\[))|kd(?:temp(?:Sync)?|irSync)\\s*\\(|odule\\.exports\\s*=)|c(?:(?:(?:h(?:mod|own)|lose)Sync|reate(?:Write|Read)Stream|p(?:Sync)?)\\s*\\(|o(?:nstructor\\s*(?:\\W*\\s*_load|\\[)|pyFile(?:Sync)?\\s*\\())|f(?:(?:(?:s(?:(?:yncS)?|tatS)|datas(?:yncS)?)ync|ch(?:mod|own)(?:Sync)?)\\s*\\(|u(?:nction\\s*\\(\\s*\\)\\s*{|times(?:Sync)?\\s*\\())|r(?:e(?:(?:ad(?:(?:File|link|dir)?Sync|v(?:Sync)?)|nameSync)\\s*\\(|quire\\s*(?:\\W*\\s*main\\b|\\[))|m(?:Sync)?\\s*\\()|process\\s*(?:\\W*\\s*(?:mainModule|binding)|\\[)|t(?:his\\.constructor|runcateSync\\s*\\()|_(?:\\$\\$ND_FUNC\\$\\$_|_js_function)|global\\s*(?:\\W*\\s*process|\\[)|String\\s*\\.\\s*fromCharCode|binding\\s*\\[)", "options": { "case_sensitive": true, "min_length": 3 @@ -5539,6 +5539,7 @@ "confidence": "0", "module": "waf" }, + "max_version": "1.24.9", "conditions": [ { "parameters": { @@ -5656,6 +5657,52 @@ ], "transformers": [] }, + { + "id": "dog-932-110", + "name": "Python: Subprocess-based command injection", + "tags": { + "type": "command_injection", + "category": "attack_attempt", + "confidence": "0", + "module": "waf" + }, + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.query" + }, + { + "address": "server.request.body" + }, + { + "address": "server.request.path_params" + }, + { + "address": "server.request.headers.no_cookies" + }, + { + "address": "grpc.server.request.message" + }, + { + "address": "graphql.server.all_resolvers" + }, + { + "address": "graphql.server.resolver" + } + ], + "regex": "(?s)\\bsubprocess\\b.*\\b(?:check_output|run|Popen|call|check_call)\\b", + "options": { + "case_sensitive": true, + "min_length": 14 + } + }, + "operator": "match_regex" + } + ], + "transformers": [] + }, { "id": "dog-934-001", "name": "XXE - XML file loads external entity", @@ -6625,7 +6672,10 @@ { "address": "graphql.server.resolver" } - ] + ], + "options": { + "path-inspection": true + } }, "operator": "ssrf_detector" } @@ -8870,6 +8920,271 @@ "transformers": [] } ], + "rules_compat": [ + { + "id": "api-001-100", + "name": "JWT: No expiry is present", + "tags": { + "type": "jwt", + "category": "api_security", + "confidence": "0", + "module": "business-logic" + }, + "min_version": "1.25.0", + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.jwt", + "key_path": [ + "payload", + "exp" + ] + } + ] + }, + "operator": "!exists" + } + ], + "transformers": [], + "output": { + "event": false, + "keep": false, + "attributes": { + "_dd.appsec.api.jwt.no_expiry": { + "value": 1 + } + } + } + }, + { + "id": "api-001-110", + "name": "JWT: Collect algorithm used", + "tags": { + "type": "jwt", + "category": "api_security", + "confidence": "0", + "module": "business-logic" + }, + "min_version": "1.25.0", + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.jwt", + "key_path": [ + "header", + "alg" + ] + } + ] + }, + "operator": "exists" + } + ], + "transformers": [], + "output": { + "event": false, + "keep": false, + "attributes": { + "_dd.appsec.api.jwt_alg": { + "address": "server.request.jwt", + "key_path": [ + "header", + "alg" + ] + } + } + } + }, + { + "id": "api-001-120", + "name": "JWT: No audience is specified", + "tags": { + "type": "jwt", + "category": "api_security", + "confidence": "0", + "module": "business-logic" + }, + "min_version": "1.25.0", + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.jwt", + "key_path": [ + "payload", + "aud" + ] + } + ] + }, + "operator": "!exists" + } + ], + "transformers": [], + "output": { + "event": false, + "keep": false, + "attributes": { + "_dd.appsec.api.jwt.no_audience": { + "value": 1 + } + } + } + }, + { + "id": "api-001-130", + "name": "JWT: None algorithm used", + "tags": { + "type": "jwt", + "category": "api_security", + "confidence": "0", + "module": "business-logic" + }, + "min_version": "1.25.0", + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.jwt", + "key_path": [ + "header", + "alg" + ] + } + ], + "list": [ + "none", + "nonE", + "noNe", + "noNE", + "nOne", + "nOnE", + "nONe", + "nONE", + "None", + "NonE", + "NoNe", + "NoNE", + "NOne", + "NOnE", + "NONe", + "NONE" + ] + }, + "operator": "exact_match" + } + ], + "transformers": [], + "output": { + "event": false, + "keep": true, + "attributes": { + "_dd.appsec.api.jwt.none_alg": { + "value": 1 + } + } + } + }, + { + "id": "ua0-600-551", + "name": "Datadog test scanner - scalar trace-tagging version: user-agent", + "tags": { + "type": "security_scanner", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "tool_name": "Datadog Canary Test", + "confidence": "1", + "module": "waf" + }, + "min_version": "1.25.0", + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "user-agent" + ] + }, + { + "address": "grpc.server.request.metadata", + "key_path": [ + "dd-canary" + ] + } + ], + "regex": "^dd-test-scanner-tag-scalar(?:$|/|\\s)" + }, + "operator": "match_regex" + } + ], + "transformers": [], + "output": { + "event": false, + "attributes": { + "_dd.appsec.test.scanner.scalar": { + "value": 1 + } + } + } + }, + { + "id": "ua0-600-552", + "name": "Datadog test scanner - reference trace-tagging version: user-agent", + "tags": { + "type": "security_scanner", + "category": "attack_attempt", + "cwe": "200", + "capec": "1000/118/169", + "tool_name": "Datadog Canary Test", + "confidence": "1", + "module": "waf" + }, + "min_version": "1.25.0", + "conditions": [ + { + "parameters": { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "user-agent" + ] + }, + { + "address": "grpc.server.request.metadata", + "key_path": [ + "dd-canary" + ] + } + ], + "regex": "^dd-test-scanner-tag-ref(?:$|/|\\s)" + }, + "operator": "match_regex" + } + ], + "transformers": [], + "output": { + "event": false, + "attributes": { + "_dd.appsec.test.scanner.reference": { + "address": "server.request.headers.no_cookies", + "key_path": [ + "user-agent" + ] + } + } + } + } + ], "processors": [ { "id": "http-endpoint-fingerprint", @@ -9074,6 +9389,28 @@ "evaluate": true, "output": true }, + { + "id": "decode-auth-jwt", + "generator": "jwt_decode", + "min_version": "1.25.0", + "parameters": { + "mappings": [ + { + "inputs": [ + { + "address": "server.request.headers.no_cookies", + "key_path": [ + "authorization" + ] + } + ], + "output": "server.request.jwt" + } + ] + }, + "evaluate": true, + "output": false + }, { "id": "http-network-fingerprint", "generator": "http_network_fingerprint", @@ -9918,6 +10255,24 @@ "category": "payment" } }, + { + "id": "c542c147-3883-43d6-a067-178e4a7bd65d", + "name": "Password", + "key": { + "operator": "match_regex", + "parameters": { + "regex": "\\bpass(?:[_-]?word|wd)?\\b|\\bpwd\\b", + "options": { + "case_sensitive": false, + "min_length": 3 + } + } + }, + "tags": { + "type": "password", + "category": "credentials" + } + }, { "id": "18b608bd7a764bff5b2344c0", "name": "Phone number", @@ -10146,4 +10501,4 @@ } } ] -} \ No newline at end of file +} From 5240423413a82951cf1938a08b2e686fce4e18d5 Mon Sep 17 00:00:00 2001 From: "dd-k9-library-go[bot]" <214463715+dd-k9-library-go[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 09:26:06 +0000 Subject: [PATCH 38/39] chore: update default ruleset to v1.15.1 (#57) Updated default ruleset to v1.15.1. --------- Co-authored-by: dd-k9-library-go[bot] <214463715+dd-k9-library-go[bot]@users.noreply.github.com> Co-authored-by: Romain Marcadier --- .github/workflows/update-rules.yml | 55 ++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/.github/workflows/update-rules.yml b/.github/workflows/update-rules.yml index 445b5f7..26bb955 100644 --- a/.github/workflows/update-rules.yml +++ b/.github/workflows/update-rules.yml @@ -7,11 +7,15 @@ on: jobs: update: runs-on: ubuntu-latest + name: Get latest ruleset outputs: mutation_happened: ${{ steps.detect.outputs.mutation_happened }} + version: ${{ steps.update.outputs.version }} steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-go@f111f3307d8850f501ac008e886eec1fd1932a34 # v5.3.0 + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Setup Go + uses: actions/setup-go@f111f3307d8850f501ac008e886eec1fd1932a34 # v5.3.0 - name: Generate a GitHub token id: generate-token uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6 @@ -22,14 +26,19 @@ jobs: repositories: appsec-event-rules permission-contents: read - name: Upgrade AppSec Rules - run: ./_tools/rules-updater/update.sh latest + id: update + run: |- + ./_tools/rules-updater/update.sh latest + VERSION=$(jq -r '.metadata.rules_version' < ./appsec/rules.json) + echo "Ruleset version: ${VERSION}" + echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" env: GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} - name: Detect Updated Code id: detect run: |- git add . - git diff --staged --patch --exit-code > ${{ runner.temp }}/repo.patch || echo "mutation_happened=true" >> $GITHUB_OUTPUT + git diff --staged --patch --exit-code > ${{ runner.temp }}/repo.patch || echo "mutation_happened=true" >> "${GITHUB_OUTPUT}" - name: Upload Patch if: steps.detect.outputs.mutation_happened uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 @@ -39,6 +48,7 @@ jobs: create-pr: needs: update + name: Create PR runs-on: ubuntu-latest permissions: contents: write @@ -50,7 +60,8 @@ jobs: with: app-id: ${{ vars.DD_K9_LIBRARY_GO_APP_ID }} private-key: ${{ secrets.DD_K9_LIBRARY_GO_APP_PRIVATE_KEY }} - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: token: ${{ steps.generate-token.outputs.token }} persist-credentials: true @@ -71,15 +82,31 @@ jobs: env: APP_SLUG: ${{ steps.generate-token.outputs.app-slug }} GITHUB_TOKEN: ${{ github.token }} - - name: Push Changes + - name: Create PR Branch + id: create-branch run: |- - git add . - git commit -m "Update embedded AppSec Rules" - git push --force-with-lease origin HEAD:automation/update-appsec-rules - - name: Create Pull Request - run: |- - gh pr create --title "Update embedded AppSec Rules to ${{ steps.apply.outputs.version }}" \ - --body "Automatically created by [GitHub Actions](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})." \ - --base "main" --head "automation/update-appsec-rules" + branch="automation/default-ruleset-update/${VERSION}" + git push --force origin "${{ github.sha }}":"refs/heads/${branch}" + echo "branch=${branch}" >> "${GITHUB_OUTPUT}" + git fetch origin "${branch}" + env: + VERSION: ${{ needs.update.outputs.version }} + - name: Create Commit on PR Branch + uses: planetscale/ghcommit-action@6a383e778f6620afde4bf4b45069d3c6983c1ae2 # v0.2.15 + with: + commit_message: "chore: update default ruleset to v${{ needs.update.outputs.version }}" + branch: ${{ steps.create-branch.outputs.branch }} + repo: ${{ github.repository }} env: GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} + - name: Create Pull Request + run: |- + git fetch origin "${{ steps.create-branch.outputs.branch }}" + git reset --hard HEAD + git switch "${{ steps.create-branch.outputs.branch }}" + gh pr create --title "chore: update default ruleset to v${VERSION}" \ + --body "Updated default ruleset to v${VERSION}." \ + --head="${{ steps.create-branch.outputs.branch }}" + env: + GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} + VERSION: ${{ needs.update.outputs.version }} From f9cc78110601e75cd2029f7a26673c2813ed1a30 Mon Sep 17 00:00:00 2001 From: Ramy Elkest <4thkest@gmail.com> Date: Fri, 3 Apr 2026 10:03:57 +0100 Subject: [PATCH 39/39] chore: remove update-rules workflow (repo deprecated) (#72) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary This repo is deprecated (last real commit: Aug 2025). Instead of migrating the `update-rules.yml` workflow from `DD_K9_LIBRARY_GO_APP_PRIVATE_KEY` to dd-octo-sts, simply remove the workflow entirely. This eliminates the dependency on the shared secret, which is the goal of the migration effort. ## Changes - Deleted `.github/workflows/update-rules.yml` (scheduled rule updater) ## Notes - The `appsec-internal-go.github.read-rules.sts.yaml` policy in appsec-event-rules (merged in DataDog/appsec-event-rules#281) is now unused but harmless to leave - After merge, the `DD_K9_LIBRARY_GO_APP_PRIVATE_KEY` secret can be removed from this repo's settings 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- Jira: APPSEC-62083 Co-authored-by: Claude Opus 4.6 (1M context) --- .github/workflows/update-rules.yml | 112 ----------------------------- 1 file changed, 112 deletions(-) delete mode 100644 .github/workflows/update-rules.yml diff --git a/.github/workflows/update-rules.yml b/.github/workflows/update-rules.yml deleted file mode 100644 index 26bb955..0000000 --- a/.github/workflows/update-rules.yml +++ /dev/null @@ -1,112 +0,0 @@ -name: Update AppSec Rules -on: - workflow_dispatch: # manually - schedule: - - cron: "0 6 * * 1" # every Monday at 06:00 UTC - -jobs: - update: - runs-on: ubuntu-latest - name: Get latest ruleset - outputs: - mutation_happened: ${{ steps.detect.outputs.mutation_happened }} - version: ${{ steps.update.outputs.version }} - steps: - - name: Checkout - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - name: Setup Go - uses: actions/setup-go@f111f3307d8850f501ac008e886eec1fd1932a34 # v5.3.0 - - name: Generate a GitHub token - id: generate-token - uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6 - with: - app-id: ${{ vars.DD_K9_LIBRARY_GO_APP_ID }} - private-key: ${{ secrets.DD_K9_LIBRARY_GO_APP_PRIVATE_KEY }} - owner: DataDog - repositories: appsec-event-rules - permission-contents: read - - name: Upgrade AppSec Rules - id: update - run: |- - ./_tools/rules-updater/update.sh latest - VERSION=$(jq -r '.metadata.rules_version' < ./appsec/rules.json) - echo "Ruleset version: ${VERSION}" - echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" - env: - GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} - - name: Detect Updated Code - id: detect - run: |- - git add . - git diff --staged --patch --exit-code > ${{ runner.temp }}/repo.patch || echo "mutation_happened=true" >> "${GITHUB_OUTPUT}" - - name: Upload Patch - if: steps.detect.outputs.mutation_happened - uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 - with: - name: repo.patch - path: ${{ runner.temp }}/repo.patch - - create-pr: - needs: update - name: Create PR - runs-on: ubuntu-latest - permissions: - contents: write - if: needs.update.outputs.mutation_happened - steps: - - name: Generate a GitHub token - id: generate-token - uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6 - with: - app-id: ${{ vars.DD_K9_LIBRARY_GO_APP_ID }} - private-key: ${{ secrets.DD_K9_LIBRARY_GO_APP_PRIVATE_KEY }} - - name: Checkout - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - token: ${{ steps.generate-token.outputs.token }} - persist-credentials: true - - name: Download Patch - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 - with: - name: repo.patch - path: ${{ runner.temp }} - - name: Apply Patch - id: apply - run: |- - git apply ${{ runner.temp }}/repo.patch - echo "version=$(jq -r '.metadata.rules_version' < ./appsec/rules.json)" >> $GITHUB_OUTPUT - - name: Configure git identity - run: |- - git config user.name "${APP_SLUG}[bot]" - git config user.email "$(gh api "/users/${APP_SLUG}[bot]" | jq .id)+${APP_SLUG}[bot]@users.noreply.github.com" - env: - APP_SLUG: ${{ steps.generate-token.outputs.app-slug }} - GITHUB_TOKEN: ${{ github.token }} - - name: Create PR Branch - id: create-branch - run: |- - branch="automation/default-ruleset-update/${VERSION}" - git push --force origin "${{ github.sha }}":"refs/heads/${branch}" - echo "branch=${branch}" >> "${GITHUB_OUTPUT}" - git fetch origin "${branch}" - env: - VERSION: ${{ needs.update.outputs.version }} - - name: Create Commit on PR Branch - uses: planetscale/ghcommit-action@6a383e778f6620afde4bf4b45069d3c6983c1ae2 # v0.2.15 - with: - commit_message: "chore: update default ruleset to v${{ needs.update.outputs.version }}" - branch: ${{ steps.create-branch.outputs.branch }} - repo: ${{ github.repository }} - env: - GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} - - name: Create Pull Request - run: |- - git fetch origin "${{ steps.create-branch.outputs.branch }}" - git reset --hard HEAD - git switch "${{ steps.create-branch.outputs.branch }}" - gh pr create --title "chore: update default ruleset to v${VERSION}" \ - --body "Updated default ruleset to v${VERSION}." \ - --head="${{ steps.create-branch.outputs.branch }}" - env: - GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} - VERSION: ${{ needs.update.outputs.version }}