Security sweep: fix open redirect, XFF rate-limit bypass, SSRF; harden image and compose
- Reject control chars and backslashes in redirect targets - Use proxy-added X-Forwarded-For entry, cap limiter keys - Block private/loopback/link-local addresses on image fetch - HSTS over HTTPS, generic error on custom CSS - x/crypto 0.59.0, pin golang:1.27.4-alpine3.24 and alpine:3.24.4 - Compose: cap_drop ALL, no-new-privileges, read_only, limits, labels - Add SECURITY.md, CHANGELOG.md, TODO.md Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cb2604bd05
commit
796384420b
15 files changed
+220
-17
No files matched your search
@@ -0,0 +1,15 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 2026-11-23
|
||||||
|
|
||||||
|
- Security sweep.
|
||||||
|
- Fixed an open redirect: `next=/%09/evil.example` after login or site unlock sent browsers off-site. Redirect targets now reject control characters and backslashes.
|
||||||
|
- Login and unlock rate limits use the proxy-added `X-Forwarded-For` entry, so clients can't dodge them with a fake header. The limiter now caps how many addresses it tracks.
|
||||||
|
- Image downloads refuse private, loopback and link-local addresses.
|
||||||
|
- HSTS header when served over HTTPS.
|
||||||
|
- golang.org/x/crypto 0.59.0. Base images pinned to golang:1.27.4-alpine3.24 and alpine:3.24.4.
|
||||||
|
- Compose: cap_drop ALL (plus what the entrypoint needs), no-new-privileges, read-only root, memory and pid limits.
|
||||||
|
|
||||||
|
## 2026-10-26
|
||||||
|
|
||||||
|
- Project created.
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
FROM golang:1-alpine AS build
|
FROM golang:1.27.4-alpine3.24 AS build
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
@@ -6,7 +6,7 @@ COPY . .
|
|||||||
ARG VERSION=dev
|
ARG VERSION=dev
|
||||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/canon ./cmd/canon
|
RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/canon ./cmd/canon
|
||||||
|
|
||||||
FROM alpine:3
|
FROM alpine:3.24.4
|
||||||
RUN apk add --no-cache ca-certificates tzdata su-exec \
|
RUN apk add --no-cache ca-certificates tzdata su-exec \
|
||||||
&& mkdir -p /data /backups
|
&& mkdir -p /data /backups
|
||||||
COPY --from=build /out/canon /usr/local/bin/canon
|
COPY --from=build /out/canon /usr/local/bin/canon
|
||||||
|
|||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
# Security
|
||||||
|
|
||||||
|
## Reporting
|
||||||
|
|
||||||
|
Found a problem? Open an issue on the Gitea repo, or if it's sensitive, contact the repo owner directly before posting details.
|
||||||
|
|
||||||
|
## Supported versions
|
||||||
|
|
||||||
|
Only the latest commit on `main` gets fixes.
|
||||||
|
|
||||||
|
## Known accepted risks
|
||||||
|
|
||||||
|
| Risk | Why | Accepted by | Date |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Container starts as root (trivy DS-0002) | The entrypoint needs root to chown `/data` and `/backups` to PUID:PGID, then drops to that user with su-exec. Compose drops all other capabilities and sets `no-new-privileges`. | Chris (deploy go-ahead after the sweep report) | 2026-11-23 |
|
||||||
+16
-2
@@ -10,13 +10,27 @@ services:
|
|||||||
context: .
|
context: .
|
||||||
args:
|
args:
|
||||||
VERSION: ${CANON_VERSION:-dev}
|
VERSION: ${CANON_VERSION:-dev}
|
||||||
image: canon:latest
|
image: canon:1.0.0
|
||||||
# Never look for canon:latest on a registry: every deploy (including
|
# Never look for canon:latest on a registry: every deploy (including
|
||||||
# Arcane's "Pull image" / "Redeploy after sync") builds from the source
|
# Arcane's "Pull image" / "Redeploy after sync") builds from the source
|
||||||
# that was just synced.
|
# that was just synced.
|
||||||
pull_policy: build
|
pull_policy: build
|
||||||
container_name: canon
|
container_name: canon-app
|
||||||
|
labels:
|
||||||
|
org.stack: canon
|
||||||
|
org.purpose: "canon app"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
# The entrypoint starts as root only to chown /data and /backups, then
|
||||||
|
# drops to PUID:PGID with su-exec. These are the only capabilities that
|
||||||
|
# step needs.
|
||||||
|
cap_drop: [ALL]
|
||||||
|
cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETUID, SETGID]
|
||||||
|
security_opt: [no-new-privileges:true]
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
mem_limit: 512m
|
||||||
|
pids_limit: 256
|
||||||
ports:
|
ports:
|
||||||
- "${CANON_BIND:-0.0.0.0}:${CANON_PUBLISH_PORT:-4242}:4242"
|
- "${CANON_BIND:-0.0.0.0}:${CANON_PUBLISH_PORT:-4242}:4242"
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ module github.com/cdnutter/canon
|
|||||||
go 1.26.0
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
golang.org/x/crypto v0.57.0
|
golang.org/x/crypto v0.59.0
|
||||||
modernc.org/sqlite v1.59.0
|
modernc.org/sqlite v1.59.0
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ require (
|
|||||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
golang.org/x/sys v0.48.0 // indirect
|
golang.org/x/sys v0.50.0 // indirect
|
||||||
modernc.org/libc v1.75.7 // indirect
|
modernc.org/libc v1.75.7 // indirect
|
||||||
modernc.org/mathutil v1.7.1 // indirect
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
modernc.org/memory v1.12.1 // indirect
|
modernc.org/memory v1.12.1 // indirect
|
||||||
|
|||||||
@@ -12,14 +12,14 @@ github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOF
|
|||||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||||
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||||
modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=
|
modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=
|
||||||
|
|||||||
@@ -77,10 +77,22 @@ func (l *Limiter) Blocked(key string) bool {
|
|||||||
return len(l.prune(key, time.Now())) >= l.max
|
return len(l.prune(key, time.Now())) >= l.max
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// maxKeys caps how many keys a Limiter tracks, so a flood of failures from
|
||||||
|
// many addresses can't grow it without bound.
|
||||||
|
const maxKeys = 10000
|
||||||
|
|
||||||
func (l *Limiter) Fail(key string) {
|
func (l *Limiter) Fail(key string) {
|
||||||
l.mu.Lock()
|
l.mu.Lock()
|
||||||
defer l.mu.Unlock()
|
defer l.mu.Unlock()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
if _, ok := l.hits[key]; !ok && len(l.hits) >= maxKeys {
|
||||||
|
for k := range l.hits {
|
||||||
|
l.prune(k, now)
|
||||||
|
}
|
||||||
|
if len(l.hits) >= maxKeys {
|
||||||
|
return // still full: drop this one rather than grow
|
||||||
|
}
|
||||||
|
}
|
||||||
l.hits[key] = append(l.prune(key, now), now)
|
l.hits[key] = append(l.prune(key, now), now)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,11 +10,14 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -33,9 +36,43 @@ func New(dataDir, userAgent string) (*Cache, error) {
|
|||||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &Cache{dir: dir, ua: userAgent, client: &http.Client{Timeout: 30 * time.Second}}, nil
|
// Image URLs come from the admin UI and from metadata providers, so the
|
||||||
|
// server only fetches from public addresses (no SSRF into the LAN).
|
||||||
|
dialer := &net.Dialer{Timeout: 10 * time.Second, Control: publicOnly}
|
||||||
|
transport := &http.Transport{
|
||||||
|
Proxy: http.ProxyFromEnvironment,
|
||||||
|
DialContext: dialer.DialContext,
|
||||||
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
|
ForceAttemptHTTP2: true,
|
||||||
|
}
|
||||||
|
return &Cache{dir: dir, ua: userAgent, client: &http.Client{Timeout: 30 * time.Second, Transport: transport}}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// errPrivateAddr is returned when an image URL points at a private address.
|
||||||
|
var errPrivateAddr = errors.New("image URL points at a private or local address")
|
||||||
|
|
||||||
|
// publicOnly refuses connections to loopback, private, link-local,
|
||||||
|
// multicast and unspecified addresses. It runs after DNS resolution, so a
|
||||||
|
// public name that resolves to a LAN address is refused too.
|
||||||
|
func publicOnly(network, address string, _ syscall.RawConn) error {
|
||||||
|
host, _, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ip, err := netip.ParseAddr(host)
|
||||||
|
if err != nil {
|
||||||
|
return errPrivateAddr
|
||||||
|
}
|
||||||
|
ip = ip.Unmap()
|
||||||
|
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() ||
|
||||||
|
cgnat.Contains(ip) {
|
||||||
|
return errPrivateAddr
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var cgnat = netip.MustParsePrefix("100.64.0.0/10")
|
||||||
|
|
||||||
func (c *Cache) Dir() string { return c.dir }
|
func (c *Cache) Dir() string { return c.dir }
|
||||||
|
|
||||||
var nameRe = regexp.MustCompile(`^[0-9a-f]{40}\.(jpg|png|webp|gif|avif)$`)
|
var nameRe = regexp.MustCompile(`^[0-9a-f]{40}\.(jpg|png|webp|gif|avif)$`)
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package imgcache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFetchRefusesLocalAddresses(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Error("request reached a loopback server")
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
c, err := New(t.TempDir(), "test")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, u := range []string{srv.URL + "/a.png", "http://10.0.0.2/a.png", "http://169.254.169.254/latest", "http://[::1]/a.png", "http://0.0.0.0/"} {
|
||||||
|
if _, err := c.Fetch(context.Background(), u); !errors.Is(err, errPrivateAddr) {
|
||||||
|
t.Errorf("Fetch(%s) err = %v, want errPrivateAddr", u, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublicOnly(t *testing.T) {
|
||||||
|
for addr, ok := range map[string]bool{"93.184.215.14:443": true, "[2606:4700::1]:443": true,
|
||||||
|
"127.0.0.1:80": false, "192.168.1.5:80": false, "100.64.1.1:80": false, "[fd00::1]:80": false, "[::ffff:10.0.0.1]:80": false} {
|
||||||
|
if err := publicOnly("tcp", addr, nil); (err == nil) != ok {
|
||||||
|
t.Errorf("publicOnly(%s) = %v, want ok=%v", addr, err, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,9 +15,24 @@ type loginPage struct {
|
|||||||
Next string
|
Next string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// localPath reports whether next is a path on this site. Browsers drop tabs
|
||||||
|
// and newlines from URLs and treat a backslash like "/", so "/\t/evil.example"
|
||||||
|
// would become "//evil.example"; any control character or backslash fails.
|
||||||
|
func localPath(next string) bool {
|
||||||
|
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := 0; i < len(next); i++ {
|
||||||
|
if c := next[i]; c < 0x20 || c == 0x7f || c == '\\' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// safeNext only allows local redirect targets.
|
// safeNext only allows local redirect targets.
|
||||||
func safeNext(next string) string {
|
func safeNext(next string) string {
|
||||||
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") {
|
if !localPath(next) {
|
||||||
return "/admin"
|
return "/admin"
|
||||||
}
|
}
|
||||||
return next
|
return next
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import (
|
|||||||
"crypto/subtle"
|
"crypto/subtle"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/cdnutter/canon/internal/auth"
|
"github.com/cdnutter/canon/internal/auth"
|
||||||
@@ -90,7 +89,7 @@ func (s *Server) gatedAsset(h http.HandlerFunc) http.HandlerFunc {
|
|||||||
|
|
||||||
// safePublicNext is safeNext for visitors: it falls back to the home page.
|
// safePublicNext is safeNext for visitors: it falls back to the home page.
|
||||||
func safePublicNext(next string) string {
|
func safePublicNext(next string) string {
|
||||||
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") {
|
if !localPath(next) {
|
||||||
return "/"
|
return "/"
|
||||||
}
|
}
|
||||||
return next
|
return next
|
||||||
|
|||||||
@@ -86,7 +86,8 @@ func DefaultTitle(ownerName string) string {
|
|||||||
func (s *Server) handleCustomCSS(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleCustomCSS(w http.ResponseWriter, r *http.Request) {
|
||||||
set, err := s.store.Settings(r.Context())
|
set, err := s.store.Settings(r.Context())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
s.log.Error("loading custom css", "err", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "text/css; charset=utf-8")
|
w.Header().Set("Content-Type", "text/css; charset=utf-8")
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/cdnutter/canon/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSafeNextBlocksOffsite(t *testing.T) {
|
||||||
|
bad := []string{"", "x", "https://evil.example", "//evil.example", "/\\evil.example",
|
||||||
|
"/\t/evil.example", "/\n/evil.example", "/\r/evil.example", "/%09/evil.example\x00",
|
||||||
|
"/a\\b", "\\\\evil.example", "/\x7f/evil.example"}
|
||||||
|
for _, in := range bad {
|
||||||
|
if got := safeNext(in); got != "/admin" {
|
||||||
|
t.Errorf("safeNext(%q) = %q, want /admin", in, got)
|
||||||
|
}
|
||||||
|
if got := safePublicNext(in); got != "/" {
|
||||||
|
t.Errorf("safePublicNext(%q) = %q, want /", in, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, in := range []string{"/", "/admin", "/l/movies?x=1", "/admin/lists/3#top"} {
|
||||||
|
if got := safeNext(in); got != in {
|
||||||
|
t.Errorf("safeNext(%q) = %q, want unchanged", in, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The redirect a browser actually sees must stay on this site.
|
||||||
|
for _, in := range bad {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
http.Redirect(w, httptest.NewRequest("GET", "/login", nil), safeNext(in), http.StatusSeeOther)
|
||||||
|
if loc := w.Header().Get("Location"); loc != "/admin" {
|
||||||
|
t.Errorf("next=%q redirected to %q", in, loc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClientIPUsesProxyAddedEntry(t *testing.T) {
|
||||||
|
s := &Server{cfg: config.Config{TrustProxy: true}}
|
||||||
|
r := httptest.NewRequest("GET", "/", nil)
|
||||||
|
r.Header.Set("X-Forwarded-For", "6.6.6.6, 203.0.113.9")
|
||||||
|
if got := s.clientIP(r); got != "203.0.113.9" {
|
||||||
|
t.Errorf("clientIP = %q, want the proxy-added 203.0.113.9", got)
|
||||||
|
}
|
||||||
|
s.cfg.TrustProxy = false
|
||||||
|
if got := s.clientIP(r); got != "192.0.2.1" {
|
||||||
|
t.Errorf("clientIP without proxy trust = %q, want RemoteAddr host", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -218,6 +218,9 @@ func (s *Server) securityHeaders(next http.Handler) http.Handler {
|
|||||||
h.Set("X-Content-Type-Options", "nosniff")
|
h.Set("X-Content-Type-Options", "nosniff")
|
||||||
h.Set("Referrer-Policy", "same-origin")
|
h.Set("Referrer-Policy", "same-origin")
|
||||||
h.Set("X-Frame-Options", "SAMEORIGIN")
|
h.Set("X-Frame-Options", "SAMEORIGIN")
|
||||||
|
if s.isHTTPS(r) {
|
||||||
|
h.Set("Strict-Transport-Security", "max-age=31536000")
|
||||||
|
}
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -297,9 +300,16 @@ func (s *Server) sameOrigin(r *http.Request) bool {
|
|||||||
|
|
||||||
func (s *Server) clientIP(r *http.Request) string {
|
func (s *Server) clientIP(r *http.Request) string {
|
||||||
if s.cfg.TrustProxy {
|
if s.cfg.TrustProxy {
|
||||||
|
// Use the last entry: it's the one the proxy added. Earlier
|
||||||
|
// entries come from the client and can be anything, which would
|
||||||
|
// let it dodge the login rate limit.
|
||||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||||
first, _, _ := strings.Cut(xff, ",")
|
if i := strings.LastIndexByte(xff, ','); i >= 0 {
|
||||||
return strings.TrimSpace(first)
|
xff = xff[i+1:]
|
||||||
|
}
|
||||||
|
if ip := strings.TrimSpace(xff); ip != "" {
|
||||||
|
return ip
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if xr := r.Header.Get("X-Real-IP"); xr != "" {
|
if xr := r.Header.Get("X-Real-IP"); xr != "" {
|
||||||
return xr
|
return xr
|
||||||
|
|||||||
Reference in new issue
Block a user