From 08d9f6ab6348c40bf2c345d3ab49dab42e349944 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:50:22 +0000 Subject: [PATCH 1/4] Log failed agent logins with the client address Write a fixed log line with the address of the client for every failed agent login, so tools like fail2ban can block clients that guess agent tokens. Behind a proxy the addresses from the X-Real-IP and X-Forwarded-For headers are added, only if they are valid addresses, so a client cannot write its own text into the line. The token is not logged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018qcZ1ktsVkUYXuNWeLQtsR --- server/rpc/auth_server.go | 45 ++++++++++++++++++++- server/rpc/auth_server_test.go | 73 ++++++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+), 1 deletion(-) diff --git a/server/rpc/auth_server.go b/server/rpc/auth_server.go index ebbbc400370..56b48d44882 100644 --- a/server/rpc/auth_server.go +++ b/server/rpc/auth_server.go @@ -18,8 +18,12 @@ import ( "context" "errors" "fmt" + "net" + "strings" "github.com/rs/zerolog/log" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/peer" "go.woodpecker-ci.org/woodpecker/v3/rpc/proto" "go.woodpecker-ci.org/woodpecker/v3/server/model" @@ -38,9 +42,10 @@ func NewWoodpeckerAuthServer(jwtManager *JWTManager, agentMasterToken string, st return &WoodpeckerAuthServer{jwtManager: jwtManager, agentMasterToken: agentMasterToken, store: store} } -func (s *WoodpeckerAuthServer) Auth(_ context.Context, req *proto.AuthRequest) (*proto.AuthResponse, error) { +func (s *WoodpeckerAuthServer) Auth(ctx context.Context, req *proto.AuthRequest) (*proto.AuthResponse, error) { agent, err := s.getAgent(req.AgentId, req.AgentToken) if err != nil { + logAuthFailure(ctx, err) return nil, fmt.Errorf("agent could not auth: %w", err) } @@ -97,3 +102,41 @@ func (s *WoodpeckerAuthServer) getAgent(agentID int64, agentToken string) (*mode } return agent, err } + +// logAuthFailure logs a failed agent login in the format the fail2ban docs match. +func logAuthFailure(ctx context.Context, err error) { + var msg strings.Builder + msg.WriteString("agent authentication failed") + event := log.Warn().Err(err) + if p, ok := peer.FromContext(ctx); ok { + // a unix socket has no address + if addr, ok := p.Addr.(*net.TCPAddr); ok { + msg.WriteString(" from " + addr.IP.String()) + event = event.Str("ip", addr.IP.String()) + } + } + if md, ok := metadata.FromIncomingContext(ctx); ok { + for _, header := range []string{"x-real-ip", "x-forwarded-for"} { + if ips := forwardedIPs(md.Get(header)); ips != "" { + msg.WriteString(" " + header + "=" + ips) + event = event.Str(header, ips) + } + } + } + event.Msg(msg.String()) +} + +// forwardedIPs returns the header addresses, or nothing if one is not an IP. +func forwardedIPs(values []string) string { + var ips []string + for _, value := range values { + for entry := range strings.SplitSeq(value, ",") { + ip := net.ParseIP(strings.TrimSpace(entry)) + if ip == nil { + return "" + } + ips = append(ips, ip.String()) + } + } + return strings.Join(ips, ",") +} diff --git a/server/rpc/auth_server_test.go b/server/rpc/auth_server_test.go index d73ee755257..ce766501a46 100644 --- a/server/rpc/auth_server_test.go +++ b/server/rpc/auth_server_test.go @@ -15,11 +15,18 @@ package rpc import ( + "bytes" "errors" + "net" "testing" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/peer" "go.woodpecker-ci.org/woodpecker/v3/rpc/proto" "go.woodpecker-ci.org/woodpecker/v3/server/model" @@ -283,3 +290,69 @@ func TestGetAgent(t *testing.T) { assert.Equal(t, int64(8), got.ID) }) } + +// The fail2ban docs match this line. +func TestAuthLogsFailureWithClientAddress(t *testing.T) { + var buf bytes.Buffer + orig := log.Logger + log.Logger = zerolog.New(&buf).With().Timestamp().Logger() + t.Cleanup(func() { log.Logger = orig }) + + store := store_mocks.NewMockStore(t) + store.On("AgentFindByToken", mock.Anything).Return(nil, types.ErrRecordNotExist) + srv := newAuthServer(t, "master", store) + + ctx := peer.NewContext(t.Context(), &peer.Peer{Addr: &net.TCPAddr{IP: net.ParseIP("203.0.113.7"), Port: 41234}}) + _, err := srv.Auth(ctx, &proto.AuthRequest{AgentId: 3, AgentToken: "wrong-token"}) + require.Error(t, err) + assert.Contains(t, buf.String(), "agent authentication failed from 203.0.113.7") + assert.NotContains(t, buf.String(), "wrong-token") + + ctx = peer.NewContext(t.Context(), &peer.Peer{Addr: &net.TCPAddr{IP: net.ParseIP("2001:db8::1"), Port: 41234}}) + _, err = srv.Auth(ctx, &proto.AuthRequest{AgentId: 3, AgentToken: "wrong-token"}) + require.Error(t, err) + assert.Contains(t, buf.String(), "agent authentication failed from 2001:db8::1") +} + +// Only valid addresses from proxy headers are logged. +func TestAuthLogsForwardedClientAddress(t *testing.T) { + var buf bytes.Buffer + orig := log.Logger + log.Logger = zerolog.New(&buf).With().Timestamp().Logger() + t.Cleanup(func() { log.Logger = orig }) + + store := store_mocks.NewMockStore(t) + store.On("AgentFindByToken", mock.Anything).Return(nil, types.ErrRecordNotExist) + srv := newAuthServer(t, "master", store) + proxy := &peer.Peer{Addr: &net.TCPAddr{IP: net.ParseIP("10.0.0.2"), Port: 41234}} + + for name, tc := range map[string]struct { + md metadata.MD + want string + }{ + "no headers": { + md: metadata.MD{}, + want: `"agent authentication failed from 10.0.0.2"`, + }, + "both headers": { + md: metadata.Pairs("x-real-ip", "203.0.113.7", "x-forwarded-for", "198.51.100.1, 203.0.113.7"), + want: `"agent authentication failed from 10.0.0.2 x-real-ip=203.0.113.7 x-forwarded-for=198.51.100.1,203.0.113.7"`, + }, + "ipv6": { + md: metadata.Pairs("x-forwarded-for", "2001:db8::1"), + want: `"agent authentication failed from 10.0.0.2 x-forwarded-for=2001:db8::1"`, + }, + "text is not logged": { + md: metadata.Pairs("x-real-ip", "1.2.3.4 x-real-ip=9.9.9.9", "x-forwarded-for", "evil, 203.0.113.7"), + want: `"agent authentication failed from 10.0.0.2"`, + }, + } { + t.Run(name, func(t *testing.T) { + buf.Reset() + ctx := metadata.NewIncomingContext(peer.NewContext(t.Context(), proxy), tc.md) + _, err := srv.Auth(ctx, &proto.AuthRequest{AgentId: 3, AgentToken: "wrong-token"}) + require.Error(t, err) + assert.Contains(t, buf.String(), `"message":`+tc.want) + }) + } +} From 0a74a9466c95ce658b9e73821416904c71cf61ad Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:50:22 +0000 Subject: [PATCH 2/4] Add a fail2ban setup page Show the fail2ban filters for failed agent logins, direct and behind a proxy, and jails for the journal, a log file and Docker. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018qcZ1ktsVkUYXuNWeLQtsR --- .../05-installation/40-fail2ban.md | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 docs/docs/30-administration/05-installation/40-fail2ban.md diff --git a/docs/docs/30-administration/05-installation/40-fail2ban.md b/docs/docs/30-administration/05-installation/40-fail2ban.md new file mode 100644 index 00000000000..973ed3493f2 --- /dev/null +++ b/docs/docs/30-administration/05-installation/40-fail2ban.md @@ -0,0 +1,119 @@ +# Fail2ban + +Woodpecker logs every failed agent login together with the address of the client. +You can use [fail2ban](https://github.com/fail2ban/fail2ban) to block clients that try to guess agent tokens. + +```json +{"level":"warn","error":"...","ip":"203.0.113.7","time":"2026-11-20T10:00:00Z","message":"agent authentication failed from 203.0.113.7"} +``` + +:::note +Agents that connect over a unix socket have no address and cannot be blocked. +::: + +Keep the logs in JSON format, as only it contains the date fail2ban needs. +This is the default if the server does not run in a terminal, or set `WOODPECKER_DEBUG_PRETTY=false`. + +## Filter + +Use this filter if agents connect to the gRPC port of the server (`WOODPECKER_GRPC_ADDR`, default `:9000`) directly: + +```ini title="/etc/fail2ban/filter.d/woodpecker-agent.conf" +[Definition] +failregex = agent authentication failed from (?:"|\s|$) +ignoreregex = +``` + +### Behind a proxy + +Behind a proxy the server only sees the address of the proxy. +It then also logs the addresses it gets in the `X-Real-IP` and `X-Forwarded-For` headers: + +```json +{"level":"warn","error":"...","ip":"10.0.0.2","x-forwarded-for":"198.51.100.1,203.0.113.7","time":"2026-11-20T10:00:00Z","message":"agent authentication failed from 10.0.0.2 x-forwarded-for=198.51.100.1,203.0.113.7"} +``` + +Clients can send these headers themselves, so only use them if agents can reach the gRPC port of the server through your proxy alone. +This filter takes the last address of `X-Forwarded-For`, the one your proxy added: + +```ini title="/etc/fail2ban/filter.d/woodpecker-agent-proxy.conf" +[Init] +# header with the client address, set by your proxy: x-forwarded-for or x-real-ip +header = x-forwarded-for + +[Definition] +failregex = agent authentication failed from \S+ (?:\S+ )*?
=(?:[^\s",]+,)*(?:"|\s|$) +ignoreregex = +``` + +Caddy and Traefik set `X-Forwarded-For` by default. +With nginx, add `grpc_set_header X-Forwarded-For $remote_addr;` next to `grpc_pass`. +If your proxy sets `X-Real-IP` instead and overwrites the value a client sent, use `filter = woodpecker-agent-proxy[header=x-real-ip]` in the jail. + +The server does not understand the PROXY protocol, so use the headers instead. +Add the address of your proxy to `ignoreip` of the jail, so fail2ban never blocks it. + +## Jail + +Choose how fail2ban reads the logs of the server. +Behind a proxy, set `filter = woodpecker-agent-proxy` instead. + +### systemd + +If you use the [packages](./30-packages.md), the server logs to the journal: + +```ini title="/etc/fail2ban/jail.d/woodpecker.local" +[woodpecker-agent] +enabled = true +filter = woodpecker-agent +backend = systemd +journalmatch = _SYSTEMD_UNIT=woodpecker-server.service +port = 9000 +maxretry = 10 +findtime = 10m +bantime = 1h +``` + +### Log file + +Let the server write its logs to a file with `WOODPECKER_LOG_FILE=/var/log/woodpecker/server.log`: + +```ini title="/etc/fail2ban/jail.d/woodpecker.local" +[woodpecker-agent] +enabled = true +filter = woodpecker-agent +logpath = /var/log/woodpecker/server.log +port = 9000 +maxretry = 10 +findtime = 10m +bantime = 1h +``` + +### Docker + +Mount a folder of the host into the server container and use the log file setup above. +Docker passes published ports around the `INPUT` chain, so ban in the `DOCKER-USER` chain instead +and use the port inside the container: + +```ini title="/etc/fail2ban/jail.d/woodpecker.local" +[woodpecker-agent] +enabled = true +filter = woodpecker-agent +logpath = /var/log/woodpecker/server.log +banaction = iptables-multiport +chain = DOCKER-USER +port = 9000 +maxretry = 10 +findtime = 10m +bantime = 1h +``` + +## Test + +Check that the filter finds the failed logins in your logs: + +```sh +fail2ban-regex /var/log/woodpecker/server.log /etc/fail2ban/filter.d/woodpecker-agent.conf +``` + +After a change of the jail, reload fail2ban with `fail2ban-client reload` and check it with `fail2ban-client status woodpecker-agent`. From 4dc8d8a11f1764aa88986b7ecf5720b613d78e50 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:50:23 +0000 Subject: [PATCH 3/4] Recommend fail2ban in the security boundaries Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018qcZ1ktsVkUYXuNWeLQtsR --- docs/docs/20-usage/17-security-boundaries.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/docs/20-usage/17-security-boundaries.md b/docs/docs/20-usage/17-security-boundaries.md index 130f6b16d16..366cfd785db 100644 --- a/docs/docs/20-usage/17-security-boundaries.md +++ b/docs/docs/20-usage/17-security-boundaries.md @@ -131,6 +131,7 @@ and return configurations, secrets or registries. They are called before a pipel Agents connect with a [system or agent token](../30-administration/10-configuration/30-agent.md#agent-registration), using TLS only with [`WOODPECKER_GRPC_SECURE`](../30-administration/10-configuration/30-agent.md#grpc_secure). The server serves gRPC without TLS, so put it behind a [TLS proxy](../30-administration/10-configuration/10-server.md#reverse-proxy) or use a [unix socket](../30-administration/10-configuration/10-server.md#grpc_addr) for agents on the same host. +The server logs failed agent logins with the client address, so we recommend [fail2ban](../30-administration/05-installation/40-fail2ban.md) to block clients that guess agent tokens. Organization admins, and every user for their own repositories, can add own agents, unless [`WOODPECKER_DISABLE_USER_AGENT_REGISTRATION`](../30-administration/10-configuration/10-server.md#disable_user_agent_registration) is set. Every admin of an organization can see the tokens of all its agents, also of the ones other admins added, and can edit and remove them. This gives no more access than adding an own agent, as [organization agents](../30-administration/10-configuration/30-agent.md#agent-filters) only get workflows of their organization. From e6afc88579475cb5cd3972cada2ec2b574b1fc12 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Nov 2026 01:06:56 +0100 Subject: [PATCH 4/4] dont fmt --- docs/docs/30-administration/05-installation/40-fail2ban.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/30-administration/05-installation/40-fail2ban.md b/docs/docs/30-administration/05-installation/40-fail2ban.md index 973ed3493f2..570814c3934 100644 --- a/docs/docs/30-administration/05-installation/40-fail2ban.md +++ b/docs/docs/30-administration/05-installation/40-fail2ban.md @@ -3,7 +3,7 @@ Woodpecker logs every failed agent login together with the address of the client. You can use [fail2ban](https://github.com/fail2ban/fail2ban) to block clients that try to guess agent tokens. -```json +```log {"level":"warn","error":"...","ip":"203.0.113.7","time":"2026-11-20T10:00:00Z","message":"agent authentication failed from 203.0.113.7"} ``` @@ -29,7 +29,7 @@ ignoreregex = Behind a proxy the server only sees the address of the proxy. It then also logs the addresses it gets in the `X-Real-IP` and `X-Forwarded-For` headers: -```json +```log {"level":"warn","error":"...","ip":"10.0.0.2","x-forwarded-for":"198.51.100.1,203.0.113.7","time":"2026-11-20T10:00:00Z","message":"agent authentication failed from 10.0.0.2 x-forwarded-for=198.51.100.1,203.0.113.7"} ```