Files
Kelx/cmd/sshterm/main.go
T
antonn 78193254ad Security: fix ws-upgrade crash, per-user TOFU eviction, token log leaks; rebuild sshterm
Panel (index.js, client, views):
- upgrade handler: error guard on every upgraded socket (any path) plus a 3s
  zero-byte orphan reaper; engine.io destroyUpgrade disabled — closes the
  unauthenticated ECONNRESET crash of the whole panel and stops engine.io's
  1s timer from killing slow ssh-terminal handshakes
- /api/ssh-terminal/session: per-session token reuse cache in front of the
  rate limiter — floating-terminal auto-restore no longer burns the 10/min
  mint budget (tokens are re-served only to the same panel session + IP)
- global error middleware redacts credential-bearing query params via
  utils/url-sanitize.js — ssh-terminal ?token= values no longer reach logs
- floating-terminal restore consumes the persisted live flag: after the
  frame reported the SSH session dead, restore drops the stored session id
  and starts a clean connect; script cache busters bumped

sshterm (cmd/sshterm/main.go, rebuilt and deployed):
- TOFU store eviction is per-user and offender-pays (per-user caps: 64 pins
  and 256 contributed advisory hosts; total caps remain as backstops that
  evict the largest contributor first) — one user flooding first-use pins
  to hosts they control can no longer evict another user's pinned key or
  suppress their divergence warning
- the store file is reloaded on mtime/size change: admin edits to
  data/ssh_known_hosts.json now take effect on the next connection without
  a restart; corrupt files keep the last good state, deleted files clear
  the store, other read errors fail closed
- regression tests for flood/eviction/reload/healing + negative controls
- also lands the previously uncommitted IP-binding, trusted-proxy,
  allowed-hosts and metadata-blocking hardening; binary rebuilt through
  initialize.sh --repair-sshterm and verified live at
  /usr/local/bin/adpanel-sshterm (sha256 6bc0363479b91e6c49af9b153c8e552fd4ad8f9a5f787d73bbdc238ce0f7579e)
2026-09-23 17:50:40 +00:00

