diff --git a/README.md b/README.md index a576b32..989cf1e 100644 --- a/README.md +++ b/README.md @@ -225,3 +225,7 @@ GitHub Actions verifies tests, Go formatting, types, binary builds, and Docker b ## License [MIT](LICENSE) + +## RDP remote desktop (V1) + +IronRDP WASM adds NLA remote desktop sessions, keyboard/mouse input, fullscreen, dynamic resize and manual clipboard transfer while retaining single-binary deployment. Passwords are entered per connection and are never saved. See the [RDP setup and validation guide](docs/rdp.md) for certificate configuration and compatibility limits. diff --git a/README_CN.md b/README_CN.md index 2e39a69..bc403b1 100644 --- a/README_CN.md +++ b/README_CN.md @@ -221,3 +221,7 @@ GitHub Actions 检查前后端测试、Go 格式、类型、构建及 Docker 构 - JWT 有效期 24 小时。WebSocket 仍通过查询参数认证,应用访问日志不记录查询参数;**反向代理也必须过滤 token,或不要记录终端请求的完整 URL**。 - 应用按同源方式使用,不开放通配 CORS。请使用 HTTPS,不要把尚未初始化的实例直接暴露到公网。 - 当前仍是共享管理员的服务器管理工具,不提供多租户隔离;SFTP 可访问范围由远端 SSH 账号权限决定。 + +## RDP 远程桌面(第一版) + +新增 IronRDP WASM 远程桌面,保持单二进制部署,密码每次连接时输入、不保存。配置、证书指纹和兼容性验收说明见 [RDP 使用文档](docs/rdp.md)。 diff --git a/docs/rdp.md b/docs/rdp.md new file mode 100644 index 0000000..b207a7a --- /dev/null +++ b/docs/rdp.md @@ -0,0 +1,46 @@ +# RDP 第一版 + +OpsUp 使用 IronRDP WASM 在浏览器内运行远程桌面,Go 内置 RDCleanPath 网关负责目标连接、X.224 协商、TLS 和 WebSocket 转发。无需 guacd、FreeRDP 或额外守护进程;前端及 WASM 随 Go 二进制内嵌。 + +## 使用 + +1. 使用 HTTPS 访问 OpsUp(本机 localhost/127.0.0.1 开发调试除外)。反向代理需支持 `/api/rdp/` 的 WebSocket Upgrade,并设置足够长的会话超时。 +2. 添加服务器,连接类型选择 RDP,填写主机、端口(默认 3389)、用户名和可选域。Windows 目标须开启远程桌面并支持 NLA,且允许该账户远程登录。 +3. 若目标使用受系统信任的 CA 证书,证书指纹可留空,后端会验证证书链和主机名。自签名证书须填写从独立可信渠道取得的 **叶证书 SHA256 指纹**,64 位十六进制,可用冒号分隔。证书更新后需重新核验指纹。没有“忽略证书错误”选项。 +4. 点击服务器,在 RDP 标签页中输入本次登录密码。关闭标签页或退出 OpsUp 会释放对应浏览器会话。 +5. 工具栏提供断开、全屏、Ctrl+Alt+Del,以及手动双向剪贴板操作。浏览器可能要求剪贴板权限。调整窗口或切换回标签页时请求更新远程分辨率;目标不支持动态分辨率时仍可按画面比例缩放。 + +从 Windows 可信控制台获取正在使用的 RDP 证书 SHA256 指纹,可在 PowerShell 中运行: + +```powershell +$rdpSettings = Get-CimInstance -Namespace root/cimv2/TerminalServices -ClassName Win32_TSGeneralSetting -Filter "TerminalName='RDP-tcp'" +$rdpCertificate = Get-ChildItem 'Cert:\LocalMachine\Remote Desktop', 'Cert:\LocalMachine\My' | Where-Object Thumbprint -eq $rdpSettings.SSLCertificateSHA1Hash | Select-Object -First 1 +if (-not $rdpCertificate) { throw '未找到 RDP 使用的证书,请在证书管理器中核对' } +$rdpHasher = [System.Security.Cryptography.SHA256]::Create() +try { ([BitConverter]::ToString($rdpHasher.ComputeHash($rdpCertificate.RawData))).Replace('-', '').ToLowerInvariant() } finally { $rdpHasher.Dispose() } +``` + +Windows 设置中的 SHA1 thumbprint 仅用于定位证书,不能直接填入 OpsUp 的 SHA256 字段。 + +## 范围与凭据 + +- 支持多个不同服务器的 RDP 标签页,以及与 SSH 标签页并存;每个桌面运行在独立同源 iframe 中,避免上游组件全局状态和剪贴板互相干扰。 +- 登录密码只在浏览器会话内存中使用,不提交给服务器管理 API,不存 SQLite、localStorage 或日志。浏览器仍需接触密码,Go TLS 网关仍处于受信任会话链路中。 +- JWT 在 RDCleanPath 首帧中传输,不放入 URL。后端先验证 JWT,再按服务器 ID 查询目标;客户端提供的 destination 不决定实际拨号地址。 +- TLS 最低为 1.2,并要求 NLA;不支持旧版纯 RDP 安全模式。 +- RDP 记录拒绝保存密码、SSH 私钥、密钥复用、SSH 指纹和跳板机设置。SSH 转为 RDP 会清除原凭据。旧数据库记录迁移后仍为 SSH。 +- 不提供音频、打印机、磁盘映射、文件传输、USB、SSH 跳板或 Kerberos KDC 代理配置。域名字段可用于 NTLM/NLA,不代表所有仅 Kerberos 的域环境均可连接。 +- 剪贴板采用用户主动操作,不在后台自动同步。RDP 目标不显示 SFTP 功能。 + +## 构建与验证 + +构建命令不变:`cd ui && npm ci && npm run build`,随后在仓库根目录执行 `CGO_ENABLED=1 go build .`。Vite 同时生成 `index.html` 和 `rdp.html`。依赖锁定为 `@devolutions/iron-remote-desktop@0.11.0`、`@devolutions/iron-remote-desktop-rdp@0.7.0`(MIT OR Apache-2.0)。WASM 随 npm 包嵌入 JS,首次打开 RDP 时加载约 6 MB 未压缩资源;SSH 页面不加载该资源。 + +自动化覆盖 DER 线格式、NLA 要求、证书验证、无效 JWT、跨源升级拒绝、保存目标绑定、TLS 双向转发、断线资源回收、迁移与凭据清除、表单和 iframe 消息来源校验。 + +发布前仍需真实 Windows 验收:Windows 10/11 和 Server 2016/2019/2022/2025 的 NLA 登录、错误密码、键鼠、中文剪贴板、全屏/缩放、多标签切换、断线重连、证书轮换及长时间空闲。自动化中的模拟 TLS 服务器不等于完整 Windows RDP 兼容性测试。 + +上游协议和客户端参考: + +- https://github.com/Devolutions/IronRDP/tree/master/crates/ironrdp-rdcleanpath +- https://github.com/Devolutions/IronRDP/tree/master/web-client/iron-remote-desktop diff --git a/internal/api/connection.go b/internal/api/connection.go index 23e8df1..9e2b3df 100644 --- a/internal/api/connection.go +++ b/internal/api/connection.go @@ -15,8 +15,8 @@ import ( func loadConnectionServer(ctx context.Context, db *sql.DB, id int64) (*models.Server, error) { var server models.Server err := db.QueryRowContext(ctx, - `SELECT id, host, port, username, auth_type, host_key, private_key, password, jump_server_id FROM servers WHERE id = ?`, id, - ).Scan(&server.ID, &server.Host, &server.Port, &server.Username, &server.AuthType, &server.HostKey, &server.PrivateKey, &server.Password, &server.JumpServerID) + `SELECT id, host, port, username, auth_type, host_key, private_key, password, jump_server_id, protocol FROM servers WHERE id = ?`, id, + ).Scan(&server.ID, &server.Host, &server.Port, &server.Username, &server.AuthType, &server.HostKey, &server.PrivateKey, &server.Password, &server.JumpServerID, &server.Protocol) if err == sql.ErrNoRows { return nil, nil } @@ -27,6 +27,9 @@ func loadConnectionServer(ctx context.Context, db *sql.DB, id int64) (*models.Se } func connectionConfig(server *models.Server, encKey string) (sshclient.Config, error) { + if server.Protocol == "rdp" { + return sshclient.Config{}, fmt.Errorf("RDP servers do not support SSH or SFTP") + } cfg := sshclient.Config{Host: server.Host, Port: server.Port, Username: server.Username, AuthType: server.AuthType, HostKey: server.HostKey} var err error if server.PrivateKey != "" { diff --git a/internal/api/connection_db_test.go b/internal/api/connection_db_test.go index a3ade6a..7c779a9 100644 --- a/internal/api/connection_db_test.go +++ b/internal/api/connection_db_test.go @@ -20,7 +20,7 @@ func connectionTestDB(t *testing.T) *sql.DB { } db.SetMaxOpenConns(1) t.Cleanup(func() { _ = db.Close() }) - _, err = db.Exec(`CREATE TABLE servers (id INTEGER PRIMARY KEY, host TEXT NOT NULL DEFAULT '127.0.0.1', port INTEGER NOT NULL DEFAULT 22, username TEXT NOT NULL DEFAULT 'test', auth_type TEXT NOT NULL DEFAULT 'password', host_key TEXT NOT NULL DEFAULT '', private_key TEXT NOT NULL DEFAULT '', password TEXT NOT NULL DEFAULT '', jump_server_id INTEGER)`) + _, err = db.Exec(`CREATE TABLE servers (id INTEGER PRIMARY KEY, host TEXT NOT NULL DEFAULT '127.0.0.1', port INTEGER NOT NULL DEFAULT 22, username TEXT NOT NULL DEFAULT 'test', auth_type TEXT NOT NULL DEFAULT 'password', host_key TEXT NOT NULL DEFAULT '', private_key TEXT NOT NULL DEFAULT '', password TEXT NOT NULL DEFAULT '', jump_server_id INTEGER, protocol TEXT NOT NULL DEFAULT 'ssh')`) if err != nil { t.Fatal(err) } diff --git a/internal/api/rdp_handler.go b/internal/api/rdp_handler.go new file mode 100644 index 0000000..d7fd790 --- /dev/null +++ b/internal/api/rdp_handler.go @@ -0,0 +1,243 @@ +package api + +import ( + "bytes" + "context" + "crypto/sha256" + "crypto/subtle" + "crypto/tls" + "encoding/asn1" + "encoding/binary" + "encoding/hex" + "fmt" + "io" + "net" + "net/http" + "strconv" + "time" + + "github.com/azzliang6/opsup/internal/auth" + "github.com/azzliang6/opsup/internal/models" + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" +) + +// RDCleanPath v1 uses DER with EXPLICIT context-specific fields. The browser +// performs CredSSP; this gateway handles X.224 and the target TLS transport. +type rdpRequest struct { + Version int `asn1:"explicit,tag:0"` + Destination string `asn1:"explicit,tag:2,utf8"` + ProxyAuth string `asn1:"explicit,tag:3,utf8"` + X224 []byte `asn1:"explicit,tag:6"` +} +type rdpResponse struct { + Version int `asn1:"explicit,tag:0"` + X224 []byte `asn1:"explicit,tag:6"` + Certificates [][]byte `asn1:"explicit,tag:7"` + Address string `asn1:"explicit,tag:9,utf8"` +} + +func parseRDPRequest(data []byte) (rdpRequest, error) { + var req rdpRequest + rest, err := asn1.Unmarshal(data, &req) + if err != nil || len(rest) != 0 || req.Version != 3390 || req.ProxyAuth == "" { + return req, fmt.Errorf("invalid RDCleanPath request") + } + // Unmarshal permits trailing SEQUENCE fields: canonical re-encoding rejects + // them, as well as unsupported server_auth / PCB / VMConnect extensions. + canonical, err := asn1.Marshal(req) + if err != nil || string(canonical) != string(data) { + return req, fmt.Errorf("unsupported RDCleanPath fields") + } + p := req.X224 + if len(p) < 19 || len(p) > 4096 || p[0] != 3 || p[1] != 0 || int(binary.BigEndian.Uint16(p[2:4])) != len(p) || int(p[4])+5 != len(p) || p[5] != 0xe0 { + return req, fmt.Errorf("invalid X.224 request") + } + n := p[len(p)-8:] + if n[0] != 1 || binary.LittleEndian.Uint16(n[2:4]) != 8 || binary.LittleEndian.Uint32(n[4:])&2 == 0 { + return req, fmt.Errorf("RDP V1 requires NLA") + } + return req, nil +} + +func rdpTLSConfig(server *models.Server) (*tls.Config, error) { + cfg := &tls.Config{MinVersion: tls.VersionTLS12, ServerName: server.Host} + if server.RDPCertFingerprint == "" { + return cfg, nil + } + expected, err := hex.DecodeString(server.RDPCertFingerprint) + if err != nil || len(expected) != sha256.Size { + return nil, fmt.Errorf("invalid certificate pin") + } + // Explicit pin validation replaces PKI verification for self-signed hosts. + cfg.InsecureSkipVerify = true + cfg.VerifyConnection = func(cs tls.ConnectionState) error { + if len(cs.PeerCertificates) == 0 { + return fmt.Errorf("missing RDP certificate") + } + actual := sha256.Sum256(cs.PeerCertificates[0].Raw) + if subtle.ConstantTimeCompare(expected, actual[:]) != 1 { + return fmt.Errorf("RDP certificate fingerprint mismatch") + } + return nil + } + return cfg, nil +} + +func negotiateRDP(ctx context.Context, raw net.Conn, request []byte, cfg *tls.Config) (*tls.Conn, []byte, error) { + _ = raw.SetDeadline(time.Now().Add(15 * time.Second)) + if _, err := io.Copy(raw, bytes.NewReader(request)); err != nil { + return nil, nil, err + } + header := make([]byte, 4) + if _, err := io.ReadFull(raw, header); err != nil { + return nil, nil, err + } + size := int(binary.BigEndian.Uint16(header[2:])) + if header[0] != 3 || header[1] != 0 || size != 19 { + return nil, nil, fmt.Errorf("invalid RDP negotiation response") + } + response := make([]byte, size) + copy(response, header) + if _, err := io.ReadFull(raw, response[4:]); err != nil { + return nil, nil, err + } + selected := binary.LittleEndian.Uint32(response[15:19]) + if response[4] != 14 || response[5] != 0xd0 || response[11] != 2 || binary.LittleEndian.Uint16(response[13:15]) != 8 || (selected != 2 && selected != 8) { + return nil, nil, fmt.Errorf("server must support TLS with NLA") + } + secured := tls.Client(raw, cfg) + if err := secured.HandshakeContext(ctx); err != nil { + return nil, nil, fmt.Errorf("RDP TLS certificate or handshake failed: %w", err) + } + _ = secured.SetDeadline(time.Time{}) + return secured, response, nil +} + +func RDPHandler(cfg AppConfig) gin.HandlerFunc { + return func(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("serverId"), 10, 64) + if err != nil || id <= 0 { + c.AbortWithStatus(http.StatusBadRequest) + return + } + ws, err := upgrader.Upgrade(c.Writer, c.Request, nil) + if err != nil { + return + } + defer ws.Close() + fail := func(reason string) { + _ = ws.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.ClosePolicyViolation, reason), time.Now().Add(wsWriteTimeout)) + } + ws.SetReadLimit(64 * 1024) + _ = ws.SetReadDeadline(time.Now().Add(10 * time.Second)) + kind, data, err := ws.ReadMessage() + if err != nil || kind != websocket.BinaryMessage { + fail("Expected RDCleanPath binary handshake") + return + } + req, err := parseRDPRequest(data) + if err != nil { + fail("Invalid RDCleanPath handshake") + return + } + if _, err := auth.ValidateToken(req.ProxyAuth, cfg.JWTSecret); err != nil { + fail("Authentication required") + return + } + server, err := models.GetServer(getDB(c), id) + if err != nil || server == nil || server.Protocol != "rdp" || server.JumpServerID != nil { + fail("RDP server unavailable") + return + } + // Never use the client-supplied destination for dialing. Authorization binds + // the route to a managed record. Credentials are never accepted or persisted. + address := net.JoinHostPort(server.Host, strconv.Itoa(server.Port)) + tlsCfg, err := rdpTLSConfig(server) + if err != nil { + fail("Invalid RDP certificate configuration") + return + } + ctx, cancel := context.WithCancel(c.Request.Context()) + defer cancel() + raw, err := (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, "tcp", address) + if err != nil { + fail("RDP server unreachable") + return + } + defer raw.Close() + stop := context.AfterFunc(ctx, func() { _ = raw.Close(); _ = ws.Close() }) + defer stop() + conn, x224, err := negotiateRDP(ctx, raw, req.X224, tlsCfg) + if err != nil { + fail("RDP negotiation or certificate verification failed") + return + } + defer conn.Close() + certs := make([][]byte, 0) + for _, cert := range conn.ConnectionState().PeerCertificates { + certs = append(certs, cert.Raw) + } + host, _, _ := net.SplitHostPort(raw.RemoteAddr().String()) + response, err := asn1.Marshal(rdpResponse{3390, x224, certs, host}) + if err != nil { + return + } + writer := &wsWriter{conn: ws} + if err := writer.write(websocket.BinaryMessage, response); err != nil { + return + } + relayRDP(ctx, cancel, ws, conn, writer) + } +} + +func relayRDP(ctx context.Context, cancel context.CancelFunc, ws *websocket.Conn, conn net.Conn, writer *wsWriter) { + ws.SetReadLimit(4 * 1024 * 1024) + _ = ws.SetReadDeadline(time.Now().Add(60 * time.Second)) + ws.SetPongHandler(func(string) error { return ws.SetReadDeadline(time.Now().Add(60 * time.Second)) }) + done := make(chan struct{}) + go func() { + defer close(done) + defer cancel() + for { + kind, data, err := ws.ReadMessage() + if err != nil || kind != websocket.BinaryMessage { + return + } + _ = conn.SetWriteDeadline(time.Now().Add(15 * time.Second)) + if _, err := io.Copy(conn, bytes.NewReader(data)); err != nil { + return + } + } + }() + pingDone := make(chan struct{}) + go func() { + defer close(pingDone) + ticker := time.NewTicker(15 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if writer.write(websocket.PingMessage, nil) != nil { + cancel() + return + } + } + } + }() + defer func() { cancel(); _ = conn.Close(); _ = ws.Close(); <-done; <-pingDone }() + buffer := make([]byte, 64*1024) + for { + n, err := conn.Read(buffer) + if n > 0 { + if writer.write(websocket.BinaryMessage, buffer[:n]) != nil { + return + } + } + if err != nil { + return + } + } +} diff --git a/internal/api/rdp_handler_test.go b/internal/api/rdp_handler_test.go new file mode 100644 index 0000000..32ed5e9 --- /dev/null +++ b/internal/api/rdp_handler_test.go @@ -0,0 +1,258 @@ +package api + +import ( + "bytes" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/asn1" + "encoding/hex" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/azzliang6/opsup/internal/auth" + "github.com/azzliang6/opsup/internal/models" + "github.com/gorilla/websocket" +) + +var testX224 = []byte{3, 0, 0, 19, 14, 0xe0, 0, 0, 0, 0, 0, 1, 0, 8, 0, 3, 0, 0, 0} + +func TestRDPRequestStrictParsing(t *testing.T) { + req := rdpRequest{3390, "ignored:3389", "token", testX224} + good, err := asn1.Marshal(req) + if err != nil { + t.Fatal(err) + } + if _, err := parseRDPRequest(good); err != nil { + t.Fatal(err) + } + for _, data := range [][]byte{nil, good[:len(good)-1], append(append([]byte{}, good...), 0)} { + if _, err := parseRDPRequest(data); err == nil { + t.Fatal("accepted malformed request") + } + } + req.X224 = append([]byte{}, testX224...) + req.X224[15] = 1 + bad, _ := asn1.Marshal(req) + if _, err := parseRDPRequest(bad); err == nil { + t.Fatal("accepted non-NLA request") + } + // Unknown trailing sequence fields must not be silently ignored by Go ASN.1. + bad = append(append([]byte{}, good...), 0xa9, 3, 0x0c, 1, 'x') + bad[1] += 5 + if _, err := parseRDPRequest(bad); err == nil { + t.Fatal("accepted unsupported extension") + } +} + +func TestRDPResponseUpstreamDER(t *testing.T) { + // Wire fixture from IronRDP's rdcleanpath conformance test. + p := []byte{0xde, 0xad, 0xbe, 0xff} + encoded, err := asn1.Marshal(rdpResponse{3390, p, [][]byte{p, p, p}, "192.168.7.95"}) + if err != nil { + t.Fatal(err) + } + expected := "3034a00402020d3ea6060404deadbeffa71430120404deadbeff0404deadbeff0404deadbeffa90e0c0c3139322e3136382e372e3935" + if hex.EncodeToString(encoded) != expected { + t.Fatalf("incompatible DER: %x", encoded) + } +} + +func TestRDPCertificatePolicy(t *testing.T) { + cert := &x509.Certificate{Raw: []byte("certificate")} + sum := sha256.Sum256(cert.Raw) + cfg, err := rdpTLSConfig(&models.Server{Host: "host"}) + if err != nil || cfg.InsecureSkipVerify || cfg.ServerName != "host" { + t.Fatal("PKI validation must be the default") + } + cfg, err = rdpTLSConfig(&models.Server{Host: "host", RDPCertFingerprint: hex.EncodeToString(sum[:])}) + if err != nil { + t.Fatal(err) + } + if err := cfg.VerifyConnection(tls.ConnectionState{PeerCertificates: []*x509.Certificate{cert}}); err != nil { + t.Fatal(err) + } + if err := cfg.VerifyConnection(tls.ConnectionState{PeerCertificates: []*x509.Certificate{{Raw: []byte("other")}}}); err == nil { + t.Fatal("accepted mismatching pin") + } + if err := cfg.VerifyConnection(tls.ConnectionState{}); err == nil { + t.Fatal("accepted no certificate") + } +} + +func TestRDPServerAPINeverStoresCredentials(t *testing.T) { + r, cfg := securityRouter(t) + token, _, _ := auth.GenerateToken(1, "admin", cfg.JWTSecret) + body := `{"protocol":"rdp","name":"Windows","host":"localhost","username":"Administrator","rdp_domain":"EXAMPLE"}` + res := performRequest(r, "POST", "/api/servers", body, token) + if res.Code != 201 { + t.Fatalf("%d %s", res.Code, res.Body) + } + s, err := models.GetServer(cfg.DB, 1) + if err != nil || s.Port != 3389 || s.Protocol != "rdp" || s.RDPDomain != "EXAMPLE" || s.Password != "" || s.PrivateKey != "" { + t.Fatalf("unexpected record: %+v %v", s, err) + } + for _, extra := range []string{`"password":"secret"`, `"private_key":"key"`, `"copy_key_from":1`, `"jump_server_id":1`, `"rdp_cert_fingerprint":"bad"`, `"port":65536`} { + res = performRequest(r, "POST", "/api/servers", strings.TrimSuffix(body, "}")+","+extra+"}", token) + if res.Code != 400 { + t.Fatalf("accepted %s: %d", extra, res.Code) + } + } + if _, err := connectionConfig(s, cfg.EncryptionKey); err == nil { + t.Fatal("RDP allowed through SSH/SFTP") + } + // Switching a saved SSH record to RDP must delete old encrypted credentials. + if _, err := cfg.DB.Exec("UPDATE servers SET protocol='ssh', password='old', private_key='old' WHERE id=1"); err != nil { + t.Fatal(err) + } + res = performRequest(r, "PUT", "/api/servers/1", body, token) + if res.Code != 200 { + t.Fatalf("%d %s", res.Code, res.Body) + } + s, _ = models.GetServer(cfg.DB, 1) + if s.Password != "" || s.PrivateKey != "" { + t.Fatal("retained credentials after protocol switch") + } +} + +func TestRDPEndToEndGateway(t *testing.T) { + r, cfg := securityRouter(t) + // Reuse httptest's self-signed certificate in a minimal RDP TLS peer. + certServer := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + certificate := certServer.TLS.Certificates[0] + certServer.Close() + hash := sha256.Sum256(certificate.Certificate[0]) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + peerDone := make(chan error, 1) + go func() { + raw, err := listener.Accept() + if err != nil { + peerDone <- err + return + } + defer raw.Close() + _ = raw.SetDeadline(time.Now().Add(5 * time.Second)) + request := make([]byte, len(testX224)) + if _, err = io.ReadFull(raw, request); err != nil { + peerDone <- err + return + } + if !bytes.Equal(request, testX224) { + peerDone <- io.ErrUnexpectedEOF + return + } + response := append([]byte{}, testX224...) + response[5] = 0xd0 + response[11] = 2 + response[15] = 2 + if _, err = raw.Write(response); err != nil { + peerDone <- err + return + } + secured := tls.Server(raw, &tls.Config{Certificates: []tls.Certificate{certificate}, MinVersion: tls.VersionTLS12}) + if err = secured.Handshake(); err != nil { + peerDone <- err + return + } + data := make([]byte, 4) + if _, err = io.ReadFull(secured, data); err == nil { + _, err = secured.Write(data) + } + if err != nil { + peerDone <- err + return + } + // The gateway must release the target when its browser socket closes. + _, err = secured.Read(data) + if err == nil { + peerDone <- io.ErrNoProgress + return + } + if timeout, ok := err.(net.Error); ok && timeout.Timeout() { + peerDone <- err + return + } + peerDone <- nil + }() + host, port, _ := net.SplitHostPort(listener.Addr().String()) + p, _ := strconv.Atoi(port) + s := &models.Server{Name: "RDP", Host: host, Port: p, Username: "admin", Protocol: "rdp", RDPCertFingerprint: hex.EncodeToString(hash[:])} + if err := models.CreateServer(cfg.DB, s); err != nil { + t.Fatal(err) + } + httpServer := httptest.NewServer(r) + defer httpServer.Close() + url := "ws" + strings.TrimPrefix(httpServer.URL, "http") + "/api/rdp/" + strconv.FormatInt(s.ID, 10) + // Reject cross-origin upgrades before opening a target connection. + ws, res, err := websocket.DefaultDialer.Dial(url, http.Header{"Origin": []string{"https://untrusted.invalid"}}) + if err == nil { + ws.Close() + t.Fatal("accepted cross-origin websocket") + } + if res.StatusCode != 403 { + t.Fatal(res.StatusCode) + } + ws, _, err = websocket.DefaultDialer.Dial(url, nil) + if err != nil { + t.Fatal(err) + } + invalid, _ := asn1.Marshal(rdpRequest{3390, "127.0.0.1:1", "invalid", testX224}) + _ = ws.WriteMessage(websocket.BinaryMessage, invalid) + _ = ws.SetReadDeadline(time.Now().Add(2 * time.Second)) + if _, _, err = ws.ReadMessage(); err == nil { + t.Fatal("accepted invalid JWT") + } + ws.Close() + ws, _, err = websocket.DefaultDialer.Dial(url, nil) + if err != nil { + t.Fatal(err) + } + defer ws.Close() + token, _, _ := auth.GenerateToken(1, "admin", cfg.JWTSecret) + // A hostile destination is ignored; only the saved server endpoint is dialed. + request, _ := asn1.Marshal(rdpRequest{3390, "127.0.0.1:1", token, testX224}) + if err = ws.WriteMessage(websocket.BinaryMessage, request); err != nil { + t.Fatal(err) + } + _ = ws.SetReadDeadline(time.Now().Add(5 * time.Second)) + _, data, err := ws.ReadMessage() + if err != nil { + t.Fatal(err) + } + var response rdpResponse + if _, err = asn1.Unmarshal(data, &response); err != nil || !bytes.Equal(response.Certificates[0], certificate.Certificate[0]) { + t.Fatalf("bad handshake %v", err) + } + if err = ws.WriteMessage(websocket.BinaryMessage, []byte("ping")); err != nil { + t.Fatal(err) + } + _, data, err = ws.ReadMessage() + if err != nil || string(data) != "ping" { + t.Fatalf("relay: %q %v", data, err) + } + ws.Close() + select { + case err := <-peerDone: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("target connection leaked") + } + // Ensure response metadata contains no proxy authentication material. + out, _ := json.Marshal(s.ToListItem()) + if bytes.Contains(out, []byte(token)) { + t.Fatal("leaked token") + } +} diff --git a/internal/api/router.go b/internal/api/router.go index b168951..f7a943d 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -38,6 +38,9 @@ func SetupRouter(cfg AppConfig) *gin.Engine { c.Header("X-Content-Type-Options", "nosniff") c.Header("Referrer-Policy", "no-referrer") c.Header("X-Frame-Options", "DENY") + if c.Request.URL.Path == "/rdp.html" { + c.Header("X-Frame-Options", "SAMEORIGIN") + } if strings.HasPrefix(c.Request.URL.Path, "/api/") { c.Header("Cache-Control", "no-store") if !strings.HasSuffix(c.Request.URL.Path, "/files/upload") { @@ -70,6 +73,7 @@ func SetupRouter(cfg AppConfig) *gin.Engine { files.POST("/mkdir", SFTPMkdir(cfg.EncryptionKey)) files.DELETE("", SFTPDelete(cfg.EncryptionKey)) api.GET("/terminal/:serverId", TerminalHandler(cfg)) + api.GET("/rdp/:serverId", RDPHandler(cfg)) } distFS, err := fs.Sub(cfg.DistFS, "ui/dist") diff --git a/internal/api/server_handler.go b/internal/api/server_handler.go index 2ebe612..eb9f09d 100644 --- a/internal/api/server_handler.go +++ b/internal/api/server_handler.go @@ -3,6 +3,7 @@ package api import ( "database/sql" "encoding/base64" + "encoding/hex" "fmt" "net/http" "strconv" @@ -14,6 +15,10 @@ import ( ) type serverCreateReq struct { + Protocol string `json:"protocol"` + RDPDomain string `json:"rdp_domain"` + RDPCertFingerprint string `json:"rdp_cert_fingerprint"` + Name string `json:"name" binding:"required"` Host string `json:"host" binding:"required"` Port int `json:"port"` @@ -29,12 +34,36 @@ type serverCreateReq struct { } func (r *serverCreateReq) validate() error { + if r.Protocol == "" { + r.Protocol = "ssh" + } + if r.Protocol != "ssh" && r.Protocol != "rdp" { + return fmt.Errorf("protocol must be ssh or rdp") + } + if r.Protocol == "rdp" && r.Port == 0 { + r.Port = 3389 + } if r.Port == 0 { r.Port = 22 } if r.Port < 1 || r.Port > 65535 { return fmt.Errorf("port must be between 1 and 65535") } + if r.Protocol == "rdp" { + if r.Password != "" || r.PrivateKey != "" || r.CopyKeyFrom != 0 || r.HostKey != "" || r.JumpServerID != nil { + return fmt.Errorf("RDP V1 does not store credentials or support SSH settings") + } + r.AuthType = "password" + r.RDPCertFingerprint = strings.ToLower(strings.ReplaceAll(strings.TrimSpace(r.RDPCertFingerprint), ":", "")) + if r.RDPCertFingerprint != "" { + b, err := hex.DecodeString(r.RDPCertFingerprint) + if err != nil || len(b) != 32 { + return fmt.Errorf("RDP certificate fingerprint must be SHA256 (64 hex digits)") + } + } + return nil + } + r.RDPDomain, r.RDPCertFingerprint = "", "" if r.AuthType == "" { r.AuthType = "key" } @@ -86,6 +115,9 @@ func GetServer(c *gin.Context) { } func resolveCredentials(db *sql.DB, req *serverCreateReq, current *models.Server, key string) (string, string, error) { + if req.Protocol == "rdp" { + return "", "", nil + } privateKey, password := "", "" if current != nil { privateKey, password = current.PrivateKey, current.Password @@ -162,7 +194,7 @@ func saveServer(encKey string, update bool) gin.HandlerFunc { return } jump, err := models.GetServer(getDB(c), *req.JumpServerID) - if err != nil || jump == nil { + if err != nil || jump == nil || jump.Protocol == "rdp" { c.JSON(http.StatusBadRequest, gin.H{"error": "jump server not found"}) return } @@ -173,6 +205,7 @@ func saveServer(encKey string, update bool) gin.HandlerFunc { return } server := &models.Server{ + Protocol: req.Protocol, RDPDomain: req.RDPDomain, RDPCertFingerprint: req.RDPCertFingerprint, ID: id, Name: req.Name, Host: req.Host, Port: req.Port, Username: req.Username, AuthType: req.AuthType, HostKey: req.HostKey, PrivateKey: privateKey, Password: password, Description: req.Description, @@ -214,6 +247,10 @@ func TestConnection(encKey string) gin.HandlerFunc { c.JSON(http.StatusNotFound, gin.H{"error": "server not found"}) return } + if server.Protocol == "rdp" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Open the RDP tab to test authentication"}) + return + } client, err := dialServer(c.Request.Context(), getDB(c), server, encKey) if err != nil { c.JSON(http.StatusOK, gin.H{"success": false, "error": err.Error()}) diff --git a/internal/database/database.go b/internal/database/database.go index f9f4817..6f26a71 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -14,6 +14,11 @@ func Init(dbPath string) (*sql.DB, error) { if err != nil { return nil, fmt.Errorf("database path: %w", err) } + // A Windows drive path must become file:///C:/..., not a URI authority. + absolute = filepath.ToSlash(absolute) + if len(absolute) >= 2 && absolute[1] == ':' { + absolute = "/" + absolute + } dsn := (&url.URL{Scheme: "file", Path: absolute}).String() db, err := sql.Open("sqlite3", dsn+"?_journal_mode=WAL&_foreign_keys=on&_busy_timeout=5000&_txlock=immediate") if err != nil { diff --git a/internal/database/database_test.go b/internal/database/database_test.go index 72139cc..2d557a4 100644 --- a/internal/database/database_test.go +++ b/internal/database/database_test.go @@ -31,17 +31,17 @@ func TestAdoptLegacySchemaAndReopen(t *testing.T) { t.Fatal(err) } var version int - var name, password, fingerprint string + var name, password, fingerprint, protocol string if err := db.QueryRow("PRAGMA user_version").Scan(&version); err != nil { t.Fatal(err) } if version != len(migrations) { t.Fatalf("schema version: %d", version) } - if err := db.QueryRow("SELECT name,password,host_key FROM servers").Scan(&name, &password, &fingerprint); err != nil { + if err := db.QueryRow("SELECT name,password,host_key,protocol FROM servers").Scan(&name, &password, &fingerprint, &protocol); err != nil { t.Fatal(err) } - if name != "old" || password != "" || fingerprint != "" { + if name != "old" || password != "" || fingerprint != "" || protocol != "ssh" { t.Fatal("legacy data changed") } db.Close() diff --git a/internal/database/migrations.go b/internal/database/migrations.go index 362f7fd..52f922d 100644 --- a/internal/database/migrations.go +++ b/internal/database/migrations.go @@ -57,6 +57,14 @@ var migrations = []func(*sql.Tx) error{ func(tx *sql.Tx) error { return addServerColumn(tx, "host_key", "TEXT NOT NULL DEFAULT ''") }, + func(tx *sql.Tx) error { + for _, c := range []struct{ name, definition string }{{"protocol", "TEXT NOT NULL DEFAULT 'ssh'"}, {"rdp_domain", "TEXT NOT NULL DEFAULT ''"}, {"rdp_cert_fingerprint", "TEXT NOT NULL DEFAULT ''"}} { + if err := addServerColumn(tx, c.name, c.definition); err != nil { + return err + } + } + return nil + }, } func migrate(db *sql.DB) error { diff --git a/internal/models/server.go b/internal/models/server.go index 2b5c18c..3b0ad5d 100644 --- a/internal/models/server.go +++ b/internal/models/server.go @@ -6,6 +6,10 @@ import ( ) type Server struct { + Protocol string `json:"protocol"` + RDPDomain string `json:"rdp_domain"` + RDPCertFingerprint string `json:"rdp_cert_fingerprint"` + ID int64 `json:"id"` Name string `json:"name"` Host string `json:"host"` @@ -24,7 +28,7 @@ type Server struct { func ListServers(db *sql.DB) ([]Server, error) { rows, err := db.Query( - "SELECT id, name, host, port, username, auth_type, host_key, description, group_name, jump_server_id, created_at, updated_at FROM servers ORDER BY group_name, name", + "SELECT id, name, host, port, username, auth_type, host_key, description, group_name, jump_server_id, protocol, rdp_domain, rdp_cert_fingerprint, created_at, updated_at FROM servers ORDER BY group_name, name", ) if err != nil { return nil, err @@ -33,7 +37,7 @@ func ListServers(db *sql.DB) ([]Server, error) { var servers []Server for rows.Next() { var s Server - if err := rows.Scan(&s.ID, &s.Name, &s.Host, &s.Port, &s.Username, &s.AuthType, &s.HostKey, &s.Description, &s.Group, &s.JumpServerID, &s.CreatedAt, &s.UpdatedAt); err != nil { + if err := rows.Scan(&s.ID, &s.Name, &s.Host, &s.Port, &s.Username, &s.AuthType, &s.HostKey, &s.Description, &s.Group, &s.JumpServerID, &s.Protocol, &s.RDPDomain, &s.RDPCertFingerprint, &s.CreatedAt, &s.UpdatedAt); err != nil { return nil, err } servers = append(servers, s) @@ -44,9 +48,9 @@ func ListServers(db *sql.DB) ([]Server, error) { func GetServer(db *sql.DB, id int64) (*Server, error) { var s Server err := db.QueryRow( - "SELECT id, name, host, port, username, auth_type, host_key, private_key, password, description, group_name, jump_server_id, created_at, updated_at FROM servers WHERE id = ?", + "SELECT id, name, host, port, username, auth_type, host_key, private_key, password, description, group_name, jump_server_id, protocol, rdp_domain, rdp_cert_fingerprint, created_at, updated_at FROM servers WHERE id = ?", id, - ).Scan(&s.ID, &s.Name, &s.Host, &s.Port, &s.Username, &s.AuthType, &s.HostKey, &s.PrivateKey, &s.Password, &s.Description, &s.Group, &s.JumpServerID, &s.CreatedAt, &s.UpdatedAt) + ).Scan(&s.ID, &s.Name, &s.Host, &s.Port, &s.Username, &s.AuthType, &s.HostKey, &s.PrivateKey, &s.Password, &s.Description, &s.Group, &s.JumpServerID, &s.Protocol, &s.RDPDomain, &s.RDPCertFingerprint, &s.CreatedAt, &s.UpdatedAt) if err == sql.ErrNoRows { return nil, nil } @@ -57,9 +61,12 @@ func GetServer(db *sql.DB, id int64) (*Server, error) { } func CreateServer(db *sql.DB, s *Server) error { + if s.Protocol == "" { + s.Protocol = "ssh" + } result, err := db.Exec( - "INSERT INTO servers (name, host, port, username, auth_type, host_key, private_key, password, description, group_name, jump_server_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - s.Name, s.Host, s.Port, s.Username, s.AuthType, s.HostKey, s.PrivateKey, s.Password, s.Description, s.Group, s.JumpServerID, + "INSERT INTO servers (name, host, port, username, auth_type, host_key, private_key, password, description, group_name, jump_server_id, protocol, rdp_domain, rdp_cert_fingerprint) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + s.Name, s.Host, s.Port, s.Username, s.AuthType, s.HostKey, s.PrivateKey, s.Password, s.Description, s.Group, s.JumpServerID, s.Protocol, s.RDPDomain, s.RDPCertFingerprint, ) if err != nil { return fmt.Errorf("insert server: %w", err) @@ -69,9 +76,12 @@ func CreateServer(db *sql.DB, s *Server) error { } func UpdateServer(db *sql.DB, s *Server) error { + if s.Protocol == "" { + s.Protocol = "ssh" + } _, err := db.Exec( - "UPDATE servers SET name=?, host=?, port=?, username=?, auth_type=?, host_key=?, private_key=?, password=?, description=?, group_name=?, jump_server_id=?, updated_at=datetime('now') WHERE id=?", - s.Name, s.Host, s.Port, s.Username, s.AuthType, s.HostKey, s.PrivateKey, s.Password, s.Description, s.Group, s.JumpServerID, s.ID, + "UPDATE servers SET name=?, host=?, port=?, username=?, auth_type=?, host_key=?, private_key=?, password=?, description=?, group_name=?, jump_server_id=?, protocol=?, rdp_domain=?, rdp_cert_fingerprint=?, updated_at=datetime('now') WHERE id=?", + s.Name, s.Host, s.Port, s.Username, s.AuthType, s.HostKey, s.PrivateKey, s.Password, s.Description, s.Group, s.JumpServerID, s.Protocol, s.RDPDomain, s.RDPCertFingerprint, s.ID, ) return err } @@ -82,6 +92,10 @@ func DeleteServer(db *sql.DB, id int64) error { } type ServerListItem struct { + Protocol string `json:"protocol"` + RDPDomain string `json:"rdp_domain"` + RDPCertFingerprint string `json:"rdp_cert_fingerprint"` + ID int64 `json:"id"` Name string `json:"name"` Host string `json:"host"` @@ -98,6 +112,7 @@ type ServerListItem struct { func (s *Server) ToListItem() ServerListItem { return ServerListItem{ + Protocol: s.Protocol, RDPDomain: s.RDPDomain, RDPCertFingerprint: s.RDPCertFingerprint, ID: s.ID, Name: s.Name, Host: s.Host, Port: s.Port, Username: s.Username, AuthType: s.AuthType, HostKey: s.HostKey, Description: s.Description, Group: s.Group, JumpServerID: s.JumpServerID, diff --git a/ui/package-lock.json b/ui/package-lock.json index ba6a653..b9e41db 100644 --- a/ui/package-lock.json +++ b/ui/package-lock.json @@ -10,6 +10,8 @@ "license": "ISC", "dependencies": { "@ant-design/icons": "^6.1.1", + "@devolutions/iron-remote-desktop": "0.11.0", + "@devolutions/iron-remote-desktop-rdp": "0.7.0", "@xterm/addon-fit": "^0.11.0", "@xterm/addon-web-links": "^0.12.0", "@xterm/xterm": "^6.0.0", @@ -296,6 +298,18 @@ "node": ">=18" } }, + "node_modules/@devolutions/iron-remote-desktop": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@devolutions/iron-remote-desktop/-/iron-remote-desktop-0.11.0.tgz", + "integrity": "sha512-ZH8xfabDA+6rAXkW2V3XgRdj0LHOsHoXAzars/H22DmKsHM39LdMfheKFUR3qLaFDM8mjf6DTFngzjgr+Byx0Q==", + "license": "MIT OR Apache-2.0" + }, + "node_modules/@devolutions/iron-remote-desktop-rdp": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@devolutions/iron-remote-desktop-rdp/-/iron-remote-desktop-rdp-0.7.0.tgz", + "integrity": "sha512-CclAh4OS9aBoPJT0l7bih7ETOHPnB9KjT0drB0a6r5+Qh95pTEuQCx7uFN/XA2AlkFlrqx+DBAMDGYXmgsjHAQ==", + "license": "MIT OR Apache-2.0" + }, "node_modules/@emotion/hash": { "version": "0.8.0", "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.8.0.tgz", diff --git a/ui/package.json b/ui/package.json index 63dd420..364353e 100644 --- a/ui/package.json +++ b/ui/package.json @@ -16,6 +16,8 @@ "type": "module", "dependencies": { "@ant-design/icons": "^6.1.1", + "@devolutions/iron-remote-desktop": "0.11.0", + "@devolutions/iron-remote-desktop-rdp": "0.7.0", "@xterm/addon-fit": "^0.11.0", "@xterm/addon-web-links": "^0.12.0", "@xterm/xterm": "^6.0.0", diff --git a/ui/public/third-party/ironrdp-license.txt b/ui/public/third-party/ironrdp-license.txt new file mode 100644 index 0000000..9806c22 --- /dev/null +++ b/ui/public/third-party/ironrdp-license.txt @@ -0,0 +1,29 @@ +IronRDP / Iron Remote Desktop +https://github.com/Devolutions/IronRDP +@devolutions/iron-remote-desktop 0.11.0 +@devolutions/iron-remote-desktop-rdp 0.7.0 +Used under the MIT license (upstream offers MIT OR Apache-2.0). + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/ui/rdp.html b/ui/rdp.html new file mode 100644 index 0000000..4ba2b82 --- /dev/null +++ b/ui/rdp.html @@ -0,0 +1,19 @@ + +
密码在每次连接时输入,不保存。第一版仅支持直连。
+ > : <>