package server import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "encoding/hex" "encoding/json" "errors" "net/http" "os" "strconv" "strings" "sync" "github.com/x-grk/longpolling-remote-access/internal/proto" ) // Saved SSH hosts: each user keeps their own list of hosts with the way in - // password or key - so the SSH dialog connects with one choice. The secret is // sealed with AES-256-GCM under the server's key, which lives apart from the // database (LPRA_SECRET_KEY, or a file beside the database made on first // use), and bound to its owner: a row read out of the database, or moved to // another user, opens to nobody. type savedHost struct { ID int64 `json:"id"` Label string `json:"label"` Host string `json:"host"` Port int `json:"port"` User string `json:"user"` Auth string `json:"auth"` // password, key or agent } type sshSecret struct { Password string `json:"password,omitempty"` Key string `json:"key,omitempty"` Passphrase string `json:"passphrase,omitempty"` } var ( secretKeyOnce sync.Once secretKey []byte secretKeyErr error ) // sealKey is the server's key for saved secrets. func (s *Server) sealKey() ([]byte, error) { secretKeyOnce.Do(func() { if v := strings.TrimSpace(os.Getenv("LPRA_SECRET_KEY")); v != "" { k, err := hex.DecodeString(v) if err != nil || len(k) != 32 { k, err = base64.StdEncoding.DecodeString(v) } if err != nil || len(k) != 32 { secretKeyErr = errors.New("LPRA_SECRET_KEY: нужны 32 байта (hex или base64)") return } secretKey = k return } path := s.db.path + ".key" if b, err := os.ReadFile(path); err == nil { k, err := hex.DecodeString(strings.TrimSpace(string(b))) if err != nil || len(k) != 32 { secretKeyErr = errors.New(path + ": испорчен ключ") return } secretKey = k return } k := make([]byte, 32) _, _ = rand.Read(k) if err := os.WriteFile(path, []byte(hex.EncodeToString(k)+"\n"), 0o600); err != nil { secretKeyErr = err return } secretKey = k }) return secretKey, secretKeyErr } func (s *Server) seal(owner int64, plain []byte) (string, error) { k, err := s.sealKey() if err != nil { return "", err } blk, _ := aes.NewCipher(k) g, _ := cipher.NewGCM(blk) nonce := make([]byte, g.NonceSize()) _, _ = rand.Read(nonce) out := g.Seal(nonce, nonce, plain, []byte("ssh:"+strconv.FormatInt(owner, 10))) return base64.StdEncoding.EncodeToString(out), nil } func (s *Server) open(owner int64, sealed string) ([]byte, error) { k, err := s.sealKey() if err != nil { return nil, err } b, err := base64.StdEncoding.DecodeString(sealed) blk, _ := aes.NewCipher(k) g, _ := cipher.NewGCM(blk) if err != nil || len(b) < g.NonceSize() { return nil, errors.New("испорчена запись") } return g.Open(nil, b[:g.NonceSize()], b[g.NonceSize():], []byte("ssh:"+strconv.FormatInt(owner, 10))) } func (s *Server) saveSSHHost(owner int64, h savedHost, sec sshSecret) (int64, error) { plain, _ := json.Marshal(sec) sealed, err := s.seal(owner, plain) if err != nil { return 0, err } res, err := s.db.sql.Exec(`INSERT INTO ssh_hosts (admin_id, label, host, port, user, auth, secret) VALUES (?, ?, ?, ?, ?, ?, ?)`, owner, h.Label, h.Host, h.Port, h.User, h.Auth, sealed) if err != nil { return 0, err } return res.LastInsertId() } func (s *Server) listSSHHosts(owner int64) []savedHost { rows, err := s.db.sql.Query(`SELECT id, label, host, port, user, auth FROM ssh_hosts WHERE admin_id = ? ORDER BY label, host`, owner) list := []savedHost{} if err != nil { return list } defer rows.Close() for rows.Next() { var h savedHost if rows.Scan(&h.ID, &h.Label, &h.Host, &h.Port, &h.User, &h.Auth) == nil { list = append(list, h) } } return list } // fillSaved puts the saved host t.Saved of owner - address and way in - into // t, which then goes on as if typed in. func (s *Server) fillSaved(owner int64, t *proto.SSHTarget) error { if t == nil || t.Saved == 0 { return nil } var h savedHost var sealed string err := s.db.sql.QueryRow(`SELECT host, port, user, auth, secret FROM ssh_hosts WHERE id = ? AND admin_id = ?`, t.Saved, owner). Scan(&h.Host, &h.Port, &h.User, &h.Auth, &sealed) if err != nil { return errors.New("сохранённый хост не найден") } plain, err := s.open(owner, sealed) if err != nil { return errors.New("сохранённый хост не расшифровался") } var sec sshSecret _ = json.Unmarshal(plain, &sec) *t = proto.SSHTarget{Host: h.Host, Port: h.Port, User: h.User, Password: sec.Password, Key: sec.Key, Passphrase: sec.Passphrase} return nil } // GET /api/panel/ssh/hosts - the user's saved hosts, without secrets. func (s *Server) handleSSHHosts(w http.ResponseWriter, r *http.Request) { writeJSON(w, s.listSSHHosts(s.currentAdmin(r).ID)) } // POST /api/panel/ssh/hosts - save a host: {label, host, port, user, auth, // password | key, passphrase}. func (s *Server) handleSSHHostAdd(w http.ResponseWriter, r *http.Request) { var in struct { savedHost sshSecret } if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&in); err != nil { writeJSON(w, map[string]any{"ok": false, "error": "плохой запрос"}) return } h := in.savedHost h.Host, h.User, h.Label = strings.TrimSpace(h.Host), strings.TrimSpace(h.User), strings.TrimSpace(h.Label) if h.Port == 0 { h.Port = 22 } if h.Host == "" || h.User == "" || h.Port < 1 || h.Port > 65535 || strings.ContainsAny(h.Host+h.User, " \t\r\n/") { writeJSON(w, map[string]any{"ok": false, "error": "нужны хост, порт и пользователь"}) return } if h.Label == "" { h.Label = h.User + "@" + h.Host } sec := in.sshSecret switch h.Auth { case "key": sec.Password = "" case "agent": sec = sshSecret{} default: h.Auth = "password" sec.Key, sec.Passphrase = "", "" } id, err := s.saveSSHHost(s.currentAdmin(r).ID, h, sec) if err != nil { writeJSON(w, map[string]any{"ok": false, "error": err.Error()}) return } writeJSON(w, map[string]any{"ok": true, "id": id}) } // POST /api/panel/ssh/hosts/{hid}/delete func (s *Server) handleSSHHostDelete(w http.ResponseWriter, r *http.Request) { id, _ := strconv.ParseInt(r.PathValue("hid"), 10, 64) _, _ = s.db.sql.Exec(`DELETE FROM ssh_hosts WHERE id = ? AND admin_id = ?`, id, s.currentAdmin(r).ID) writeJSON(w, map[string]any{"ok": true}) }