Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/docs/20-usage/17-security-boundaries.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
119 changes: 119 additions & 0 deletions docs/docs/30-administration/05-installation/40-fail2ban.md
Original file line number Diff line number Diff line change
@@ -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.

```log
{"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 <ADDR>(?:"|\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:

```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"}
```

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+ )*?<header>=(?:[^\s",]+,)*<ADDR>(?:"|\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`.
45 changes: 44 additions & 1 deletion server/rpc/auth_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)
}

Expand Down Expand Up @@ -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, ",")
}
73 changes: 73 additions & 0 deletions server/rpc/auth_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
})
}
}