Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 4 additions & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,7 @@ GitHub Actions 检查前后端测试、Go 格式、类型、构建及 Docker 构
- JWT 有效期 24 小时。WebSocket 仍通过查询参数认证,应用访问日志不记录查询参数;**反向代理也必须过滤 token,或不要记录终端请求的完整 URL**。
- 应用按同源方式使用,不开放通配 CORS。请使用 HTTPS,不要把尚未初始化的实例直接暴露到公网。
- 当前仍是共享管理员的服务器管理工具,不提供多租户隔离;SFTP 可访问范围由远端 SSH 账号权限决定。

## RDP 远程桌面(第一版)

新增 IronRDP WASM 远程桌面,保持单二进制部署,密码每次连接时输入、不保存。配置、证书指纹和兼容性验收说明见 [RDP 使用文档](docs/rdp.md)。
46 changes: 46 additions & 0 deletions docs/rdp.md
Original file line number Diff line number Diff line change
@@ -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
7 changes: 5 additions & 2 deletions internal/api/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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 != "" {
Expand Down
2 changes: 1 addition & 1 deletion internal/api/connection_db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
243 changes: 243 additions & 0 deletions internal/api/rdp_handler.go
Original file line number Diff line number Diff line change
@@ -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
}
}
}
Loading
Loading