Files
Kelx/cmd/sshterm/security_test.go
T
2026-11-30 16:32:37 +00:00

360 lines
12 KiB
Go

package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
"time"
)
func TestIsForbiddenMetadataIP(t *testing.T) {
cases := []struct {
ip string
block bool
}{
{"169.254.169.254", true}, // AWS/GCP/Azure metadata
{"169.254.169.253", true}, // AWS IPv6-transition helper
{"169.254.10.5", true}, // whole link-local range
{"::ffff:169.254.169.254", true}, // IPv4-mapped form
{"fd00:ec2::254", true}, // AWS IPv6 metadata
{"fd00:ec2::1", true}, // inside fd00:ec2::/32
{"169.253.0.1", false}, // outside 169.254.0.0/16
{"169.255.1.1", false},
{"fd00:ec3::254", false}, // outside fd00:ec2::/32
{"2001:db8::1", false},
{"8.8.8.8", false},
{"127.0.0.1", false},
{"::1", false},
{"100.100.100.200", true}, // Alibaba Cloud ECS metadata
{"168.63.129.16", true}, // Azure Wireserver / guest agent
{"::ffff:100.100.100.200", true}, // IPv4-mapped Alibaba metadata
{"::ffff:168.63.129.16", true}, // IPv4-mapped Azure Wireserver
{"100.100.100.201", false}, // adjacent to Alibaba metadata
{"168.63.129.17", false}, // adjacent to Azure Wireserver
{"100.101.100.200", false}, // different /16
}
for _, tc := range cases {
if got := isForbiddenMetadataIP(net.ParseIP(tc.ip)); got != tc.block {
t.Errorf("isForbiddenMetadataIP(%s) = %v, want %v", tc.ip, got, tc.block)
}
}
if isForbiddenMetadataIP(nil) {
t.Error("nil IP must not be blocked")
}
}
// TestSSHTargetAllowedRefusesMetadataLiterals pins the literal-host half of
// the metadata gate: every forbiddenSSHHosts entry is refused even with an
// empty SSH_TERMINAL_ALLOWED_HOSTS allowlist, and near-miss addresses stay
// dialable.
func TestSSHTargetAllowedRefusesMetadataLiterals(t *testing.T) {
cfg := appConfig{} // empty AllowedHosts: the blocklist is the only gate
for _, bad := range []string{
"169.254.169.254",
"169.254.169.253",
"100.100.100.200", // Alibaba Cloud ECS metadata
"168.63.129.16", // Azure Wireserver / guest agent
"fd00:ec2::254",
"metadata",
"metadata.internal",
"metadata.google.internal",
} {
if err := sshTargetAllowed(cfg, sshTarget{Host: bad}); err == nil {
t.Errorf("sshTargetAllowed(%q) must refuse a cloud metadata literal", bad)
}
}
for _, good := range []string{"example.com", "8.8.8.8", "100.100.100.201", "168.63.129.17"} {
if err := sshTargetAllowed(cfg, sshTarget{Host: good}); err != nil {
t.Errorf("sshTargetAllowed(%q) must pass with an empty allowlist: %v", good, err)
}
}
}
func TestLastForwardedValue(t *testing.T) {
cases := []struct {
in string
want string
}{
{"1.1.1.1", "1.1.1.1"},
{"1.1.1.1, 2.2.2.2", "2.2.2.2"},
{" 1.1.1.1 , , 2.2.2.2 ", "2.2.2.2"},
{" , ", ""},
{"", ""},
{" , 3.3.3.3", "3.3.3.3"},
}
for _, tc := range cases {
if got := lastForwardedValue(tc.in); got != tc.want {
t.Errorf("lastForwardedValue(%q) = %q, want %q", tc.in, got, tc.want)
}
}
}
func TestParseTrustedProxies(t *testing.T) {
// Empty / whitespace: loopback default.
for _, raw := range []string{"", " ", " , "} {
got := parseTrustedProxies(raw)
if !isTrustedProxyAddr("127.0.0.1", got) || !isTrustedProxyAddr("::1", got) {
t.Errorf("parseTrustedProxies(%q) must trust loopback, got %v", raw, got)
}
if isTrustedProxyAddr("10.0.0.9", got) {
t.Errorf("parseTrustedProxies(%q) must not trust 10.0.0.9", raw)
}
}
// All-unparseable input: fail safe to the loopback default, not empty.
got := parseTrustedProxies("not-an-ip")
if !isTrustedProxyAddr("127.0.0.1", got) {
t.Error("all-unparseable SSH_TERM_TRUSTED_PROXIES must fall back to loopback trust")
}
// Single IPv4 / IPv6 literals.
got = parseTrustedProxies("10.1.2.3")
if !isTrustedProxyAddr("10.1.2.3", got) || isTrustedProxyAddr("10.1.2.4", got) {
t.Error("single IPv4 entry must trust exactly that /32")
}
got = parseTrustedProxies("2001:db8::5")
if !isTrustedProxyAddr("2001:db8::5", got) || isTrustedProxyAddr("2001:db8::6", got) {
t.Error("single IPv6 entry must trust exactly that /128")
}
// Bracketed IPv6 literal.
got = parseTrustedProxies("[::1]")
if !isTrustedProxyAddr("::1", got) {
t.Error("bracketed IPv6 literal [::1] must be accepted")
}
// CIDRs, mixed with garbage entries.
got = parseTrustedProxies("10.0.0.0/8, garbage, 2001:db8::/32")
if !isTrustedProxyAddr("10.9.9.9", got) || isTrustedProxyAddr("11.0.0.1", got) {
t.Error("10.0.0.0/8 CIDR entry not honored")
}
if !isTrustedProxyAddr("2001:db8:dead::1", got) || isTrustedProxyAddr("2001:db9::1", got) {
t.Error("2001:db8::/32 CIDR entry not honored")
}
}
func TestRequestIPTrustPolicy(t *testing.T) {
loopback := parseTrustedProxies("")
// Spoofed XFF from an untrusted (non-loopback) peer is ignored.
req := httptest.NewRequest(http.MethodGet, "http://panel.example/", nil)
req.RemoteAddr = "203.0.113.7:44444"
req.Header.Set("X-Forwarded-For", "1.2.3.4")
if got := requestIP(req, loopback); got != "203.0.113.7" {
t.Errorf("untrusted peer: requestIP = %q, want the socket address", got)
}
// Trusted loopback peer: XFF is honored (last element).
req = httptest.NewRequest(http.MethodGet, "http://panel.example/", nil)
req.RemoteAddr = "127.0.0.1:55555"
req.Header.Set("X-Forwarded-For", "198.51.100.9")
if got := requestIP(req, loopback); got != "198.51.100.9" {
t.Errorf("trusted peer: requestIP = %q, want 198.51.100.9", got)
}
req.Header.Set("X-Forwarded-For", "198.51.100.9, 10.0.0.1")
if got := requestIP(req, loopback); got != "10.0.0.1" {
t.Errorf("trusted peer: requestIP = %q, want the last XFF element 10.0.0.1", got)
}
// X-Real-IP fallback when XFF is absent/blank.
req = httptest.NewRequest(http.MethodGet, "http://panel.example/", nil)
req.RemoteAddr = "[::1]:6666"
req.Header.Set("X-Real-IP", "198.51.100.11")
if got := requestIP(req, loopback); got != "198.51.100.11" {
t.Errorf("trusted peer: X-Real-IP fallback = %q, want 198.51.100.11", got)
}
// Trusted peer without forwarding headers: the loopback address itself.
req = httptest.NewRequest(http.MethodGet, "http://panel.example/", nil)
req.RemoteAddr = "127.0.0.1:7777"
if got := requestIP(req, loopback); got != "127.0.0.1" {
t.Errorf("trusted peer without headers: requestIP = %q, want 127.0.0.1", got)
}
}
func TestSameIP(t *testing.T) {
if !sameIP("1.2.3.4", "1.2.3.4") {
t.Error("identical IPv4 must match")
}
if !sameIP("::ffff:1.2.3.4", "1.2.3.4") {
t.Error("IPv4-mapped form must match the plain IPv4")
}
if !sameIP("2001:0DB8:0000:0000:0000:0000:0000:0001", "2001:db8::1") {
t.Error("canonicalized IPv6 forms must match")
}
if sameIP("", "1.2.3.4") || sameIP("1.2.3.4", "") || sameIP("garbage", "1.2.3.4") {
t.Error("empty/unparseable inputs must never match")
}
}
func signTestToken(t *testing.T, secret []byte, payload map[string]any) string {
t.Helper()
raw, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
payloadB64 := base64.RawURLEncoding.EncodeToString(raw)
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(payloadB64))
return payloadB64 + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
func TestVerifyTokenIPBinding(t *testing.T) {
secret := []byte("test-secret-0123456789abcdef")
validPayload := func() map[string]any {
return map[string]any{
"v": 1,
"uid": "admin@example.com",
"ip": "198.51.100.9",
"exp": time.Now().Add(5 * time.Minute).UnixMilli(),
}
}
// Matching IP: accepted.
tok := signTestToken(t, secret, validPayload())
payload, err := verifyToken(secret, tok, "198.51.100.9")
if err != nil {
t.Fatalf("matching IP must pass, got: %v", err)
}
if payload.UserID != "admin@example.com" {
t.Errorf("UserID = %q, want admin@example.com", payload.UserID)
}
// Replay from another IP: refused (the M6 fix).
if _, err := verifyToken(secret, tok, "203.0.113.7"); err == nil {
t.Error("mismatched IP must be refused")
} else if !strings.Contains(err.Error(), "ip binding") {
t.Errorf("mismatched IP error should mention ip binding, got: %v", err)
}
// Mapped-v4 spellings of the same address match.
if _, err := verifyToken(secret, tok, "::ffff:198.51.100.9"); err != nil {
t.Errorf("IPv4-mapped request IP must match the plain bound IP, got: %v", err)
}
// Token without a usable IP binding: refused (fail closed).
unbound := validPayload()
unbound["ip"] = ""
if _, err := verifyToken(secret, signTestToken(t, secret, unbound), "198.51.100.9"); err == nil {
t.Error("token without ip binding must be refused")
}
// Expired token: refused.
expired := validPayload()
expired["exp"] = time.Now().Add(-time.Minute).UnixMilli()
if _, err := verifyToken(secret, signTestToken(t, secret, expired), "198.51.100.9"); err == nil {
t.Error("expired token must be refused")
}
// Bad signature: refused.
if _, err := verifyToken([]byte("another-secret-0123456789"), tok, "198.51.100.9"); err == nil {
t.Error("wrong secret must be refused")
}
// Malformed token strings: refused.
for _, bad := range []string{"", "garbage", tok + ".trailing", "a.b"} {
if _, err := verifyToken(secret, bad, "198.51.100.9"); err == nil {
t.Errorf("malformed token %q must be refused", bad)
}
}
}
// newIndexRequest builds a GET / request whose token is bound to the address
// the handler will resolve for it: with a nil TrustedProxies policy the
// request is attributed to its socket address, so the token IP matches it.
func newIndexRequest(t *testing.T, secret []byte) *http.Request {
t.Helper()
tok := signTestToken(t, secret, map[string]any{
"v": 1,
"uid": "admin@example.com",
"ip": "198.51.100.9",
"exp": time.Now().Add(5 * time.Minute).UnixMilli(),
})
req := httptest.NewRequest(http.MethodGet, "http://panel.example/?token="+tok, nil)
req.RemoteAddr = "198.51.100.9:44444"
return req
}
func TestHandleIndexCSPNonce(t *testing.T) {
secret := []byte("test-secret-0123456789abcdef")
rec := httptest.NewRecorder()
handleIndex(appConfig{Secret: secret}, rec, newIndexRequest(t, secret))
if rec.Code != http.StatusOK {
t.Fatalf("handleIndex status = %d, want 200; body: %s", rec.Code, rec.Body.String())
}
// (a) The policy is nonce-gated: no 'unsafe-inline', no jsDelivr.
csp := rec.Header().Get("Content-Security-Policy")
if csp == "" {
t.Fatal("Content-Security-Policy header missing")
}
if !strings.Contains(csp, "'nonce-") {
t.Errorf("CSP must be nonce-gated, got: %s", csp)
}
for _, banned := range []string{"'unsafe-inline'", "cdn.jsdelivr.net"} {
if strings.Contains(csp, banned) {
t.Errorf("CSP must not contain %s, got: %s", banned, csp)
}
}
if !strings.Contains(csp, "frame-ancestors 'self'") {
t.Errorf("CSP must pin frame-ancestors to 'self', got: %s", csp)
}
// (b) The header nonce must gate both script-src and style-src and match
// the rendered inline <style>/<script> tags.
m := regexp.MustCompile(`'nonce-([A-Za-z0-9+/=]+)'`).FindStringSubmatch(csp)
if m == nil {
t.Fatalf("CSP nonce not parsable, got: %s", csp)
}
nonce := m[1]
body := rec.Body.String()
if got := strings.Count(csp, "'nonce-"+nonce+"'"); got != 2 {
t.Errorf("CSP must gate script-src and style-src with the nonce, got %d occurrences in: %s", got, csp)
}
for _, tag := range []string{"<style", "<script"} {
if !strings.Contains(body, tag+` nonce="`+nonce+`">`) {
t.Errorf("body must contain %s nonce=%q matching the header nonce", tag, nonce)
}
}
if got := strings.Count(body, `nonce="`+nonce+`"`); got != 2 {
t.Errorf("expected exactly two nonce-bearing tags in the body, got %d", got)
}
// (c) No inline style attributes and no unreplaced placeholders.
if strings.Contains(body, `style="`) {
t.Error("rendered body must not contain inline style attributes")
}
for _, placeholder := range []string{"__CSP_NONCE__", "__TOKEN__", "__USER__", "__WS_FALLBACK__"} {
if strings.Contains(body, placeholder) {
t.Errorf("placeholder %s must not survive rendering", placeholder)
}
}
}
func TestHandleIndexCSPNoncePerRequest(t *testing.T) {
secret := []byte("test-secret-0123456789abcdef")
nonceOf := func() string {
rec := httptest.NewRecorder()
handleIndex(appConfig{Secret: secret}, rec, newIndexRequest(t, secret))
if rec.Code != http.StatusOK {
t.Fatalf("handleIndex status = %d, want 200", rec.Code)
}
m := regexp.MustCompile(`'nonce-([A-Za-z0-9+/=]+)'`).FindStringSubmatch(rec.Header().Get("Content-Security-Policy"))
if m == nil {
t.Fatalf("CSP nonce missing, got: %s", rec.Header().Get("Content-Security-Policy"))
}
return m[1]
}
if nonceOf() == nonceOf() {
t.Error("each request must receive a fresh CSP nonce")
}
}