Просмотр исходного кода

feat: warn when HMAC webhook actions use unsigned request arguments (#1185)

James Read 1 день назад
Родитель
Сommit
1eb4471ce6

+ 18 - 0
docs/modules/ROOT/pages/action_execution/onwebhook.adoc

@@ -223,6 +223,8 @@ actions:
 
 Header names that contain hyphens become argument keys with the same hyphens (for example `webhook_header_x-request-id`). Use the `index` map-lookup form shown above, because Go templates treat hyphens in bare identifiers as subtraction.
 
+These metadata arguments come from the request's path, query string and headers, which HMAC signatures do not cover. Do not rely on them for values an action needs to trust; see <<what-hmac-signatures-cover,What HMAC signatures cover>>.
+
 == Webhook Authentication
 
 OliveTin supports several authentication methods to verify webhook requests:
@@ -276,6 +278,22 @@ execOnWebhook:
       X-Event-Type: push
 ----
 
+[#what-hmac-signatures-cover]
+=== What HMAC signatures cover
+
+HMAC signatures, including the ones checked for the GitHub `template` webhooks, are worked out by the sender over the request body only. This is how GitHub, GitLab and similar services sign webhooks, so OliveTin cannot check anything more than the sender signed:
+
+* The request path, query string and headers are not signed. Anyone who has seen one signed request can send it again with a different path, query string or headers, and it will still pass the signature check.
+* There is no timestamp or nonce, so a signed request can be sent again, and it will run the action again.
+
+To keep webhooks safe:
+
+* Send webhooks to OliveTin over HTTPS, so that signed requests cannot be read or changed on the way.
+* Take any value that an action needs to trust from the request body, with `extract`. Do not use the `webhook_path`, `webhook_query` or `webhook_header_*` arguments for those values with HMAC webhooks. The xref:advanced_configuration/diagnostics.adoc[Diagnostics] page shows a warning (code `webhook_unsigned_argument`) for an action that does.
+* Make webhook-triggered actions safe to run more than once.
+
+`bearer` and `basic` authentication do not sign anything: they check that the request carries the secret. Anyone who has the secret can send any request.
+
 === Bearer Token
 
 Verify webhooks using a Bearer token in the Authorization header:

+ 10 - 0
service/internal/config/config.go

@@ -112,6 +112,16 @@ func IsKnownWebhookTemplate(name string) bool {
 	return slices.Contains(WebhookTemplateNames, name)
 }
 
+// HmacWebhookAuthTypes sign only the request body. The older of the two hash
+// functions is only accepted so that OliveTin can check signatures from
+// senders that still use it, such as older GitHub webhooks; OliveTin does not
+// use it for anything else.
+var HmacWebhookAuthTypes = []string{"hmac-sha256", "hmac-sha1"} // DevSkim: ignore DS126858
+
+func IsHmacWebhookAuthType(authType string) bool {
+	return slices.Contains(HmacWebhookAuthTypes, authType)
+}
+
 type WebhookConfig struct {
 	Secret        string            `koanf:"secret"`        // Optional: secret for signature verification
 	AuthType      string            `koanf:"authType"`      // Required unless set by a template: "hmac-sha256", "hmac-sha1", "bearer", "basic", "none"

+ 52 - 0
service/internal/configcheck/rebuild.go

@@ -6,6 +6,7 @@ import (
 	"fmt"
 	"os"
 	"path/filepath"
+	"slices"
 	"strings"
 
 	"github.com/OliveTin/OliveTin/internal/config"
@@ -41,6 +42,7 @@ func Rebuild(cfg *config.Config, extra ...configissues.Issue) {
 	collected = append(collected, collectWatcherPathIssues(cfg)...)
 	collected = append(collected, collectDashboardTypeIssues(cfg)...)
 	collected = append(collected, collectWebhookAuthIssues(cfg)...)
+	collected = append(collected, collectWebhookUnsignedArgumentIssues(cfg)...)
 	collected = append(collected, extra...)
 	configissues.Replace(collected)
 }
@@ -624,3 +626,53 @@ func webhookAuthTypeIssues(action *config.Action, webhook config.WebhookConfig,
 		"Webhook has no authType, so its requests are rejected. Set an authType such as hmac-sha256 or bearer, or authType: none to allow unauthenticated requests",
 		source, "")}
 }
+
+func collectWebhookUnsignedArgumentIssues(cfg *config.Config) []configissues.Issue {
+	out := make([]configissues.Issue, 0)
+
+	for _, action := range cfg.Actions {
+		if action == nil || !actionHasBodyOnlySignedWebhook(action) {
+			continue
+		}
+
+		out = append(out, unsignedWebhookArgumentIssues(action)...)
+	}
+
+	return out
+}
+
+// HMAC webhook signatures, including the GitHub templates, only cover the
+// request body. The path, query string and headers that OliveTin passes to
+// webhook_path, webhook_query and webhook_header_* arguments are not signed,
+// so anyone who has captured one signed request can change them.
+func actionHasBodyOnlySignedWebhook(action *config.Action) bool {
+	return slices.ContainsFunc(action.ExecOnWebhook, webhookSignsBodyOnly)
+}
+
+func webhookSignsBodyOnly(webhook config.WebhookConfig) bool {
+	if webhook.AuthType == "" {
+		return config.IsKnownWebhookTemplate(webhook.Template)
+	}
+
+	return config.IsHmacWebhookAuthType(webhook.AuthType)
+}
+
+func isUnsignedWebhookArgument(name string) bool {
+	return name == "webhook_path" || name == "webhook_query" || strings.HasPrefix(name, "webhook_header_")
+}
+
+func unsignedWebhookArgumentIssues(action *config.Action) []configissues.Issue {
+	out := make([]configissues.Issue, 0)
+
+	for _, arg := range action.Arguments {
+		if !isUnsignedWebhookArgument(arg.Name) {
+			continue
+		}
+
+		out = append(out, actionIssue(action, configissues.SeverityWarning, configissues.CodeWebhookUnsignedArg,
+			"Argument comes from the webhook request's path, query string or headers, which HMAC webhook signatures do not cover, so its value is not authenticated. Take values you need to trust from the request body with extract instead",
+			arg.Name, arg.Name))
+	}
+
+	return out
+}

+ 73 - 0
service/internal/configcheck/webhook_unsigned_args_test.go

@@ -0,0 +1,73 @@
+package configcheck_test
+
+import (
+	"testing"
+
+	"github.com/OliveTin/OliveTin/internal/config"
+	"github.com/OliveTin/OliveTin/internal/configcheck"
+	"github.com/OliveTin/OliveTin/internal/configissues"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+)
+
+func unsignedArgIssues(webhook config.WebhookConfig, argNames ...string) []configissues.Issue {
+	configissues.BeginConfigLoad()
+
+	args := make([]config.ActionArgument, 0, len(argNames))
+	for _, name := range argNames {
+		args = append(args, config.ActionArgument{Name: name, Type: "ascii_identifier"})
+	}
+
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{{
+		ID:            "deploy",
+		Title:         "Deploy",
+		Exec:          []string{"true"},
+		Arguments:     args,
+		ExecOnWebhook: []config.WebhookConfig{webhook},
+	}}
+
+	configcheck.Rebuild(cfg)
+
+	return issuesWithCode(configissues.List(), configissues.CodeWebhookUnsignedArg)
+}
+
+func hmacWebhook() config.WebhookConfig {
+	return config.WebhookConfig{AuthType: "hmac-sha256", Secret: "s3cret"}
+}
+
+func TestRebuildWarnsForUnsignedArgumentsOnHmacWebhook(t *testing.T) {
+	issues := unsignedArgIssues(hmacWebhook(), "webhook_header_x-target", "webhook_query", "webhook_path", "branch")
+
+	require.Len(t, issues, 3)
+	names := []string{issues[0].ArgumentName, issues[1].ArgumentName, issues[2].ArgumentName}
+	assert.ElementsMatch(t, []string{"webhook_header_x-target", "webhook_query", "webhook_path"}, names)
+	assert.Equal(t, configissues.SeverityWarning, issues[0].Severity)
+	assert.Contains(t, issues[0].Message, "extract")
+}
+
+func TestRebuildWarnsForUnsignedArgumentsOnEveryHmacAuthTypeAndTemplate(t *testing.T) {
+	for _, authType := range config.HmacWebhookAuthTypes {
+		assert.Len(t, unsignedArgIssues(config.WebhookConfig{AuthType: authType, Secret: "s"}, "webhook_query"), 1, authType)
+	}
+
+	assert.Len(t, unsignedArgIssues(config.WebhookConfig{Template: "github-push", Secret: "s"}, "webhook_query"), 1)
+}
+
+func TestRebuildDoesNotWarnForArgumentsTakenFromTheBody(t *testing.T) {
+	assert.Empty(t, unsignedArgIssues(hmacWebhook(), "branch", "webhook_method"))
+}
+
+func TestRebuildDoesNotWarnForWebhooksThatAuthenticateTheWholeRequest(t *testing.T) {
+	for _, webhook := range []config.WebhookConfig{
+		{AuthType: "bearer", Secret: "token"},
+		{AuthType: "basic", Secret: "user:pass"},
+		{AuthType: config.WebhookAuthTypeNone},
+	} {
+		assert.Empty(t, unsignedArgIssues(webhook, "webhook_query"), webhook.AuthType)
+	}
+}
+
+func TestRebuildDoesNotTreatUnknownWebhookTemplateAsHmac(t *testing.T) {
+	assert.Empty(t, unsignedArgIssues(config.WebhookConfig{Template: "github-pus", Secret: "s"}, "webhook_query"))
+}

+ 1 - 0
service/internal/configissues/issue.go

@@ -27,6 +27,7 @@ const (
 	CodeDashboardTypeUnknown   = "dashboard_type_unknown"
 	CodeWebhookAuthTypeUnset   = "webhook_auth_type_unset"
 	CodeWebhookTemplateUnknown = "webhook_template_unknown"
+	CodeWebhookUnsignedArg     = "webhook_unsigned_argument"
 )
 
 // Issue is a configuration warning or error surfaced on Diagnostics.

+ 9 - 0
service/internal/webhooks/auth_type_required_test.go

@@ -87,3 +87,12 @@ func TestKnownWebhookTemplateNamesMatchTemplateAppliers(t *testing.T) {
 		assert.True(t, config.IsKnownWebhookTemplate(name), "template %q must be listed in config.WebhookTemplateNames", name)
 	}
 }
+
+func TestHmacWebhookAuthTypesAreVerified(t *testing.T) {
+	for _, authType := range config.HmacWebhookAuthTypes {
+		verifier := NewAuthVerifier(config.WebhookConfig{AuthType: authType, Secret: "s3cret"})
+
+		assert.NotNil(t, verifier.getVerifier(), "HMAC auth type %q must have a verifier", authType)
+		assert.False(t, verifier.Verify(unauthenticatedWebhookRequest(t), []byte(`{}`)), "unsigned request must be rejected for %q", authType)
+	}
+}