package main import ( "context" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "html" "io" "log" "net" "net/http" "net/url" "os" "path/filepath" "strconv" "strings" "sync" "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 } const terminalResumeGrace = 15 * time.Minute const terminalIdleTimeout = 20 * time.Minute 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" } bind = "0.0.0.0:" + 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"))), } 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)) 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") cspConnect := "connect-src " + websocketConnectSrc(cfg.WSOrigin) + ";" w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+cspConnect+" img-src 'self' data:;") page := strings.ReplaceAll(indexHTML, "__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)) 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 := 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 := 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, 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 } stdout, _ := session.StdoutPipe() stderr, _ := session.StderrPipe() if err := session.Shell(); err != nil { _ = client.Close() _ = session.Close() _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "failed to start remote shell: " + sanitizeReason(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" } 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 } func probeSSHReachability(target sshTarget, timeout time.Duration) error { addr := net.JoinHostPort(target.Host, strconv.Itoa(target.Port)) d := net.Dialer{Timeout: timeout} conn, err := d.Dial("tcp", addr) if err != nil { return err } _ = conn.Close() return nil } // knownHostsMu serializes read/modify/write access to the on-disk TOFU store so // concurrent terminal sessions cannot corrupt it or race on first-use pinning. var knownHostsMu sync.Mutex // 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[:]) } // 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. type knownHostsStore struct { Pins map[string]string `json:"pins"` Global map[string][]string `json:"global"` } func userHostKey(userID, hostport string) string { return strings.TrimSpace(userID) + "\x00" + strings.ToLower(strings.TrimSpace(hostport)) } func loadKnownHosts(path string) knownHostsStore { st := knownHostsStore{Pins: map[string]string{}, Global: map[string][]string{}} b, err := os.ReadFile(path) if err != nil || len(b) == 0 { return st } _ = json.Unmarshal(b, &st) if st.Pins == nil { st.Pins = map[string]string{} } if st.Global == nil { st.Global = map[string][]string{} } return st } func saveKnownHosts(path string, st knownHostsStore) error { if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return err } b, err := json.MarshalIndent(st, "", " ") if err != nil { return err } tmp := path + ".tmp" if err := os.WriteFile(tmp, b, 0o600); err != nil { return err } return 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. // // 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) knownHostsMu.Lock() defer knownHostsMu.Unlock() st := loadKnownHosts(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. st.Pins[uhk] = fp if !seenThis { st.Global[host] = append(seen, fp) } if err := saveKnownHosts(storePath, st); err != nil { return fmt.Errorf("host key store unavailable: %w", err) } return nil } } func openSSHSession(target sshTarget, password, knownHostsStore, userID string, cols, rows int) (*ssh.Client, *ssh.Session, io.WriteCloser, 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)) client, err := ssh.Dial("tcp", addr, config) if err != nil { return nil, nil, nil, err } session, err := client.NewSession() if err != nil { client.Close() return nil, nil, nil, err } stdin, err := session.StdinPipe() if err != nil { session.Close() client.Close() return 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, err } return client, session, stdin, nil } func parseSSHCommand(input string) (sshTarget, error) { trimmed := strings.TrimSpace(input) parts := strings.Fields(trimmed) if len(parts) < 2 || !strings.EqualFold(parts[0], "ssh") { return sshTarget{}, errors.New("only ssh user@host -p is allowed") } args := parts[1:] dest := "" cliPort := 0 for i := 0; i < len(args); i++ { arg := strings.TrimSpace(args[i]) if arg == "" { continue } // Tolerate accidental spacing around '@', e.g. "root@ 1.2.3.4" or "root @1.2.3.4". if dest != "" { if strings.HasSuffix(dest, "@") && !strings.HasPrefix(arg, "-") { dest += arg continue } if strings.HasPrefix(arg, "@") && !strings.Contains(dest, "@") { dest += arg continue } } if strings.HasPrefix(arg, "-p") { portText := "" if arg == "-p" { if i+1 >= len(args) { return sshTarget{}, errors.New("invalid port") } i++ portText = strings.TrimSpace(args[i]) } else { portText = strings.TrimSpace(strings.TrimPrefix(arg, "-p")) } n, err := strconv.Atoi(portText) if err != nil || n < 1 || n > 65535 { return sshTarget{}, errors.New("invalid port") } cliPort = n continue } if strings.HasPrefix(arg, "-") { return sshTarget{}, errors.New("only -p is accepted") } if dest != "" { return sshTarget{}, errors.New("only one ssh destination is allowed") } dest = arg } if dest == "" { return sshTarget{}, errors.New("missing ssh destination") } at := strings.Index(dest, "@") if at <= 0 || at == len(dest)-1 { return sshTarget{}, errors.New("invalid ssh destination") } user := dest[:at] host, inlinePort, err := splitSSHHostPort(dest[at+1:]) if err != nil { return sshTarget{}, err } if !isSafeSSHUser(user) || !isSafeSSHHost(host) { return sshTarget{}, errors.New("invalid user or host") } port := 22 if inlinePort > 0 { port = inlinePort } if cliPort > 0 { port = cliPort } return sshTarget{User: user, Host: host, Port: port}, nil } func splitSSHHostPort(raw string) (string, int, error) { hostPart := strings.TrimSpace(raw) if hostPart == "" { return "", 0, errors.New("invalid ssh destination") } if strings.HasPrefix(hostPart, "[") { closeIdx := strings.Index(hostPart, "]") if closeIdx <= 1 { return "", 0, errors.New("invalid user or host") } host := hostPart[1:closeIdx] rest := strings.TrimSpace(hostPart[closeIdx+1:]) if rest == "" { return host, 0, nil } if !strings.HasPrefix(rest, ":") { return "", 0, errors.New("invalid user or host") } portText := strings.TrimSpace(rest[1:]) n, err := strconv.Atoi(portText) if err != nil || n < 1 || n > 65535 { return "", 0, errors.New("invalid port") } return host, n, nil } lastColon := strings.LastIndex(hostPart, ":") if lastColon > 0 && lastColon < len(hostPart)-1 { portText := hostPart[lastColon+1:] if isDecimalDigits(portText) { host := hostPart[:lastColon] if strings.Count(host, ":") == 0 { n, err := strconv.Atoi(portText) if err != nil || n < 1 || n > 65535 { return "", 0, errors.New("invalid port") } return host, n, nil } } } return hostPart, 0, nil } func isDecimalDigits(input string) bool { if input == "" { return false } for _, c := range input { if c < '0' || c > '9' { return false } } return true } func isSafeSSHUser(user string) bool { if len(user) < 1 || len(user) > 32 { return false } for _, c := range user { if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.' { continue } return false } return true } func isSafeSSHHost(host string) bool { if len(host) < 1 || len(host) > 253 { return false } for _, c := range host { if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == ':' || c == '-' { continue } return false } return true } func verifyToken(secret []byte, token string, requestIP string) (tokenPayload, error) { parts := strings.Split(token, ".") if len(parts) != 2 { return tokenPayload{}, errors.New("invalid token format") } payloadB64 := parts[0] sigRaw, err := decodeB64URL(parts[1]) if err != nil { return tokenPayload{}, errors.New("invalid token signature") } mac := hmac.New(sha256.New, secret) _, _ = mac.Write([]byte(payloadB64)) expected := mac.Sum(nil) if !hmac.Equal(expected, sigRaw) { return tokenPayload{}, errors.New("token signature mismatch") } payloadRaw, err := decodeB64URL(payloadB64) if err != nil { return tokenPayload{}, errors.New("invalid token payload") } var payload tokenPayload if err := json.Unmarshal(payloadRaw, &payload); err != nil { return tokenPayload{}, errors.New("invalid token json") } if payload.ExpMS < time.Now().UnixMilli() { return tokenPayload{}, errors.New("token expired") } 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() } func requestIP(r *http.Request) string { if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" { return normalizeIP(xff) } if xr := strings.TrimSpace(r.Header.Get("X-Real-IP")); xr != "" { return normalizeIP(xr) } return normalizeIP(r.RemoteAddr) } func decodeB64URL(s string) ([]byte, error) { s = strings.TrimSpace(s) if s == "" { return nil, errors.New("empty base64url") } if b, err := base64.RawURLEncoding.DecodeString(s); err == nil { return b, nil } if m := len(s) % 4; m != 0 { s += strings.Repeat("=", 4-m) } if b, err := base64.URLEncoding.DecodeString(s); err == nil { return b, nil } std := strings.ReplaceAll(strings.ReplaceAll(s, "-", "+"), "_", "/") return base64.StdEncoding.DecodeString(std) } func loadDotEnv(path string) error { b, err := os.ReadFile(path) if err != nil { return err } lines := strings.Split(strings.ReplaceAll(string(b), "\r\n", "\n"), "\n") for _, line := range lines { line = strings.TrimSpace(line) if line == "" || strings.HasPrefix(line, "#") { continue } eq := strings.IndexByte(line, '=') if eq <= 0 { continue } k := strings.TrimSpace(line[:eq]) v := strings.TrimSpace(line[eq+1:]) if len(v) >= 2 { if (strings.HasPrefix(v, "\"") && strings.HasSuffix(v, "\"")) || (strings.HasPrefix(v, "'") && strings.HasSuffix(v, "'")) { v = v[1 : len(v)-1] } } if k != "" { if _, exists := os.LookupEnv(k); exists { continue } _ = os.Setenv(k, v) } } return nil } const indexHTML = ` ADPanel SSH Terminal
`