package main import ( "context" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "html" "io" "log" "net" "net/http" "net/url" "os" "path/filepath" "sort" "strconv" "strings" "sync" "syscall" "time" "golang.org/x/crypto/ssh" "nhooyr.io/websocket" "nhooyr.io/websocket/wsjson" ) type tokenPayload struct { Version int `json:"v"` UserID string `json:"uid"` IP string `json:"ip"` ExpMS int64 `json:"exp"` } type wsMessage struct { Type string `json:"type"` SessionID string `json:"sessionId,omitempty"` Command string `json:"command,omitempty"` Password string `json:"password,omitempty"` Data string `json:"data,omitempty"` 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 { User string Host string Port int } type appConfig struct { BindAddr string Secret []byte PanelRoot string ReadTimout time.Duration UseTLS bool TLSCert string TLSKey string WSFallback string WSOrigin string // AllowedHosts restricts which ssh targets this service will dial. Empty // means no allowlist (panel host can ssh anywhere it can reach); cloud // metadata endpoints are always refused. AllowedHosts []string // TrustedProxies lists the network ranges whose X-Forwarded-For / // X-Real-IP headers are believed when resolving the client IP a token is // bound to. Defaults to loopback only (the panel's own proxy hop); direct // connections from any other address are attributed to their socket // address, so a client cannot claim an arbitrary bound IP. Operators who // run the panel on a separate host extend this via // SSH_TERM_TRUSTED_PROXIES (CSV of IPs/CIDRs). TrustedProxies []*net.IPNet } const terminalResumeGrace = 15 * time.Minute const terminalIdleTimeout = 20 * time.Minute // sshSetupTimeout bounds the entire SSH setup path (handshake/KEX/auth, // NewSession, RequestPty and Shell; the TCP dial itself is bounded separately // by ClientConfig.Timeout) so a target that accepts the connection but stalls // the handshake cannot pin a goroutine and socket forever. Enforced as a // deadline on the raw conn and cleared before the interactive session is // handed back; the live session is bounded only by the 20-minute idle timeout // above. 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 // 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 } var terminalSessions = struct { sync.Mutex items map[string]*terminalSession }{items: make(map[string]*terminalSession)} func main() { cwd, _ := os.Getwd() panelRoot := strings.TrimSpace(os.Getenv("SSH_TERM_PANEL_ROOT")) if panelRoot == "" { panelRoot = cwd } _ = loadDotEnv(filepath.Join(panelRoot, ".env")) bind := strings.TrimSpace(os.Getenv("SSH_TERM_BIND")) if bind == "" { port := strings.TrimSpace(os.Getenv("SSH_TERM_PORT")) if port == "" { port = "9393" } // Loopback by default. The terminal proxy carries panel session // credentials and is normally reached through the panel's own proxy; // defaulting to 0.0.0.0 silently exposed an unauthenticated terminal // endpoint on every interface for manual deployments (installer // deployments already pin 127.0.0.1 via .env). Operators who want the // proxy directly reachable set SSH_TERM_BIND explicitly. bind = "127.0.0.1:" + port } secretText := strings.TrimSpace(os.Getenv("SSH_TERM_TOKEN_SECRET")) if secretText == "" { sessionSecret := strings.TrimSpace(os.Getenv("SESSION_SECRET")) if sessionSecret != "" { h := hmac.New(sha256.New, []byte(sessionSecret)) _, _ = h.Write([]byte("adpanel-ssh-term-token-key-v1")) secretText = fmt.Sprintf("%x", h.Sum(nil)) } } if len(secretText) < 16 { log.Fatal("missing SSH_TERM_TOKEN_SECRET or SESSION_SECRET (must be >= 16 chars)") } cfg := appConfig{ BindAddr: bind, Secret: []byte(secretText), PanelRoot: panelRoot, ReadTimout: 20 * time.Second, UseTLS: parseBoolEnv("ENABLE_HTTPS"), TLSCert: strings.TrimSpace(os.Getenv("SSL_CERT_PATH")), TLSKey: strings.TrimSpace(os.Getenv("SSL_KEY_PATH")), WSFallback: buildWSFallbackURL(bind, strings.TrimSpace(os.Getenv("SSH_TERM_PUBLIC_URL")), strings.TrimSpace(os.Getenv("SSH_TERM_WS_PUBLIC_URL"))), } // Optional egress allowlist, e.g. SSH_TERMINAL_ALLOWED_HOSTS="*.example.com,10.0.0.5" for _, entry := range strings.Split(strings.TrimSpace(os.Getenv("SSH_TERMINAL_ALLOWED_HOSTS")), ",") { entry = strings.ToLower(strings.TrimSpace(entry)) if entry != "" { cfg.AllowedHosts = append(cfg.AllowedHosts, entry) } } cfg.TrustedProxies = parseTrustedProxies(os.Getenv("SSH_TERM_TRUSTED_PROXIES")) cfg.WSOrigin = websocketOrigin(cfg.WSFallback) if cfg.UseTLS && (cfg.TLSCert == "" || cfg.TLSKey == "") { cfg.UseTLS = false } mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { handleIndex(cfg, w, r) }) mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { handleWS(cfg, w, r) }) mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Cache-Control", "no-store") _, _ = w.Write([]byte("ok")) }) srv := &http.Server{ Addr: cfg.BindAddr, Handler: mux, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, WriteTimeout: 0, } if cfg.UseTLS { log.Printf("[ssh-term] listening on https://%s", cfg.BindAddr) if err := srv.ListenAndServeTLS(cfg.TLSCert, cfg.TLSKey); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatalf("server failed: %v", err) } return } log.Printf("[ssh-term] listening on http://%s", cfg.BindAddr) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatalf("server failed: %v", err) } } func parseBoolEnv(key string) bool { v := strings.ToLower(strings.TrimSpace(os.Getenv(key))) return v == "1" || v == "true" || v == "yes" || v == "on" } func handleIndex(cfg appConfig, w http.ResponseWriter, r *http.Request) { token := strings.TrimSpace(r.URL.Query().Get("token")) payload, err := verifyToken(cfg.Secret, token, requestIP(r, cfg.TrustedProxies)) if err != nil { log.Printf("[ssh-term] index token reject: %v", err) http.Error(w, "invalid or expired terminal token", http.StatusUnauthorized) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Referrer-Policy", "no-referrer") // Inline script/style are nonce-gated per request: the page body varies // per request (token/user placeholders), so a static hash cannot work. // The previous broad inline-execution and third-party CDN script/style // sources were removed; frame-ancestors is pinned to 'self' (the panel is // the only legitimate framer) because it does not inherit from // default-src. nonceBytes := make([]byte, 16) if _, err := rand.Read(nonceBytes); err != nil { http.Error(w, "internal error", http.StatusInternalServerError) return } nonce := base64.StdEncoding.EncodeToString(nonceBytes) cspConnect := "connect-src " + websocketConnectSrc(cfg.WSOrigin) + ";" w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'nonce-"+nonce+"'; style-src 'self' 'nonce-"+nonce+"'; "+cspConnect+" img-src 'self' data:; frame-ancestors 'self';") page := strings.ReplaceAll(indexHTML, "__CSP_NONCE__", nonce) page = strings.ReplaceAll(page, "__TOKEN__", html.EscapeString(token)) page = strings.ReplaceAll(page, "__USER__", html.EscapeString(payload.UserID)) page = strings.ReplaceAll(page, "__WS_FALLBACK__", html.EscapeString(cfg.WSFallback)) _, _ = w.Write([]byte(page)) } func buildWSFallbackURL(bindAddr string, publicURL string, wsPublicURL string) string { if raw := strings.TrimSpace(wsPublicURL); raw != "" { if u, ok := normalizeWSURL(raw); ok { return u } } if raw := strings.TrimSpace(publicURL); raw != "" { value := raw if !strings.HasPrefix(strings.ToLower(value), "http://") && !strings.HasPrefix(strings.ToLower(value), "https://") { value = "http://" + value } if u, err := url.Parse(value); err == nil { wsProto := "ws" if strings.EqualFold(u.Scheme, "https") { wsProto = "wss" } host := u.Host if host != "" { return wsProto + "://" + host + "/ws" } } } _ = bindAddr return "" } func normalizeWSURL(raw string) (string, bool) { value := strings.TrimSpace(raw) if value == "" { return "", false } if !strings.HasPrefix(strings.ToLower(value), "ws://") && !strings.HasPrefix(strings.ToLower(value), "wss://") { value = "ws://" + value } u, err := url.Parse(value) if err != nil || u == nil || u.Host == "" { return "", false } pathPart := u.Path if strings.TrimSpace(pathPart) == "" { pathPart = "/ws" } u.Path = pathPart u.RawQuery = "" u.Fragment = "" return u.String(), true } func websocketOrigin(wsURL string) string { u, err := url.Parse(strings.TrimSpace(wsURL)) if err != nil || u == nil || u.Host == "" { return "" } if u.Scheme != "ws" && u.Scheme != "wss" { return "" } return u.Scheme + "://" + u.Host } func websocketConnectSrc(wsOrigin string) string { base := []string{"'self'"} u, err := url.Parse(strings.TrimSpace(wsOrigin)) if err != nil || u == nil || u.Host == "" { return strings.Join(base, " ") } base = append(base, "ws://"+u.Host, "wss://"+u.Host) seen := make(map[string]struct{}, len(base)) uniq := make([]string, 0, len(base)) for _, item := range base { if _, ok := seen[item]; ok { continue } seen[item] = struct{}{} uniq = append(uniq, item) } return strings.Join(uniq, " ") } func normalizeTerminalSessionID(raw string) string { id := strings.TrimSpace(raw) if len(id) < 8 || len(id) > 128 { return "" } for _, r := range id { if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' || r == ':' { continue } return "" } return id } func terminalSessionKey(owner string, id string) string { return owner + "\x00" + id } func getTerminalSession(owner string, id string) *terminalSession { id = normalizeTerminalSessionID(id) if owner == "" || id == "" { return nil } terminalSessions.Lock() ts := terminalSessions.items[terminalSessionKey(owner, id)] terminalSessions.Unlock() if ts == nil { return nil } ts.mu.Lock() closed := ts.closed ts.mu.Unlock() if closed { return nil } return ts } func registerTerminalSession(ts *terminalSession) { if ts == nil || ts.owner == "" || ts.id == "" { return } key := terminalSessionKey(ts.owner, ts.id) terminalSessions.Lock() if old := terminalSessions.items[key]; old != nil && old != ts { go old.closeWithMessage("\r\n[adpanel] terminal replaced by a new connection\r\n") } terminalSessions.items[key] = ts terminalSessions.Unlock() } func removeTerminalSession(ts *terminalSession) { if ts == nil || ts.owner == "" || ts.id == "" { return } key := terminalSessionKey(ts.owner, ts.id) terminalSessions.Lock() if terminalSessions.items[key] == ts { delete(terminalSessions.items, key) } 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{}), lastActive: time.Now(), } pump := func(reader io.Reader) { buf := make([]byte, 4096) for { n, rerr := reader.Read(buf) if n > 0 { ts.addOutput(string(buf[:n])) } if rerr != nil { if !errors.Is(rerr, io.EOF) { ts.addOutput("\r\n[adpanel] remote stream closed\r\n") } return } } } go pump(stdout) go pump(stderr) go func() { err := session.Wait() if err != nil { ts.mu.Lock() ts.waitErr = err ts.mu.Unlock() ts.closeWithMessage("\r\n[adpanel] ssh session ended: " + sanitizeReason(err) + "\r\n") return } ts.closeWithMessage("\r\n[adpanel] ssh session ended\r\n") }() return ts } func (ts *terminalSession) addOutput(data string) { if ts == nil || data == "" { return } msg := wsMessage{Type: "output", Data: data} ts.mu.Lock() if ts.closed { 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:] } // 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 { 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) { ch := make(chan wsMessage, 256) ts.mu.Lock() defer ts.mu.Unlock() if ts.closed { return nil, "", false } ts.subs[ch] = struct{}{} return ch, string(ts.replay), true } func (ts *terminalSession) unsubscribe(ch chan wsMessage) { ts.mu.Lock() if ch != nil { delete(ts.subs, ch) } noSubs := len(ts.subs) == 0 ts.lastDetach = time.Now() ts.mu.Unlock() if noSubs { time.AfterFunc(terminalResumeGrace, cleanupIdleTerminalSessions) } } func cleanupIdleTerminalSessions() { now := time.Now() var stale []*terminalSession terminalSessions.Lock() for _, ts := range terminalSessions.items { ts.mu.Lock() idleDetached := len(ts.subs) == 0 && !ts.lastDetach.IsZero() && now.Sub(ts.lastDetach) >= terminalResumeGrace idleActive := now.Sub(ts.lastActive) >= terminalIdleTimeout closed := ts.closed ts.mu.Unlock() if !closed && (idleDetached || idleActive) { stale = append(stale, ts) } } terminalSessions.Unlock() for _, ts := range stale { ts.closeWithMessage("") } } func (ts *terminalSession) closeWithMessage(message string) { if ts == nil { return } if strings.TrimSpace(message) != "" { ts.addOutput(message) } ts.closeOnce.Do(func() { ts.mu.Lock() ts.closed = true ts.mu.Unlock() if ts.stdin != nil { _ = ts.stdin.Close() } if ts.session != nil { _ = ts.session.Close() } if ts.client != nil { _ = 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) }) } func (ts *terminalSession) writeInput(data string) error { if ts == nil || data == "" { return nil } ts.mu.Lock() if ts.closed { ts.mu.Unlock() return errors.New("terminal session closed") } ts.lastActive = time.Now() stdin := ts.stdin ts.mu.Unlock() if stdin == nil { return errors.New("terminal input unavailable") } _, err := io.WriteString(stdin, data) return err } func (ts *terminalSession) resize(cols int, rows int) { if ts == nil || ts.session == nil { return } if rows <= 0 { rows = 24 } if cols <= 0 { cols = 80 } _ = ts.session.WindowChange(rows, cols) } func attachTerminalSession(ctx context.Context, conn *websocket.Conn, ts *terminalSession) { outCh, replay, ok := ts.subscribe() if !ok { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "terminal session closed"}) return } defer ts.unsubscribe(outCh) write := func(msg wsMessage) bool { wctx, cancel := context.WithTimeout(ctx, 10*time.Second) err := wsjson.Write(wctx, conn, msg) cancel() return err == nil } if !write(wsMessage{Type: "connected", SessionID: ts.id}) { return } if replay != "" && !write(wsMessage{Type: "output", Data: replay}) { return } inputCh := make(chan wsMessage, 16) errCh := make(chan error, 1) go func() { for { var msg wsMessage if err := wsjson.Read(ctx, conn, &msg); err != nil { errCh <- err return } select { case inputCh <- msg: case <-ctx.Done(): return } } }() ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ts.done: return case <-ticker.C: ts.mu.Lock() 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") return } case err := <-errCh: if errors.Is(err, context.DeadlineExceeded) { ts.closeWithMessage("\r\n[adpanel] session expired after 20 minutes of inactivity\r\n") } return case msg := <-inputCh: switch msg.Type { case "input": if err := ts.writeInput(msg.Data); err != nil { ts.closeWithMessage("\r\n[adpanel] terminal input failed: " + sanitizeReason(err) + "\r\n") return } case "resize": ts.resize(msg.Cols, msg.Rows) case "disconnect": // 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 } if !write(msg) { return } } } } func handleWS(cfg appConfig, w http.ResponseWriter, r *http.Request) { token := strings.TrimSpace(r.URL.Query().Get("token")) payload, err := verifyToken(cfg.Secret, token, requestIP(r, cfg.TrustedProxies)) if err != nil { log.Printf("[ssh-term] ws token reject: %v", err) 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 { return } defer conn.Close(websocket.StatusNormalClosure, "bye") ctx := r.Context() conn.SetReadLimit(1 << 20) var first wsMessage if err := wsjson.Read(ctx, conn, &first); err != nil { return } if first.Type == "attach" { sessionID := normalizeTerminalSessionID(first.SessionID) if sessionID == "" { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "terminal session id is missing"}) return } if existing := getTerminalSession(payload.UserID, sessionID); existing != nil { attachTerminalSession(ctx, conn, existing) return } _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "terminal session not found"}) 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) if err != nil { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: err.Error()}) return } if err := sshTargetAllowed(cfg, target); err != nil { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: err.Error()}) return } if err := probeSSHReachability(target, 6*time.Second); err != nil { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh target unreachable: " + sanitizeReason(err)}) return } if err := wsjson.Write(ctx, conn, wsMessage{Type: "probe-ok"}); err != nil { return } if err := wsjson.Read(ctx, conn, &connectMsg); err != nil { return } if connectMsg.Type != "connect" { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "expected connect message"}) return } if strings.TrimSpace(connectMsg.Command) == "" { connectMsg.Command = first.Command } if strings.TrimSpace(connectMsg.SessionID) == "" { connectMsg.SessionID = first.SessionID } } if connectMsg.Type != "connect" { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "expected connect message"}) return } target, err := parseSSHCommand(connectMsg.Command) if err != nil { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: err.Error()}) return } if err := sshTargetAllowed(cfg, target); err != nil { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: err.Error()}) return } if err := probeSSHReachability(target, 6*time.Second); err != nil { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh target unreachable: " + sanitizeReason(err)}) return } if strings.TrimSpace(connectMsg.Password) == "" { _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "password is required"}) return } sessionID := normalizeTerminalSessionID(connectMsg.SessionID) if sessionID == "" { sessionID = fmt.Sprintf("session-%d", time.Now().UnixNano()) } // 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 { 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 } term := newTerminalSession(payload.UserID, sessionID, client, session, stdin, stdout, stderr) registerTerminalSession(term) attachTerminalSession(ctx, conn, term) } func sanitizeReason(err error) string { if err == nil { return "unknown error" } reason := strings.TrimSpace(err.Error()) reason = strings.ReplaceAll(reason, "\n", " ") if len(reason) > 220 { reason = reason[:220] } if reason == "" { return "unknown error" } return reason } func explainSSHConnectError(err error) string { reason := sanitizeReason(err) lower := strings.ToLower(reason) if strings.Contains(lower, "host key mismatch") || strings.Contains(lower, "man-in-the-middle") { 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). 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" } if strings.Contains(lower, "unable to authenticate") || strings.Contains(lower, "no supported methods remain") { return "remote server rejected password authentication (wrong password or password login is disabled)" } return reason } // 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 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": {}, "metadata.google.internal": {}, } // errSSHTargetNotAllowed is deliberately identical to the allowlist rejection // text: a rejected target never reveals whether it failed the name allowlist // 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), 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 { return ip16[0] == 0xfd && ip16[1] == 0x00 && ip16[2] == 0x0e && ip16[3] == 0xc2 } return false } // assertSSHHostNotMetadata resolves host and refuses it when any resolved // address is a metadata endpoint. Resolution failure returns nil — the dial // itself will surface the real error, which is sanitized downstream. func assertSSHHostNotMetadata(host string) error { if strings.TrimSpace(host) == "" { return nil } ips, err := net.LookupIP(host) if err != nil { return nil } for _, ip := range ips { if isForbiddenMetadataIP(ip) { return errSSHTargetNotAllowed } } return nil } // guardedSSHDialer returns a dialer whose Control hook re-validates the // concrete resolved address right before the connect syscall. This is the // authoritative metadata block: it sees the address the kernel will actually // dial, so a DNS rebinding between a pre-check and the connect cannot slip a // metadata endpoint through. func guardedSSHDialer(timeout time.Duration) *net.Dialer { return &net.Dialer{ Timeout: timeout, Control: func(_, address string, _ syscall.RawConn) error { host, _, err := net.SplitHostPort(address) if err != nil { return err } if isForbiddenMetadataIP(net.ParseIP(host)) { return errSSHTargetNotAllowed } return nil }, } } // sshTargetAllowed enforces the optional SSH_TERMINAL_ALLOWED_HOSTS allowlist // (exact host or "*.suffix" entries, matched case-insensitively) and always // refuses cloud metadata endpoints. It runs BEFORE reachability probing so a // denied target cannot be used as an internal port scanner either. func sshTargetAllowed(cfg appConfig, target sshTarget) error { host := strings.ToLower(strings.TrimSpace(target.Host)) if host == "" { return errors.New("missing ssh host") } if _, bad := forbiddenSSHHosts[host]; bad { return errors.New("ssh target is not allowed") } if len(cfg.AllowedHosts) == 0 { return nil } for _, entry := range cfg.AllowedHosts { pattern := strings.ToLower(strings.TrimSpace(entry)) if pattern == "" { continue } if strings.HasPrefix(pattern, "*.") { suffix := strings.TrimPrefix(pattern, "*.") if host == suffix || strings.HasSuffix(host, "."+suffix) { return nil } continue } if host == pattern { return nil } } return errors.New("ssh target is not in SSH_TERMINAL_ALLOWED_HOSTS") } // probeSSHReachability is the "probe" message handler's connect test. M6: it // is intentionally not a free TCP-connect oracle anymore — the pre-resolve // metadata check plus the guarded dialer apply the same address-level // metadata block the real connection enforces, so a hostname that resolves // to 169.254.169.254 (or any link-local / AWS IPv6 metadata address) is // refused before and during the connect. func probeSSHReachability(target sshTarget, timeout time.Duration) error { if err := assertSSHHostNotMetadata(target.Host); err != nil { return err } addr := net.JoinHostPort(target.Host, strconv.Itoa(target.Port)) conn, err := guardedSSHDialer(timeout).Dial("tcp", addr) if err != nil { return err } _ = conn.Close() return nil } // knownHostsMu serializes read/modify/write access to the TOFU host-key store // (the resident cache below and the on-disk file it is persisted to) so // concurrent terminal sessions cannot corrupt it or race on first-use // pinning. The lock is still taken on every connection, but the critical // section is O(1) memory work: the parsed store stays resident and is only // re-read when the store file changed on disk (see cachedKnownHosts), so a // connection no longer re-reads and re-parses the whole store file from disk // on every handshake. var knownHostsMu sync.Mutex // knownHostsCache keeps the parsed TOFU store resident between connections. // The store file is re-read from disk whenever it changes externally // (detected via the size+mtime snapshot below), so an admin edit to // data/ssh_known_hosts.json — e.g. removing a pin after a legitimate server // reinstall — takes effect on the next connection attempt, while // steady-state connections still skip the re-read/re-parse. It is keyed by // store path (production has exactly one) and guarded by knownHostsMu — // every access must hold that mutex. var knownHostsCache struct { path string store *knownHostsStore // loadedModTime / loadedSize snapshot the store file as of the last // load, reload or save; they are compared against a fresh os.Stat to // detect external edits. Unexported so encoding/json ignores them: they // are runtime cache state, never persisted. loadedModTime int64 loadedSize int64 } // snapshotKnownHostsStat records the current size+mtime of the store file so // the next cachedKnownHosts call can detect external edits. The caller must // hold knownHostsMu. When expectSize >= 0 the stat is only trusted if the // file on disk still has exactly that size — i.e. it is still the file the // caller just saved; an external edit that landed between the save's rename // and this stat is NOT recorded as our own (that would hide the edit until // the file changes again). Instead the snapshot is invalidated so the next // cachedKnownHosts call reloads the file. (A same-size external write in // that window remains undetectable — inherent to stat-based change // detection.) If the stat itself fails the snapshot is left as-is: the next // call re-stats and self-heals (at worst one extra reload). func snapshotKnownHostsStat(storePath string, expectSize int64) { info, err := os.Stat(storePath) if err != nil { return } if expectSize >= 0 && info.Size() != expectSize { knownHostsCache.loadedModTime = 0 knownHostsCache.loadedSize = 0 return } knownHostsCache.loadedModTime = info.ModTime().UnixNano() knownHostsCache.loadedSize = info.Size() } // cachedKnownHosts returns the resident, parsed store for storePath, loading // it from disk (and healing it to the store caps) on first use and // RE-loading it whenever the file changed on disk since the last load/save, // so admin edits take effect on the next connection without a restart. On an // unparseable file the last good resident store is kept (logged once per // file change; on the very FIRST load there is no last good state, so an // unparseable file yields an empty store); a deleted file is adopted as an // empty store ("clear all" — // the next save recreates the file); any other stat error keeps the resident // store. The caller must hold knownHostsMu. func cachedKnownHosts(storePath string) *knownHostsStore { if knownHostsCache.store != nil && knownHostsCache.path == storePath { info, err := os.Stat(storePath) if err == nil { if info.ModTime().UnixNano() != knownHostsCache.loadedModTime || info.Size() != knownHostsCache.loadedSize { st, lerr := loadKnownHosts(storePath) if lerr != nil { // Corrupt store: keep the last good resident state and // still refresh the snapshot so a permanently corrupt // file is logged once per change, not per connection. log.Printf("[ssh-term] known-hosts store reload failed (keeping last good state): %v", lerr) } else { knownHostsCache.store = &st } knownHostsCache.loadedModTime = info.ModTime().UnixNano() knownHostsCache.loadedSize = info.Size() } } else if os.IsNotExist(err) { // The store file was deleted: treat that as "clear all" (the // next save recreates it) rather than serve stale pins. knownHostsCache.store = &knownHostsStore{ Pins: map[string]string{}, Global: map[string][]string{}, GlobalContrib: map[string]string{}, } knownHostsCache.loadedModTime = 0 knownHostsCache.loadedSize = 0 } else { log.Printf("[ssh-term] known-hosts store stat failed (keeping last good state): %v", err) } return knownHostsCache.store } // First use for this store path in this process. st, err := loadKnownHosts(storePath) if err != nil { // No resident state exists yet to fall back to, so an unparseable // file degrades to an empty store (TOFU re-pin), same as the // pre-cache behavior. Reloads below keep the last good state // instead, so an in-flight store never regresses to empty. log.Printf("[ssh-term] known-hosts store load failed (starting from an empty store): %v", err) } knownHostsCache.path = storePath knownHostsCache.store = &st knownHostsCache.loadedModTime = 0 knownHostsCache.loadedSize = 0 // expectSize < 0: we did not just write the file, so adopt whatever stat // says (a stat failure leaves the 0/0 snapshot above, which only costs // one extra reload if the file appears later). snapshotKnownHostsStat(storePath, -1) return knownHostsCache.store } // knownHostsPath returns the path of the TOFU known-hosts store, derived from the // panel root. Kept alongside other node state so it survives restarts. func knownHostsPath(panelRoot string) string { root := strings.TrimSpace(panelRoot) if root == "" { root = "." } return filepath.Join(root, "data", "ssh_known_hosts.json") } // hostKeyFingerprint returns a stable, comparable fingerprint for a host key. // We use the SHA-256 of the wire-format public key (the same bytes OpenSSH // fingerprints), base64-encoded, which is collision-resistant and unambiguous. func hostKeyFingerprint(key ssh.PublicKey) string { sum := sha256.Sum256(key.Marshal()) return key.Type() + ":SHA256:" + base64.StdEncoding.EncodeToString(sum[:]) } // TOFU store bounds. The store is attacker-influenced: an authorized panel // user can point the terminal at servers they control with rotating // hostnames, so an unbounded store would let them fill the disk and slow // every user's terminal. Every collection is therefore capped. Eviction is // OFFENDER-PAYS: each user is capped individually (evicting their own oldest // entries first), and the total caps below are backstops that evict from the // largest contributor first — a flood by one user can never evict another // user's entries (insertion order is tracked in PinsOrder/GlobalOrder and // persisted alongside the data). const ( // maxKnownHostsPins caps the total number of per-user pins. maxKnownHostsPins = 2048 // maxKnownHostsPinsPerUser caps one user's share of the pin store. It // bounds one user's blast radius: a flood of first-use pins by a single // user can only evict that user's OWN oldest pins, never another user's // (offender-pays eviction; the total cap above is only a backstop). maxKnownHostsPinsPerUser = 64 // maxKnownHostsGlobalHosts caps the number of distinct hosts tracked in // the advisory Global divergence map. maxKnownHostsGlobalHosts = 2048 // maxGlobalHostsPerUser caps one user's contribution to the advisory // Global map, with the same per-user blast-radius rationale as // maxKnownHostsPinsPerUser. maxGlobalHostsPerUser = 256 // maxKnownHostsFingerprintsPerHost caps a host's advisory fingerprint // history; the oldest fingerprint is dropped first. maxKnownHostsFingerprintsPerHost = 16 // maxKnownHostsIDLen caps the length of a pin identifier // ("userID\x00host:port"); longer identifiers are refused (fail closed) // rather than pinned as an unverifiable host. maxKnownHostsIDLen = 320 ) // knownHostsStore is the on-disk TOFU model. // // Pins are keyed PER USER ("uid\x00host:port" -> fingerprint) so one user can // never pin a host key on behalf of another. This closes the multi-user // pre-pinning attack: a malicious panel user pinning a trap key only affects // their OWN store, and a victim still performs their own first-use pinning // against the real server. // // Global holds the union of every fingerprint that has EVER been seen for a // host:port across all users. It is advisory only: when a user pins a host for // the first time and the presented key is NOT among the keys other users have // already seen, we surface a warning (divergence => possible interception), // but we still pin the user's own observation. This way a victim is never // silently bound to an attacker's key and gets a visible signal on divergence. // // Bounds and eviction: Pins is capped at maxKnownHostsPins entries total and // Global at maxKnownHostsGlobalHosts hosts with at most // maxKnownHostsFingerprintsPerHost fingerprints each. Eviction is per-user // and offender-pays: each user is additionally capped at // maxKnownHostsPinsPerUser pins and maxGlobalHostsPerUser contributed // advisory hosts, and hitting either cap evicts that user's OWN oldest // entries — a flood by one user can never evict another user's entries. The // total caps remain as backstops and evict from the LARGEST contributor // first (ties broken by insertion order). Per-host fingerprint histories // keep their most recent fingerprints. PinsOrder/GlobalOrder record the // insertion order so eviction order survives restarts; they are plain // optional JSON fields, so older stores without them load fine and their // order is rebuilt from the sorted keys on load. A store loaded over any cap // is trimmed back down immediately, so a previously-abused file heals itself // on the next save. type knownHostsStore struct { Pins map[string]string `json:"pins"` Global map[string][]string `json:"global"` // GlobalContrib records, per advisory host, the first user that // contributed it ("host:port" -> uid), so per-user cap enforcement and // offender-pays eviction can attribute hosts to users. Optional: stores // written before this field existed load fine, and their unattributed // hosts count toward a legacy ("") bucket that is capped and evicted // like any other single contributor's. GlobalContrib map[string]string `json:"globalContrib,omitempty"` // Insertion order of the Pins / Global keys, used for oldest-first // eviction (see the caps above). PinsOrder []string `json:"pinsOrder,omitempty"` GlobalOrder []string `json:"globalOrder,omitempty"` } // normalizeOwner strips NUL bytes (and surrounding whitespace) from a uid so // every ownership attribution uses the same canonical form; combined with // pinOwner this guarantees the prefix before the first "\x00" of a pin key // is always the true owner. func normalizeOwner(userID string) string { return strings.ReplaceAll(strings.TrimSpace(userID), "\x00", "") } // userHostKey builds the per-user pin key "uid\x00host:port". The uid is // normalized (NUL bytes stripped) before joining, so the prefix before the // first "\x00" of a pin key is ALWAYS the true owner: a crafted uid cannot // forge or blur per-user ownership attribution (see pinOwner). func userHostKey(userID, hostport string) string { return normalizeOwner(userID) + "\x00" + strings.ToLower(strings.TrimSpace(hostport)) } // pinOwner returns the owning user of a per-user pin key (the substring // before the first "\x00"); the empty string means the key carries no owner // segment. func pinOwner(uhk string) string { if i := strings.IndexByte(uhk, '\x00'); i >= 0 { return uhk[:i] } return "" } // keySet returns the key set of a map, regardless of its value type. func keySet[V any](m map[string]V) map[string]struct{} { keys := make(map[string]struct{}, len(m)) for k := range m { keys[k] = struct{}{} } return keys } // normalizeKnownHostsOrder returns an order slice listing exactly the keys in // keys: stale entries (no longer in the map) and duplicates are dropped, and // map keys missing from order are appended in sorted order, so stores written // before the order fields existed load with a stable, deterministic order. func normalizeKnownHostsOrder(order []string, keys map[string]struct{}) []string { out := make([]string, 0, len(keys)) seen := make(map[string]struct{}, len(order)) for _, k := range order { if _, ok := keys[k]; !ok { continue } if _, dup := seen[k]; dup { continue } seen[k] = struct{}{} out = append(out, k) } missing := make([]string, 0, len(keys)) for k := range keys { if _, ok := seen[k]; !ok { missing = append(missing, k) } } sort.Strings(missing) return append(out, missing...) } // countPinsPerUser returns how many pins each owner holds (owners are the // uid prefixes of the pin keys, see pinOwner). func countPinsPerUser(st *knownHostsStore) map[string]int { counts := make(map[string]int, len(st.Pins)) for _, k := range st.PinsOrder { counts[pinOwner(k)]++ } return counts } // countUserPins returns how many pins in st belong to userID. func countUserPins(st *knownHostsStore, userID string) int { n := 0 for _, k := range st.PinsOrder { if pinOwner(k) == userID { n++ } } return n } // countGlobalHostsPerContributor returns how many advisory hosts each // contributor holds (per GlobalContrib); hosts with no contributor entry // (legacy data) count toward the "" bucket. func countGlobalHostsPerContributor(st *knownHostsStore) map[string]int { counts := make(map[string]int, len(st.Global)) for _, host := range st.GlobalOrder { counts[st.GlobalContrib[host]]++ } return counts } // countUserGlobalHosts returns how many advisory hosts in st were // contributed by userID. Like countGlobalHostsPerContributor (and the // evictors below) it walks GlobalOrder and looks the contributor up in // GlobalContrib, so counting and eviction always agree even if GlobalContrib // carries a stale entry for a host that is no longer in Global. func countUserGlobalHosts(st *knownHostsStore, userID string) int { n := 0 for _, host := range st.GlobalOrder { if st.GlobalContrib[host] == userID { n++ } } return n } // evictOldestPinForUser drops the OLDEST pin owned by userID (first match in // PinsOrder), removing it from both the map and the order slice. It reports // whether such a pin existed. func evictOldestPinForUser(st *knownHostsStore, userID string) bool { for i, k := range st.PinsOrder { if pinOwner(k) != userID { continue } st.PinsOrder = append(st.PinsOrder[:i], st.PinsOrder[i+1:]...) delete(st.Pins, k) return true } return false } // evictOldestOffenderPin is the total-cap backstop: it evicts the OLDEST pin // (front of PinsOrder) belonging to the user with the MOST pins, so an // overflowing insert costs the largest contributor ("offender pays") instead // of the globally-oldest pin, which may belong to an unrelated user. Ties // are broken deterministically: the owner whose pin comes FIRST in PinsOrder // wins. It reports whether a pin was evicted (false only when the store // holds no evictable pin). func evictOldestOffenderPin(st *knownHostsStore) bool { counts := countPinsPerUser(st) top, topCount := "", -1 for _, k := range st.PinsOrder { owner := pinOwner(k) if counts[owner] > topCount { top, topCount = owner, counts[owner] } } if topCount <= 0 { return false } return evictOldestPinForUser(st, top) } // evictOldestGlobalHostForUser drops the OLDEST advisory host contributed by // userID (first match in GlobalOrder), removing it from the map, the order // slice and GlobalContrib. It reports whether such a host existed. func evictOldestGlobalHostForUser(st *knownHostsStore, userID string) bool { for i, host := range st.GlobalOrder { if st.GlobalContrib[host] != userID { continue } st.GlobalOrder = append(st.GlobalOrder[:i], st.GlobalOrder[i+1:]...) delete(st.Global, host) delete(st.GlobalContrib, host) return true } return false } // evictOldestOffenderGlobalHost is the advisory-map backstop: it evicts the // OLDEST host (front of GlobalOrder) belonging to the contributor with the // MOST contributed hosts. Hosts with no GlobalContrib entry (legacy data) // count toward the "" bucket and are only evicted by this function when no // real contributor has a strictly higher count. Ties are broken // deterministically (the contributor whose host comes FIRST in GlobalOrder // wins). It reports whether a host was evicted. func evictOldestOffenderGlobalHost(st *knownHostsStore) bool { counts := countGlobalHostsPerContributor(st) top, topCount := "", -1 for _, host := range st.GlobalOrder { owner := st.GlobalContrib[host] if counts[owner] > topCount { top, topCount = owner, counts[owner] } } if topCount <= 0 { return false } return evictOldestGlobalHostForUser(st, top) } // trimKnownHostsToCaps heals a store that is over any of the bounds (e.g. one // written before the caps existed): the total caps are backstops that evict // offender-pays (the largest contributor's oldest entries first), any user // over their per-user cap loses their OWN oldest entries until they fit, and // over-long advisory fingerprint histories keep only their most recent // fingerprints. The healed store is persisted on the next save. func trimKnownHostsToCaps(st *knownHostsStore) { for len(st.Pins) > maxKnownHostsPins { if !evictOldestOffenderPin(st) { break } } for uid, n := range countPinsPerUser(st) { for n > maxKnownHostsPinsPerUser { if !evictOldestPinForUser(st, uid) { break } n-- } } for len(st.Global) > maxKnownHostsGlobalHosts { if !evictOldestOffenderGlobalHost(st) { break } } for uid, n := range countGlobalHostsPerContributor(st) { for n > maxGlobalHostsPerUser { if !evictOldestGlobalHostForUser(st, uid) { break } n-- } } for h, fps := range st.Global { if len(fps) > maxKnownHostsFingerprintsPerHost { st.Global[h] = append([]string(nil), fps[len(fps)-maxKnownHostsFingerprintsPerHost:]...) } } } // recordPin inserts a per-user pin. The per-user cap // (maxKnownHostsPinsPerUser) is enforced first by evicting the user's OWN // oldest pins, so a flood by one user only costs that user; the total cap // (maxKnownHostsPins) remains as a backstop and evicts offender-pays (see // evictOldestOffenderPin). The owner is derived from the normalized uid, // which always equals pinOwner(uhk) for keys built by userHostKey, so // per-user accounting cannot be spoofed by a crafted uid. Overwriting an // existing pin keeps its position (the key's first use remains its age). func recordPin(st *knownHostsStore, userID, uhk, fp string) { if _, exists := st.Pins[uhk]; !exists { owner := normalizeOwner(userID) for countUserPins(st, owner) >= maxKnownHostsPinsPerUser { if !evictOldestPinForUser(st, owner) { break // order/map drift: give up rather than loop forever } } for len(st.Pins) >= maxKnownHostsPins { if !evictOldestOffenderPin(st) { break // nothing evictable: prefer availability over the cap } } st.PinsOrder = append(st.PinsOrder, uhk) } st.Pins[uhk] = fp } // recordGlobalFingerprint records fp in a host's advisory fingerprint // history, creating the host entry (capped per-contributor first, then // offender-pays at the total cap) or dropping the host's OLDEST fingerprint // when its history is full. Global is advisory-only divergence data: the // per-user pin check is exact and capped separately, so trimming here never // weakens it. New hosts are attributed to their first contributor // (GlobalContrib) so the per-user cap (maxGlobalHostsPerUser) and the // offender-pays backstop can attribute them; a user flooding the advisory // map only ever evicts their OWN contributed hosts. func recordGlobalFingerprint(st *knownHostsStore, host, fp, userID string) { if _, exists := st.Global[host]; !exists { owner := normalizeOwner(userID) for countUserGlobalHosts(st, owner) >= maxGlobalHostsPerUser { if !evictOldestGlobalHostForUser(st, owner) { break // order/map drift: give up rather than loop forever } } for len(st.Global) >= maxKnownHostsGlobalHosts { if !evictOldestOffenderGlobalHost(st) { break // nothing evictable: prefer availability over the cap } } st.GlobalOrder = append(st.GlobalOrder, host) st.Global[host] = []string{fp} if st.GlobalContrib == nil { st.GlobalContrib = map[string]string{} } st.GlobalContrib[host] = owner return } lst := append([]string(nil), st.Global[host]...) if len(lst) >= maxKnownHostsFingerprintsPerHost { lst = lst[len(lst)-maxKnownHostsFingerprintsPerHost+1:] } st.Global[host] = append(lst, fp) } // cloneKnownHostsStore deep-copies st so a pin mutation can be built and // persisted without touching the resident cache; only the rare first-use pin // path pays for the copy. func cloneKnownHostsStore(st *knownHostsStore) *knownHostsStore { next := knownHostsStore{ Pins: make(map[string]string, len(st.Pins)+1), Global: make(map[string][]string, len(st.Global)+1), GlobalContrib: make(map[string]string, len(st.GlobalContrib)+1), PinsOrder: append([]string(nil), st.PinsOrder...), GlobalOrder: append([]string(nil), st.GlobalOrder...), } for k, v := range st.Pins { next.Pins[k] = v } for k, v := range st.Global { next.Global[k] = append([]string(nil), v...) } for k, v := range st.GlobalContrib { next.GlobalContrib[k] = v } return &next } // loadKnownHosts reads and heals the store at path. A missing or empty file // yields an empty store and a nil error; a file that exists but cannot be // READ (permissions, I/O error, the path turned into a directory, ...) or // cannot be parsed returns the error, so callers can distinguish a corrupt / // unreadable store (and keep their last good state) from a fresh one. // Conflating a read error with "empty store" would make the reload path drop // every resident pin on a transient read failure, and the next connection // would silently re-pin whatever key it is shown. func loadKnownHosts(path string) (knownHostsStore, error) { empty := knownHostsStore{Pins: map[string]string{}, Global: map[string][]string{}, GlobalContrib: map[string]string{}} st := knownHostsStore{Pins: map[string]string{}, Global: map[string][]string{}, GlobalContrib: map[string]string{}} b, err := os.ReadFile(path) if err != nil { if os.IsNotExist(err) { // A missing file is a fresh store, not a failure: the next save // recreates it (same semantics as cachedKnownHosts' deleted-file // branch, which covers the race where the file vanishes between // its stat and this read). return empty, nil } return empty, err } if len(b) == 0 { return empty, nil } if err := json.Unmarshal(b, &st); err != nil { return empty, err } if st.Pins == nil { st.Pins = map[string]string{} } if st.Global == nil { st.Global = map[string][]string{} } if st.GlobalContrib == nil { st.GlobalContrib = map[string]string{} } // Drop GlobalContrib entries whose host is gone (e.g. a hand edit that // removed a host but left its contributor behind): nothing reads them, // so they would just be dead weight persisted forever. for host := range st.GlobalContrib { if _, ok := st.Global[host]; !ok { delete(st.GlobalContrib, host) } } // Rebuild the eviction order for stores written before the order fields // existed (or whose slices drifted from the maps), then trim a store // over any cap back down to the caps so a previously-abused file heals // itself (persisted on the next save). st.PinsOrder = normalizeKnownHostsOrder(st.PinsOrder, keySet(st.Pins)) st.GlobalOrder = normalizeKnownHostsOrder(st.GlobalOrder, keySet(st.Global)) trimKnownHostsToCaps(&st) return st, nil } // saveKnownHosts atomically persists st (tmp file + rename) and returns the // number of bytes written, so the caller can verify the file on disk is // still the one it just wrote before snapshotting its stat. func saveKnownHosts(path string, st knownHostsStore) (int, error) { if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return 0, err } b, err := json.MarshalIndent(st, "", " ") if err != nil { return 0, err } tmp := path + ".tmp" if err := os.WriteFile(tmp, b, 0o600); err != nil { return 0, err } return len(b), os.Rename(tmp, path) } // tofuHostKeyCallback implements PER-USER Trust-On-First-Use host-key // verification with a cross-user divergence check. // // - The first time a given USER connects to host:port, the presented key is // pinned for that user and the connection is allowed. // - Every subsequent connection by the SAME user must present the SAME key, // otherwise the connection is rejected (classic MITM defense). // - Pins are namespaced by user, so no panel user can pre-pin a key that // another user will inherit (defeats the first-come pre-pinning attack). // - On a user's first use, if other users have previously recorded a // DIFFERENT key for the same host, that is a divergence signal (possible // interception). We reject by default and require the connecting user to // explicitly accept, surfacing the risk instead of silently trusting it. // - The store is bounded (see knownHostsStore): a pin identifier longer // than maxKnownHostsIDLen is refused (fail closed), and pins / advisory // global entries are evicted per-user (offender pays: a flood by one // user only ever evicts that user's own oldest entries) at the caps. // // The parsed store is kept resident under knownHostsMu (knownHostsCache), so // a connection's critical section is O(1) memory work and the store file is // only re-read when it changed on disk — an admin edit (e.g. removing a pin // after a legitimate reinstall) takes effect on the next connection without // a restart. On the pin path the mutation is applied to a private clone of // the store and swapped into the cache only AFTER the save succeeds: if the // save fails the connection is refused ("host key store unavailable") and // connection is refused ("host key store unavailable") and the cache still // matches the on-disk state, so the pin is simply retried on the next // attempt — the same fail-closed semantics as the previous behavior, where a // failed save left the pin nowhere. // // 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)) if host == "" { host = strings.ToLower(strings.TrimSpace(remote.String())) } fp := hostKeyFingerprint(key) uhk := userHostKey(userID, host) // Bound the pin identifier before any store work: an over-long // "userID\x00host:port" can never be pinned, so refuse it instead of // silently allowing an unverifiable host. if len(uhk) > maxKnownHostsIDLen { return fmt.Errorf("host key store identifier for %q is too long (%d bytes, max %d); refusing an unverifiable host", host, len(uhk), maxKnownHostsIDLen) } knownHostsMu.Lock() defer knownHostsMu.Unlock() st := cachedKnownHosts(storePath) if pinned, ok := st.Pins[uhk]; ok { // This user already pinned a key for this host: must match exactly. if hmac.Equal([]byte(pinned), []byte(fp)) { return nil } return fmt.Errorf("host key mismatch for %s: possible man-in-the-middle attack (pinned %s, got %s)", host, pinned, fp) } // First use for THIS user. Check divergence against what others saw. seen := st.Global[host] seenThis := false for _, s := range seen { if s == fp { seenThis = true break } } if len(seen) > 0 && !seenThis && !allowDivergentFirstUse { // 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. // 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 // mutation (with cap eviction) is applied to a private clone and // committed to the resident cache only after the save succeeds, so a // failed save leaves the in-memory and on-disk views coherent. next := cloneKnownHostsStore(st) recordPin(next, userID, uhk, fp) if !seenThis { recordGlobalFingerprint(next, host, fp, userID) } written, err := saveKnownHosts(storePath, *next) if err != nil { return fmt.Errorf("host key store unavailable: %w", err) } *st = *next // Refresh the size+mtime snapshot: the file just saved is already // reflected in the resident store, so the next connection must not // pointlessly reload it. The expected size makes the snapshot reject // a file that was externally replaced between our rename and this // stat (it would otherwise be recorded as our own and the edit // silently skipped until the file changed again): the snapshot is // invalidated instead, forcing a reload on the next connection. snapshotKnownHostsStat(storePath, int64(written)) return nil } } 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 } if rows <= 0 { rows = 30 } config := &ssh.ClientConfig{ User: target.User, Auth: []ssh.AuthMethod{ ssh.Password(password), ssh.KeyboardInteractive(func(_ string, _ string, questions []string, _ []bool) ([]string, error) { answers := make([]string, len(questions)) for i := range questions { answers[i] = password } return answers, nil }), }, // 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, } addr := net.JoinHostPort(target.Host, strconv.Itoa(target.Port)) // M6: dial through the guarded dialer instead of ssh.Dial so the real // SSH connection (not only the pre-flight probe) re-validates the // resolved address against the metadata block — closing the DNS-rebinding // window between the reachability probe and this dial. conn, err := guardedSSHDialer(config.Timeout).Dial("tcp", addr) if err != nil { return nil, nil, nil, nil, nil, err } // Deadline the raw conn so the whole setup path — banner exchange, KEX and // auth inside NewClientConn, NewSession, RequestPty and Shell — is bounded // by sshSetupTimeout: each of them blocks on reads/writes of this conn, so // a target that accepts TCP but stalls the handshake cannot pin a // goroutine and socket forever. The deadline is cleared once the shell is // running; a failed clear would leave a live session killing itself 30s // in, so fail closed instead. if err := conn.SetDeadline(time.Now().Add(sshSetupTimeout)); err != nil { _ = conn.Close() return nil, nil, nil, nil, nil, err } clientConn, chans, reqs, err := ssh.NewClientConn(conn, addr, config) if err != nil { _ = conn.Close() return nil, nil, nil, nil, nil, err } client := ssh.NewClient(clientConn, chans, reqs) session, err := client.NewSession() if err != nil { client.Close() return nil, nil, nil, nil, nil, err } stdin, err := session.StdinPipe() if err != nil { session.Close() client.Close() return nil, nil, nil, nil, nil, err } stdout, err := session.StdoutPipe() if err != nil { stdin.Close() session.Close() client.Close() return nil, nil, nil, nil, nil, err } stderr, err := session.StderrPipe() if err != nil { stdin.Close() session.Close() client.Close() return nil, nil, nil, nil, nil, err } modes := ssh.TerminalModes{ ssh.ECHO: 1, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400, } if err := session.RequestPty("xterm-256color", rows, cols, modes); err != nil { stdin.Close() session.Close() client.Close() return nil, nil, nil, nil, nil, err } // Shell is the last bounded step: a target that accepts the request // stream but never confirms the shell still hits the conn deadline. if err := session.Shell(); err != nil { stdin.Close() session.Close() client.Close() return nil, nil, nil, nil, nil, fmt.Errorf("failed to start remote shell: %w", err) } // The interactive session must not be bounded by the setup deadline — the // 20-minute idle timeout is enforced separately by the attach loop — so // clear it exactly once, after Shell succeeds. On success the deadline is // guaranteed to be gone. if err := conn.SetDeadline(time.Time{}); err != nil { stdin.Close() session.Close() client.Close() return nil, nil, nil, nil, nil, fmt.Errorf("failed to clear ssh setup deadline: %w", err) } return client, session, stdin, stdout, stderr, nil } func parseSSHCommand(input string) (sshTarget, error) { trimmed := strings.TrimSpace(input) parts := strings.Fields(trimmed) if len(parts) < 2 || !strings.EqualFold(parts[0], "ssh") { return sshTarget{}, errors.New("only ssh user@host -p is allowed") } args := parts[1:] dest := "" cliPort := 0 for i := 0; i < len(args); i++ { arg := strings.TrimSpace(args[i]) if arg == "" { continue } // Tolerate accidental spacing around '@', e.g. "root@ 1.2.3.4" or "root @1.2.3.4". if dest != "" { if strings.HasSuffix(dest, "@") && !strings.HasPrefix(arg, "-") { dest += arg continue } if strings.HasPrefix(arg, "@") && !strings.Contains(dest, "@") { dest += arg continue } } if strings.HasPrefix(arg, "-p") { portText := "" if arg == "-p" { if i+1 >= len(args) { return sshTarget{}, errors.New("invalid port") } i++ portText = strings.TrimSpace(args[i]) } else { portText = strings.TrimSpace(strings.TrimPrefix(arg, "-p")) } n, err := strconv.Atoi(portText) if err != nil || n < 1 || n > 65535 { return sshTarget{}, errors.New("invalid port") } cliPort = n continue } if strings.HasPrefix(arg, "-") { return sshTarget{}, errors.New("only -p is accepted") } if dest != "" { return sshTarget{}, errors.New("only one ssh destination is allowed") } dest = arg } if dest == "" { return sshTarget{}, errors.New("missing ssh destination") } at := strings.Index(dest, "@") if at <= 0 || at == len(dest)-1 { return sshTarget{}, errors.New("invalid ssh destination") } user := dest[:at] host, inlinePort, err := splitSSHHostPort(dest[at+1:]) if err != nil { return sshTarget{}, err } if !isSafeSSHUser(user) || !isSafeSSHHost(host) { return sshTarget{}, errors.New("invalid user or host") } port := 22 if inlinePort > 0 { port = inlinePort } if cliPort > 0 { port = cliPort } return sshTarget{User: user, Host: host, Port: port}, nil } func splitSSHHostPort(raw string) (string, int, error) { hostPart := strings.TrimSpace(raw) if hostPart == "" { return "", 0, errors.New("invalid ssh destination") } if strings.HasPrefix(hostPart, "[") { closeIdx := strings.Index(hostPart, "]") if closeIdx <= 1 { return "", 0, errors.New("invalid user or host") } host := hostPart[1:closeIdx] rest := strings.TrimSpace(hostPart[closeIdx+1:]) if rest == "" { return host, 0, nil } if !strings.HasPrefix(rest, ":") { return "", 0, errors.New("invalid user or host") } portText := strings.TrimSpace(rest[1:]) n, err := strconv.Atoi(portText) if err != nil || n < 1 || n > 65535 { return "", 0, errors.New("invalid port") } return host, n, nil } lastColon := strings.LastIndex(hostPart, ":") if lastColon > 0 && lastColon < len(hostPart)-1 { portText := hostPart[lastColon+1:] if isDecimalDigits(portText) { host := hostPart[:lastColon] if strings.Count(host, ":") == 0 { n, err := strconv.Atoi(portText) if err != nil || n < 1 || n > 65535 { return "", 0, errors.New("invalid port") } return host, n, nil } } } return hostPart, 0, nil } func isDecimalDigits(input string) bool { if input == "" { return false } for _, c := range input { if c < '0' || c > '9' { return false } } return true } func isSafeSSHUser(user string) bool { if len(user) < 1 || len(user) > 32 { return false } for _, c := range user { if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.' { continue } return false } return true } func isSafeSSHHost(host string) bool { if len(host) < 1 || len(host) > 253 { return false } for _, c := range host { if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == ':' || c == '-' { continue } return false } return true } func verifyToken(secret []byte, token string, requestIP string) (tokenPayload, error) { parts := strings.Split(token, ".") if len(parts) != 2 { return tokenPayload{}, errors.New("invalid token format") } payloadB64 := parts[0] sigRaw, err := decodeB64URL(parts[1]) if err != nil { return tokenPayload{}, errors.New("invalid token signature") } mac := hmac.New(sha256.New, secret) _, _ = mac.Write([]byte(payloadB64)) expected := mac.Sum(nil) if !hmac.Equal(expected, sigRaw) { return tokenPayload{}, errors.New("token signature mismatch") } payloadRaw, err := decodeB64URL(payloadB64) if err != nil { return tokenPayload{}, errors.New("invalid token payload") } var payload tokenPayload if err := json.Unmarshal(payloadRaw, &payload); err != nil { return tokenPayload{}, errors.New("invalid token json") } if payload.ExpMS < time.Now().UnixMilli() { return tokenPayload{}, errors.New("token expired") } // M6: enforce the client-IP binding the panel baked into the payload. The // token travels in URLs (logs, browser history, Referer), so the HMAC // alone left 20 minutes of arbitrary-SSH-dial capability to whoever // captured it. sameIP requires both sides to normalize to a real address, // so a token without a usable IP binding is refused here as well — the // issuing panel always embeds one. if !sameIP(payload.IP, requestIP) { return tokenPayload{}, errors.New("token ip binding mismatch") } return payload, nil } func sameIP(a, b string) bool { na := normalizeIP(a) nb := normalizeIP(b) return na != "" && nb != "" && na == nb } func normalizeIP(raw string) string { s := strings.TrimSpace(raw) if s == "" { return "" } if strings.Contains(s, ",") { s = strings.TrimSpace(strings.Split(s, ",")[0]) } host, _, err := net.SplitHostPort(s) if err == nil { s = host } s = strings.TrimPrefix(s, "::ffff:") ip := net.ParseIP(s) if ip == nil { return "" } return ip.String() } // parseTrustedProxies builds the proxy-trust list for client-IP resolution. // Defaults to loopback only: the panel's own proxy hop. Empty/unparseable // entries never widen trust (fail closed); an operator typo that leaves ZERO // usable entries falls back to the loopback default instead of silently // distrusting even the panel's own hop (which would brick the terminal). func parseTrustedProxies(raw string) []*net.IPNet { entries := []string{"127.0.0.0/8", "::1/128"} if strings.TrimSpace(raw) != "" { entries = nil for _, entry := range strings.Split(raw, ",") { entry = strings.TrimSpace(entry) // Tolerate bracketed IPv6 literals ("[::1]") copied from URLs/logs. if strings.HasPrefix(entry, "[") && strings.HasSuffix(entry, "]") { entry = strings.TrimSuffix(strings.TrimPrefix(entry, "["), "]") } if entry == "" { continue } entries = append(entries, entry) } } out := parseTrustedProxyEntries(entries) if len(out) == 0 { if strings.TrimSpace(raw) != "" { log.Printf("[ssh-term] no usable SSH_TERM_TRUSTED_PROXIES entries in %q — falling back to loopback-only trust", raw) } out = parseTrustedProxyEntries([]string{"127.0.0.0/8", "::1/128"}) } return out } func parseTrustedProxyEntries(entries []string) []*net.IPNet { var out []*net.IPNet for _, entry := range entries { if strings.Contains(entry, "/") { _, ipnet, err := net.ParseCIDR(entry) if err != nil { log.Printf("[ssh-term] ignoring unparseable SSH_TERM_TRUSTED_PROXIES entry %q: %v", entry, err) continue } out = append(out, ipnet) continue } ip := net.ParseIP(entry) if ip == nil { log.Printf("[ssh-term] ignoring unparseable SSH_TERM_TRUSTED_PROXIES entry %q", entry) continue } if ip4 := ip.To4(); ip4 != nil { out = append(out, &net.IPNet{IP: ip4, Mask: net.CIDRMask(32, 32)}) } else { out = append(out, &net.IPNet{IP: ip, Mask: net.CIDRMask(128, 128)}) } } return out } func isTrustedProxyAddr(remoteIP string, trusted []*net.IPNet) bool { ip := net.ParseIP(normalizeIP(remoteIP)) if ip == nil { return false } for _, ipnet := range trusted { if ipnet != nil && ipnet.Contains(ip) { return true } } return false } // lastForwardedValue returns the X-Forwarded-For entry closest to this // service. The panel proxy overwrites the header with the client IP it // resolved, so under the default (loopback) trust policy that entry IS the // panel-asserted client address; client-supplied prefix hops can never win. func lastForwardedValue(header string) string { parts := strings.Split(header, ",") for i := len(parts) - 1; i >= 0; i-- { if v := strings.TrimSpace(parts[i]); v != "" { return v } } return "" } // requestIP resolves the address a token is bound against. X-Forwarded-For / // X-Real-IP are honored only from trusted proxy ranges (loopback by default — // the panel's proxy hop); a direct connection from any other address is // attributed to its socket address, so a client cannot assert an arbitrary // bound IP. M6 hardened: previously every caller-supplied X-Forwarded-For was // trusted, which would have made the token IP binding trivially spoofable. func requestIP(r *http.Request, trusted []*net.IPNet) string { remote := normalizeIP(r.RemoteAddr) if isTrustedProxyAddr(remote, trusted) { if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" { if ip := normalizeIP(lastForwardedValue(xff)); ip != "" { return ip } } if xr := strings.TrimSpace(r.Header.Get("X-Real-IP")); xr != "" { if ip := normalizeIP(xr); ip != "" { return ip } } } return remote } func decodeB64URL(s string) ([]byte, error) { s = strings.TrimSpace(s) if s == "" { return nil, errors.New("empty base64url") } if b, err := base64.RawURLEncoding.DecodeString(s); err == nil { return b, nil } if m := len(s) % 4; m != 0 { s += strings.Repeat("=", 4-m) } if b, err := base64.URLEncoding.DecodeString(s); err == nil { return b, nil } std := strings.ReplaceAll(strings.ReplaceAll(s, "-", "+"), "_", "/") return base64.StdEncoding.DecodeString(std) } func loadDotEnv(path string) error { b, err := os.ReadFile(path) if err != nil { return err } lines := strings.Split(strings.ReplaceAll(string(b), "\r\n", "\n"), "\n") for _, line := range lines { line = strings.TrimSpace(line) if line == "" || strings.HasPrefix(line, "#") { continue } eq := strings.IndexByte(line, '=') if eq <= 0 { continue } k := strings.TrimSpace(line[:eq]) v := strings.TrimSpace(line[eq+1:]) if len(v) >= 2 { if (strings.HasPrefix(v, "\"") && strings.HasSuffix(v, "\"")) || (strings.HasPrefix(v, "'") && strings.HasSuffix(v, "'")) { v = v[1 : len(v)-1] } } if k != "" { if _, exists := os.LookupEnv(k); exists { continue } _ = os.Setenv(k, v) } } return nil } const indexHTML = ` ADPanel SSH Terminal
`