From 58b2de1e58aee986279b7c7b88d88cfc76394640 Mon Sep 17 00:00:00 2001 From: Dan Kortschak <90160302+efd6@users.noreply.github.com> Date: Tue, 24 Oct 2023 09:10:45 +1030 Subject: [PATCH] x-pack/filebeat/input/cel: add support for digest authentication (#36932) --- CHANGELOG.next.asciidoc | 1 + NOTICE.txt | 31 ++++ go.mod | 1 + go.sum | 2 + .../filebeat/docs/inputs/input-cel.asciidoc | 36 ++++- x-pack/filebeat/input/cel/config_auth.go | 46 +++++- x-pack/filebeat/input/cel/config_test.go | 72 +++++++-- x-pack/filebeat/input/cel/input.go | 14 ++ x-pack/filebeat/input/cel/input_test.go | 148 ++++++++++++++++++ 9 files changed, 331 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.next.asciidoc b/CHANGELOG.next.asciidoc index 890675b2385..7fbe4c0e480 100644 --- a/CHANGELOG.next.asciidoc +++ b/CHANGELOG.next.asciidoc @@ -243,6 +243,7 @@ is collected by it. - Add cache processor. {pull}36786[36786] - Avoid unwanted publication of Azure entity records. {pull}36753[36753] - Avoid unwanted publication of Okta entity records. {pull}36770[36770] +- Add support for Digest Authentication to CEL input. {issue}35514[35514] {pull}36932[36932] *Auditbeat* diff --git a/NOTICE.txt b/NOTICE.txt index 019668a2a8f..7061208f1ef 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -20004,6 +20004,37 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-------------------------------------------------------------------------------- +Dependency : github.com/icholy/digest +Version: v0.1.22 +Licence type (autodetected): MIT +-------------------------------------------------------------------------------- + +Contents of probable licence file $GOMODCACHE/github.com/icholy/digest@v0.1.22/LICENSE: + +MIT License + +Copyright (c) 2020 Ilia Choly + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + -------------------------------------------------------------------------------- Dependency : github.com/elastic/dhcp Version: v0.0.0-20200227161230-57ec251c7eb3 diff --git a/go.mod b/go.mod index fc3e8eab686..227b7659e63 100644 --- a/go.mod +++ b/go.mod @@ -213,6 +213,7 @@ require ( github.com/googleapis/gax-go/v2 v2.11.0 github.com/gorilla/handlers v1.5.1 github.com/gorilla/mux v1.8.0 + github.com/icholy/digest v0.1.22 github.com/lestrrat-go/jwx/v2 v2.0.11 github.com/otiai10/copy v1.12.0 github.com/pierrec/lz4/v4 v4.1.16 diff --git a/go.sum b/go.sum index 47cb095833b..6ce895072b5 100644 --- a/go.sum +++ b/go.sum @@ -1201,6 +1201,8 @@ github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbc github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/icholy/digest v0.1.22 h1:dRIwCjtAcXch57ei+F0HSb5hmprL873+q7PoVojdMzM= +github.com/icholy/digest v0.1.22/go.mod h1:uLAeDdWKIWNFMH0wqbwchbTQOmJWhzSnL7zmqSPqEEc= github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= diff --git a/x-pack/filebeat/docs/inputs/input-cel.asciidoc b/x-pack/filebeat/docs/inputs/input-cel.asciidoc index aef0c4862ab..786f98aa842 100644 --- a/x-pack/filebeat/docs/inputs/input-cel.asciidoc +++ b/x-pack/filebeat/docs/inputs/input-cel.asciidoc @@ -22,6 +22,7 @@ This input supports: * Auth ** Basic +** Digest ** OAuth2 * Retrieval at a configurable interval * Pagination @@ -239,7 +240,7 @@ As noted above the `cel` input provides functions, macros, and global variables In addition to the extensions provided in the packages listed above, a global variable `useragent` is also provided which gives the user CEL program access to the {beatname_lc} user-agent string. -Additionally, it supports authentication via Basic auth, HTTP Headers or oauth2. +Additionally, it supports authentication via Basic Authentication, Digest Authentication or OAuth2. Example configurations with authentication: @@ -253,6 +254,16 @@ filebeat.inputs: resource.url: http://localhost ---- +["source","yaml",subs="attributes"] +---- +filebeat.inputs: +- type: cel + auth.digest: + user: user@domain.tld + password: P@$$W0₹D + resource.url: http://localhost +---- + ["source","yaml",subs="attributes"] ---- filebeat.inputs: @@ -398,6 +409,29 @@ The user to authenticate with. The password to use. +[float] +==== `auth.digest.enabled` + +When set to `false`, disables the digest auth configuration. Default: `true`. + +NOTE: digest auth settings are disabled if either `enabled` is set to `false` or +the `auth.digest` section is missing. + +[float] +==== `auth.digest.user` + +The user to authenticate with. + +[float] +==== `auth.digest.password` + +The password to use. + +[float] +==== `auth.digest.no_reuse` + +When set to `true`, Digest Authentication challenges are not reused. + [float] ==== `auth.oauth2.enabled` diff --git a/x-pack/filebeat/input/cel/config_auth.go b/x-pack/filebeat/input/cel/config_auth.go index 5c80507fdad..e550a9635d5 100644 --- a/x-pack/filebeat/input/cel/config_auth.go +++ b/x-pack/filebeat/input/cel/config_auth.go @@ -24,12 +24,23 @@ import ( ) type authConfig struct { - Basic *basicAuthConfig `config:"basic"` - OAuth2 *oAuth2Config `config:"oauth2"` + Basic *basicAuthConfig `config:"basic"` + Digest *digestAuthConfig `config:"digest"` + OAuth2 *oAuth2Config `config:"oauth2"` } func (c authConfig) Validate() error { - if c.Basic.isEnabled() && c.OAuth2.isEnabled() { + var n int + if c.Basic.isEnabled() { + n++ + } + if c.Digest.isEnabled() { + n++ + } + if c.OAuth2.isEnabled() { + n++ + } + if n > 1 { return errors.New("only one kind of auth can be enabled") } return nil @@ -41,7 +52,7 @@ type basicAuthConfig struct { Password string `config:"password"` } -// IsEnabled returns true if the `enable` field is set to true in the yaml. +// isEnabled returns true if the `enable` field is set to true in the yaml. func (b *basicAuthConfig) isEnabled() bool { return b != nil && (b.Enabled == nil || *b.Enabled) } @@ -59,6 +70,31 @@ func (b *basicAuthConfig) Validate() error { return nil } +type digestAuthConfig struct { + Enabled *bool `config:"enabled"` + User string `config:"user"` + Password string `config:"password"` + NoReuse *bool `config:"no_reuse"` +} + +// isEnabled returns true if the `enable` field is set to true in the yaml. +func (d *digestAuthConfig) isEnabled() bool { + return d != nil && (d.Enabled == nil || *d.Enabled) +} + +// Validate checks if oauth2 config is valid. +func (d *digestAuthConfig) Validate() error { + if !d.isEnabled() { + return nil + } + + if d.User == "" || d.Password == "" { + return errors.New("both user and password must be set") + } + + return nil +} + // An oAuth2Provider represents a supported oauth provider. type oAuth2Provider string @@ -107,7 +143,7 @@ type oAuth2Config struct { OktaJWKJSON common.JSONBlob `config:"okta.jwk_json"` } -// IsEnabled returns true if the `enable` field is set to true in the yaml. +// isEnabled returns true if the `enable` field is set to true in the yaml. func (o *oAuth2Config) isEnabled() bool { return o != nil && (o.Enabled == nil || *o.Enabled) } diff --git a/x-pack/filebeat/input/cel/config_test.go b/x-pack/filebeat/input/cel/config_test.go index e19c08399cb..0cd404705e2 100644 --- a/x-pack/filebeat/input/cel/config_test.go +++ b/x-pack/filebeat/input/cel/config_test.go @@ -39,26 +39,45 @@ func TestGetProviderIsCanonical(t *testing.T) { } func TestIsEnabled(t *testing.T) { - oauth2 := oAuth2Config{} - if !oauth2.isEnabled() { - t.Errorf("OAuth2 not enabled by default") + type enabler interface { + isEnabled() bool + take(*bool) } + for _, test := range []struct { + name string + auth enabler + }{ + {name: "basic", auth: &basicAuthConfig{}}, + {name: "digest", auth: &digestAuthConfig{}}, + {name: "OAuth2", auth: &oAuth2Config{}}, + } { + t.Run(test.name, func(t *testing.T) { + if !test.auth.isEnabled() { + t.Errorf("auth not enabled by default") + } - var enabled bool - for i := 0; i < 4; i++ { - oauth2.Enabled = &enabled - if got := oauth2.isEnabled(); got != enabled { - t.Errorf("unexpected OAuth2 enabled state on iteration %d: got:%t want:%t", i, got, enabled) - } - enabled = !enabled - } + var enabled bool + for i := 0; i < 4; i++ { + test.auth.take(&enabled) + if got := test.auth.isEnabled(); got != enabled { + t.Errorf("unexpected auth enabled state on iteration %d: got:%t want:%t", i, got, enabled) + } + enabled = !enabled + } - oauth2.Enabled = nil - if !oauth2.isEnabled() { - t.Errorf("OAuth2 not enabled if nilled") + test.auth.take(nil) + if !test.auth.isEnabled() { + t.Errorf("auth not enabled if nilled") + } + }) } } +// take methods are for testing only. +func (b *basicAuthConfig) take(on *bool) { b.Enabled = on } +func (d *digestAuthConfig) take(on *bool) { d.Enabled = on } +func (o *oAuth2Config) take(on *bool) { o.Enabled = on } + func TestOAuth2GetTokenURL(t *testing.T) { const host = "http://localhost" for _, test := range []struct { @@ -143,6 +162,31 @@ var oAuth2ValidationTests = []struct { }, }, }, + { + name: "can't_set_oauth2_and_digest_auth_together", + wantErr: errors.New("only one kind of auth can be enabled accessing 'auth'"), + input: map[string]interface{}{ + "auth.digest.user": "user", + "auth.digest.password": "pass", + "auth.oauth2": map[string]interface{}{ + "token_url": "localhost", + "client": map[string]interface{}{ + "id": "a_client_id", + "secret": "a_client_secret", + }, + }, + }, + }, + { + name: "can't_set_basic_and_digest_auth_together", + wantErr: errors.New("only one kind of auth can be enabled accessing 'auth'"), + input: map[string]interface{}{ + "auth.basic.user": "user", + "auth.basic.password": "pass", + "auth.digest.user": "user", + "auth.digest.password": "pass", + }, + }, { name: "can_set_oauth2_and_basic_auth_together_if_oauth2_is_disabled", input: map[string]interface{}{ diff --git a/x-pack/filebeat/input/cel/input.go b/x-pack/filebeat/input/cel/input.go index ea4958b9c30..499ae97f7fa 100644 --- a/x-pack/filebeat/input/cel/input.go +++ b/x-pack/filebeat/input/cel/input.go @@ -24,6 +24,7 @@ import ( "time" retryablehttp "github.com/hashicorp/go-retryablehttp" + "github.com/icholy/digest" "github.com/rcrowley/go-metrics" "go.elastic.co/ecszap" "go.uber.org/zap" @@ -688,6 +689,19 @@ func newClient(ctx context.Context, cfg config, log *logp.Logger) (*http.Client, return nil, err } + if cfg.Auth.Digest.isEnabled() { + var noReuse bool + if cfg.Auth.Digest.NoReuse != nil { + noReuse = *cfg.Auth.Digest.NoReuse + } + c.Transport = &digest.Transport{ + Transport: c.Transport, + Username: cfg.Auth.Digest.User, + Password: cfg.Auth.Digest.Password, + NoReuse: noReuse, + } + } + if cfg.Resource.Tracer != nil { w := zapcore.AddSync(cfg.Resource.Tracer) go func() { diff --git a/x-pack/filebeat/input/cel/input_test.go b/x-pack/filebeat/input/cel/input_test.go index bc0cf171471..1a0a7b44211 100644 --- a/x-pack/filebeat/input/cel/input_test.go +++ b/x-pack/filebeat/input/cel/input_test.go @@ -7,6 +7,7 @@ package cel import ( "context" + "flag" "fmt" "io" "math/rand" @@ -22,6 +23,7 @@ import ( "time" "github.com/google/go-cmp/cmp" + "github.com/icholy/digest" v2 "github.com/elastic/beats/v7/filebeat/input/v2" inputcursor "github.com/elastic/beats/v7/filebeat/input/v2/input-cursor" @@ -31,8 +33,11 @@ import ( "github.com/elastic/elastic-agent-libs/mapstr" ) +var runRemote = flag.Bool("run_remote", false, "run tests using remote endpoints") + var inputTests = []struct { name string + remote bool server func(*testing.T, http.HandlerFunc, map[string]interface{}) handler http.HandlerFunc config map[string]interface{} @@ -1055,6 +1060,100 @@ var inputTests = []struct { }, // Authenticated access tests. + { + name: "digest_accept", + server: func(t *testing.T, h http.HandlerFunc, config map[string]interface{}) { + s := httptest.NewServer(h) + config["resource.url"] = s.URL + t.Cleanup(s.Close) + }, + config: map[string]interface{}{ + "interval": 1, + "auth.digest.user": "test_client", + "auth.digest.password": "secret_password", + "program": ` + bytes(get(state.url).Body).as(body, { + "events": [body.decode_json()] + }) + `, + }, + handler: digestAuthHandler( + "test_client", + "secret_password", + "test", + "random_string", + defaultHandler(http.MethodGet, ""), + ), + want: []map[string]interface{}{ + { + "hello": []interface{}{ + map[string]interface{}{ + "world": "moon", + }, + map[string]interface{}{ + "space": []interface{}{ + map[string]interface{}{ + "cake": "pumpkin", + }, + }, + }, + }, + }, + }, + }, + { + name: "digest_reject", + server: func(t *testing.T, h http.HandlerFunc, config map[string]interface{}) { + s := httptest.NewServer(h) + config["resource.url"] = s.URL + t.Cleanup(s.Close) + }, + config: map[string]interface{}{ + "interval": 1, + "auth.digest.user": "test_client", + "auth.digest.password": "wrong_secret_password", + "program": ` + bytes(get(state.url).Body).as(body, { + "events": [body.decode_json()] + }) + `, + }, + handler: digestAuthHandler( + "test_client", + "secret_password", + "test", + "random_string", + defaultHandler(http.MethodGet, ""), + ), + want: []map[string]interface{}{ + { + "error": "not authorized", + }, + }, + }, + { + // Test case modelled on `curl --digest -u test_user:secret_password https://httpbin.org/digest-auth/auth/test_user/secret_password/md5`. + name: "digest_remote", + remote: true, + server: func(_ *testing.T, _ http.HandlerFunc, _ map[string]interface{}) {}, + config: map[string]interface{}{ + "resource.url": "https://httpbin.org/digest-auth/auth/test_user/secret_password/md5", + "interval": 1, + "auth.digest.user": "test_user", + "auth.digest.password": "secret_password", + "program": ` + bytes(get(state.url).Body).as(body, { + "events": [body.decode_json()] + }) + `, + }, + want: []map[string]interface{}{ + { + "authenticated": true, + "user": "test_user", + }, + }, + }, { name: "OAuth2", server: func(t *testing.T, h http.HandlerFunc, config map[string]interface{}) { @@ -1248,6 +1347,9 @@ func TestInput(t *testing.T) { if reason, skip := skipOnWindows[test.name]; runtime.GOOS == "windows" && skip { t.Skip(reason) } + if test.remote && !*runRemote { + t.Skip("skipping remote endpoint test") + } if test.server != nil { test.server(t, test.handler, test.config) @@ -1482,6 +1584,52 @@ func retryHandler() http.HandlerFunc { } } +//nolint:errcheck // No point checking errors in test server. +func digestAuthHandler(user, pass, realm, nonce string, handle http.HandlerFunc) http.HandlerFunc { + chal := &digest.Challenge{ + Realm: realm, + Nonce: nonce, + Algorithm: "MD5", + QOP: []string{"auth"}, + } + return func(w http.ResponseWriter, r *http.Request) { + auth := r.Header.Get("Authorization") + if auth == "" { + w.Header().Add("WWW-Authenticate", chal.String()) + w.WriteHeader(http.StatusUnauthorized) + return + } + + reqCred, err := digest.ParseCredentials(auth) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + srvCred, err := digest.Digest(chal, digest.Options{ + Method: r.Method, + URI: r.URL.RequestURI(), + Cnonce: reqCred.Cnonce, + Count: reqCred.Nc, + Username: user, + Password: pass, + }) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + if reqCred.Response != srvCred.Response { + w.Header().Set("content-type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte(`{"error":"not authorized"}`)) + return + } + + handle(w, r) + } +} + //nolint:errcheck // No point checking errors in test server. func oauth2Handler(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/token" {