3276 lines
104 KiB
Go

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"`
}
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
lastInput 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()
}
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(),
}
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
}
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))
for ch := range ts.subs {
subs = append(subs, ch)
}
ts.mu.Unlock()
for _, ch := range subs {
select {
case ch <- msg:
default:
}
}
}
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
idleInput := now.Sub(ts.lastInput) >= terminalIdleTimeout
closed := ts.closed
ts.mu.Unlock()
if !closed && (idleDetached || idleInput) {
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)
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.lastInput = 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.lastInput) >= 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":
ts.closeWithMessage("")
return
}
case msg := <-outCh:
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
}
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
}
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())
}
client, session, stdin, stdout, stderr, err := openSSHSession(target, strings.TrimSpace(connectMsg.Password), knownHostsPath(cfg.PanelRoot), payload.UserID, connectMsg.Cols, connectMsg.Rows)
if err != nil {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh connection failed: " + explainSSHConnectError(err)})
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). Verify the server fingerprint out-of-band before trusting it"
}
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 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).
var forbiddenSSHHosts = map[string]struct{}{
"169.254.169.254": {},
"169.254.169.253": {},
"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")
// 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.
func isForbiddenMetadataIP(ip net.IP) bool {
if ip == nil {
return false
}
if ip4 := ip.To4(); ip4 != nil {
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.
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.
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)
}
// 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) (*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; an explicit accept flow can
// pass allowDivergentFirstUse=true after warning the user.
HostKeyCallback: tofuHostKeyCallback(knownHostsStore, userID, false),
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 <port> 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 <port> 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 = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ADPanel SSH Terminal</title>
<style nonce="__CSP_NONCE__">
* { box-sizing: border-box; }
body {
margin: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
background: #000;
}
#terminal {
width: 100%;
height: 100%;
background: #000;
color: #d1d5db;
font: 14px/1.35 "IBM Plex Mono", Menlo, Monaco, Consolas, monospace;
white-space: pre-wrap;
word-break: break-word;
padding: 12px;
outline: none;
overflow: auto;
-ms-overflow-style: none;
scrollbar-width: none;
caret-color: transparent;
user-select: text;
}
#terminal::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
.cursor {
background-color: #d1d5db;
color: #000;
display: inline-block;
animation: blink 1s step-end infinite;
}
.conn-hint {
color: #6b7280;
font-size: 0.85em;
}
@keyframes blink {
0%, 50% {
background-color: #d1d5db;
color: #000;
}
50.01%, 100% {
background-color: transparent;
color: #d1d5db;
}
}
</style>
</head>
<body>
<div id="terminal" tabindex="0" role="application" aria-label="SSH terminal"></div>
<script nonce="__CSP_NONCE__">
const TOKEN = '__TOKEN__';
const WS_FALLBACK = '__WS_FALLBACK__';
const terminal = document.getElementById('terminal');
let socket = null;
let connected = false;
let intentionalDisconnect = false;
let inputMode = 'command';
let commandBuffer = '';
let commandCursorPos = 0;
let passwordBuffer = '';
let pendingCommand = '';
let connectInFlight = false;
let wsAttemptIndex = 0;
let screen = '';
// ── VT100 viewport ──────────────────────────────────────────────────────
// termCols / termRows: dimensiunea fizică a terminalului (actualizată la resize)
// viewport: array fix de termRows linii (fiecare linie = string de termCols chars)
// scrollback: liniile care au ieșit din viewport prin scroll-up
// termRow / termCol: poziția cursorului în viewport (0-indexed)
let termCols = 80;
let termRows = 24;
let viewport = [];
let scrollback = [];
let termRow = 0;
let termCol = 0;
function initViewport(cols, rows) {
termCols = Math.max(10, cols || 80);
termRows = Math.max(4, rows || 24);
viewport = [];
for (let i = 0; i < termRows; i++) viewport.push('');
scrollback = [];
termRow = 0;
termCol = 0;
}
function resizeViewport(newCols, newRows) {
newCols = Math.max(10, newCols || 80);
newRows = Math.max(4, newRows || 24);
// Ajustează numărul de linii
while (viewport.length < newRows) {
// Adaugă linii goale jos
viewport.push('');
}
while (viewport.length > newRows) {
// Mută liniile de sus în scrollback
scrollback.push(viewport.shift());
termRow = Math.max(0, termRow - 1);
}
termCols = newCols;
termRows = newRows;
termRow = Math.max(0, Math.min(termRow, termRows - 1));
termCol = Math.max(0, Math.min(termCol, termCols - 1));
}
// Scroll viewport cu o linie în sus (linia de sus merge în scrollback)
function scrollUp() {
scrollback.push(viewport.shift());
viewport.push('');
// Limitează scrollback la 5000 linii
if (scrollback.length > 5000) scrollback.shift();
}
// Scroll viewport cu o linie în jos (linia de jos dispare, sus apare linie goală)
function scrollDown() {
viewport.pop();
viewport.unshift('');
}
const commandHistory = [];
let commandHistoryIndex = -1;
let commandHistoryDraft = '';
const PROMPT = 'root@adpanel:~# ';
// Boot parameters travel in the URL fragment: the fragment never
// reaches the server, survives page reloads (token refresh), and is
// readable inside this sandboxed frame whose opaque origin has no
// usable localStorage. sid = terminal session id chosen by the panel
// parent (stable across dashboard navigations), fresh = skip the
// attach attempt for a brand-new session. rt = one-shot token-refresh
// marker, accepted from the fragment OR the query string: the
// self-heal reload carries it in the query because a fragment-only
// change does not force the browser to re-commit the URL before a
// reload.
function readBootParams() {
try {
const params = new URLSearchParams(String(window.location.hash || '').replace(/^#/, ''));
const query = new URLSearchParams(String(window.location.search || ''));
const sid = String(params.get('sid') || '').trim();
return {
sid: /^[A-Za-z0-9._:-]{8,128}$/.test(sid) ? sid : '',
rt: String(params.get('rt') || '') === '1' || String(query.get('rt') || '') === '1',
fresh: String(params.get('fresh') || '') === '1'
};
} catch {
return { sid: '', rt: false, fresh: false };
}
}
function writeBootParams(patch) {
const next = Object.assign(readBootParams(), patch);
const parts = [];
if (next.sid) parts.push('sid=' + encodeURIComponent(next.sid));
if (next.rt) parts.push('rt=1');
if (next.fresh) parts.push('fresh=1');
try { window.location.replace('#' + parts.join('&')); } catch { }
}
const BOOT_PARAMS = readBootParams();
const TERMINAL_SESSION_ID = BOOT_PARAMS.sid || newEphemeralSessionId();
// The panel parent owns the persistent session id and passes it in
// the URL fragment (see readBootParams); an ephemeral id is only used
// when the page is opened standalone without a parent. This sandboxed
// frame has an opaque origin and no usable localStorage, so nothing
// is stored.
function newEphemeralSessionId() {
return (window.crypto && typeof window.crypto.randomUUID === 'function')
? window.crypto.randomUUID()
: 'session-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);
}
function setTerminalLive(value) {
// Persistence belongs to the parent: this frame is sandbox="allow-scripts"
// (opaque origin, no localStorage). The receiver authenticates us with
// event.source === frame.contentWindow; the payload is a single boolean
// and no secrets, so "*" mirrors the parent→child close-signal rationale.
if (window.parent && window.parent !== window) {
try { window.parent.postMessage({ type: 'adpanel-ssh-terminal-live', live: !!value }, '*'); } catch { }
}
}
function escapeHtml(text) {
return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function stripAnsi(s) {
let out = String(s || '');
out = out.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '');
out = out.replace(/\x1b[P^_].*?\x1b\\/g, '');
out = out.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '');
out = out.replace(/\x1b[@-_]/g, '');
out = out.replace(/[\x00-\x08\x0b-\x1a\x1c-\x1f\x7f]/g, '');
return out;
}
function syncTerminalLinesFromScreen() {
// La tranziția spre modul connected, inițializăm viewport-ul
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
// Punem conținutul existent din screen în viewport (ultimele termRows linii)
const lines = String(screen || '').split('\n');
const start = Math.max(0, lines.length - termRows);
for (let i = start; i < lines.length; i++) {
viewport[i - start] = lines[i] || '';
}
termRow = Math.min(lines.length - start - 1, termRows - 1);
termCol = viewport[termRow] ? viewport[termRow].length : 0;
}
function syncScreenFromTerminalLines() {
// Nu mai e necesar - viewport e sursa de adevăr
}
function ensureCursorLine() {
if (termRow < 0) termRow = 0;
if (termRow >= termRows) {
// Cursor a depășit ultima linie - scroll up
const overflow = termRow - (termRows - 1);
for (let i = 0; i < overflow; i++) scrollUp();
termRow = termRows - 1;
}
if (termCol < 0) termCol = 0;
}
function clampCursorToLine() {
ensureCursorLine();
// Nu clampăm la lungimea liniei - terminalul poate poziționa cursorul oriunde în cols
}
function writeTerminalChar(ch) {
ensureCursorLine();
const line = viewport[termRow] || '';
const pad = termCol > line.length ? ' '.repeat(termCol - line.length) : '';
viewport[termRow] = line.slice(0, termCol) + pad + ch + line.slice(Math.min(termCol + 1, line.length));
termCol += 1;
// Wrap automat la depășirea coloanei
if (termCol >= termCols) {
termCol = 0;
termRow += 1;
ensureCursorLine();
}
}
function terminalLineFeed() {
termRow += 1;
if (termRow >= termRows) {
scrollUp();
termRow = termRows - 1;
}
}
function terminalBackspace() {
if (termCol > 0) {
termCol -= 1;
} else if (termRow > 0) {
// Wrap înapoi pe linia anterioară
termRow -= 1;
termCol = termCols - 1;
}
}
function terminalTab() {
const spaces = 8 - (termCol % 8);
const newCol = termCol + spaces;
if (newCol < termCols) {
termCol = newCol;
} else {
termCol = termCols - 1;
}
}
function eraseInLine(mode) {
ensureCursorLine();
const line = viewport[termRow] || '';
if (mode === 1) {
// Șterge de la început până la cursor (inclusiv)
viewport[termRow] = ' '.repeat(Math.min(termCol + 1, termCols)) + line.slice(termCol + 1);
} else if (mode === 2) {
// Șterge toată linia
viewport[termRow] = '';
} else {
// Șterge de la cursor până la sfârșit
viewport[termRow] = line.slice(0, termCol);
}
}
function eraseInDisplay(mode) {
ensureCursorLine();
if (mode === 2 || mode === 3) {
// Șterge tot ecranul
for (let i = 0; i < termRows; i++) viewport[i] = '';
termRow = 0;
termCol = 0;
return;
}
if (mode === 1) {
// Șterge de la început până la cursor
for (let i = 0; i < termRow; i++) viewport[i] = '';
viewport[termRow] = ' '.repeat(Math.min(termCol + 1, termCols)) + (viewport[termRow] || '').slice(termCol + 1);
return;
}
// mode === 0: șterge de la cursor până la sfârșit
viewport[termRow] = (viewport[termRow] || '').slice(0, termCol);
for (let i = termRow + 1; i < termRows; i++) viewport[i] = '';
}
function insertBlankChars(count) {
ensureCursorLine();
const line = viewport[termRow] || '';
const col = Math.max(0, Math.min(termCol, line.length));
const n = Math.max(1, count || 1);
viewport[termRow] = (line.slice(0, col) + ' '.repeat(n) + line.slice(col)).slice(0, termCols);
}
function deleteChars(count) {
ensureCursorLine();
const line = viewport[termRow] || '';
const col = Math.max(0, Math.min(termCol, line.length));
const n = Math.max(1, count || 1);
viewport[termRow] = line.slice(0, col) + line.slice(col + n);
}
function eraseChars(count) {
ensureCursorLine();
const line = viewport[termRow] || '';
const col = Math.max(0, Math.min(termCol, line.length));
const n = Math.max(1, count || 1);
if (col >= line.length) return;
const end = Math.min(line.length, col + n);
viewport[termRow] = line.slice(0, col) + ' '.repeat(end - col) + line.slice(end);
}
function insertLines(count) {
ensureCursorLine();
const n = Math.max(1, count || 1);
for (let i = 0; i < n; i++) {
viewport.splice(termRow, 0, '');
if (viewport.length > termRows) viewport.pop();
}
}
function deleteLines(count) {
ensureCursorLine();
const n = Math.max(1, count || 1);
for (let i = 0; i < n; i++) {
viewport.splice(termRow, 1);
viewport.push('');
}
}
// A hostile or buggy remote can emit a CSI sequence with an astronomically
// large count (e.g. ESC[999999999999L); real terminal sequences never need
// counts beyond the 5000-line scrollback cap, so every numeric CSI parameter
// is clamped to keep the loops and string builds bounded (this code runs
// inside socket.onmessage in the browser tab).
const MAX_CSI_PARAM = 10000;
function parseCsiParams(raw) {
const clean = String(raw || '').replace(/[?>!]/g, '');
if (!clean) return [0];
return clean.split(';').map((part) => {
const n = parseInt(part, 10);
if (!Number.isFinite(n) || n < 0) return 0;
return Math.min(n, MAX_CSI_PARAM);
});
}
function applyCsi(rawParams, finalChar) {
const params = parseCsiParams(rawParams);
const first = params[0] || 0;
const count = Math.max(1, first || 1);
switch (finalChar) {
case '@':
insertBlankChars(count);
break;
case 'A':
termRow = Math.max(0, termRow - count);
break;
case 'B':
termRow = Math.min(termRows - 1, termRow + count);
break;
case 'C':
termCol = Math.min(termCols - 1, termCol + count);
break;
case 'D':
termCol = Math.max(0, termCol - count);
break;
case 'G':
termCol = Math.max(0, Math.min(termCols - 1, count - 1));
break;
case 'H':
case 'f':
termRow = Math.max(0, Math.min(termRows - 1, (params[0] || 1) - 1));
termCol = Math.max(0, Math.min(termCols - 1, (params[1] || 1) - 1));
break;
case 'J':
eraseInDisplay(first);
break;
case 'K':
eraseInLine(first);
break;
case 'L':
insertLines(count);
break;
case 'M':
deleteLines(count);
break;
case 'P':
deleteChars(count);
break;
case 'S':
// Scroll up
for (let i = 0; i < count; i++) scrollUp();
break;
case 'T':
// Scroll down
for (let i = 0; i < count; i++) scrollDown();
break;
case 'X':
eraseChars(count);
break;
case 'd':
// Cursor vertical absolute
termRow = Math.max(0, Math.min(termRows - 1, first - 1));
break;
default:
break;
}
}
function processTerminalOutput(text) {
const value = String(text || '').replace(/\r\n/g, '\r\n');
for (let i = 0; i < value.length; i++) {
const ch = value[i];
if (ch === '\x1b') {
const next = value[i + 1] || '';
if (next === '[') {
const match = value.slice(i).match(/^\x1b\[([0-?]*)([ -/]*)([@-~])/);
if (match) {
applyCsi(match[1], match[3]);
i += match[0].length - 1;
continue;
}
}
if (next === ']') {
let end = i + 2;
while (end < value.length && value[end] !== '\x07' && !(value[end] === '\x1b' && value[end + 1] === '\\')) end++;
i = value[end] === '\x1b' ? end + 1 : end;
continue;
}
if (next >= '@' && next <= '_') {
i += 1;
continue;
}
continue;
}
if (ch === '\r') {
termCol = 0;
continue;
}
if (ch === '\n') {
terminalLineFeed();
continue;
}
if (ch === '\b') {
terminalBackspace();
continue;
}
if (ch === '\t') {
terminalTab();
continue;
}
const code = ch.charCodeAt(0);
if (code < 32 || code === 127) continue;
writeTerminalChar(ch);
}
}
function renderConnectedScreen() {
// Afișăm scrollback + viewport
const allLines = scrollback.concat(viewport);
return allLines.map((line, index) => {
const viewportIndex = index - scrollback.length;
if (viewportIndex !== termRow) return escapeHtml(line);
const col = Math.max(0, Math.min(termCol, line.length));
const before = escapeHtml(line.slice(0, col));
const cursorChar = col < line.length ? escapeHtml(line[col]) : ' ';
const after = escapeHtml(line.slice(col + 1));
return before + '<span class="cursor">' + cursorChar + '</span>' + after;
}).join('\n');
}
function render() {
let active = '';
if (inputMode === 'command') {
const before = escapeHtml(commandBuffer.slice(0, commandCursorPos));
const cursorChar = commandCursorPos < commandBuffer.length ? escapeHtml(commandBuffer[commandCursorPos]) : ' ';
const after = escapeHtml(commandBuffer.slice(commandCursorPos + 1));
active = escapeHtml(PROMPT) + before + '<span class="cursor">' + cursorChar + '</span>' + after;
} else if (inputMode === 'password') {
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>';
}
terminal.innerHTML = inputMode === 'connected'
? renderConnectedScreen()
: escapeHtml(screen) + active;
terminal.scrollTop = terminal.scrollHeight;
}
function writeScreen(text) {
if (inputMode === 'connected' || connected) {
processTerminalOutput(text);
} else {
screen += stripAnsi(String(text || '')).replace(/\r\n/g, '\n').replace(/\r/g, '');
// Limitează screen la ultimele 500 de linii pentru a preveni DOM-ul enorm
const lines = screen.split('\n');
if (lines.length > 500) {
screen = lines.slice(lines.length - 500).join('\n');
}
}
render();
}
function clearScreen() {
screen = '';
if (inputMode === 'connected' || connected) {
for (let i = 0; i < termRows; i++) viewport[i] = '';
scrollback = [];
termRow = 0;
termCol = 0;
}
render();
}
function resetCommandMode() {
inputMode = 'command';
commandBuffer = '';
commandCursorPos = 0;
passwordBuffer = '';
pendingCommand = '';
connectInFlight = false;
// 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
const viewportText = scrollback.concat(viewport).join('\n').replace(/\n+$/, '');
if (viewportText.trim()) {
screen = viewportText + '\n';
}
// Resetăm viewport-ul
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
}
render();
}
function resetHistoryNavigation() {
commandHistoryIndex = -1;
commandHistoryDraft = '';
}
function rememberCommand(command) {
const value = String(command || '');
if (!value.trim()) return;
if (commandHistory[commandHistory.length - 1] !== value) {
commandHistory.push(value);
if (commandHistory.length > 200) commandHistory.shift();
}
resetHistoryNavigation();
}
function showPreviousCommand() {
if (!commandHistory.length) return;
if (commandHistoryIndex === -1) {
commandHistoryDraft = commandBuffer;
commandHistoryIndex = commandHistory.length - 1;
} else if (commandHistoryIndex > 0) {
commandHistoryIndex -= 1;
} else {
return; // deja la primul din history, nu face nimic
}
commandBuffer = commandHistory[commandHistoryIndex] || '';
commandCursorPos = commandBuffer.length;
render();
}
function showNextCommand() {
if (commandHistoryIndex === -1) return;
if (commandHistoryIndex < commandHistory.length - 1) {
commandHistoryIndex += 1;
commandBuffer = commandHistory[commandHistoryIndex] || '';
} else {
commandHistoryIndex = -1;
commandBuffer = commandHistoryDraft;
commandHistoryDraft = '';
}
commandCursorPos = commandBuffer.length;
render();
}
function cancelConnecting() {
intentionalDisconnect = true;
closeSocketQuietly();
connected = false;
connectInFlight = false;
setTerminalLive(false);
writeScreen('^C\n');
resetCommandMode();
}
function isPrintableKey(e) {
return e.key && e.key.length === 1 && !e.ctrlKey && !e.metaKey;
}
function validCommand(cmd) {
const s = String(cmd || '').trim();
if (!/^ssh\b/i.test(s)) return false;
const normalized = s.replace(/\s*@\s*/g, '@');
return /\S+@\S+/.test(normalized);
}
function showReject() {
writeScreen("Only SSH commands are allowed. Try: ssh root@1.2.3.4 or ssh -p 2222 root@1.2.3.4\n");
resetCommandMode();
}
function wsURL() {
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
return proto + '://' + window.location.host + '/ssh-terminal/ws?token=' + encodeURIComponent(TOKEN);
}
function wsURLs() {
const primary = wsURL();
const urls = [primary];
const trimmed = String(WS_FALLBACK || '').trim();
if (trimmed) {
try {
const parsed = new URL(trimmed);
if (window.location.protocol === 'https:' && parsed.protocol === 'ws:') {
parsed.protocol = 'wss:';
}
const fallback = parsed.toString() + '?token=' + encodeURIComponent(TOKEN);
if (fallback !== primary) urls.push(fallback);
} catch { }
}
return urls;
}
function connectSocketWithFallback(command, attachOnly = false) {
const candidates = wsURLs();
if (wsAttemptIndex >= candidates.length) {
// All candidates were rejected before any byte was proxied — an
// expired page token answers as a bare 1006. One reload re-runs
// the panel's launch route, which mints a fresh token
// server-side. The rt marker rides the QUERY so it survives the
// reload deterministically, and it bounds this to a single
// automatic retry per successful connection (the in-memory
// flag is cleared on 'connected'), so a persistently broken
// tunnel degrades to the explicit message below instead of a
// reload loop. The fragment keeps the session id, so after the
// reload the page re-attaches to a still-live session when one
// exists.
if (!BOOT_PARAMS.rt) {
BOOT_PARAMS.rt = true;
try {
const retryUrl = new URL(window.location.href);
retryUrl.searchParams.set('rt', '1');
// The timestamp guarantees the navigation URL differs from
// the current one even when rt was already in the query,
// so this replace always reloads the page.
retryUrl.searchParams.set('rtc', String(Date.now()));
// Rebuild the fragment with the same boot semantics the
// parent gave us: keep the session id, and keep fresh=1
// for a minted-but-never-connected session so the
// reloaded page does not attempt a doomed attach.
retryUrl.hash = BOOT_PARAMS.sid
? '#sid=' + encodeURIComponent(BOOT_PARAMS.sid) + (BOOT_PARAMS.fresh ? '&fresh=1' : '')
: '';
window.location.replace(retryUrl.toString());
} catch {
window.location.reload();
}
return;
}
if (attachOnly) {
setTerminalLive(false);
screen = '';
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
writeScreen('[adpanel] previous SSH session expired\n');
} else {
writeScreen('\n[adpanel] terminal tunnel failed after retry — if this keeps happening, close and reopen the terminal window to refresh the session token\n');
}
connectInFlight = false;
resetCommandMode();
return;
}
const url = candidates[wsAttemptIndex];
closeSocketQuietly();
socket = new WebSocket(url);
socket.onopen = () => {
if (attachOnly) {
send('attach', { sessionId: TERMINAL_SESSION_ID });
} else {
send('probe', { command: pendingCommand, sessionId: TERMINAL_SESSION_ID });
}
};
socket.onmessage = (ev) => {
let msg = null;
try { msg = JSON.parse(ev.data); } catch { return; }
if (!msg || !msg.type) return;
if (msg.type === 'error') {
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
// budget for a later genuine tunnel expiry.
BOOT_PARAMS.rt = false;
setTerminalLive(false);
screen = '';
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
writeScreen('[adpanel] previous SSH session expired\n');
} else if (msg.error) {
writeScreen(msg.error + '\n');
}
connected = false;
connectInFlight = false;
closeSocketQuietly();
resetCommandMode();
return;
}
if (msg.type === 'probe-ok') {
connectInFlight = false;
inputMode = 'password';
render();
return;
}
if (msg.type === 'connected') {
connected = true;
intentionalDisconnect = false;
setTerminalLive(true);
// 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
// leftover rt=1 in the query dies with this page (a restored
// window always builds a fresh URL from the parent).
BOOT_PARAMS.rt = false;
BOOT_PARAMS.fresh = false;
writeBootParams({ rt: false, fresh: false });
connectInFlight = false;
inputMode = 'connected';
// Inițializează viewport-ul cu dimensiunea curentă a terminalului
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
render();
return;
}
if (msg.type === 'output' && typeof msg.data === 'string') {
writeScreen(msg.data);
}
};
socket.onclose = (ev) => {
// Dacă am anulat intenționat (Ctrl+C în connecting), ignorăm onclose
if (intentionalDisconnect && !connected) {
socket = null;
return;
}
if (!connected && connectInFlight) {
wsAttemptIndex += 1;
if (wsAttemptIndex < candidates.length) {
writeScreen('[adpanel] retrying tunnel...\n');
}
// attachOnly must survive the fallback retries, and once the
// last candidate has failed this re-call lands in the
// exhaustion guard at the top of connectSocketWithFallback
// (token self-heal, final messages). Re-calling
// unconditionally is what makes that guard reachable.
connectSocketWithFallback(command, attachOnly);
return;
}
if (connected) {
writeScreen('\n[adpanel] session closed\n');
if (intentionalDisconnect) setTerminalLive(false);
} else if (connectInFlight) {
const code = Number(ev && ev.code) || 0;
const reason = String((ev && ev.reason) || '').trim();
if (reason) {
writeScreen('\n[adpanel] terminal tunnel failed (code ' + String(code) + '): ' + reason + '\n');
} else {
writeScreen('\n[adpanel] terminal tunnel failed (code ' + String(code) + ')\n');
}
} else if (inputMode === 'password') {
writeScreen('\n[adpanel] connection closed before authentication\n');
}
connected = false;
connectInFlight = false;
socket = null;
resetCommandMode();
};
socket.onerror = () => {
if (!connected && !intentionalDisconnect) writeScreen('[adpanel] connection error\n');
};
}
function send(type, payload = {}) {
if (!socket || socket.readyState !== WebSocket.OPEN) return;
socket.send(JSON.stringify(Object.assign({ type }, payload)));
}
function estimateSize() {
const w = Math.max(640, terminal.clientWidth || window.innerWidth || 1200);
const h = Math.max(320, terminal.clientHeight || window.innerHeight || 700);
const cols = Math.max(80, Math.floor((w - 24) / 8.4));
const rows = Math.max(24, Math.floor((h - 24) / 18));
return { cols, rows };
}
function closeSocketQuietly() {
if (!socket) return;
try { socket.close(); } catch { }
socket = null;
}
function startProbe(command) {
if (connectInFlight) return;
connectInFlight = true;
intentionalDisconnect = false;
wsAttemptIndex = 0;
pendingCommand = command;
passwordBuffer = '';
inputMode = 'connecting';
render();
connectSocketWithFallback(command, false);
}
function startAttach() {
// Attach only when the panel parent handed us a session id (a
// standalone page without a fragment has nothing to attach to);
// when the session is genuinely gone the server replies "terminal
// session not found" and the client already degrades gracefully to
// a fresh prompt.
if (connectInFlight || connected || !BOOT_PARAMS.sid || BOOT_PARAMS.fresh) return;
connectInFlight = true;
intentionalDisconnect = false;
wsAttemptIndex = 0;
pendingCommand = '';
passwordBuffer = '';
inputMode = 'connecting';
render();
connectSocketWithFallback('', true);
}
function sendConnectWithPassword(password) {
if (!pendingCommand) {
showReject();
return;
}
if (!socket || socket.readyState !== WebSocket.OPEN) {
writeScreen('[adpanel] terminal tunnel is not ready, retry command\n');
resetCommandMode();
return;
}
connectInFlight = true;
inputMode = 'connecting';
render();
const sz = estimateSize();
send('connect', {
sessionId: TERMINAL_SESSION_ID,
command: pendingCommand,
password,
cols: sz.cols,
rows: sz.rows,
});
}
window.addEventListener('message', (event) => {
// This page is embedded by the panel with sandbox="allow-scripts"
// (no allow-same-origin), so our own origin is opaque and the
// panel parent cannot target us with a concrete postMessage
// origin — the parent must send with targetOrigin "*". The
// unforgeable sender check is event.source: only the real parent
// window can be this frame's window.parent. Keep the sandbox
// without allow-same-origin.
if (event.source !== window.parent) return;
if (!event.data || event.data.type !== 'adpanel-ssh-terminal-close') return;
intentionalDisconnect = true;
setTerminalLive(false);
if (socket && socket.readyState === WebSocket.OPEN) {
send('disconnect', { sessionId: TERMINAL_SESSION_ID });
}
closeSocketQuietly();
connected = false;
resetCommandMode();
});
terminal.addEventListener('keydown', (e) => {
if (inputMode === 'connected') {
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
send('input', { data: '\u0003' });
return;
}
if (e.key === 'Enter') {
e.preventDefault();
send('input', { data: '\r' });
return;
}
if (e.key === 'Backspace') {
e.preventDefault();
send('input', { data: '\u007f' });
return;
}
if (e.key === 'Delete') { e.preventDefault(); send('input', { data: '\x1b[3~' }); return; }
if (e.key === 'ArrowLeft') { e.preventDefault(); send('input', { data: '\x1b[D' }); return; }
if (e.key === 'ArrowRight') { e.preventDefault(); send('input', { data: '\x1b[C' }); return; }
if (e.key === 'ArrowUp') { e.preventDefault(); send('input', { data: '\x1b[A' }); return; }
if (e.key === 'ArrowDown') { e.preventDefault(); send('input', { data: '\x1b[B' }); return; }
if (e.key === 'Home') { e.preventDefault(); send('input', { data: '\x1b[H' }); return; }
if (e.key === 'End') { e.preventDefault(); send('input', { data: '\x1b[F' }); return; }
if (e.key === 'Tab') { e.preventDefault(); send('input', { data: '\t' }); return; }
if (isPrintableKey(e)) {
e.preventDefault();
send('input', { data: e.key });
return;
}
return;
}
if (inputMode === 'connecting') {
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
cancelConnecting();
return;
}
e.preventDefault();
return;
}
if (inputMode === 'password') {
if (e.key === 'Enter') {
e.preventDefault();
writeScreen('Password: ' + '*'.repeat(passwordBuffer.length) + '\n');
if (!passwordBuffer) {
showReject();
return;
}
const pwd = passwordBuffer;
passwordBuffer = '';
sendConnectWithPassword(pwd);
return;
}
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
writeScreen('^C\n');
resetCommandMode();
return;
}
if (e.key === 'Backspace') {
e.preventDefault();
if (passwordBuffer.length) passwordBuffer = passwordBuffer.slice(0, -1);
render();
return;
}
if (isPrintableKey(e)) {
e.preventDefault();
passwordBuffer += e.key;
render();
}
return;
}
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
writeScreen('^C\n');
resetCommandMode();
return;
}
if (e.key === 'Enter') {
e.preventDefault();
const cmd = commandBuffer.trim();
rememberCommand(commandBuffer);
writeScreen(PROMPT + commandBuffer + '\n');
if (cmd === 'clear') {
commandBuffer = '';
commandCursorPos = 0;
clearScreen();
return;
}
if (!validCommand(cmd)) {
showReject();
return;
}
commandBuffer = '';
commandCursorPos = 0;
startProbe(cmd);
return;
}
if (e.key === 'Backspace') {
e.preventDefault();
resetHistoryNavigation();
if (commandCursorPos > 0) {
commandBuffer = commandBuffer.slice(0, commandCursorPos - 1) + commandBuffer.slice(commandCursorPos);
commandCursorPos--;
render();
}
return;
}
if (e.key === 'Delete') {
e.preventDefault();
resetHistoryNavigation();
if (commandCursorPos < commandBuffer.length) {
commandBuffer = commandBuffer.slice(0, commandCursorPos) + commandBuffer.slice(commandCursorPos + 1);
render();
}
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
showPreviousCommand();
return;
}
if (e.key === 'ArrowDown') {
e.preventDefault();
showNextCommand();
return;
}
if (e.key === 'ArrowLeft') {
e.preventDefault();
if (commandCursorPos > 0) {
commandCursorPos--;
render();
}
return;
}
if (e.key === 'ArrowRight') {
e.preventDefault();
if (commandCursorPos < commandBuffer.length) {
commandCursorPos++;
render();
}
return;
}
if (e.key === 'Home') {
e.preventDefault();
commandCursorPos = 0;
render();
return;
}
if (e.key === 'End') {
e.preventDefault();
commandCursorPos = commandBuffer.length;
render();
return;
}
if (e.key === 'Tab') {
e.preventDefault();
const trimmed = commandBuffer.trim();
if ('ssh'.startsWith(trimmed.toLowerCase()) && !trimmed.includes(' ')) {
resetHistoryNavigation();
commandBuffer = 'ssh ';
commandCursorPos = commandBuffer.length;
render();
}
return;
}
if (isPrintableKey(e)) {
e.preventDefault();
resetHistoryNavigation();
commandBuffer = commandBuffer.slice(0, commandCursorPos) + e.key + commandBuffer.slice(commandCursorPos);
commandCursorPos++;
render();
}
});
terminal.addEventListener('paste', (e) => {
const text = String((e.clipboardData && e.clipboardData.getData('text')) || '').replace(/\r\n/g, '\n');
if (!text) return;
e.preventDefault();
if (inputMode === 'connected') {
send('input', { data: text.replace(/\n/g, '\r') });
return;
}
if (inputMode === 'connecting') return;
const inlineText = text.replace(/[\r\n]+/g, '');
if (!inlineText) return;
if (inputMode === 'password') {
passwordBuffer += inlineText;
render();
return;
}
resetHistoryNavigation();
commandBuffer = commandBuffer.slice(0, commandCursorPos) + inlineText + commandBuffer.slice(commandCursorPos);
commandCursorPos += inlineText.length;
render();
});
terminal.addEventListener('click', () => terminal.focus());
window.addEventListener('resize', () => {
if (!connected) return;
const sz = estimateSize();
resizeViewport(sz.cols, sz.rows);
send('resize', { cols: sz.cols, rows: sz.rows });
});
window.addEventListener('load', () => {
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
render();
terminal.focus();
startAttach();
});
</script>
</body>
</html>`