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 diff --git a/.github/workflows/update-rules.yml b/.github/workflows/update-rules.yml deleted file mode 100644 index c24c442..0000000 --- a/.github/workflows/update-rules.yml +++ /dev/null @@ -1,65 +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 - outputs: - mutation_happened: ${{ steps.detect.outputs.mutation_happened }} - steps: - - 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: - GITHUB_TOKEN: ${{ secrets.UPDATE_RULES_GITHUB_TOKEN || secrets.GITHUB_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 - runs-on: ubuntu-latest - permissions: - contents: write - if: needs.update.outputs.mutation_happened - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - 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 "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 --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.MUTATOR_GITHUB_TOKEN || secrets.GITHUB_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)) +) 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 f24f0c3..54cc54f 100644 --- a/appsec/config.go +++ b/appsec/config.go @@ -24,6 +24,9 @@ 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. + // 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" // EnvObfuscatorValue is the env var used to provide the WAF value obfuscation regexp @@ -48,10 +51,14 @@ 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 - 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 @@ -63,6 +70,7 @@ const ( type APISecConfig struct { Sampler apisec.Sampler Enabled bool + IsProxy bool // Deprecated: use the new [APISecConfig.Sampler] instead. SampleRate float64 } @@ -79,12 +87,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 +135,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 +269,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/appsec/embed.go b/appsec/embed.go index ac8bea8..125f298 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.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.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.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 +} 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) +} 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") + }) +}