diff --git a/api/cmd/main.go b/api/cmd/main.go index ea49aeec4..e30a865f4 100644 --- a/api/cmd/main.go +++ b/api/cmd/main.go @@ -420,9 +420,14 @@ func main() { // bottleneck there is the dashboard's own polling). p.Use(mutationRateLimit) p.Use(rbac.MiddlewareWithFiles(reg, fileAccess)) + // PostgreSQL panels re-check every long stream. On SQLite only SFTP session transfers are + // re-checked, so a revoked or expired SFTP session cannot keep an upload or download running + // after the SFTP endpoint has been told to drop it. + revalidate := auth.SFTPSessionStream(isStreamingRequest) if store.Driver == "postgres" { - p.Use(sessions.RevalidateStreams(isStreamingRequest, 5*time.Second, rbac.StreamGrantValidator(reg))) + revalidate = isStreamingRequest } + p.Use(sessions.RevalidateStreams(revalidate, 5*time.Second, rbac.StreamGrantValidator(reg))) handlers.MountResources(p, reg, store, auditor) handlers.MountFleet(p, reg, store) diff --git a/api/internal/auth/sessions.go b/api/internal/auth/sessions.go index e3ec2c920..f3e8552c8 100644 --- a/api/internal/auth/sessions.go +++ b/api/internal/auth/sessions.go @@ -295,6 +295,9 @@ func (s *SessionStore) streamRecheck(req *http.Request) (func(context.Context) ( if err != nil || sess.ID != sessionID { return nil, false } + // A running transfer is use of the session: slide it (at most once a minute), so a + // long upload or download is not cut when the 15-minute lifetime runs out mid-stream. + s.slideSFTPSession(ctx, sessionID) return u, true }, true } diff --git a/api/internal/auth/sftp_guard.go b/api/internal/auth/sftp_guard.go index 6f6fa6957..759cc3aa8 100644 --- a/api/internal/auth/sftp_guard.go +++ b/api/internal/auth/sftp_guard.go @@ -194,3 +194,12 @@ func (s *SessionStore) SFTPServiceAuth(next http.Handler) http.Handler { next.ServeHTTP(w, req.WithContext(ctx)) }) } + +// SFTPSessionStream narrows isStream to requests made with an SFTP session token, for +// RevalidateStreams on panels that do not re-check every stream. +func SFTPSessionStream(isStream func(*http.Request) bool) func(*http.Request) bool { + return func(req *http.Request) bool { + caller, ok := SFTPCallerFromContext(req.Context()) + return ok && caller.SessionID != 0 && isStream(req) + } +} diff --git a/api/internal/auth/sftp_stream_hardening_test.go b/api/internal/auth/sftp_stream_hardening_test.go new file mode 100644 index 000000000..bd3db0d66 --- /dev/null +++ b/api/internal/auth/sftp_stream_hardening_test.go @@ -0,0 +1,81 @@ +package auth + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestSFTPSessionStream(t *testing.T) { + always := func(*http.Request) bool { return true } + never := func(*http.Request) bool { return false } + plain := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/servers/mc/files/download", nil) + withCaller := func(c SFTPCaller) *http.Request { + return plain.WithContext(WithSFTPCaller(plain.Context(), c)) + } + for name, tc := range map[string]struct { + req *http.Request + isStream func(*http.Request) bool + want bool + }{ + "browser stream": {plain, always, false}, + "sftp session stream": {withCaller(SFTPCaller{Cluster: "local", SessionID: 7}), always, true}, + "sftp session non-stream": {withCaller(SFTPCaller{Cluster: "local", SessionID: 7}), never, false}, + "sftp service token": {withCaller(SFTPCaller{Cluster: "local", ServiceTokenID: 3}), always, false}, + } { + if got := SFTPSessionStream(tc.isStream)(tc.req); got != tc.want { + t.Errorf("%s: SFTPSessionStream = %v, want %v", name, got, tc.want) + } + } +} + +// A running SFTP transfer counts as use of its session: the stream re-check slides the session's +// expiry, so a long transfer is not cut when the original 15-minute lifetime runs out. +func TestRevalidateStreams_SFTPTransferSlidesSession(t *testing.T) { + ctx := context.Background() + st := newAuthDB(t) + seedUser(t, st, "alice", "hunter2", "admin") + s := NewSessionStore(st) + raw, _, err := s.IssueSFTPSession(ctx, sftpUserID(t, s, "alice"), "local", "password", 0) + if err != nil { + t.Fatalf("IssueSFTPSession: %v", err) + } + _, sess, err := s.LookupSFTPSessionToken(ctx, raw) + if err != nil { + t.Fatalf("LookupSFTPSessionToken: %v", err) + } + // Leave the session with 30 seconds to live and clear the per-process slide throttle. + if err := s.SlideSFTPSession(ctx, sess.ID, time.Now().Add(30*time.Second)); err != nil { + t.Fatalf("SlideSFTPSession: %v", err) + } + sftpLastSlide.Delete(sess.ID) + t.Cleanup(func() { sftpLastSlide.Delete(sess.ID) }) + + handler := s.RevalidateStreams( + func(*http.Request) bool { return true }, + 10*time.Millisecond, + func(context.Context, int64) bool { return true }, + )(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-r.Context().Done(): + w.WriteHeader(http.StatusGatewayTimeout) + case <-time.After(100 * time.Millisecond): + w.WriteHeader(http.StatusOK) + } + })) + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, sftpStreamRequest(t, s, raw)) + if rec.Code != http.StatusOK { + t.Fatalf("transfer status = %d, want 200", rec.Code) + } + + _, after, err := s.LookupSFTPSessionToken(ctx, raw) + if err != nil { + t.Fatalf("LookupSFTPSessionToken after transfer: %v", err) + } + if left := time.Until(after.ExpiresAt); left < 10*time.Minute { + t.Fatalf("session has %v left after a running transfer, want it slid to about 15m", left) + } +} diff --git a/api/specs.md b/api/specs.md index 7d4521eff..cc8bfdf2d 100644 --- a/api/specs.md +++ b/api/specs.md @@ -356,6 +356,8 @@ trust assumptions, rotation behavior and surfaces outside this protocol. **Permissions:** reading needs `servers:read` (or ownership or collaborator access); writing, renaming and deleting need `servers:write` (or the same ownership or collaborator access). The data-root and server folders are read-only over SFTP. +**Running transfers:** every SFTP session stream (download and `files/stream` upload) is wrapped by `RevalidateStreams` on SQLite as well as PostgreSQL (`auth.SFTPSessionStream` selects them on SQLite; PostgreSQL re-checks every stream). Every 5 s the session token is looked up again; a revoked, expired or epoch-mismatched session, or changed permissions, cancel the request context and so the transfer. Each successful re-check slides the session (at most once a minute), so a long transfer keeps its session alive. + ### OIDC role mapping and Helm-seeded provider (install-time configuration) **Helm-seeded provider synthesis & coexistence:** diff --git a/changelog/unreleased/1093-sftp-security-hardening.md b/changelog/unreleased/1093-sftp-security-hardening.md new file mode 100644 index 000000000..87bada91a --- /dev/null +++ b/changelog/unreleased/1093-sftp-security-hardening.md @@ -0,0 +1,3 @@ +# SFTP endpoint hardening + +The SFTP endpoint now refuses a plain `http://` API address in remote mode (`sftp.apiURL` must be `https://`) and never follows redirects from the API, closes connections whose session the API has not confirmed for 2 minutes, stops running SFTP uploads and downloads when their session is revoked on SQLite installs too, caps channels per connection and logins in progress per source IP (new value `sftp.maxPreAuthPerIP`, default 8), and serves its unauthenticated metrics only when `serviceMonitors.enabled` is set, on a separate in-cluster `gameplane-sftp-metrics` Service. See [SFTP access](../../docs/sftp.md). [PR #1093](https://github.com/GameplanePanel/Gameplane/pull/1093) diff --git a/charts/gameplane/templates/sftp.yaml b/charts/gameplane/templates/sftp.yaml index 3a8ad6e16..2157026f5 100644 --- a/charts/gameplane/templates/sftp.yaml +++ b/charts/gameplane/templates/sftp.yaml @@ -14,6 +14,9 @@ sftp.serviceTokenSecret must hold the token created there. {{- if and $local (not $apiEnabled) }} {{- fail "sftp.enabled=true with api.enabled=false requires sftp.apiURL (the central panel the SFTP pod logs in to)" }} {{- end }} +{{- if and (not $local) (not (hasPrefix "https://" $sftp.apiURL)) }} +{{- fail "sftp.apiURL must be an https:// URL: the SFTP pod sends the service token, passwords and session tokens to it" }} +{{- end }} {{- if and (not $local) (not $sftp.serviceTokenSecret) }} {{- fail "sftp.apiURL is set (remote mode): sftp.serviceTokenSecret must name a Secret with the service token (key token) created in the central panel" }} {{- end }} @@ -30,6 +33,8 @@ sftp.serviceTokenSecret must hold the token created there. {{- /* Local mode always uses the chart-generated token the API seeds; remote mode uses the operator-supplied Secret. */}} {{- $tokenSecret := ternary "gameplane-sftp-service-token" $sftp.serviceTokenSecret $local }} {{- $apiURL := ternary (printf "http://gameplane-api.%s.svc" .Release.Namespace) $sftp.apiURL $local }} +{{- /* /metrics has no authentication: it listens on the pod address only when a ServiceMonitor scrapes it, and never on the public SFTP Service. */}} +{{- $metrics := .Values.serviceMonitors.enabled }} {{- /* Generated once: lookup returns the live Secret on install and upgrade; offline renders regenerate it. */}} {{- if not $sftp.hostKeySecret }} {{- $old := lookup "v1" "Secret" .Release.Namespace "gameplane-sftp-host-key" }} @@ -95,6 +100,11 @@ spec: - { name: GAMEPLANE_SFTP_LISTEN, value: {{ printf ":%d" (int $sftp.port) | quote }} } - { name: GAMEPLANE_SFTP_HOST_KEY, value: /etc/gameplane/sftp/hostkeys } - { name: GAMEPLANE_SFTP_API_URL, value: {{ $apiURL | quote }} } + {{- if $local }} + # Local mode talks to the API Service over the pod network, which has no TLS listener; + # the SFTP NetworkPolicy limits this pod's egress to the API pods. + - { name: GAMEPLANE_SFTP_ALLOW_INSECURE_API, value: "true" } + {{- end }} - { name: GAMEPLANE_SFTP_SERVICE_TOKEN_FILE, value: /etc/gameplane/sftp-token/token } {{- if $sftp.apiCASecret }} - { name: GAMEPLANE_SFTP_CA_FILE, value: /etc/gameplane/sftp-ca/ca.crt } @@ -102,11 +112,18 @@ spec: - { name: GAMEPLANE_SFTP_IDLE_TIMEOUT, value: {{ $sftp.idleTimeout | quote }} } - { name: GAMEPLANE_SFTP_MAX_SESSIONS_PER_USER, value: {{ printf "%d" (int $sftp.maxSessionsPerUser) | quote }} } - { name: GAMEPLANE_SFTP_MAX_TRANSFERS_PER_USER, value: {{ printf "%d" (int $sftp.maxTransfersPerUser) | quote }} } + - { name: GAMEPLANE_SFTP_MAX_PREAUTH_PER_IP, value: {{ printf "%d" (int ($sftp.maxPreAuthPerIP | default 8)) | quote }} } - { name: GAMEPLANE_SFTP_DEFAULT_NAMESPACE, value: {{ .Values.gamesNamespace | quote }} } + {{- if $metrics }} - { name: GAMEPLANE_SFTP_METRICS_ADDR, value: ":9102" } + {{- else }} + - { name: GAMEPLANE_SFTP_METRICS_ADDR, value: "" } + {{- end }} ports: - { name: ssh, containerPort: {{ int $sftp.port }} } + {{- if $metrics }} - { name: metrics, containerPort: 9102 } + {{- end }} livenessProbe: { tcpSocket: { port: ssh }, initialDelaySeconds: 5, periodSeconds: 20 } readinessProbe: { tcpSocket: { port: ssh }, initialDelaySeconds: 2, periodSeconds: 10 } resources: {{- toYaml $sftp.resources | nindent 12 }} @@ -162,6 +179,39 @@ spec: {{- if and (eq $sftp.serviceType "NodePort") $sftp.nodePort }} nodePort: {{ int $sftp.nodePort }} {{- end }} +{{- if $metrics }} +--- +# In-cluster scrape target only; the public gameplane-sftp Service never carries the metrics port. +apiVersion: v1 +kind: Service +metadata: + name: gameplane-sftp-metrics + namespace: {{ .Release.Namespace }} + labels: + app.kubernetes.io/name: gameplane-sftp-metrics + {{- include "gameplane.labels" . | nindent 4 }} +spec: + type: ClusterIP + selector: { app.kubernetes.io/name: gameplane-sftp } + ports: + - { name: metrics, port: 9102, targetPort: metrics } +--- +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + name: gameplane-sftp + namespace: {{ .Release.Namespace }} + labels: + {{- include "gameplane.labels" . | nindent 4 }} + {{- with .Values.serviceMonitors.labels }} + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + selector: + matchLabels: { app.kubernetes.io/name: gameplane-sftp-metrics } + endpoints: + - { port: metrics, interval: 30s, path: /metrics } +{{- end }} {{- if .Values.networkPolicies.enabled }} --- # SFTP clients come from the internet, so ingress is open on the SFTP port only. Egress is @@ -180,6 +230,16 @@ spec: ingress: - ports: - { protocol: TCP, port: {{ int $sftp.port }} } + {{- if $metrics }} + {{- with .Values.serviceMonitors.scrapeNamespaceSelector }} + # Prometheus only, on the metrics port (serviceMonitors.scrapeNamespaceSelector). + - from: + - namespaceSelector: + {{- toYaml . | nindent 12 }} + ports: + - { protocol: TCP, port: 9102 } + {{- end }} + {{- end }} egress: - to: - namespaceSelector: diff --git a/charts/gameplane/tests/sftp.sh b/charts/gameplane/tests/sftp.sh index 59a22fe8a..292f22b6b 100755 --- a/charts/gameplane/tests/sftp.sh +++ b/charts/gameplane/tests/sftp.sh @@ -15,6 +15,14 @@ render "$scratch/lb.yaml" --set sftp.enabled=true --set sftp.serviceType=LoadBal render "$scratch/remote.yaml" --set api.enabled=false --set sftp.enabled=true \ --set sftp.apiURL=https://panel.example.com --set sftp.serviceTokenSecret=panel-sftp-token render "$scratch/hostkey.yaml" --set sftp.enabled=true --set sftp.hostKeySecret=panel-host-key +render "$scratch/metrics.yaml" --set sftp.enabled=true --set serviceMonitors.enabled=true \ + --set serviceMonitors.scrapeNamespaceSelector.matchLabels.name=monitoring +# Remote mode must refuse a plain-HTTP central API URL. +if helm template gameplane charts/gameplane --namespace gameplane-system --set api.enabled=false --set sftp.enabled=true \ + --set sftp.apiURL=http://panel.example.com --set sftp.serviceTokenSecret=panel-sftp-token > /dev/null 2>&1; then + echo 'sftp.apiURL=http:// rendered, want a failure' >&2 + exit 1 +fi python3 - "$scratch" <<'PY' import pathlib,sys,yaml root=pathlib.Path(sys.argv[1]) @@ -117,5 +125,29 @@ env=api_env_of(hostkey) assert env['GAMEPLANE_SFTP_HOST_KEY_SECRET']=='panel-host-key', env check_host_key_role(hostkey, 'panel-host-key') assert find(hostkey,'Secret','gameplane-sftp-host-key') is None, 'custom hostKeySecret must not render the chart host key' +# 7. Transport and metrics hardening: only local mode may use plain HTTP to the API (pod network), +# /metrics is off unless a ServiceMonitor scrapes it, and the public Service never carries it. +env=env_of(local) +assert env['GAMEPLANE_SFTP_ALLOW_INSECURE_API']=='true', env +assert env['GAMEPLANE_SFTP_METRICS_ADDR']=='', env +assert env['GAMEPLANE_SFTP_MAX_PREAUTH_PER_IP']=='8', env +dep=find(local,'Deployment','gameplane-sftp') +assert [p['name'] for p in dep['spec']['template']['spec']['containers'][0]['ports']]==['ssh'], dep['spec']['template']['spec']['containers'][0]['ports'] +assert find(local,'Service','gameplane-sftp-metrics') is None, 'metrics Service rendered without serviceMonitors' +assert len(np_local:=find(local,'NetworkPolicy','gameplane-sftp')['spec']['ingress'])==1, np_local +assert 'GAMEPLANE_SFTP_ALLOW_INSECURE_API' not in env_of(remote), 'remote mode must not allow plain HTTP' + +metrics=docs('metrics.yaml') +env=env_of(metrics) +assert env['GAMEPLANE_SFTP_METRICS_ADDR']==':9102', env +svc=find(metrics,'Service','gameplane-sftp') +assert [p['name'] for p in svc['spec']['ports']]==['ssh'], svc['spec']['ports'] +msvc=find(metrics,'Service','gameplane-sftp-metrics') +assert msvc is not None and msvc['spec']['type']=='ClusterIP', msvc +assert msvc['spec']['ports']==[{'name':'metrics','port':9102,'targetPort':'metrics'}], msvc['spec']['ports'] +sm=find(metrics,'ServiceMonitor','gameplane-sftp') +assert sm is not None and sm['spec']['selector']['matchLabels']=={'app.kubernetes.io/name':'gameplane-sftp-metrics'}, sm +ingress=find(metrics,'NetworkPolicy','gameplane-sftp')['spec']['ingress'] +assert ingress[1]=={'from':[{'namespaceSelector':{'matchLabels':{'name':'monitoring'}}}],'ports':[{'protocol':'TCP','port':9102}]}, ingress print('sftp chart checks ok') PY diff --git a/charts/gameplane/values.yaml b/charts/gameplane/values.yaml index daa708f39..629fb6adc 100644 --- a/charts/gameplane/values.yaml +++ b/charts/gameplane/values.yaml @@ -836,6 +836,12 @@ sftp: idleTimeout: 15m maxSessionsPerUser: 4 maxTransfersPerUser: 8 + # Connections one source IP may have open before login finishes; more are closed at once. Raise it + # when many users reach the pod from one address (a LoadBalancer that rewrites client IPs). + maxPreAuthPerIP: 8 + # /metrics (port 9102, no authentication) is served only when serviceMonitors.enabled is true, on a + # separate in-cluster gameplane-sftp-metrics Service; the public SFTP Service carries only SSH. + # Remote mode (apiURL set) requires an https:// URL. replicas: 1 nodeSelector: {} tolerations: [] diff --git a/docs/security.md b/docs/security.md index f58b9a4a1..82c252781 100644 --- a/docs/security.md +++ b/docs/security.md @@ -787,7 +787,31 @@ second internet-facing listener, so it gets the same treatment as the dashboard: never starts the game. Enabling SFTP grants the operator `pods: create, delete` in game namespaces so it can run that file-only pod. - **Revocation and disable** end open sessions within 60 seconds and refuse new - logins (FR-007, SC-006). + logins (FR-007, SC-006). The SFTP pod fails closed: when it cannot confirm a + session with the API for 2 minutes (for example, the API is down), it closes + the connection, and a file request the API answers with 401 closes it at once. + The API also re-checks every running SFTP upload or download against its + session every 5 seconds, on SQLite as well as PostgreSQL, so a transfer stops + when its session is revoked or expires. +- **API hop.** The SFTP pod refuses an `http` API URL unless it is started with + `--allow-insecure-api`. The chart sets that only in local mode, where the pod + talks to the API Service over the cluster's pod network and its + NetworkPolicy limits egress to the API pods. Remote mode needs an `https` + `sftp.apiURL` (the chart refuses anything else), with the certificate checked + against the system roots or `sftp.apiCASecret`. The pod never follows a + redirect from the API, so it never re-sends a password, key or token to + another address. +- **Exposed listener.** Each connection may hold at most 2 session channels, + and a channel that does not start SFTP within 10 seconds is closed. + Connections still logging in are capped at 64 in total and at + `sftp.maxPreAuthPerIP` (default 8) per source IP, so one address cannot + starve everyone else. +- **Metrics.** `/metrics` has no authentication. The SFTP pod binds it to + loopback by default. The chart serves it on the pod address only when + `serviceMonitors.enabled` is true, through the separate in-cluster + `gameplane-sftp-metrics` Service and a NetworkPolicy rule for + `serviceMonitors.scrapeNamespaceSelector`. The public `gameplane-sftp` + Service carries only SSH. - **Transfers.** Uploads are capped by `files.maxUploadSize` and the volume's free space. Idle sessions close after `sftp.idleTimeout`. diff --git a/docs/sftp.md b/docs/sftp.md index e4344b43a..9cdfa2c7c 100644 --- a/docs/sftp.md +++ b/docs/sftp.md @@ -34,6 +34,13 @@ Other values: - `sftp.port` (default `2222`): the port the SFTP server listens on. - `sftp.idleTimeout` (default `15m`): an idle SFTP session is closed after this. - `sftp.maxSessionsPerUser` (default `4`) and `sftp.maxTransfersPerUser` (default `8`). +- `sftp.maxPreAuthPerIP` (default `8`): connections one address may have open + while logging in; more are closed at once. Raise it if many users reach the + pod from one address, for example behind a load balancer that hides client + addresses. +- Metrics: with `serviceMonitors.enabled=true` the chart adds a + `gameplane-sftp-metrics` Service (port 9102, in-cluster only) and a + ServiceMonitor. Without it the SFTP pod serves no metrics outside the pod. - `files.maxUploadSize` (default `20Gi`): the largest single file one upload can send, through SFTP and the dashboard. It accepts Kubernetes quantities (`Ki`, `Mi`, `Gi`, `Ti`, `K`, `M`, `G`, `T`) or a plain byte count. Uploads @@ -183,8 +190,11 @@ drawer: The remote endpoint sends each login and file operation to the central API, and the API reaches the files through the remote gateway. The remote cluster must -be able to reach the central API over HTTPS. If it cannot, logins fail, and the -SFTP pod logs a clear message about the API. +be able to reach the central API over HTTPS. `sftp.apiURL` must start with +`https://`; the chart refuses an `http://` address, and the SFTP pod does not +follow redirects. If the API cannot be reached, logins fail, and the SFTP pod +logs a clear message about the API. Open sessions are closed after about 2 +minutes without a successful check with the API. ## Stopped and sleeping servers @@ -239,8 +249,9 @@ folders are read-only over SFTP. check that the `gameplane-files` pod in the games namespace is running. **The session closes on its own.** It was idle for longer than -`sftp.idleTimeout`, the key or password was revoked, or the server pod could -not be reached. The SFTP pod's logs show which. +`sftp.idleTimeout`, the key or password was revoked, the SFTP pod could not +confirm the session with the API for 2 minutes, or the server pod could not be +reached. The SFTP pod's logs show which. Logs: `kubectl -n gameplane logs deploy/gameplane-sftp`. Audit entries for SFTP file changes show `source: sftp` in the audit log.