From e5b7e3f2b1ae33be678446251617072e0b999287 Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Wed, 2 Apr 2025 11:52:29 +0200 Subject: [PATCH 01/14] 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 02/14] 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 03/14] 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 04/14] 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 05/14] 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 06/14] 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 07/14] 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 08/14] 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 09/14] 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 10/14] 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 11/14] 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 12/14] 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 13/14] 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 14/14] 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 }}