Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,465 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"errors"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// The scenarios below exercise the accept-after-warning flow for cross-user
|
||||
// first-use host-key divergence: a user hitting the divergence refusal (two
|
||||
// different servers behind one shared hostname:port — NAT/bastion/reinstall)
|
||||
// must have an in-product recovery (explicit accept) instead of a permanent
|
||||
// dead end, WITHOUT weakening any TOFU invariant:
|
||||
//
|
||||
// - the DEFAULT remains refuse (the accept flag only lives on the retry
|
||||
// that follows the client's informed confirmation),
|
||||
// - a PINNED-key mismatch is refused even with the flag (the flag never
|
||||
// enables replacing one's own pin),
|
||||
// - a clean first use behaves identically with the flag,
|
||||
// - a failed store save still fails closed (the pin is not committed).
|
||||
|
||||
// setupDivergence pins keyA for userA on the shared host and returns the
|
||||
// pieces the divergence tests need.
|
||||
func setupDivergence(t *testing.T, store string, keyA ssh.PublicKey) {
|
||||
t.Helper()
|
||||
first := tofuHostKeyCallback(store, "userA", false)
|
||||
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
|
||||
if err := first("shared.example:22", addr, keyA); err != nil {
|
||||
t.Fatalf("setup: userA first-use pin failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Default refusal: the second user presenting a different key on a host
|
||||
// another user already recorded gets the typed divergence error carrying the
|
||||
// presented fingerprint and the previously-seen ones — that is the payload
|
||||
// handleWS forwards to the client as the structured divergence notice.
|
||||
func TestDivergenceDefaultRefusalIsTypedWithFingerprints(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
|
||||
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
|
||||
host := "shared.example:22"
|
||||
|
||||
keyA := mkKey(t)
|
||||
keyB := mkKey(t)
|
||||
setupDivergence(t, store, keyA)
|
||||
|
||||
second := tofuHostKeyCallback(store, "userB", false)
|
||||
err := second(host, addr, keyB)
|
||||
if err == nil {
|
||||
t.Fatal("default must refuse a divergent first-use key")
|
||||
}
|
||||
var dke *hostKeyDivergenceError
|
||||
if !errors.As(err, &dke) {
|
||||
t.Fatalf("refusal must be a *hostKeyDivergenceError, got %T: %v", err, err)
|
||||
}
|
||||
if dke.presented != hostKeyFingerprint(keyB) {
|
||||
t.Fatalf("presented must be key B's fingerprint, got %q", dke.presented)
|
||||
}
|
||||
if len(dke.known) != 1 || dke.known[0] != hostKeyFingerprint(keyA) {
|
||||
t.Fatalf("known must contain exactly key A's fingerprint, got %v", dke.known)
|
||||
}
|
||||
if dke.host != host {
|
||||
t.Fatalf("host must be the dial target, got %q", dke.host)
|
||||
}
|
||||
// Error() text is the historical refusal text: the divergence branch of
|
||||
// explainSSHConnectError keys on it, and the client-facing message keeps
|
||||
// demanding an explicit confirmation.
|
||||
msg := dke.Error()
|
||||
if !strings.Contains(msg, "host key divergence") || !strings.Contains(msg, "possible interception") {
|
||||
t.Fatalf("historical refusal text must be preserved, got: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Explicit accept: the same divergence WITH allowDivergentFirstUse=true —
|
||||
// the server-side effect of the client's accept-after-warning retry — pins
|
||||
// the presented key for the accepting user and records it in the advisory
|
||||
// Global set.
|
||||
func TestDivergenceExplicitAcceptPinsPresentedKey(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
|
||||
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
|
||||
host := "shared.example:22"
|
||||
|
||||
keyA := mkKey(t)
|
||||
keyB := mkKey(t)
|
||||
setupDivergence(t, store, keyA)
|
||||
|
||||
accepting := tofuHostKeyCallback(store, "userB", true)
|
||||
if err := accepting(host, addr, keyB); err != nil {
|
||||
t.Fatalf("explicit accept must succeed, got: %v", err)
|
||||
}
|
||||
|
||||
st := loadKnownHostsMust(t, store)
|
||||
if got := st.Pins[userHostKey("userB", host)]; got != hostKeyFingerprint(keyB) {
|
||||
t.Fatalf("userB must be pinned to the presented key B, got %q", got)
|
||||
}
|
||||
found := false
|
||||
for _, fp := range st.Global[host] {
|
||||
if fp == hostKeyFingerprint(keyB) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("key B's fingerprint must be recorded in Global[%s], got %v", host, st.Global[host])
|
||||
}
|
||||
// The accepting user must never inherit userA's key either.
|
||||
if got := st.Pins[userHostKey("userB", host)]; got == hostKeyFingerprint(keyA) {
|
||||
t.Fatal("userB must NOT be pinned to userA's key")
|
||||
}
|
||||
}
|
||||
|
||||
// 3. After the accepted pin, the same user's subsequent DEFAULT connection
|
||||
// (flag false — the normal connect path) succeeds against key B: the
|
||||
// divergence flow only ever needed to run once.
|
||||
func TestDivergenceAfterAcceptDefaultConnectSucceeds(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
|
||||
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
|
||||
host := "shared.example:22"
|
||||
|
||||
keyA := mkKey(t)
|
||||
keyB := mkKey(t)
|
||||
setupDivergence(t, store, keyA)
|
||||
|
||||
accepting := tofuHostKeyCallback(store, "userB", true)
|
||||
if err := accepting(host, addr, keyB); err != nil {
|
||||
t.Fatalf("explicit accept failed: %v", err)
|
||||
}
|
||||
|
||||
normal := tofuHostKeyCallback(store, "userB", false)
|
||||
if err := normal(host, addr, keyB); err != nil {
|
||||
t.Fatalf("post-accept default connection must succeed on the pin match, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Pinned-mismatch invariant: a user's own pin stays ABSOLUTE. The accept
|
||||
// flag must never enable replacing one's own pinned key with a presented one.
|
||||
func TestPinnedMismatchRefusedEvenWithAllowDivergentFirstUse(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
|
||||
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
|
||||
host := "pinned.example:22"
|
||||
|
||||
keyA := mkKey(t)
|
||||
keyB := mkKey(t)
|
||||
|
||||
user := tofuHostKeyCallback(store, "userA", false)
|
||||
if err := user(host, addr, keyA); err != nil {
|
||||
t.Fatalf("initial pin failed: %v", err)
|
||||
}
|
||||
|
||||
withFlag := tofuHostKeyCallback(store, "userA", true)
|
||||
err := withFlag(host, addr, keyB)
|
||||
if err == nil {
|
||||
t.Fatal("a pinned mismatch must be refused even with allowDivergentFirstUse=true")
|
||||
}
|
||||
var dke *hostKeyDivergenceError
|
||||
if errors.As(err, &dke) {
|
||||
t.Fatalf("pinned mismatch must NOT surface as a divergence error (it stays admin-mediated), got: %v", err)
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "host key mismatch") {
|
||||
t.Fatalf("expected the pinned-mismatch refusal, got: %v", err)
|
||||
}
|
||||
|
||||
// The pin is unchanged and the presented key never entered the advisory
|
||||
// set: the accept path did not run at all.
|
||||
st := loadKnownHostsMust(t, store)
|
||||
if got := st.Pins[userHostKey("userA", host)]; got != hostKeyFingerprint(keyA) {
|
||||
t.Fatalf("the original pin must be untouched, got %q", got)
|
||||
}
|
||||
for _, fp := range st.Global[host] {
|
||||
if fp == hostKeyFingerprint(keyB) {
|
||||
t.Fatal("the refused key must not be recorded in the advisory set")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Clean first use with the flag true (empty Global for that host — no
|
||||
// divergence to confirm) still pins normally: the flag changes nothing when
|
||||
// there is no divergence.
|
||||
func TestCleanFirstUseWithFlagStillPins(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
|
||||
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
|
||||
host := "clean.example:22"
|
||||
|
||||
key := mkKey(t)
|
||||
|
||||
cb := tofuHostKeyCallback(store, "userC", true)
|
||||
if err := cb(host, addr, key); err != nil {
|
||||
t.Fatalf("clean first use with the flag must pin normally, got: %v", err)
|
||||
}
|
||||
st := loadKnownHostsMust(t, store)
|
||||
if got := st.Pins[userHostKey("userC", host)]; got != hostKeyFingerprint(key) {
|
||||
t.Fatalf("clean first use must pin the presented key, got %q", got)
|
||||
}
|
||||
// Reconnect with the same key (flag true again) still matches the pin.
|
||||
if err := cb(host, addr, key); err != nil {
|
||||
t.Fatalf("pin match must succeed regardless of the flag, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 6. The divergence branch of explainSSHConnectError must describe the
|
||||
// in-product recovery (confirm to accept when prompted) instead of the old
|
||||
// dead-end advice.
|
||||
func TestExplainSSHConnectErrorDivergenceDescribesConfirmFlow(t *testing.T) {
|
||||
dke := &hostKeyDivergenceError{
|
||||
host: "shared.example:22",
|
||||
presented: "ssh-ed25519:SHA256:presented",
|
||||
known: []string{"ssh-ed25519:SHA256:known"},
|
||||
}
|
||||
msg := explainSSHConnectError(dke)
|
||||
lower := strings.ToLower(msg)
|
||||
|
||||
if !strings.Contains(lower, "confirm to accept it when prompted") {
|
||||
t.Fatalf("explanation must point at the in-product confirm flow, got: %s", msg)
|
||||
}
|
||||
const oldDeadEnd = "verify the server fingerprint out-of-band"
|
||||
if strings.Contains(lower, oldDeadEnd) {
|
||||
t.Fatalf("explanation must not contain the old dead-end phrase %q, got: %s", oldDeadEnd, msg)
|
||||
}
|
||||
if !strings.Contains(lower, "possible interception") {
|
||||
t.Fatalf("explanation must keep the interception warning, got: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Fail-closed on store save errors is unchanged on the accept path too: a
|
||||
// save failure refuses the connection AND commits nothing, so the accepting
|
||||
// user is not silently pinned to the presented key.
|
||||
func TestDivergenceAcceptFailsClosedWhenSaveFails(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
|
||||
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
|
||||
host := "shared.example:22"
|
||||
|
||||
keyA := mkKey(t)
|
||||
keyB := mkKey(t)
|
||||
setupDivergence(t, store, keyA)
|
||||
|
||||
// Replace the store FILE with a directory: loads keep the resident
|
||||
// last-good state (so the divergence is still detected) but every save
|
||||
// fails — the accept path must fail closed on it.
|
||||
if err := os.Remove(store); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(store, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
accepting := tofuHostKeyCallback(store, "userB", true)
|
||||
err := accepting(host, addr, keyB)
|
||||
if err == nil || !strings.Contains(strings.ToLower(err.Error()), "host key store unavailable") {
|
||||
t.Fatalf("accept path must fail closed when the save fails, got: %v", err)
|
||||
}
|
||||
|
||||
// Nothing was committed: the accepting user has no pin, so their next
|
||||
// DEFAULT attempt is still the divergence refusal (a committed pin would
|
||||
// have made it succeed).
|
||||
normal := tofuHostKeyCallback(store, "userB", false)
|
||||
if err := normal(host, addr, keyB); err == nil {
|
||||
t.Fatal("a failed save must not commit the accept: the next default attempt must still be refused")
|
||||
} else if !errors.As(err, new(*hostKeyDivergenceError)) {
|
||||
t.Fatalf("next attempt must still be the divergence refusal, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// mkSignerKey generates a fresh ed25519 keypair as an ssh.Signer (for the
|
||||
// in-process server below) plus its public key.
|
||||
func mkSignerKey(t *testing.T) (ssh.PublicKey, ssh.Signer) {
|
||||
t.Helper()
|
||||
_, priv, err := ed25519.GenerateKey(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signer, err := ssh.NewSignerFromKey(priv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return signer.PublicKey(), signer
|
||||
}
|
||||
|
||||
// startDivergenceSSHServer runs an in-process SSH server that presents
|
||||
// serverSigner's host key and accepts any password, servicing pty/shell
|
||||
// requests so openSSHSession can complete a REAL handshake against it. The
|
||||
// returned string is the dial target ("127.0.0.1:port") — exactly the
|
||||
// hostport string tofuHostKeyCallback sees as t.dialAddress during that
|
||||
// handshake.
|
||||
func startDivergenceSSHServer(t *testing.T, serverSigner ssh.Signer) string {
|
||||
t.Helper()
|
||||
config := &ssh.ServerConfig{
|
||||
PasswordCallback: func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error) {
|
||||
return &ssh.Permissions{}, nil
|
||||
},
|
||||
}
|
||||
config.AddHostKey(serverSigner)
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
go func() {
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go serveDivergenceSSHConn(c, config)
|
||||
}
|
||||
}()
|
||||
return ln.Addr().String()
|
||||
}
|
||||
|
||||
func serveDivergenceSSHConn(c net.Conn, config *ssh.ServerConfig) {
|
||||
sconn, chans, reqs, err := ssh.NewServerConn(c, config)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer sconn.Close()
|
||||
go func() {
|
||||
for req := range reqs {
|
||||
if req.WantReply {
|
||||
_ = req.Reply(false, nil)
|
||||
}
|
||||
}
|
||||
}()
|
||||
for newCh := range chans {
|
||||
if newCh.ChannelType() != "session" {
|
||||
_ = newCh.Reject(ssh.UnknownChannelType, "unsupported channel type")
|
||||
continue
|
||||
}
|
||||
ch, chReqs, err := newCh.Accept()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
defer ch.Close()
|
||||
for req := range chReqs {
|
||||
switch req.Type {
|
||||
case "pty-req", "shell", "env":
|
||||
if req.WantReply {
|
||||
_ = req.Reply(true, nil)
|
||||
}
|
||||
default:
|
||||
if req.WantReply {
|
||||
_ = req.Reply(false, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// 8. THE propagation proof: the divergence refusal raised inside the TOFU
|
||||
// host-key callback must survive the whole x/crypto handshake path (kexLoop
|
||||
// → readOnePacket → clientHandshake → the "ssh: handshake failed: %w" wrap in
|
||||
// NewClientConn) so handleWS's errors.As can still match it and upgrade the
|
||||
// refusal to the structured client notice. Verified against a real in-process
|
||||
// SSH server presenting a different key than the one userA pinned.
|
||||
func TestDivergenceRefusalPropagatesThroughRealHandshake(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
|
||||
|
||||
keyA := mkKey(t)
|
||||
serverKey, serverSigner := mkSignerKey(t)
|
||||
|
||||
// userA pins keyA for the REAL listener address, so the global advisory
|
||||
// set holds a fingerprint that differs from the server's key.
|
||||
target := startDivergenceSSHServer(t, serverSigner)
|
||||
first := tofuHostKeyCallback(store, "userA", false)
|
||||
if err := first(target, &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}, keyA); err != nil {
|
||||
t.Fatalf("setup: userA first-use pin failed: %v", err)
|
||||
}
|
||||
|
||||
_, _, _, _, _, err := openSSHSession(sshTarget{User: "root", Host: "127.0.0.1", Port: portOf(t, target)}, "pw", store, "userB", 80, 24, false)
|
||||
if err == nil {
|
||||
t.Fatal("default connect against the divergent server must be refused")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "ssh: handshake failed:") {
|
||||
t.Fatalf("refusal must surface through the real x/crypto handshake wrap, got: %v", err)
|
||||
}
|
||||
var dke *hostKeyDivergenceError
|
||||
if !errors.As(err, &dke) {
|
||||
t.Fatalf("divergence error must survive the handshake for errors.As (got %T: %v)", err, err)
|
||||
}
|
||||
if dke.presented != hostKeyFingerprint(serverKey) {
|
||||
t.Fatalf("presented must be the server's key fingerprint, got %q", dke.presented)
|
||||
}
|
||||
if len(dke.known) != 1 || dke.known[0] != hostKeyFingerprint(keyA) {
|
||||
t.Fatalf("known must contain exactly userA's fingerprint, got %v", dke.known)
|
||||
}
|
||||
if dke.host != target {
|
||||
t.Fatalf("host must be the dial target, got %q", dke.host)
|
||||
}
|
||||
}
|
||||
|
||||
// 9. The accept retry (flag true) against the SAME divergent server completes
|
||||
// a real end-to-end connection, pins the presented key, and its audit log
|
||||
// line carries fingerprints only — never the password.
|
||||
func TestDivergenceAcceptRetryCompletesRealConnection(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
|
||||
|
||||
keyA := mkKey(t)
|
||||
serverKey, serverSigner := mkSignerKey(t)
|
||||
|
||||
target := startDivergenceSSHServer(t, serverSigner)
|
||||
first := tofuHostKeyCallback(store, "userA", false)
|
||||
if err := first(target, &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}, keyA); err != nil {
|
||||
t.Fatalf("setup: userA first-use pin failed: %v", err)
|
||||
}
|
||||
|
||||
const password = "sup3r-secret-password-DO-NOT-LOG"
|
||||
|
||||
// The initial (default) attempt is the divergence refusal — the client's
|
||||
// warning step.
|
||||
if _, _, _, _, _, err := openSSHSession(sshTarget{User: "root", Host: "127.0.0.1", Port: portOf(t, target)}, password, store, "userB", 80, 24, false); !errors.As(err, new(*hostKeyDivergenceError)) {
|
||||
t.Fatalf("pre-accept attempt must be the divergence refusal, got: %v", err)
|
||||
}
|
||||
|
||||
// Capture the package log while the accept retry runs.
|
||||
var logBuf strings.Builder
|
||||
prevWriter := log.Writer()
|
||||
log.SetOutput(&logBuf)
|
||||
t.Cleanup(func() { log.SetOutput(prevWriter) })
|
||||
|
||||
client, _, _, _, _, err := openSSHSession(sshTarget{User: "root", Host: "127.0.0.1", Port: portOf(t, target)}, password, store, "userB", 80, 24, true)
|
||||
if err != nil {
|
||||
t.Fatalf("accept retry must complete a real connection, got: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
|
||||
logged := logBuf.String()
|
||||
if !strings.Contains(logged, "explicitly accepted divergent host key") {
|
||||
t.Fatalf("the accept must leave the audit line, got log: %q", logged)
|
||||
}
|
||||
if strings.Contains(logged, password) {
|
||||
t.Fatalf("the audit line must never contain the password, got log: %q", logged)
|
||||
}
|
||||
|
||||
st := loadKnownHostsMust(t, store)
|
||||
if got := st.Pins[userHostKey("userB", target)]; got != hostKeyFingerprint(serverKey) {
|
||||
t.Fatalf("the accept retry must pin the server's presented key, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func portOf(t *testing.T, hostport string) int {
|
||||
t.Helper()
|
||||
_, portText, err := net.SplitHostPort(hostport)
|
||||
if err != nil {
|
||||
t.Fatalf("bad test listener address %q: %v", hostport, err)
|
||||
}
|
||||
port, err := strconv.Atoi(portText)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
t.Fatalf("bad port %q", portText)
|
||||
}
|
||||
return port
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The idle reapers must treat remote output as activity, not just keystrokes:
|
||||
// a tail -f or long build that only scrolls used to be killed mid-stream by
|
||||
// the 20-minute idle timeout. The detach grace rule must keep working exactly
|
||||
// as before — fresh activity never rescues a session nobody is watching.
|
||||
func TestCleanupIdleTerminalSessionsCountsOutputAsActivity(t *testing.T) {
|
||||
stale := time.Now().Add(-terminalIdleTimeout - time.Minute)
|
||||
|
||||
outputActive := &terminalSession{
|
||||
owner: "idle-output@example.com",
|
||||
id: "idle-output-active",
|
||||
done: make(chan struct{}),
|
||||
lastActive: stale, // stale on purpose: only addOutput can rescue it
|
||||
}
|
||||
outputActive.addOutput("build output\r\n")
|
||||
|
||||
trulyIdle := &terminalSession{
|
||||
owner: "idle-quiet@example.com",
|
||||
id: "idle-quiet-stale",
|
||||
done: make(chan struct{}),
|
||||
lastActive: stale, // no input, no output, never detached (zero lastDetach)
|
||||
}
|
||||
detached := &terminalSession{
|
||||
owner: "idle-detached@example.com",
|
||||
id: "idle-detached-grace",
|
||||
done: make(chan struct{}),
|
||||
lastActive: time.Now(), // fresh activity, but no viewer and grace elapsed
|
||||
lastDetach: time.Now().Add(-terminalResumeGrace - time.Minute),
|
||||
}
|
||||
|
||||
terminalSessions.Lock()
|
||||
terminalSessions.items[terminalSessionKey(outputActive.owner, outputActive.id)] = outputActive
|
||||
terminalSessions.items[terminalSessionKey(trulyIdle.owner, trulyIdle.id)] = trulyIdle
|
||||
terminalSessions.items[terminalSessionKey(detached.owner, detached.id)] = detached
|
||||
terminalSessions.Unlock()
|
||||
t.Cleanup(func() {
|
||||
terminalSessions.Lock()
|
||||
for _, ts := range []*terminalSession{outputActive, trulyIdle, detached} {
|
||||
delete(terminalSessions.items, terminalSessionKey(ts.owner, ts.id))
|
||||
}
|
||||
terminalSessions.Unlock()
|
||||
})
|
||||
|
||||
outputActive.mu.Lock()
|
||||
refreshed := time.Since(outputActive.lastActive) < terminalIdleTimeout
|
||||
outputActive.mu.Unlock()
|
||||
if !refreshed {
|
||||
t.Fatal("addOutput must refresh the session activity timestamp")
|
||||
}
|
||||
|
||||
cleanupIdleTerminalSessions()
|
||||
|
||||
select {
|
||||
case <-outputActive.done:
|
||||
t.Fatal("session with fresh output activity must not be reaped as idle")
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-trulyIdle.done:
|
||||
default:
|
||||
t.Fatal("session with no input and no output after the timeout must be reaped")
|
||||
}
|
||||
select {
|
||||
case <-detached.done:
|
||||
default:
|
||||
t.Fatal("unwatched session past the detach grace must still be reaped despite fresh activity")
|
||||
}
|
||||
}
|
||||
+590
-50
@@ -45,6 +45,18 @@ type wsMessage struct {
|
||||
Cols int `json:"cols,omitempty"`
|
||||
Rows int `json:"rows,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
// Code, Fingerprint and KnownFingerprints are only set on the structured
|
||||
// host-key divergence refusal (Code "host-key-divergence"); every other
|
||||
// message leaves them empty. The client renders that refusal as an
|
||||
// explicit accept-after-warning prompt instead of a dead-end error line.
|
||||
Code string `json:"code,omitempty"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
KnownFingerprints []string `json:"knownFingerprints,omitempty"`
|
||||
// AcceptDivergentKey is only set by the client's explicit accept retry
|
||||
// after the divergence warning: it flips tofuHostKeyCallback into the
|
||||
// allowDivergentFirstUse path for that single connect. It never affects
|
||||
// the pinned-mismatch refusal.
|
||||
AcceptDivergentKey bool `json:"acceptDivergentKey,omitempty"`
|
||||
}
|
||||
|
||||
type sshTarget struct {
|
||||
@@ -91,19 +103,22 @@ const sshSetupTimeout = 30 * time.Second
|
||||
const terminalReplayLimit = 128 * 1024
|
||||
|
||||
type terminalSession struct {
|
||||
owner string
|
||||
id string
|
||||
client *ssh.Client
|
||||
session *ssh.Session
|
||||
stdin io.WriteCloser
|
||||
done chan struct{}
|
||||
closeOnce sync.Once
|
||||
mu sync.Mutex
|
||||
subs map[chan wsMessage]struct{}
|
||||
replay []byte
|
||||
closed bool
|
||||
waitErr error
|
||||
lastInput time.Time
|
||||
owner string
|
||||
id string
|
||||
client *ssh.Client
|
||||
session *ssh.Session
|
||||
stdin io.WriteCloser
|
||||
done chan struct{}
|
||||
closeOnce sync.Once
|
||||
mu sync.Mutex
|
||||
subs map[chan wsMessage]struct{}
|
||||
replay []byte
|
||||
closed bool
|
||||
waitErr error
|
||||
// lastActive is refreshed by both keystrokes (writeInput) and remote
|
||||
// output chunks (addOutput); the idle reapers close a session only after
|
||||
// it has produced neither for terminalIdleTimeout.
|
||||
lastActive time.Time
|
||||
lastDetach time.Time
|
||||
}
|
||||
|
||||
@@ -388,16 +403,105 @@ func removeTerminalSession(ts *terminalSession) {
|
||||
terminalSessions.Unlock()
|
||||
}
|
||||
|
||||
// terminalMaxSessionsPerUser bounds how many live terminal sessions (SSH
|
||||
// clients) one owner may hold at once. Every other attacker-influenced
|
||||
// collection in this service is capped (replay buffer, known-hosts store,
|
||||
// token cache); sessions were the one unbounded collection — each connect
|
||||
// mints a terminalSession plus an SSH client, and a scripted client holding a
|
||||
// valid 20-minute token could pin unbounded goroutines/sockets on this host.
|
||||
// The idle timeout and detach grace bound DURATION, not count. Tunable via
|
||||
// SSH_TERM_MAX_SESSIONS_PER_USER; invalid or out-of-range values fall back to
|
||||
// the default rather than disabling the cap.
|
||||
const defaultTerminalMaxSessionsPerUser = 4
|
||||
const maxTerminalSessionsPerUserLimit = 128
|
||||
|
||||
func terminalMaxSessionsPerUser() int {
|
||||
raw := strings.TrimSpace(os.Getenv("SSH_TERM_MAX_SESSIONS_PER_USER"))
|
||||
if raw == "" {
|
||||
return defaultTerminalMaxSessionsPerUser
|
||||
}
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit <= 0 {
|
||||
return defaultTerminalMaxSessionsPerUser
|
||||
}
|
||||
if limit > maxTerminalSessionsPerUserLimit {
|
||||
return maxTerminalSessionsPerUserLimit
|
||||
}
|
||||
return limit
|
||||
}
|
||||
|
||||
// Per-owner slot accounting for the session cap. Reservations are atomic
|
||||
// under the mutex, so parallel WS handshakes cannot race past the limit the
|
||||
// way a read-then-create against terminalSessions.items would. A slot is held
|
||||
// from just before openSSHSession (the dial is exactly the resource being
|
||||
// capped) until the session's closeWithMessage teardown, and released by the
|
||||
// dial-failure path — exactly one release per reservation. Owner keys are
|
||||
// trimmed so a uid with stray whitespace cannot split one owner into two
|
||||
// accounting buckets (mirrors the panel's normalized uid keys); an owner that
|
||||
// is empty after trimming is unattributable and fails closed.
|
||||
var terminalSessionSlots = struct {
|
||||
sync.Mutex
|
||||
counts map[string]int
|
||||
}{counts: make(map[string]int)}
|
||||
|
||||
func reserveTerminalSessionSlot(owner string, limit int) bool {
|
||||
key := strings.TrimSpace(owner)
|
||||
if key == "" || limit <= 0 {
|
||||
return false
|
||||
}
|
||||
terminalSessionSlots.Lock()
|
||||
defer terminalSessionSlots.Unlock()
|
||||
if terminalSessionSlots.counts[key] >= limit {
|
||||
return false
|
||||
}
|
||||
terminalSessionSlots.counts[key]++
|
||||
return true
|
||||
}
|
||||
|
||||
// Non-reserving peek for the fail-fast check: rejecting at-cap connects
|
||||
// before the reachability probe saves a 6s target dial, and a stale yes here
|
||||
// is harmless because the authoritative reserve below still gates the dial.
|
||||
func terminalSessionSlotAvailable(owner string, limit int) bool {
|
||||
key := strings.TrimSpace(owner)
|
||||
if key == "" || limit <= 0 {
|
||||
return false
|
||||
}
|
||||
terminalSessionSlots.Lock()
|
||||
defer terminalSessionSlots.Unlock()
|
||||
return terminalSessionSlots.counts[key] < limit
|
||||
}
|
||||
|
||||
func releaseTerminalSessionSlot(owner string) {
|
||||
key := strings.TrimSpace(owner)
|
||||
if key == "" {
|
||||
return
|
||||
}
|
||||
terminalSessionSlots.Lock()
|
||||
defer terminalSessionSlots.Unlock()
|
||||
if terminalSessionSlots.counts[key] <= 1 {
|
||||
delete(terminalSessionSlots.counts, key)
|
||||
return
|
||||
}
|
||||
terminalSessionSlots.counts[key]--
|
||||
}
|
||||
|
||||
// Terminal-facing rejection text for the per-owner session cap: states the
|
||||
// limit and the two legitimate ways past it (close another window, or let the
|
||||
// 20-minute idle expiry reclaim stale sessions).
|
||||
func terminalSessionCapMessage(limit int) string {
|
||||
return fmt.Sprintf("too many concurrent terminal sessions (limit %d) - close another terminal window or wait for idle sessions to expire", limit)
|
||||
}
|
||||
|
||||
func newTerminalSession(owner string, id string, client *ssh.Client, session *ssh.Session, stdin io.WriteCloser, stdout io.Reader, stderr io.Reader) *terminalSession {
|
||||
ts := &terminalSession{
|
||||
owner: owner,
|
||||
id: id,
|
||||
client: client,
|
||||
session: session,
|
||||
stdin: stdin,
|
||||
done: make(chan struct{}),
|
||||
subs: make(map[chan wsMessage]struct{}),
|
||||
lastInput: time.Now(),
|
||||
owner: owner,
|
||||
id: id,
|
||||
client: client,
|
||||
session: session,
|
||||
stdin: stdin,
|
||||
done: make(chan struct{}),
|
||||
subs: make(map[chan wsMessage]struct{}),
|
||||
lastActive: time.Now(),
|
||||
}
|
||||
|
||||
pump := func(reader io.Reader) {
|
||||
@@ -443,22 +547,46 @@ func (ts *terminalSession) addOutput(data string) {
|
||||
ts.mu.Unlock()
|
||||
return
|
||||
}
|
||||
// Remote output counts as activity: a scrolling tail -f or long build
|
||||
// must not be reaped by the idle timeout while it is visibly streaming.
|
||||
ts.lastActive = time.Now()
|
||||
ts.replay = append(ts.replay, []byte(data)...)
|
||||
if len(ts.replay) > terminalReplayLimit {
|
||||
ts.replay = ts.replay[len(ts.replay)-terminalReplayLimit:]
|
||||
}
|
||||
subs := make([]chan wsMessage, 0, len(ts.subs))
|
||||
// Fan out to every live viewer while still holding ts.mu. The sends are
|
||||
// non-blocking, so the critical section stays short; every
|
||||
// subscriber-channel send in the program happens here (callers are the
|
||||
// two pump goroutines and closeWithMessage's final notice — all funnel
|
||||
// through this method), and attachTerminalSession only ever RECEIVES on
|
||||
// a subscriber channel, so all sends are serialized by ts.mu.
|
||||
//
|
||||
// Invariant: a channel is closed only on this full-buffer path, under
|
||||
// the same lock that guards the map, and it is deleted from ts.subs
|
||||
// before (and atomically with) being closed — so a channel present in
|
||||
// ts.subs is never closed, a closed channel is never in ts.subs, and a
|
||||
// send-on-closed-channel panic is impossible. unsubscribe() only
|
||||
// deletes; it never closes.
|
||||
//
|
||||
// A viewer whose 256-slot buffer is FULL has fallen behind the producer
|
||||
// and can never catch up on the live stream. Dropping the chunk (the
|
||||
// old behavior) silently corrupted its terminal: terminal output is a
|
||||
// byte stream with no per-chunk framing, so any lost chunk garbles
|
||||
// everything after it. Instead the viewer is force-detached — removed
|
||||
// and closed here, without this chunk — so its attach loop sees the
|
||||
// closed channel, tells the client to resync, and the viewer re-attaches
|
||||
// and rebuilds its screen from ts.replay, which kept every byte.
|
||||
for ch := range ts.subs {
|
||||
subs = append(subs, ch)
|
||||
}
|
||||
ts.mu.Unlock()
|
||||
|
||||
for _, ch := range subs {
|
||||
select {
|
||||
case ch <- msg:
|
||||
default:
|
||||
// Buffer full: force-detach this viewer so it resyncs from the
|
||||
// replay buffer instead of silently losing output chunks.
|
||||
delete(ts.subs, ch)
|
||||
close(ch)
|
||||
}
|
||||
}
|
||||
ts.mu.Unlock()
|
||||
}
|
||||
|
||||
func (ts *terminalSession) subscribe() (chan wsMessage, string, bool) {
|
||||
@@ -492,10 +620,10 @@ func cleanupIdleTerminalSessions() {
|
||||
for _, ts := range terminalSessions.items {
|
||||
ts.mu.Lock()
|
||||
idleDetached := len(ts.subs) == 0 && !ts.lastDetach.IsZero() && now.Sub(ts.lastDetach) >= terminalResumeGrace
|
||||
idleInput := now.Sub(ts.lastInput) >= terminalIdleTimeout
|
||||
idleActive := now.Sub(ts.lastActive) >= terminalIdleTimeout
|
||||
closed := ts.closed
|
||||
ts.mu.Unlock()
|
||||
if !closed && (idleDetached || idleInput) {
|
||||
if !closed && (idleDetached || idleActive) {
|
||||
stale = append(stale, ts)
|
||||
}
|
||||
}
|
||||
@@ -527,6 +655,12 @@ func (ts *terminalSession) closeWithMessage(message string) {
|
||||
_ = ts.client.Close()
|
||||
}
|
||||
removeTerminalSession(ts)
|
||||
// Paired with the reserveTerminalSessionSlot in handleWS: every
|
||||
// created session closes exactly once through here (idle expiry,
|
||||
// detach grace, last-viewer disconnect, replaced-by-new-connection,
|
||||
// or its own SSH session ending), so the per-owner slot accounting
|
||||
// cannot leak.
|
||||
releaseTerminalSessionSlot(ts.owner)
|
||||
close(ts.done)
|
||||
})
|
||||
}
|
||||
@@ -540,7 +674,7 @@ func (ts *terminalSession) writeInput(data string) error {
|
||||
ts.mu.Unlock()
|
||||
return errors.New("terminal session closed")
|
||||
}
|
||||
ts.lastInput = time.Now()
|
||||
ts.lastActive = time.Now()
|
||||
stdin := ts.stdin
|
||||
ts.mu.Unlock()
|
||||
if stdin == nil {
|
||||
@@ -613,7 +747,7 @@ func attachTerminalSession(ctx context.Context, conn *websocket.Conn, ts *termin
|
||||
return
|
||||
case <-ticker.C:
|
||||
ts.mu.Lock()
|
||||
expired := time.Since(ts.lastInput) >= terminalIdleTimeout
|
||||
expired := time.Since(ts.lastActive) >= terminalIdleTimeout
|
||||
ts.mu.Unlock()
|
||||
if expired {
|
||||
ts.closeWithMessage("\r\n[adpanel] session expired after 20 minutes of inactivity\r\n")
|
||||
@@ -634,10 +768,36 @@ func attachTerminalSession(ctx context.Context, conn *websocket.Conn, ts *termin
|
||||
case "resize":
|
||||
ts.resize(msg.Cols, msg.Rows)
|
||||
case "disconnect":
|
||||
ts.closeWithMessage("")
|
||||
// An explicit disconnect tears the session down only when the
|
||||
// sender is the LAST attached viewer. The panel restores the
|
||||
// same session id into every new tab, so several connections
|
||||
// legitimately share one session, and a close in one tab must
|
||||
// not destroy it under the others — that left every other
|
||||
// viewer's terminal frozen mid-use. With other viewers still
|
||||
// attached, this connection simply detaches (the deferred
|
||||
// unsubscribe) and the session keeps running for them; the
|
||||
// last viewer's disconnect keeps the immediate teardown.
|
||||
ts.mu.Lock()
|
||||
lastViewer := len(ts.subs) <= 1
|
||||
ts.mu.Unlock()
|
||||
if lastViewer {
|
||||
ts.closeWithMessage("")
|
||||
}
|
||||
return
|
||||
}
|
||||
case msg, ok := <-outCh:
|
||||
if !ok {
|
||||
// addOutput force-detached this viewer (its buffer filled, so
|
||||
// it could no longer keep up with the live stream): the
|
||||
// channel was closed after its buffered messages, so reaching
|
||||
// ok=false means this viewer missed live output and must
|
||||
// rebuild from the replay buffer. Best-effort resync notice
|
||||
// (the client closes quietly and re-attaches to the same
|
||||
// session), then return — the deferred unsubscribe runs and
|
||||
// the websocket closes.
|
||||
_ = write(wsMessage{Type: "resync"})
|
||||
return
|
||||
}
|
||||
case msg := <-outCh:
|
||||
if !write(msg) {
|
||||
return
|
||||
}
|
||||
@@ -653,6 +813,15 @@ func handleWS(cfg appConfig, w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
// The issuing panel always embeds a uid (its upgrade gate refuses
|
||||
// uid-less tokens), so an empty owner can only arrive on a mis-issued
|
||||
// token: per-owner session accounting would be unattributable — refuse
|
||||
// rather than run such connects outside the cap.
|
||||
if strings.TrimSpace(payload.UserID) == "" {
|
||||
log.Printf("[ssh-term] ws token reject: missing uid")
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled})
|
||||
if err != nil {
|
||||
@@ -682,6 +851,17 @@ func handleWS(cfg appConfig, w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Connect/probe flows create real SSH sessions; the attach path above
|
||||
// only re-attaches a viewer and must stay ungated. Fail fast at cap
|
||||
// before the reachability probe so a rejected connect neither waits out
|
||||
// the probe's dial nor burns a connection attempt against the target;
|
||||
// the authoritative reservation below still gates the actual dial.
|
||||
if limit := terminalMaxSessionsPerUser(); !terminalSessionSlotAvailable(payload.UserID, limit) {
|
||||
log.Printf("[ssh-term] connect rejected: per-owner terminal session cap reached (limit %d)", limit)
|
||||
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: terminalSessionCapMessage(limit)})
|
||||
return
|
||||
}
|
||||
|
||||
connectMsg := first
|
||||
if first.Type == "probe" {
|
||||
target, err := parseSSHCommand(first.Command)
|
||||
@@ -746,9 +926,33 @@ func handleWS(cfg appConfig, w http.ResponseWriter, r *http.Request) {
|
||||
sessionID = fmt.Sprintf("session-%d", time.Now().UnixNano())
|
||||
}
|
||||
|
||||
client, session, stdin, stdout, stderr, err := openSSHSession(target, strings.TrimSpace(connectMsg.Password), knownHostsPath(cfg.PanelRoot), payload.UserID, connectMsg.Cols, connectMsg.Rows)
|
||||
// Authoritative cap gate: reserve a per-owner slot before dialing. The
|
||||
// reservation is atomic, so parallel handshakes cannot race past the
|
||||
// limit between a check and the session creation; the slot is released
|
||||
// here on dial failure and by the session's closeWithMessage teardown on
|
||||
// success (exactly one release per reservation).
|
||||
limit := terminalMaxSessionsPerUser()
|
||||
if !reserveTerminalSessionSlot(payload.UserID, limit) {
|
||||
log.Printf("[ssh-term] connect rejected: per-owner terminal session cap reached (limit %d)", limit)
|
||||
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: terminalSessionCapMessage(limit)})
|
||||
return
|
||||
}
|
||||
|
||||
client, session, stdin, stdout, stderr, err := openSSHSession(target, strings.TrimSpace(connectMsg.Password), knownHostsPath(cfg.PanelRoot), payload.UserID, connectMsg.Cols, connectMsg.Rows, connectMsg.AcceptDivergentKey)
|
||||
if err != nil {
|
||||
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh connection failed: " + explainSSHConnectError(err)})
|
||||
releaseTerminalSessionSlot(payload.UserID)
|
||||
errMsg := wsMessage{Type: "error", Error: "ssh connection failed: " + explainSSHConnectError(err)}
|
||||
// A typed divergence refusal becomes the structured notice the client
|
||||
// renders as an explicit accept-after-warning prompt: the presented
|
||||
// fingerprint and the previously-seen ones let the user compare them
|
||||
// out-of-band. Every other failure keeps the plain error message.
|
||||
var dke *hostKeyDivergenceError
|
||||
if errors.As(err, &dke) {
|
||||
errMsg.Code = "host-key-divergence"
|
||||
errMsg.Fingerprint = dke.presented
|
||||
errMsg.KnownFingerprints = dke.known
|
||||
}
|
||||
_ = wsjson.Write(ctx, conn, errMsg)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -779,7 +983,7 @@ func explainSSHConnectError(err error) string {
|
||||
return "host key changed since the last connection - refusing to connect (possible man-in-the-middle). If the server was legitimately reinstalled, an admin must remove its entry from data/ssh_known_hosts.json (the change takes effect on the next connection attempt - no restart needed)"
|
||||
}
|
||||
if strings.Contains(lower, "host key divergence") || strings.Contains(lower, "possible interception") {
|
||||
return "this host presented a different key to another user - refusing to connect (possible interception). Verify the server fingerprint out-of-band before trusting it"
|
||||
return "this host presented a different key to another user - refusing to connect (possible interception). Compare the presented fingerprint against the server's real fingerprint out-of-band; if the new key is legitimate, confirm to accept it when prompted"
|
||||
}
|
||||
if strings.Contains(lower, "host key store unavailable") {
|
||||
return "cannot verify the server's host key (key store unavailable) - refusing to connect"
|
||||
@@ -792,14 +996,18 @@ func explainSSHConnectError(err error) string {
|
||||
|
||||
// Cloud metadata endpoints must never be dialable as ssh targets: a panel
|
||||
// host inside a cloud VPC would otherwise let a terminal user connect to
|
||||
// services that exist only at those link-local addresses (instance credential
|
||||
// endpoints and similar). This literal-host blocklist is only the cheap
|
||||
// first gate — M6: any hostname that RESOLVES to a metadata address used to
|
||||
// slip past it, so the authoritative gate is address-based (see
|
||||
// isForbiddenMetadataIP + guardedSSHDialer below).
|
||||
// services that exist only at those addresses (instance credential
|
||||
// endpoints and similar): the 169.254.0.0/16 link-local block, Alibaba
|
||||
// Cloud's ECS metadata endpoint 100.100.100.200 and Azure's Wireserver /
|
||||
// guest-agent virtual IP 168.63.129.16. This literal-host blocklist is only
|
||||
// the cheap first gate — M6: any hostname that RESOLVES to a metadata
|
||||
// address used to slip past it, so the authoritative gate is address-based
|
||||
// (see isForbiddenMetadataIP + guardedSSHDialer below).
|
||||
var forbiddenSSHHosts = map[string]struct{}{
|
||||
"169.254.169.254": {},
|
||||
"169.254.169.253": {},
|
||||
"100.100.100.200": {},
|
||||
"168.63.129.16": {},
|
||||
"fd00:ec2::254": {},
|
||||
"metadata": {},
|
||||
"metadata.internal": {},
|
||||
@@ -811,15 +1019,29 @@ var forbiddenSSHHosts = map[string]struct{}{
|
||||
// or the resolved-address metadata check.
|
||||
var errSSHTargetNotAllowed = errors.New("ssh target is not allowed")
|
||||
|
||||
// alibabaMetadataIP is Alibaba Cloud's ECS instance metadata endpoint
|
||||
// (100.100.100.200) and azureWireserverIP is Azure's Wireserver/guest-agent
|
||||
// virtual IP (168.63.129.16). Both are single /32s outside the link-local
|
||||
// block, so isForbiddenMetadataIP matches them explicitly alongside the
|
||||
// 169.254.0.0/16 and fd00:ec2::/32 ranges.
|
||||
var (
|
||||
alibabaMetadataIP = net.IPv4(100, 100, 100, 200).To4()
|
||||
azureWireserverIP = net.IPv4(168, 63, 129, 16).To4()
|
||||
)
|
||||
|
||||
// isForbiddenMetadataIP reports whether ip points at a cloud instance
|
||||
// metadata service — or any other link-local service in 169.254.0.0/16 (AWS,
|
||||
// GCP, Azure, OpenStack all place metadata endpoints there), or AWS's IPv6
|
||||
// metadata range fd00:ec2::/32.
|
||||
// GCP, Azure, OpenStack all place metadata endpoints there), Alibaba Cloud's
|
||||
// ECS metadata endpoint 100.100.100.200, Azure's Wireserver/guest-agent
|
||||
// virtual IP 168.63.129.16, or AWS's IPv6 metadata range fd00:ec2::/32.
|
||||
func isForbiddenMetadataIP(ip net.IP) bool {
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
if ip4 := ip.To4(); ip4 != nil {
|
||||
if ip4.Equal(alibabaMetadataIP) || ip4.Equal(azureWireserverIP) {
|
||||
return true
|
||||
}
|
||||
return ip4[0] == 169 && ip4[1] == 254
|
||||
}
|
||||
if ip16 := ip.To16(); ip16 != nil {
|
||||
@@ -1550,6 +1772,22 @@ func saveKnownHosts(path string, st knownHostsStore) (int, error) {
|
||||
// If the store path is empty/unwritable we fail closed (reject) rather than
|
||||
// fall back to ignoring the key, so a misconfiguration can never silently
|
||||
// re-disable verification.
|
||||
|
||||
// hostKeyDivergenceError reports a cross-user first-use divergence. It is a
|
||||
// distinct type so the ws handler can turn the refusal into a structured,
|
||||
// machine-readable notice the client renders as an explicit accept-after-
|
||||
// warning prompt, instead of a dead-end error line. Error() text is
|
||||
// unchanged from the historical refusal text.
|
||||
type hostKeyDivergenceError struct {
|
||||
host string
|
||||
presented string
|
||||
known []string
|
||||
}
|
||||
|
||||
func (e *hostKeyDivergenceError) Error() string {
|
||||
return fmt.Sprintf("host key divergence for %s: this host previously presented a different key to another user (got %s) - possible interception; explicit confirmation required", e.host, e.presented)
|
||||
}
|
||||
|
||||
func tofuHostKeyCallback(storePath, userID string, allowDivergentFirstUse bool) ssh.HostKeyCallback {
|
||||
return func(hostport string, remote net.Addr, key ssh.PublicKey) error {
|
||||
host := strings.ToLower(strings.TrimSpace(hostport))
|
||||
@@ -1592,7 +1830,18 @@ func tofuHostKeyCallback(storePath, userID string, allowDivergentFirstUse bool)
|
||||
// Another user previously recorded a different key for this host and
|
||||
// the current key is not among them => the connection may be
|
||||
// intercepted. Refuse and force an explicit, informed decision.
|
||||
return fmt.Errorf("host key divergence for %s: this host previously presented a different key to another user (got %s) - possible interception; explicit confirmation required", host, fp)
|
||||
// The typed error lets handleWS upgrade this refusal to the
|
||||
// structured "host-key-divergence" notice the client renders as an
|
||||
// accept-after-warning prompt (the flag is only ever set there).
|
||||
return &hostKeyDivergenceError{host: host, presented: fp, known: append([]string(nil), seen...)}
|
||||
}
|
||||
|
||||
// Explicit-accept audit trail: the connecting user saw the divergence
|
||||
// warning and chose to trust this key. Log the decision (fingerprints
|
||||
// only — never credentials) before pinning so the acceptance is
|
||||
// attributable.
|
||||
if allowDivergentFirstUse && len(seen) > 0 && !seenThis {
|
||||
log.Printf("[ssh-term] user %s explicitly accepted divergent host key for %s (presented %s; previously seen: %s)", userID, host, fp, strings.Join(seen, ", "))
|
||||
}
|
||||
|
||||
// Pin for this user and record in the global advisory set. The
|
||||
@@ -1621,7 +1870,7 @@ func tofuHostKeyCallback(storePath, userID string, allowDivergentFirstUse bool)
|
||||
}
|
||||
}
|
||||
|
||||
func openSSHSession(target sshTarget, password, knownHostsStore, userID string, cols, rows int) (*ssh.Client, *ssh.Session, io.WriteCloser, io.Reader, io.Reader, error) {
|
||||
func openSSHSession(target sshTarget, password, knownHostsStore, userID string, cols, rows int, allowDivergentFirstUse bool) (*ssh.Client, *ssh.Session, io.WriteCloser, io.Reader, io.Reader, error) {
|
||||
if cols <= 0 {
|
||||
cols = 100
|
||||
}
|
||||
@@ -1641,9 +1890,12 @@ func openSSHSession(target sshTarget, password, knownHostsStore, userID string,
|
||||
return answers, nil
|
||||
}),
|
||||
},
|
||||
// Divergent first-use is refused by default; an explicit accept flow can
|
||||
// pass allowDivergentFirstUse=true after warning the user.
|
||||
HostKeyCallback: tofuHostKeyCallback(knownHostsStore, userID, false),
|
||||
// Divergent first-use is refused by default; the client's explicit
|
||||
// accept-after-warning flow passes allowDivergentFirstUse=true only on
|
||||
// the retry that follows a user's informed confirmation of the
|
||||
// structured "host-key-divergence" notice (see handleWS). The flag
|
||||
// never affects the pinned-mismatch refusal, which stays absolute.
|
||||
HostKeyCallback: tofuHostKeyCallback(knownHostsStore, userID, allowDivergentFirstUse),
|
||||
Timeout: 15 * time.Second,
|
||||
}
|
||||
|
||||
@@ -2204,6 +2456,32 @@ const indexHTML = `<!doctype html>
|
||||
let pendingCommand = '';
|
||||
let connectInFlight = false;
|
||||
let wsAttemptIndex = 0;
|
||||
// Host-key divergence confirm state: the server's structured
|
||||
// "host-key-divergence" refusal parks the connect here and the user
|
||||
// must explicitly accept (accept/yes) or cancel. pendingDivergence
|
||||
// holds the command and the password of the refused attempt so the
|
||||
// one-shot accept retry can resend the connect — the password lives
|
||||
// only in page JS memory (exactly as it already does for the whole
|
||||
// connect flow), is never rendered or logged, and is overwritten in
|
||||
// clearPendingDivergence() on every terminal transition.
|
||||
let pendingDivergence = null;
|
||||
let divergenceConfirmBuffer = '';
|
||||
// The password of the most recent connect attempt (set by
|
||||
// sendConnectWithPassword) so the divergence notice can stash it into
|
||||
// pendingDivergence when the refusal arrives.
|
||||
let lastConnectPassword = '';
|
||||
// Resync state: when a viewer cannot keep up with the live stream the
|
||||
// server force-detaches it (closed subscriber channel + a one-shot
|
||||
// 'resync' notice) and the viewer rebuilds its screen by re-attaching
|
||||
// to the SAME session, which replays the server-side buffer.
|
||||
// resyncAttempts counts consecutive auto-resyncs that never reach a
|
||||
// successful 'connected' (reset there) so a persistently failing
|
||||
// reconnect degrades to the plain session-closed path instead of
|
||||
// looping forever.
|
||||
let resyncAttempts = 0;
|
||||
const RESYNC_MAX_ATTEMPTS = 3;
|
||||
let resyncTimer = null;
|
||||
let resyncInProgress = false;
|
||||
let screen = '';
|
||||
// ── VT100 viewport ──────────────────────────────────────────────────────
|
||||
// termCols / termRows: dimensiunea fizică a terminalului (actualizată la resize)
|
||||
@@ -2643,6 +2921,8 @@ const indexHTML = `<!doctype html>
|
||||
active = 'Password: ' + '*'.repeat(passwordBuffer.length) + '<span class="cursor"> </span>';
|
||||
} else if (inputMode === 'connecting') {
|
||||
active = '[adpanel] connecting... <span class="cursor"> </span><span class="conn-hint">(Ctrl+C to cancel)</span>';
|
||||
} else if (inputMode === 'divergence-confirm') {
|
||||
active = 'Accept new host key? type accept/yes or cancel: ' + escapeHtml(divergenceConfirmBuffer) + '<span class="cursor"> </span>';
|
||||
}
|
||||
|
||||
terminal.innerHTML = inputMode === 'connected'
|
||||
@@ -2683,6 +2963,9 @@ const indexHTML = `<!doctype html>
|
||||
passwordBuffer = '';
|
||||
pendingCommand = '';
|
||||
connectInFlight = false;
|
||||
// Every reset is a terminal transition: the stashed divergence
|
||||
// confirm (and the password inside it) must not survive it.
|
||||
clearPendingDivergence();
|
||||
// Dacă am fost conectați, transferăm viewport-ul în screen pentru a păstra output-ul vizibil
|
||||
if (connected || viewport.some(l => l !== '')) {
|
||||
// Păstrăm ultimele linii din viewport ca text în screen
|
||||
@@ -2697,6 +2980,102 @@ const indexHTML = `<!doctype html>
|
||||
render();
|
||||
}
|
||||
|
||||
// Wipes the divergence confirm state. The stashed password field is
|
||||
// overwritten (not just dropped with the object) so no credential
|
||||
// lingers in page memory beyond the confirm step it was needed for.
|
||||
function clearPendingDivergence() {
|
||||
if (pendingDivergence) pendingDivergence.password = '';
|
||||
pendingDivergence = null;
|
||||
divergenceConfirmBuffer = '';
|
||||
}
|
||||
|
||||
// The server refused the connect with the structured host-key
|
||||
// divergence notice: render the explicit accept-after-warning block
|
||||
// and park the flow in divergence-confirm mode. The password of the
|
||||
// refused attempt is stashed for the ONE-SHOT accept retry; it is
|
||||
// never written to the screen or any log.
|
||||
function handleDivergenceNotice(msg) {
|
||||
// A user cancel (Ctrl+C in connecting) or a panel-driven close that
|
||||
// raced the server's refusal wins: a stale refusal frame can still
|
||||
// be delivered after closeSocketQuietly(), and parking a cancelled
|
||||
// flow back into the confirm step would clobber whatever the user
|
||||
// started next.
|
||||
if (intentionalDisconnect) return;
|
||||
const presented = String(msg.fingerprint || 'unknown');
|
||||
const known = Array.isArray(msg.knownFingerprints) ? msg.knownFingerprints.map(String) : [];
|
||||
let block = '\n=============================================\n'
|
||||
+ 'HOST KEY DIVERGENCE WARNING\n'
|
||||
+ '=============================================\n'
|
||||
+ String(msg.error || 'This host presented a different key to another user.') + '\n'
|
||||
+ 'Presented key fingerprint: ' + presented + '\n';
|
||||
if (known.length) {
|
||||
block += 'Previously seen fingerprint(s) for this host:\n';
|
||||
for (const fp of known) block += ' - ' + fp + '\n';
|
||||
}
|
||||
block += 'This can mean an interception attempt, OR a legitimately\n'
|
||||
+ 'different server answering at the same hostname:port\n'
|
||||
+ '(NAT/bastion, a reinstalled or replaced server).\n'
|
||||
+ 'Verify the presented fingerprint against the server\'s real\n'
|
||||
+ 'fingerprint out-of-band before trusting it.\n'
|
||||
+ 'Type "accept" to trust this key and connect, or anything else to cancel:\n';
|
||||
writeScreen(block);
|
||||
pendingDivergence = { command: pendingCommand, password: lastConnectPassword, accepted: false };
|
||||
divergenceConfirmBuffer = '';
|
||||
inputMode = 'divergence-confirm';
|
||||
render();
|
||||
closeSocketQuietly();
|
||||
connected = false;
|
||||
connectInFlight = false;
|
||||
}
|
||||
|
||||
// One-shot accept retry: the user typed accept/yes. Reopen a FRESH
|
||||
// websocket (the server closed the old one after the refusal) and send
|
||||
// the connect directly as the FIRST message — the client-side probe is
|
||||
// skipped because the server re-probes the target on the connect path
|
||||
// anyway. acceptDivergentKey:true is what lets the server-side TOFU
|
||||
// callback pin the presented key after the explicit confirmation.
|
||||
function retryDivergentConnect() {
|
||||
const pending = pendingDivergence;
|
||||
if (!pending || !pending.command || !pending.password) {
|
||||
clearPendingDivergence();
|
||||
resetCommandMode();
|
||||
return;
|
||||
}
|
||||
pending.accepted = true;
|
||||
intentionalDisconnect = false;
|
||||
connected = false;
|
||||
connectInFlight = true;
|
||||
inputMode = 'connecting';
|
||||
render();
|
||||
wsAttemptIndex = 0;
|
||||
connectSocketWithFallback(pending.command, false, true);
|
||||
}
|
||||
|
||||
// The connect message of the accept retry, sent from the fresh
|
||||
// socket's onopen with the SAME command/sessionId/cols/rows and the
|
||||
// stashed password as the refused attempt, plus acceptDivergentKey.
|
||||
function sendDivergentConnect() {
|
||||
const pending = pendingDivergence;
|
||||
if (!pending || !pending.command || !pending.password) {
|
||||
// The confirm state vanished between the accept and the socket
|
||||
// opening (should not happen). Refuse rather than send a
|
||||
// half-specified connect.
|
||||
closeSocketQuietly();
|
||||
writeScreen('[adpanel] confirmation state expired - run the ssh command again\n');
|
||||
resetCommandMode();
|
||||
return;
|
||||
}
|
||||
const sz = estimateSize();
|
||||
send('connect', {
|
||||
sessionId: TERMINAL_SESSION_ID,
|
||||
command: pending.command,
|
||||
password: pending.password,
|
||||
cols: sz.cols,
|
||||
rows: sz.rows,
|
||||
acceptDivergentKey: true,
|
||||
});
|
||||
}
|
||||
|
||||
function resetHistoryNavigation() {
|
||||
commandHistoryIndex = -1;
|
||||
commandHistoryDraft = '';
|
||||
@@ -2789,7 +3168,11 @@ const indexHTML = `<!doctype html>
|
||||
return urls;
|
||||
}
|
||||
|
||||
function connectSocketWithFallback(command, attachOnly = false) {
|
||||
// directConnect is only true for the host-key divergence accept retry:
|
||||
// onopen sends the connect (with acceptDivergentKey) directly as the
|
||||
// FIRST message instead of the usual probe. Every existing flow
|
||||
// (probe, attach, resync) passes the default false and is unchanged.
|
||||
function connectSocketWithFallback(command, attachOnly = false, directConnect = false) {
|
||||
const candidates = wsURLs();
|
||||
if (wsAttemptIndex >= candidates.length) {
|
||||
// All candidates were rejected before any byte was proxied — an
|
||||
@@ -2845,6 +3228,8 @@ const indexHTML = `<!doctype html>
|
||||
socket.onopen = () => {
|
||||
if (attachOnly) {
|
||||
send('attach', { sessionId: TERMINAL_SESSION_ID });
|
||||
} else if (directConnect) {
|
||||
sendDivergentConnect();
|
||||
} else {
|
||||
send('probe', { command: pendingCommand, sessionId: TERMINAL_SESSION_ID });
|
||||
}
|
||||
@@ -2856,6 +3241,19 @@ const indexHTML = `<!doctype html>
|
||||
if (!msg || !msg.type) return;
|
||||
|
||||
if (msg.type === 'error') {
|
||||
if (msg.code === 'host-key-divergence') {
|
||||
if (pendingDivergence && pendingDivergence.accepted) {
|
||||
// The ONE-SHOT accept retry failed with another
|
||||
// divergence (should not happen once pinning
|
||||
// succeeded; would indicate a host-key store write
|
||||
// failure). No loop: fall through to the generic
|
||||
// error path below and drop the confirm state.
|
||||
clearPendingDivergence();
|
||||
} else {
|
||||
handleDivergenceNotice(msg);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (attachOnly && String(msg.error || '').toLowerCase().includes('terminal session not found')) {
|
||||
// The server answered, so the token is valid — this page
|
||||
// needs no self-heal; restore the one-shot refresh
|
||||
@@ -2887,6 +3285,10 @@ const indexHTML = `<!doctype html>
|
||||
connected = true;
|
||||
intentionalDisconnect = false;
|
||||
setTerminalLive(true);
|
||||
// A successful connection (including the divergence accept
|
||||
// retry) ends the confirm step: drop the stashed state and
|
||||
// its password.
|
||||
clearPendingDivergence();
|
||||
// A successful connection resets the one-shot refresh budget
|
||||
// so a later token expiry can self-heal again. Both the
|
||||
// in-memory flags and the fragment copies are cleared; a
|
||||
@@ -2895,6 +3297,10 @@ const indexHTML = `<!doctype html>
|
||||
BOOT_PARAMS.rt = false;
|
||||
BOOT_PARAMS.fresh = false;
|
||||
writeBootParams({ rt: false, fresh: false });
|
||||
// A successful connection refills the auto-resync budget:
|
||||
// only CONSECUTIVE resyncs that never reach this point
|
||||
// count against the cap.
|
||||
resyncAttempts = 0;
|
||||
connectInFlight = false;
|
||||
inputMode = 'connected';
|
||||
// Inițializează viewport-ul cu dimensiunea curentă a terminalului
|
||||
@@ -2904,18 +3310,43 @@ const indexHTML = `<!doctype html>
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'resync') {
|
||||
// This viewer fell behind and the server closed its live
|
||||
// stream so it can resync from the replay buffer.
|
||||
handleResync();
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'output' && typeof msg.data === 'string') {
|
||||
writeScreen(msg.data);
|
||||
}
|
||||
};
|
||||
|
||||
socket.onclose = (ev) => {
|
||||
// The deliberate quiet close of a resync owns the reconnect
|
||||
// (resync timer); onclose's fallback handling must not also
|
||||
// fire for it.
|
||||
if (resyncInProgress) {
|
||||
socket = null;
|
||||
return;
|
||||
}
|
||||
// Dacă am anulat intenționat (Ctrl+C în connecting), ignorăm onclose
|
||||
if (intentionalDisconnect && !connected) {
|
||||
socket = null;
|
||||
return;
|
||||
}
|
||||
|
||||
// The divergence-confirm prompt owns the flow: the server
|
||||
// already closed this socket right after writing the
|
||||
// structured refusal, and the message handler did the cleanup
|
||||
// (connectInFlight=false). The generic close fallback below
|
||||
// must not resetCommandMode() out of the divergence-confirm
|
||||
// state — that would wipe the pending accept/cancel decision.
|
||||
if (inputMode === 'divergence-confirm') {
|
||||
socket = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!connected && connectInFlight) {
|
||||
wsAttemptIndex += 1;
|
||||
if (wsAttemptIndex < candidates.length) {
|
||||
@@ -2926,7 +3357,10 @@ const indexHTML = `<!doctype html>
|
||||
// exhaustion guard at the top of connectSocketWithFallback
|
||||
// (token self-heal, final messages). Re-calling
|
||||
// unconditionally is what makes that guard reachable.
|
||||
connectSocketWithFallback(command, attachOnly);
|
||||
// directConnect survives too, so a divergence accept retry
|
||||
// that loses its tunnel keeps resending the confirmed
|
||||
// connect (never a probe that would drop the accept flag).
|
||||
connectSocketWithFallback(command, attachOnly, directConnect);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2974,6 +3408,56 @@ const indexHTML = `<!doctype html>
|
||||
socket = null;
|
||||
}
|
||||
|
||||
// The server closed this viewer's live stream ('resync' notice)
|
||||
// because it could not keep up; instead of a garbled screen with
|
||||
// dropped chunks, re-attach to the SAME session and rebuild the
|
||||
// screen from the server's replay buffer. This goes through the
|
||||
// attach machinery directly rather than startAttach():
|
||||
// startAttach's boot-fragment guard (!BOOT_PARAMS.sid ||
|
||||
// BOOT_PARAMS.fresh) would also block a viewer that fresh-connected
|
||||
// with an ephemeral session id (no #sid fragment), yet such a viewer
|
||||
// is still legitimately bound to TERMINAL_SESSION_ID — and that is
|
||||
// exactly the id its fresh connect registered the session under, so
|
||||
// attach-with-TERMINAL_SESSION_ID works for BOTH the fresh-connect
|
||||
// and the attach flows. startAttach's normal behavior is unchanged.
|
||||
function handleResync() {
|
||||
if (intentionalDisconnect || connectInFlight || resyncInProgress || resyncTimer !== null) return;
|
||||
if (resyncAttempts >= RESYNC_MAX_ATTEMPTS) {
|
||||
// Too many consecutive resyncs without a successful reconnect:
|
||||
// stop retrying and fall back to the ordinary session-closed
|
||||
// handling for a connection that dropped while connected.
|
||||
connected = false;
|
||||
connectInFlight = false;
|
||||
resyncInProgress = false;
|
||||
setTerminalLive(false);
|
||||
writeScreen('\n[adpanel] session closed\n');
|
||||
resetCommandMode();
|
||||
return;
|
||||
}
|
||||
resyncAttempts += 1;
|
||||
// The quiet close below must not run through onclose's fallback
|
||||
// handling — the timer owns the reconnect.
|
||||
resyncInProgress = true;
|
||||
connected = false;
|
||||
setTerminalLive(false);
|
||||
closeSocketQuietly();
|
||||
inputMode = 'connecting';
|
||||
render();
|
||||
writeScreen('\n[adpanel] reconnecting to resync output...\n');
|
||||
resyncTimer = setTimeout(() => {
|
||||
resyncTimer = null;
|
||||
resyncInProgress = false;
|
||||
// A user cancel (Ctrl+C) or any real connect started while we
|
||||
// waited wins over the automatic resync.
|
||||
if (intentionalDisconnect || connectInFlight) return;
|
||||
wsAttemptIndex = 0;
|
||||
pendingCommand = '';
|
||||
passwordBuffer = '';
|
||||
connectInFlight = true;
|
||||
connectSocketWithFallback('', true);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function startProbe(command) {
|
||||
if (connectInFlight) return;
|
||||
connectInFlight = true;
|
||||
@@ -2981,6 +3465,10 @@ const indexHTML = `<!doctype html>
|
||||
wsAttemptIndex = 0;
|
||||
pendingCommand = command;
|
||||
passwordBuffer = '';
|
||||
// A new command starts a fresh flow: any leftover divergence
|
||||
// confirm state (and its stashed password) is dropped.
|
||||
clearPendingDivergence();
|
||||
lastConnectPassword = '';
|
||||
inputMode = 'connecting';
|
||||
render();
|
||||
|
||||
@@ -3015,6 +3503,11 @@ const indexHTML = `<!doctype html>
|
||||
resetCommandMode();
|
||||
return;
|
||||
}
|
||||
// Remember the password of this connect attempt so the structured
|
||||
// host-key divergence refusal (if the server sends one) can stash
|
||||
// it into pendingDivergence for the explicit accept retry. It
|
||||
// stays in page JS memory only — never rendered, never logged.
|
||||
lastConnectPassword = String(password || '');
|
||||
|
||||
connectInFlight = true;
|
||||
inputMode = 'connecting';
|
||||
@@ -3093,6 +3586,40 @@ const indexHTML = `<!doctype html>
|
||||
return;
|
||||
}
|
||||
|
||||
if (inputMode === 'divergence-confirm') {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
const answer = divergenceConfirmBuffer.trim();
|
||||
divergenceConfirmBuffer = '';
|
||||
if (/^(accept|yes)$/i.test(answer)) {
|
||||
// Explicit, informed acceptance: exactly one retry.
|
||||
retryDivergentConnect();
|
||||
} else {
|
||||
writeScreen('cancelled - the host key was not accepted\n');
|
||||
resetCommandMode();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
|
||||
e.preventDefault();
|
||||
writeScreen('^C\n');
|
||||
resetCommandMode();
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Backspace') {
|
||||
e.preventDefault();
|
||||
if (divergenceConfirmBuffer.length) divergenceConfirmBuffer = divergenceConfirmBuffer.slice(0, -1);
|
||||
render();
|
||||
return;
|
||||
}
|
||||
if (isPrintableKey(e)) {
|
||||
e.preventDefault();
|
||||
divergenceConfirmBuffer += e.key;
|
||||
render();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (inputMode === 'password') {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
@@ -3235,6 +3762,11 @@ const indexHTML = `<!doctype html>
|
||||
e.preventDefault();
|
||||
|
||||
if (inputMode === 'connected') {
|
||||
if (/\r|\n/.test(text)) {
|
||||
const lineCount = text.split(/\r|\n/).filter((line) => line.length > 0).length;
|
||||
const message = 'This paste contains ' + lineCount + ' lines. Pasting will run each line immediately in the remote shell. Paste anyway?';
|
||||
if (!window.confirm(message)) return;
|
||||
}
|
||||
send('input', { data: text.replace(/\n/g, '\r') });
|
||||
return;
|
||||
}
|
||||
@@ -3244,6 +3776,14 @@ const indexHTML = `<!doctype html>
|
||||
const inlineText = text.replace(/[\r\n]+/g, '');
|
||||
if (!inlineText) return;
|
||||
|
||||
if (inputMode === 'divergence-confirm') {
|
||||
// Pasted text goes inline into the confirm buffer; newlines
|
||||
// are stripped so a paste can never smuggle an accept/Enter.
|
||||
divergenceConfirmBuffer += inlineText;
|
||||
render();
|
||||
return;
|
||||
}
|
||||
|
||||
if (inputMode === 'password') {
|
||||
passwordBuffer += inlineText;
|
||||
render();
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// addOutput must never silently drop a chunk for a viewer that fell behind:
|
||||
// terminal output is a byte stream, so a dropped chunk garbles everything
|
||||
// after it. Instead, a subscriber whose 256-slot buffer overflows is
|
||||
// force-detached (removed from ts.subs and closed) while subscribers with
|
||||
// room keep receiving, and the closed channel still yields its buffered
|
||||
// messages (ok=true) before reporting closed (ok=false) — which is exactly
|
||||
// the resync trigger the attach loop waits on.
|
||||
func TestAddOutputForceDetachesFullSubscriber(t *testing.T) {
|
||||
ts := &terminalSession{
|
||||
owner: "resync-test@example.com",
|
||||
id: "resync-test-session-1",
|
||||
subs: make(map[chan wsMessage]struct{}),
|
||||
}
|
||||
// Register in the global map under the same key the service uses, then
|
||||
// clean up so other tests never observe this entry.
|
||||
terminalSessions.Lock()
|
||||
terminalSessions.items[terminalSessionKey(ts.owner, ts.id)] = ts
|
||||
terminalSessions.Unlock()
|
||||
t.Cleanup(func() {
|
||||
terminalSessions.Lock()
|
||||
delete(terminalSessions.items, terminalSessionKey(ts.owner, ts.id))
|
||||
terminalSessions.Unlock()
|
||||
})
|
||||
|
||||
slow, _, ok := ts.subscribe()
|
||||
if !ok {
|
||||
t.Fatal("precondition: subscribe on a live session must succeed")
|
||||
}
|
||||
// Exactly fill the slow viewer's 256-slot buffer: still subscribed, not
|
||||
// yet force-detached, nothing dropped.
|
||||
for i := 0; i < 256; i++ {
|
||||
ts.addOutput("chunk")
|
||||
}
|
||||
ts.mu.Lock()
|
||||
_, slowSubscribed := ts.subs[slow]
|
||||
ts.mu.Unlock()
|
||||
if !slowSubscribed || len(ts.subs) != 1 {
|
||||
t.Fatalf("a merely-full buffer must not detach the viewer (subscribed=%v, subs=%d)", slowSubscribed, len(ts.subs))
|
||||
}
|
||||
|
||||
// A second viewer joins with an empty buffer, then one more chunk
|
||||
// overflows the slow viewer's buffer.
|
||||
fast, _, ok := ts.subscribe()
|
||||
if !ok {
|
||||
t.Fatal("precondition: second subscribe must succeed")
|
||||
}
|
||||
ts.addOutput("overflow")
|
||||
|
||||
ts.mu.Lock()
|
||||
_, slowSubscribed = ts.subs[slow]
|
||||
_, fastSubscribed := ts.subs[fast]
|
||||
ts.mu.Unlock()
|
||||
if slowSubscribed {
|
||||
t.Fatal("overflowing subscriber must be removed from ts.subs")
|
||||
}
|
||||
if !fastSubscribed || len(ts.subs) != 1 {
|
||||
t.Fatalf("subscriber with room must stay subscribed (subscribed=%v, subs=%d)", fastSubscribed, len(ts.subs))
|
||||
}
|
||||
select {
|
||||
case msg := <-fast:
|
||||
if msg.Type != "output" || msg.Data != "overflow" {
|
||||
t.Fatalf("live viewer must keep receiving: got type=%q data=%q", msg.Type, msg.Data)
|
||||
}
|
||||
default:
|
||||
t.Fatal("live viewer must receive the chunk that overflowed the slow viewer")
|
||||
}
|
||||
// The replay buffer kept every byte (including the chunk the slow viewer
|
||||
// missed), which is what makes the replay-based resync complete.
|
||||
if got := string(ts.replay); !strings.HasSuffix(got, "overflow") || strings.Count(got, "chunk") != 256 {
|
||||
t.Fatalf("replay buffer must retain the full stream including the missed chunk (len=%d)", len(got))
|
||||
}
|
||||
|
||||
// Draining the closed channel must yield the 256 buffered messages first
|
||||
// (ok=true, in order), then report closed (ok=false) — the attach loop's
|
||||
// resync trigger. The overflowing chunk must NOT be in the channel.
|
||||
for i := 0; i < 256; i++ {
|
||||
msg, ok := <-slow
|
||||
if !ok {
|
||||
t.Fatalf("buffered message %d was dropped: channel closed early", i)
|
||||
}
|
||||
if msg.Data != "chunk" {
|
||||
t.Fatalf("buffered message %d = %q, want %q", i, msg.Data, "chunk")
|
||||
}
|
||||
}
|
||||
if msg, ok := <-slow; ok {
|
||||
t.Fatalf("channel must report closed after the buffer drained, got ok=true (data=%q)", msg.Data)
|
||||
}
|
||||
|
||||
// unsubscribe for an already-removed (and closed) channel is a no-op
|
||||
// delete — must not panic or close anything.
|
||||
ts.unsubscribe(slow)
|
||||
ts.mu.Lock()
|
||||
remaining := len(ts.subs)
|
||||
lastDetach := ts.lastDetach.IsZero()
|
||||
ts.mu.Unlock()
|
||||
if remaining != 1 {
|
||||
t.Fatalf("forced detach must already have removed the slow viewer (subs=%d)", remaining)
|
||||
}
|
||||
if lastDetach {
|
||||
t.Fatal("unsubscribe must refresh lastDetach")
|
||||
}
|
||||
ts.unsubscribe(fast)
|
||||
ts.mu.Lock()
|
||||
remaining = len(ts.subs)
|
||||
ts.mu.Unlock()
|
||||
if remaining != 0 {
|
||||
t.Fatalf("unsubscribe must remove the last viewer (subs=%d)", remaining)
|
||||
}
|
||||
}
|
||||
|
||||
// A closed session stops fanning out entirely; the forced-detach path must
|
||||
// not resurrect or double-close anything on a session that already closed.
|
||||
func TestAddOutputAfterCloseStillSafe(t *testing.T) {
|
||||
ts := &terminalSession{
|
||||
owner: "resync-closed-test@example.com",
|
||||
id: "resync-closed-session-1",
|
||||
done: make(chan struct{}),
|
||||
subs: make(map[chan wsMessage]struct{}),
|
||||
}
|
||||
terminalSessions.Lock()
|
||||
terminalSessions.items[terminalSessionKey(ts.owner, ts.id)] = ts
|
||||
terminalSessions.Unlock()
|
||||
t.Cleanup(func() {
|
||||
terminalSessions.Lock()
|
||||
delete(terminalSessions.items, terminalSessionKey(ts.owner, ts.id))
|
||||
terminalSessions.Unlock()
|
||||
})
|
||||
|
||||
ch, _, ok := ts.subscribe()
|
||||
if !ok {
|
||||
t.Fatal("precondition: subscribe on a live session must succeed")
|
||||
}
|
||||
ts.closeWithMessage("")
|
||||
ts.addOutput("ignored-after-close") // must not panic, must not deliver
|
||||
|
||||
// The close path never closes subscriber channels (a channel is closed
|
||||
// only by addOutput's full-buffer force-detach) and never delivers to
|
||||
// them afterwards: a closed+empty channel would make the receive below
|
||||
// ready with ok=false and hit the fatal, so reaching default proves the
|
||||
// channel is open and untouched.
|
||||
select {
|
||||
case msg, ok := <-ch:
|
||||
t.Fatalf("a closed session must not deliver output (got data=%q ok=%v)", msg.Data, ok)
|
||||
default:
|
||||
}
|
||||
// closeWithMessage leaves the subscriber in ts.subs — its attach loop
|
||||
// notices ts.done and detaches through the deferred unsubscribe, so the
|
||||
// close path must not close or remove the channel behind its back.
|
||||
ts.mu.Lock()
|
||||
remaining := len(ts.subs)
|
||||
closed := ts.closed
|
||||
ts.mu.Unlock()
|
||||
if !closed {
|
||||
t.Fatal("closeWithMessage must mark the session closed")
|
||||
}
|
||||
if remaining != 1 {
|
||||
t.Fatalf("closeWithMessage must leave the detach to the viewer's attach loop (subs=%d)", remaining)
|
||||
}
|
||||
ts.unsubscribe(ch)
|
||||
ts.mu.Lock()
|
||||
remaining = len(ts.subs)
|
||||
ts.mu.Unlock()
|
||||
if remaining != 0 {
|
||||
t.Fatalf("deferred-style unsubscribe must drain the last viewer (subs=%d)", remaining)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTerminalMaxSessionsPerUser(t *testing.T) {
|
||||
cases := []struct {
|
||||
raw string
|
||||
want int
|
||||
}{
|
||||
{"", defaultTerminalMaxSessionsPerUser}, // unset: default
|
||||
{" ", defaultTerminalMaxSessionsPerUser},
|
||||
{"garbage", defaultTerminalMaxSessionsPerUser},
|
||||
{"12x", defaultTerminalMaxSessionsPerUser},
|
||||
{"0", defaultTerminalMaxSessionsPerUser}, // 0 must not disable the cap
|
||||
{"-3", defaultTerminalMaxSessionsPerUser},
|
||||
{"1", 1},
|
||||
{"4", 4},
|
||||
{"16", 16},
|
||||
{"128", 128},
|
||||
{"129", maxTerminalSessionsPerUserLimit}, // clamped, never uncapped
|
||||
{"99999", maxTerminalSessionsPerUserLimit},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Setenv("SSH_TERM_MAX_SESSIONS_PER_USER", tc.raw)
|
||||
if got := terminalMaxSessionsPerUser(); got != tc.want {
|
||||
t.Errorf("terminalMaxSessionsPerUser(%q) = %d, want %d", tc.raw, got, tc.want)
|
||||
}
|
||||
}
|
||||
t.Setenv("SSH_TERM_MAX_SESSIONS_PER_USER", "")
|
||||
if got := terminalMaxSessionsPerUser(); got != defaultTerminalMaxSessionsPerUser {
|
||||
t.Errorf("empty env must yield the default, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReserveTerminalSessionSlot(t *testing.T) {
|
||||
owner := "cap-test@example.com"
|
||||
other := "cap-test-other@example.com"
|
||||
// The test holds two slots at its end; release both so the global slot
|
||||
// map is left clean for the rest of the suite.
|
||||
t.Cleanup(func() {
|
||||
releaseTerminalSessionSlot(owner)
|
||||
releaseTerminalSessionSlot(owner)
|
||||
})
|
||||
|
||||
if !terminalSessionSlotAvailable(owner, 2) {
|
||||
t.Fatal("fresh owner must have a slot available")
|
||||
}
|
||||
if !reserveTerminalSessionSlot(owner, 2) || !reserveTerminalSessionSlot(owner, 2) {
|
||||
t.Fatal("reservations up to the limit must succeed")
|
||||
}
|
||||
if terminalSessionSlotAvailable(owner, 2) || reserveTerminalSessionSlot(owner, 2) {
|
||||
t.Fatal("reserving beyond the limit must fail")
|
||||
}
|
||||
// Other owners are unaffected by one owner filling their slots.
|
||||
if !terminalSessionSlotAvailable(other, 2) || !reserveTerminalSessionSlot(other, 2) {
|
||||
t.Fatal("another owner must be able to reserve while the first is at cap")
|
||||
}
|
||||
releaseTerminalSessionSlot(other)
|
||||
|
||||
releaseTerminalSessionSlot(owner)
|
||||
if !terminalSessionSlotAvailable(owner, 2) || !reserveTerminalSessionSlot(owner, 2) {
|
||||
t.Fatal("release must free a slot for the next reservation")
|
||||
}
|
||||
}
|
||||
|
||||
// Double release must never drive the count negative (which would hand an
|
||||
// owner extra slots): the counter deletes at <=1 and is a no-op afterwards.
|
||||
func TestReleaseTerminalSessionSlotFloorsAtZero(t *testing.T) {
|
||||
owner := "cap-floor-test@example.com"
|
||||
releaseTerminalSessionSlot(owner) // release for an owner with no slot
|
||||
releaseTerminalSessionSlot(owner) // repeated: must stay a no-op
|
||||
if !terminalSessionSlotAvailable(owner, 1) {
|
||||
t.Fatal("owner with no slots must have availability")
|
||||
}
|
||||
if !reserveTerminalSessionSlot(owner, 1) {
|
||||
t.Fatal("reservation after no-op releases must succeed")
|
||||
}
|
||||
releaseTerminalSessionSlot(owner)
|
||||
releaseTerminalSessionSlot(owner)
|
||||
if !terminalSessionSlotAvailable(owner, 1) || !reserveTerminalSessionSlot(owner, 1) {
|
||||
t.Fatal("over-release must not leak extra slots to the owner")
|
||||
}
|
||||
releaseTerminalSessionSlot(owner)
|
||||
}
|
||||
|
||||
// The closeWithMessage teardown must release the slot the connect reserved,
|
||||
// exactly once — nil SSH handles are the point: the release hook has to be
|
||||
// reachable without a live SSH client, and a second close must be a no-op.
|
||||
func TestTerminalSessionCloseReleasesSlot(t *testing.T) {
|
||||
owner := "cap-close-test@example.com"
|
||||
if !reserveTerminalSessionSlot(owner, 1) {
|
||||
t.Fatal("precondition: reservation failed")
|
||||
}
|
||||
ts := &terminalSession{
|
||||
owner: owner,
|
||||
id: "cap-close-session-1",
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
ts.closeWithMessage("")
|
||||
select {
|
||||
case <-ts.done:
|
||||
default:
|
||||
t.Fatal("closeWithMessage must close the done channel")
|
||||
}
|
||||
if !terminalSessionSlotAvailable(owner, 1) || !reserveTerminalSessionSlot(owner, 1) {
|
||||
t.Fatal("session close must release the per-owner slot exactly once")
|
||||
}
|
||||
// Idempotency: a second close must not release somebody else's slot.
|
||||
releaseTerminalSessionSlot(owner)
|
||||
ts.closeWithMessage("")
|
||||
if !terminalSessionSlotAvailable(owner, 1) {
|
||||
t.Fatal("second close must not release an additional slot")
|
||||
}
|
||||
releaseTerminalSessionSlot(owner)
|
||||
}
|
||||
|
||||
func TestTerminalSessionCapMessage(t *testing.T) {
|
||||
msg := terminalSessionCapMessage(4)
|
||||
if !strings.Contains(msg, "4") {
|
||||
t.Errorf("cap message must state the limit, got: %s", msg)
|
||||
}
|
||||
if strings.ContainsAny(msg, "\n\r") {
|
||||
t.Errorf("cap message must be single-line, got: %q", msg)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Reference in new issue
Block a user