settings: an SSH server as a saved proxy, and a failed proxy says why
@laiuuui on X (tweet 2122704105005314155) was told to put Gemini behind
a proxy in a supported region. Their VPSes give only SSH (address, port,
password or key), and every http:// proxy they added failed with Go's
words alone.
A saved proxy can now be an SSH server. Settings > Network > Add proxy
has Proxy | SSH; SSH asks for the server, the user and the password, and
Advanced (closed) holds a private key and the trusted host key. magpie
logs in itself with golang.org/x/crypto/ssh (no ssh command) and resolves
the @id to a SOCKS5 server of its own on loopback, which takes only its
own random login and carries each CONNECT as a direct-tcpip channel, as
ssh -D does: lazy login, keepalive@openssh.com every 20s, one re-login
when a channel finds the connection dead.
- Save logs in first: a refused login is said there and nothing is kept.
- The host key is trusted on first use, kept in authorized_keys form and
shown as its SHA256 fingerprint; another key is refused
(HostKeyChangedError, both fingerprints said) until Trust a new key.
- The key is a secret like the password: left out of backups and
syncs without keys, kept on a sync that has none.
- ssh:// typed as a plain address is refused: its login goes with a
saved proxy.
A failed proxy says why (netproxy.Why: an English template the page
translates in all five languages, Go's words after it): an SSH server
typed as http:// or socks5:// ("is an SSH server, not a proxy: add it as
SSH"), a refused login, keyboard-interactive refused (OpenSSH without
PAM, "unexpected message type 51"), nothing listening, not SSH, TLS on a
plain proxy, 407, timeouts, hangups, and a server that logs in but won't
forward (AllowTcpForwarding no, or macOS 27's sshd, which hangs up on
every forward, OpenSSH's own ssh -W too). A check the user asks for
reads the server's first bytes when Go's text can't tell: Go reads a
real OpenSSH banner ("SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20") as an
HTTP status line with a malformed code, and an SSH server's banner can
reach Go's transport before its request goes out
("readLoopPeekFailLocked", found red 1 of 20 on mica, then 40 of 40
green). Each save is tested at once.
app.js keeps one line (api() hands a proxy_why reply to proxies.js,
where proxyWhy now lives); both script budgets are raised by that line's
52/54 bytes, with the reason in core_budget_test.go.
Run (mica, at this head on origin/main 81c666e1c):
- go test -tags nogui ./internal/netproxy/... ./internal/settings/
./internal/davsync/ ./internal/gui/ ./internal/provider/
./internal/backup/...: ok
- GOOS=linux and GOOS=windows go vet of netproxy, settings, gui; gofmt -l
internal: clean
- GUI, chromium and webkit, en/zh/zh-TW/ja/de, 1100 and 420px:
saved-ssh-proxy, saved-proxies, i18n-keys, provider-proxy-missing:
64/64
- Tests use netproxy/sshtest, an SSH server on loopback that answers
channels itself; nothing reaches the network.
Broken by hand, each red: accepting any host key
(TestSSHProxyRefusesAChangedHostKey); no login check on the SOCKS end
(TestSSHProxyLocalEndNeedsItsLogin); no SSH banner case and no banner
probe (TestProxyFailureNamesAnSSHServer, its OpenSSH-banner case); no
type-51 case (TestSSHProxySaysWhyItFailed, keyboard-interactive); no
code 2 for a hangup (TestSavedSSHProxyThatWontForward, both cases);
api() not handing proxy_why to proxies.js (saved-ssh-proxy, 20 of 20
cases red: err.why is already a failed move's reason).
Real use: Ubuntu 24.04 OpenSSH_9.6p1 (WSL magpie-desktop, a user sshd
on loopback, key login): the host key was learned, a Cloudflare trace
through the tunnel came back ip=104.194.93.45 loc=US, a wrong password
said "turned the login away", a changed host key said both
fingerprints, and http:// and socks5:// pointed at the sshd both said
"is an SSH server". mote's and mica's sshd (macOS 27, OpenSSH 10.5 and
10.3) log in and refuse every forward, now said as "won't forward
connections".
Not tried: a password login against a real sshd (the user sshd had no
shadow access), a real VPS, and the full go test ./... and full GUI
suite: both mote and mica were running other sessions' GUI suites the
whole time.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -22,6 +22,7 @@ require (
|
||||
github.com/tidwall/gjson v1.19.0
|
||||
github.com/tidwall/jsonc v0.3.3
|
||||
github.com/wailsapp/wails/v3 v3.0.0-beta.24
|
||||
golang.org/x/crypto v0.53.0
|
||||
golang.org/x/image v0.43.0
|
||||
golang.org/x/net v0.56.0
|
||||
golang.org/x/sys v0.49.0
|
||||
@@ -114,7 +115,6 @@ require (
|
||||
go.opentelemetry.io/otel/metric v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.38.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/crypto v0.53.0 // indirect
|
||||
golang.org/x/mod v0.42.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250929231259-57b25ae835d4 // indirect
|
||||
|
||||
@@ -1120,8 +1120,8 @@ func take(to *backup.Bundle, from backup.Bundle, part string) {
|
||||
px := slices.Clone(*from.Proxies)
|
||||
if !keys && to.Proxies != nil && (to.Keys || (to.ProvidersKeys != nil && *to.ProvidersKeys)) {
|
||||
for i := range px {
|
||||
if j := slices.IndexFunc(*to.Proxies, func(o settings.NamedProxy) bool { return o.ID == px[i].ID }); j >= 0 && px[i].Pass == "" {
|
||||
px[i].Pass = (*to.Proxies)[j].Pass
|
||||
if j := slices.IndexFunc(*to.Proxies, func(o settings.NamedProxy) bool { return o.ID == px[i].ID }); j >= 0 {
|
||||
px[i].KeepSecretsOf((*to.Proxies)[j]) // an SSH proxy's key with its password
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3783,6 +3783,15 @@ func fail(rw http.ResponseWriter, err error) {
|
||||
out["code"], out["blocked"] = "config_blocked", b
|
||||
}
|
||||
}
|
||||
// a proxy's failure magpie can explain (netproxy.Why), said in the
|
||||
// reader's language, Go's words beside it
|
||||
var why *netproxy.Why
|
||||
if errors.As(err, &why) {
|
||||
out["code"], out["why"], out["addr"], out["was"], out["now"] = "proxy_why", why.Why, why.Addr, why.Was, why.Now
|
||||
if why.Err != nil {
|
||||
out["detail"] = redactProxyErr(why.Err.Error())
|
||||
}
|
||||
}
|
||||
var noModels *agent.NoModelsError
|
||||
if errors.As(err, &noModels) {
|
||||
out["code"] = "no_models"
|
||||
|
||||
@@ -3770,6 +3770,17 @@ body:not(.side-nav) #addSheet > .row-head.stuck::before { opacity: 1; box-shadow
|
||||
.proxy-form .proxy-controls { justify-content: flex-end; flex: 1 1 100%; }
|
||||
.proxy-form .proxy-credential { flex: 1 1 10rem; min-width: 0; }
|
||||
.proxy-form .sub.err { flex: 1 1 100%; }
|
||||
/* an SSH server's form: Proxy | SSH over its fields, and its key and host
|
||||
key folded under Advanced */
|
||||
.proxy-form { gap: 8px; }
|
||||
.proxy-form .proxy-kind { flex: none; }
|
||||
.proxy-form .proxy-advanced { flex: 1 1 100%; min-width: 0; }
|
||||
.proxy-advanced summary { margin-left: 0; }
|
||||
.proxy-advanced .inner { display: flex; flex-direction: column; gap: 8px; padding-top: 8px; }
|
||||
.proxy-advanced textarea.proxy-key { width: 100%; max-width: 100%; box-sizing: border-box; min-height: 64px; padding: 6px 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: inherit; font: 11.5px/1.45 var(--mono, ui-monospace, monospace); resize: vertical; outline: none; }
|
||||
.proxy-advanced textarea.proxy-key:focus { border-color: var(--accent); }
|
||||
.proxy-hostkey { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }
|
||||
.proxy-hostkey .sub { min-width: 0; overflow-wrap: anywhere; font: 11.5px/1.45 var(--mono, ui-monospace, monospace); }
|
||||
.editor :is(input.concurrency, input.queue-limit, input.queue-wait)[type] { width: 12em; max-width: 100%; }
|
||||
.editor input[type="number"] { -moz-appearance: textfield; }
|
||||
.editor input[type="number"]::-webkit-inner-spin-button, .editor input[type="number"]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
|
||||
@@ -3942,16 +3953,16 @@ body:not(.side-nav) #addSheet > .row-head.stuck::before { opacity: 1; box-shadow
|
||||
reads as a control and not as a disabled hint (sylvenPR on X, a 5px ▸ in
|
||||
the muted grey); a pointer and a brighter label under it. The chevron
|
||||
starts where the fields do (--ed-at), no padding before it. */
|
||||
.editor .more summary { font-size: 12px; line-height: 18px; color: var(--fg-2); list-style: none; display: inline-flex; align-items: center; gap: 5px; padding: 3px 0; margin-left: var(--ed-at, 86px); border-radius: 4px; cursor: pointer; transition: color .12s; }
|
||||
.editor .more summary::-webkit-details-marker { display: none; }
|
||||
.editor .more summary::before { content: ""; flex: none; width: 10px; height: 10px; background: var(--muted); transition: transform .24s var(--ease-out), background-color .12s;
|
||||
.editor .more summary, .proxy-advanced summary { font-size: 12px; line-height: 18px; color: var(--fg-2); list-style: none; display: inline-flex; align-items: center; gap: 5px; padding: 3px 0; margin-left: var(--ed-at, 86px); border-radius: 4px; cursor: pointer; transition: color .12s; }
|
||||
.editor .more summary::-webkit-details-marker, .proxy-advanced summary::-webkit-details-marker { display: none; }
|
||||
.editor .more summary::before, .proxy-advanced summary::before { content: ""; flex: none; width: 10px; height: 10px; background: var(--muted); transition: transform .24s var(--ease-out), background-color .12s;
|
||||
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M3.6 1.6 7 5 3.6 8.4' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M3.6 1.6 7 5 3.6 8.4' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / contain no-repeat; }
|
||||
.editor .more[open]:not(.closing) summary::before { transform: rotate(90deg); }
|
||||
@media (prefers-reduced-motion: reduce) { .editor .more summary, .editor .more summary::before { transition: none; } }
|
||||
.editor .more summary:hover { color: var(--fg); }
|
||||
.editor .more summary:hover::before { background: var(--fg-2); }
|
||||
.editor .more summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.editor .more[open]:not(.closing) summary::before, .proxy-advanced[open] summary::before { transform: rotate(90deg); }
|
||||
@media (prefers-reduced-motion: reduce) { .editor .more summary, .editor .more summary::before, .proxy-advanced summary, .proxy-advanced summary::before { transition: none; } }
|
||||
.editor .more summary:hover, .proxy-advanced summary:hover { color: var(--fg); }
|
||||
.editor .more summary:hover::before, .proxy-advanced summary:hover::before { background: var(--fg-2); }
|
||||
.editor .more summary:focus-visible, .proxy-advanced summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
/* its labels are longer (Anthropic 地址, Responses-URL): their column takes
|
||||
the longest, on one line, rather than wrap a last 址 under it (#875) */
|
||||
.editor .more .inner { display: grid; grid-template-columns: minmax(var(--ed-lab, 72px), max-content) minmax(0, 1fr); gap: 10px 14px; align-items: first baseline; padding-top: 8px; }
|
||||
|
||||
@@ -162,6 +162,9 @@ async function api(path, body, heads, signal) {
|
||||
err.code = data.code;
|
||||
if (data.offline === "stage" || data.offline === "disconnect") err.offline = data.offline;
|
||||
}
|
||||
// a proxy's failure magpie can explain (netproxy.Why): proxies.js says
|
||||
// it in the reader's language
|
||||
if (data?.code === "proxy_why") err.proxy = data;
|
||||
// magpie has no models to connect an agent to yet: said in the
|
||||
// reader's language
|
||||
if (data?.code === "no_models") err.message = t("Add a provider or subscription in magpie first, then connect {agent}", { agent: data.agent });
|
||||
|
||||
@@ -2896,6 +2896,40 @@ const I18N = {
|
||||
"Reachable, {ms} ms": "可连接,{ms} 毫秒",
|
||||
"Unreachable: {error}": "无法连接:{error}",
|
||||
"Used by {n}": "{n} 处在用",
|
||||
"SSH server": "SSH 服务器",
|
||||
"Logging in…": "正在登录…",
|
||||
"A private key is saved; paste another to replace it": "已保存私钥;粘贴新的私钥可替换",
|
||||
"Private key (instead of or with the password)": "私钥(代替密码或与密码一起使用)",
|
||||
"Private key": "私钥",
|
||||
"The key the server shows next is trusted": "将信任服务器下次出示的密钥",
|
||||
"Host key {fingerprint}": "主机密钥 {fingerprint}",
|
||||
"Trust a new key": "信任新密钥",
|
||||
"{addr} is an SSH server, not a proxy: add it as SSH, with its user and password": "{addr} 是 SSH 服务器,不是代理:请按 SSH 添加,并填写用户和密码",
|
||||
"{addr} answered, but not as this kind of proxy: check whether it is HTTP, SOCKS5 or SSH": "{addr} 有应答,但不是这种代理:请确认它是 HTTP、SOCKS5 还是 SSH",
|
||||
"{addr} doesn't speak TLS: write http:// instead of https://": "{addr} 不支持 TLS:请把 https:// 改成 http://",
|
||||
"{addr} wants a username and password, or turned these away": "{addr} 需要用户名和密码,或拒绝了所填的用户名和密码",
|
||||
"{addr} turned the username and password away": "{addr} 拒绝了用户名和密码",
|
||||
"{addr} wants a username and password": "{addr} 需要用户名和密码",
|
||||
"nothing answers at {addr}: check the address and port, and that the proxy is running": "{addr} 无应答:请检查地址和端口,并确认代理正在运行",
|
||||
"the proxy's host name doesn't resolve": "代理的主机名无法解析",
|
||||
"no answer through {addr} in time: check the address, and that a firewall lets magpie reach it": "经 {addr} 的请求超时:请检查地址,并确认防火墙允许 magpie 访问它",
|
||||
"{addr} hung up: check whether it is HTTP, SOCKS5 or SSH, and its login": "{addr} 断开了连接:请确认它是 HTTP、SOCKS5 还是 SSH,以及登录信息",
|
||||
"an SSH server looks like 203.0.113.5:22": "SSH 服务器的格式如 203.0.113.5:22",
|
||||
"an SSH server needs the user to log in as": "SSH 服务器需要填写登录用户",
|
||||
"an SSH server is added as a saved proxy: Settings › Network › Add proxy › SSH": "SSH 服务器请作为已保存的代理添加:设置 › 网络 › 添加代理 › SSH",
|
||||
"the private key has a passphrase: type it in the password field": "私钥有口令:请把口令填在密码栏",
|
||||
"the private key's passphrase is wrong": "私钥口令不正确",
|
||||
"the private key can't be read: paste the whole file, from its BEGIN line to its END line": "无法读取私钥:请粘贴完整文件,从 BEGIN 行到 END 行",
|
||||
"an SSH server needs a password or a private key": "SSH 服务器需要密码或私钥",
|
||||
"the SSH server's host key changed: it was {was} and is now {now}. If the server was reinstalled, trust the new key under Advanced": "SSH 服务器的主机密钥变了:原为 {was},现为 {now}。如果服务器重装过,请在高级中信任新密钥",
|
||||
"the SSH server at {addr} turned the login away: check the user and the password or key": "{addr} 的 SSH 服务器拒绝登录:请检查用户和密码或私钥",
|
||||
"the SSH server at {addr} let magpie log in but won't forward connections: its sshd_config needs AllowTcpForwarding yes": "{addr} 的 SSH 服务器允许 magpie 登录,但不转发连接:它的 sshd_config 需要 AllowTcpForwarding yes",
|
||||
"the SSH server at {addr} couldn't reach the site: check that the server itself reaches the internet": "{addr} 的 SSH 服务器连不上该网站:请检查服务器本身能否访问互联网",
|
||||
"nothing answers SSH at {addr}: check the address and port": "{addr} 没有 SSH 应答:请检查地址和端口",
|
||||
"the SSH server's name doesn't resolve": "SSH 服务器的名称无法解析",
|
||||
"no answer from {addr} in time: check the address, and that the server's firewall lets SSH in": "{addr} 应答超时:请检查地址,并确认服务器防火墙放行 SSH",
|
||||
"{addr} doesn't speak SSH, or hung up": "{addr} 不是 SSH 服务,或断开了连接",
|
||||
"SSH to {addr} failed": "SSH 连接 {addr} 失败",
|
||||
"Requests to it go through this saved proxy, kept in Settings": "发往它的请求走这个已保存的代理,在设置中维护",
|
||||
"Follows the proxy in Settings": "跟随设置里的代理",
|
||||
"Requests to it go direct, whatever the proxy in Settings": "发往它的请求直连,不走设置里的代理",
|
||||
@@ -8304,6 +8338,40 @@ const I18N = {
|
||||
"Reachable, {ms} ms": "可連線,{ms} 毫秒",
|
||||
"Unreachable: {error}": "無法連線:{error}",
|
||||
"Used by {n}": "{n} 處使用中",
|
||||
"SSH server": "SSH 伺服器",
|
||||
"Logging in…": "正在登入…",
|
||||
"A private key is saved; paste another to replace it": "已儲存私鑰;貼上新的私鑰可取代",
|
||||
"Private key (instead of or with the password)": "私鑰(代替密碼或與密碼一起使用)",
|
||||
"Private key": "私鑰",
|
||||
"The key the server shows next is trusted": "將信任伺服器下次出示的金鑰",
|
||||
"Host key {fingerprint}": "主機金鑰 {fingerprint}",
|
||||
"Trust a new key": "信任新金鑰",
|
||||
"{addr} is an SSH server, not a proxy: add it as SSH, with its user and password": "{addr} 是 SSH 伺服器,不是代理:請以 SSH 新增,並填寫使用者和密碼",
|
||||
"{addr} answered, but not as this kind of proxy: check whether it is HTTP, SOCKS5 or SSH": "{addr} 有回應,但不是這種代理:請確認它是 HTTP、SOCKS5 還是 SSH",
|
||||
"{addr} doesn't speak TLS: write http:// instead of https://": "{addr} 不支援 TLS:請把 https:// 改成 http://",
|
||||
"{addr} wants a username and password, or turned these away": "{addr} 需要使用者名稱和密碼,或拒絕了所填的使用者名稱和密碼",
|
||||
"{addr} turned the username and password away": "{addr} 拒絕了使用者名稱和密碼",
|
||||
"{addr} wants a username and password": "{addr} 需要使用者名稱和密碼",
|
||||
"nothing answers at {addr}: check the address and port, and that the proxy is running": "{addr} 沒有回應:請檢查位址和連接埠,並確認代理正在執行",
|
||||
"the proxy's host name doesn't resolve": "代理的主機名稱無法解析",
|
||||
"no answer through {addr} in time: check the address, and that a firewall lets magpie reach it": "經 {addr} 的請求逾時:請檢查位址,並確認防火牆允許 magpie 存取它",
|
||||
"{addr} hung up: check whether it is HTTP, SOCKS5 or SSH, and its login": "{addr} 中斷了連線:請確認它是 HTTP、SOCKS5 還是 SSH,以及登入資訊",
|
||||
"an SSH server looks like 203.0.113.5:22": "SSH 伺服器的格式如 203.0.113.5:22",
|
||||
"an SSH server needs the user to log in as": "SSH 伺服器需要填寫登入使用者",
|
||||
"an SSH server is added as a saved proxy: Settings › Network › Add proxy › SSH": "SSH 伺服器請以已儲存的代理新增:設定 › 網路 › 新增代理 › SSH",
|
||||
"the private key has a passphrase: type it in the password field": "私鑰有密語:請把密語填在密碼欄",
|
||||
"the private key's passphrase is wrong": "私鑰密語不正確",
|
||||
"the private key can't be read: paste the whole file, from its BEGIN line to its END line": "無法讀取私鑰:請貼上完整檔案,從 BEGIN 行到 END 行",
|
||||
"an SSH server needs a password or a private key": "SSH 伺服器需要密碼或私鑰",
|
||||
"the SSH server's host key changed: it was {was} and is now {now}. If the server was reinstalled, trust the new key under Advanced": "SSH 伺服器的主機金鑰變了:原為 {was},現為 {now}。如果伺服器重灌過,請在進階中信任新金鑰",
|
||||
"the SSH server at {addr} turned the login away: check the user and the password or key": "{addr} 的 SSH 伺服器拒絕登入:請檢查使用者和密碼或私鑰",
|
||||
"the SSH server at {addr} let magpie log in but won't forward connections: its sshd_config needs AllowTcpForwarding yes": "{addr} 的 SSH 伺服器允許 magpie 登入,但不轉發連線:它的 sshd_config 需要 AllowTcpForwarding yes",
|
||||
"the SSH server at {addr} couldn't reach the site: check that the server itself reaches the internet": "{addr} 的 SSH 伺服器連不上該網站:請檢查伺服器本身能否連上網際網路",
|
||||
"nothing answers SSH at {addr}: check the address and port": "{addr} 沒有 SSH 回應:請檢查位址和連接埠",
|
||||
"the SSH server's name doesn't resolve": "SSH 伺服器的名稱無法解析",
|
||||
"no answer from {addr} in time: check the address, and that the server's firewall lets SSH in": "{addr} 回應逾時:請檢查位址,並確認伺服器防火牆放行 SSH",
|
||||
"{addr} doesn't speak SSH, or hung up": "{addr} 不是 SSH 服務,或中斷了連線",
|
||||
"SSH to {addr} failed": "SSH 連線 {addr} 失敗",
|
||||
"Requests to it go through this saved proxy, kept in Settings": "發往它的請求走這個已儲存的代理,在設定中維護",
|
||||
"Follows the proxy in Settings": "跟隨設定裡的代理",
|
||||
"Requests to it go direct, whatever the proxy in Settings": "發往它的請求直連,不走設定裡的代理",
|
||||
@@ -13686,6 +13754,40 @@ const I18N = {
|
||||
"Reachable, {ms} ms": "接続できます、{ms} ms",
|
||||
"Unreachable: {error}": "接続できません:{error}",
|
||||
"Used by {n}": "{n} 件で使用中",
|
||||
"SSH server": "SSH サーバー",
|
||||
"Logging in…": "ログイン中…",
|
||||
"A private key is saved; paste another to replace it": "秘密鍵を保存済み。別の鍵を貼り付けると置き換えます",
|
||||
"Private key (instead of or with the password)": "秘密鍵(パスワードの代わり、または併用)",
|
||||
"Private key": "秘密鍵",
|
||||
"The key the server shows next is trusted": "サーバーが次に示す鍵を信頼します",
|
||||
"Host key {fingerprint}": "ホスト鍵 {fingerprint}",
|
||||
"Trust a new key": "新しい鍵を信頼",
|
||||
"{addr} is an SSH server, not a proxy: add it as SSH, with its user and password": "{addr} は SSH サーバーでプロキシではありません:SSH として、ユーザーとパスワードを入れて追加してください",
|
||||
"{addr} answered, but not as this kind of proxy: check whether it is HTTP, SOCKS5 or SSH": "{addr} は応答しましたが、この種類のプロキシではありません:HTTP、SOCKS5、SSH のどれか確認してください",
|
||||
"{addr} doesn't speak TLS: write http:// instead of https://": "{addr} は TLS を話しません:https:// ではなく http:// と書いてください",
|
||||
"{addr} wants a username and password, or turned these away": "{addr} はユーザー名とパスワードを求めているか、入力したものを拒否しました",
|
||||
"{addr} turned the username and password away": "{addr} がユーザー名とパスワードを拒否しました",
|
||||
"{addr} wants a username and password": "{addr} はユーザー名とパスワードを求めています",
|
||||
"nothing answers at {addr}: check the address and port, and that the proxy is running": "{addr} が応答しません:アドレスとポート、プロキシが動いているか確認してください",
|
||||
"the proxy's host name doesn't resolve": "プロキシのホスト名を解決できません",
|
||||
"no answer through {addr} in time: check the address, and that a firewall lets magpie reach it": "{addr} 経由の応答が時間内にありません:アドレスと、ファイアウォールが magpie の接続を許しているか確認してください",
|
||||
"{addr} hung up: check whether it is HTTP, SOCKS5 or SSH, and its login": "{addr} が切断しました:HTTP、SOCKS5、SSH のどれか、ログイン情報を確認してください",
|
||||
"an SSH server looks like 203.0.113.5:22": "SSH サーバーは 203.0.113.5:22 の形式です",
|
||||
"an SSH server needs the user to log in as": "SSH サーバーにはログインするユーザーが必要です",
|
||||
"an SSH server is added as a saved proxy: Settings › Network › Add proxy › SSH": "SSH サーバーは保存済みプロキシとして追加します:設定 › ネットワーク › プロキシを追加 › SSH",
|
||||
"the private key has a passphrase: type it in the password field": "秘密鍵にパスフレーズがあります:パスワード欄に入力してください",
|
||||
"the private key's passphrase is wrong": "秘密鍵のパスフレーズが違います",
|
||||
"the private key can't be read: paste the whole file, from its BEGIN line to its END line": "秘密鍵を読めません:BEGIN 行から END 行までファイル全体を貼り付けてください",
|
||||
"an SSH server needs a password or a private key": "SSH サーバーにはパスワードか秘密鍵が必要です",
|
||||
"the SSH server's host key changed: it was {was} and is now {now}. If the server was reinstalled, trust the new key under Advanced": "SSH サーバーのホスト鍵が変わりました:以前は {was}、現在は {now}。サーバーを再インストールした場合は、詳細設定で新しい鍵を信頼してください",
|
||||
"the SSH server at {addr} turned the login away: check the user and the password or key": "{addr} の SSH サーバーがログインを拒否しました:ユーザーとパスワードまたは鍵を確認してください",
|
||||
"the SSH server at {addr} let magpie log in but won't forward connections: its sshd_config needs AllowTcpForwarding yes": "{addr} の SSH サーバーは magpie のログインを受け付けましたが、接続を転送しません:sshd_config に AllowTcpForwarding yes が必要です",
|
||||
"the SSH server at {addr} couldn't reach the site: check that the server itself reaches the internet": "{addr} の SSH サーバーがサイトに接続できません:サーバー自体がインターネットに接続できるか確認してください",
|
||||
"nothing answers SSH at {addr}: check the address and port": "{addr} で SSH が応答しません:アドレスとポートを確認してください",
|
||||
"the SSH server's name doesn't resolve": "SSH サーバーの名前を解決できません",
|
||||
"no answer from {addr} in time: check the address, and that the server's firewall lets SSH in": "{addr} から時間内に応答がありません:アドレスと、サーバーのファイアウォールが SSH を通すか確認してください",
|
||||
"{addr} doesn't speak SSH, or hung up": "{addr} は SSH を話さないか、切断しました",
|
||||
"SSH to {addr} failed": "{addr} への SSH に失敗しました",
|
||||
"Requests to it go through this saved proxy, kept in Settings": "このプロバイダへのリクエストは保存済みのプロキシを経由します。設定で管理します",
|
||||
"Follows the proxy in Settings": "設定のプロキシに従う",
|
||||
"Requests to it go direct, whatever the proxy in Settings": "設定のプロキシに関係なく、このプロバイダへのリクエストは直接送られます",
|
||||
@@ -19103,6 +19205,40 @@ const I18N = {
|
||||
"Reachable, {ms} ms": "Erreichbar, {ms} ms",
|
||||
"Unreachable: {error}": "Nicht erreichbar: {error}",
|
||||
"Used by {n}": "An {n} Stellen verwendet",
|
||||
"SSH server": "SSH-Server",
|
||||
"Logging in…": "Anmeldung…",
|
||||
"A private key is saved; paste another to replace it": "Ein privater Schlüssel ist gespeichert; einen anderen einfügen, um ihn zu ersetzen",
|
||||
"Private key (instead of or with the password)": "Privater Schlüssel (statt oder mit dem Passwort)",
|
||||
"Private key": "Privater Schlüssel",
|
||||
"The key the server shows next is trusted": "Der Schlüssel, den der Server als Nächstes zeigt, wird vertraut",
|
||||
"Host key {fingerprint}": "Host-Schlüssel {fingerprint}",
|
||||
"Trust a new key": "Neuem Schlüssel vertrauen",
|
||||
"{addr} is an SSH server, not a proxy: add it as SSH, with its user and password": "{addr} ist ein SSH-Server, kein Proxy: als SSH hinzufügen, mit Benutzer und Passwort",
|
||||
"{addr} answered, but not as this kind of proxy: check whether it is HTTP, SOCKS5 or SSH": "{addr} antwortet, aber nicht als diese Art Proxy: prüfen, ob es HTTP, SOCKS5 oder SSH ist",
|
||||
"{addr} doesn't speak TLS: write http:// instead of https://": "{addr} spricht kein TLS: http:// statt https:// schreiben",
|
||||
"{addr} wants a username and password, or turned these away": "{addr} verlangt Benutzername und Passwort oder hat die angegebenen abgelehnt",
|
||||
"{addr} turned the username and password away": "{addr} hat Benutzername und Passwort abgelehnt",
|
||||
"{addr} wants a username and password": "{addr} verlangt Benutzername und Passwort",
|
||||
"nothing answers at {addr}: check the address and port, and that the proxy is running": "Unter {addr} antwortet nichts: Adresse und Port prüfen, und ob der Proxy läuft",
|
||||
"the proxy's host name doesn't resolve": "Der Hostname des Proxys lässt sich nicht auflösen",
|
||||
"no answer through {addr} in time: check the address, and that a firewall lets magpie reach it": "Keine rechtzeitige Antwort über {addr}: Adresse prüfen, und ob eine Firewall magpie durchlässt",
|
||||
"{addr} hung up: check whether it is HTTP, SOCKS5 or SSH, and its login": "{addr} hat aufgelegt: prüfen, ob es HTTP, SOCKS5 oder SSH ist, und die Anmeldung",
|
||||
"an SSH server looks like 203.0.113.5:22": "Ein SSH-Server sieht aus wie 203.0.113.5:22",
|
||||
"an SSH server needs the user to log in as": "Ein SSH-Server braucht den Benutzer für die Anmeldung",
|
||||
"an SSH server is added as a saved proxy: Settings › Network › Add proxy › SSH": "Ein SSH-Server wird als gespeicherter Proxy hinzugefügt: Einstellungen › Netzwerk › Proxy hinzufügen › SSH",
|
||||
"the private key has a passphrase: type it in the password field": "Der private Schlüssel hat eine Passphrase: im Passwortfeld eingeben",
|
||||
"the private key's passphrase is wrong": "Die Passphrase des privaten Schlüssels ist falsch",
|
||||
"the private key can't be read: paste the whole file, from its BEGIN line to its END line": "Der private Schlüssel ist nicht lesbar: die ganze Datei einfügen, von der BEGIN- bis zur END-Zeile",
|
||||
"an SSH server needs a password or a private key": "Ein SSH-Server braucht ein Passwort oder einen privaten Schlüssel",
|
||||
"the SSH server's host key changed: it was {was} and is now {now}. If the server was reinstalled, trust the new key under Advanced": "Der Host-Schlüssel des SSH-Servers hat sich geändert: vorher {was}, jetzt {now}. Wurde der Server neu installiert, unter Erweitert dem neuen Schlüssel vertrauen",
|
||||
"the SSH server at {addr} turned the login away: check the user and the password or key": "Der SSH-Server unter {addr} hat die Anmeldung abgelehnt: Benutzer und Passwort oder Schlüssel prüfen",
|
||||
"the SSH server at {addr} let magpie log in but won't forward connections: its sshd_config needs AllowTcpForwarding yes": "Der SSH-Server unter {addr} lässt magpie anmelden, leitet aber keine Verbindungen weiter: seine sshd_config braucht AllowTcpForwarding yes",
|
||||
"the SSH server at {addr} couldn't reach the site: check that the server itself reaches the internet": "Der SSH-Server unter {addr} erreicht die Seite nicht: prüfen, ob der Server selbst ins Internet kommt",
|
||||
"nothing answers SSH at {addr}: check the address and port": "Unter {addr} antwortet kein SSH: Adresse und Port prüfen",
|
||||
"the SSH server's name doesn't resolve": "Der Name des SSH-Servers lässt sich nicht auflösen",
|
||||
"no answer from {addr} in time: check the address, and that the server's firewall lets SSH in": "Keine rechtzeitige Antwort von {addr}: Adresse prüfen, und ob die Firewall des Servers SSH durchlässt",
|
||||
"{addr} doesn't speak SSH, or hung up": "{addr} spricht kein SSH oder hat aufgelegt",
|
||||
"SSH to {addr} failed": "SSH zu {addr} fehlgeschlagen",
|
||||
"Requests to it go through this saved proxy, kept in Settings": "Anfragen gehen über diesen gespeicherten Proxy, der in den Einstellungen verwaltet wird",
|
||||
"Follows the proxy in Settings": "Folgt dem Proxy aus den Einstellungen",
|
||||
"Requests to it go direct, whatever the proxy in Settings": "Anfragen gehen direkt, unabhängig vom Proxy in den Einstellungen",
|
||||
|
||||
+106
-27
@@ -1,12 +1,39 @@
|
||||
// Settings › Network's saved proxies: their rows, the test and the form.
|
||||
// app.js imports this when Settings draws them, so it weighs nothing on the core.
|
||||
|
||||
let proxyForm = null; // { id, name, url, user, hasPass, err } while one is added or edited
|
||||
// { id, kind, name, url, user, hasPass, hasKey, hostKey, trust, adv, err,
|
||||
// busy } while one is added or edited; kind is "proxy" or "ssh", and an
|
||||
// SSH server's url is its host:port, without ssh://
|
||||
let proxyForm = null;
|
||||
const proxyChecks = {}; // id -> { busy, out }
|
||||
const isSSH = (url) => /^ssh:\/\//i.test(url || "");
|
||||
const bareSSH = (url) => (url || "").replace(/^ssh:\/\//i, "");
|
||||
// a proxy's failure magpie explained (netproxy.Why) in the reader's
|
||||
// language, Go's words after it
|
||||
function proxyWhy(o) {
|
||||
const s = t(o.why, { addr: o.addr, was: o.was, now: o.now }), d = o.detail ?? o.error;
|
||||
return d ? s + " (" + d + ")" : s;
|
||||
}
|
||||
// a check's failure, said as magpie explained it when it could
|
||||
const proxyFailed = (out) => (out.why ? proxyWhy(out) : out.error || "");
|
||||
function testSavedProxy(id) {
|
||||
proxyChecks[id] = { busy: true };
|
||||
renderSettings();
|
||||
api("proxies/test", { id })
|
||||
.then((o) => { proxyChecks[id] = { out: o }; })
|
||||
.catch((e) => { proxyChecks[id] = { out: { ok: false, error: t(e.message) } }; })
|
||||
.finally(renderSettings);
|
||||
}
|
||||
window.renderSavedProxies = function (s) {
|
||||
const box = $("#proxiesList");
|
||||
box.replaceChildren();
|
||||
const done = (ns) => { prefs = ns; proxyForm = null; renderSettings(); };
|
||||
const done = (ns, id) => {
|
||||
prefs = ns;
|
||||
proxyForm = null;
|
||||
// a save is tested at once, so a proxy that can't be used says why now
|
||||
if (id) testSavedProxy(id);
|
||||
else renderSettings();
|
||||
};
|
||||
for (const p of s.proxies || []) {
|
||||
if (proxyForm && proxyForm.id === p.id) { box.append(proxyFormRow(done)); continue; }
|
||||
const r = el("div", "row pref saved-proxy");
|
||||
@@ -15,28 +42,26 @@ window.renderSavedProxies = function (s) {
|
||||
who.append(el("div", "name", p.name), sub);
|
||||
const chk = proxyChecks[p.id];
|
||||
const out = chk?.out || p.check;
|
||||
const line = [p.user ? p.user + "@" + p.url : p.url];
|
||||
const ssh = isSSH(p.url);
|
||||
const addr = ssh ? bareSSH(p.url) : p.url;
|
||||
const line = [ssh ? "SSH " + (p.user ? p.user + "@" : "") + addr : p.user ? p.user + "@" + p.url : p.url];
|
||||
if (chk?.busy) line.push(t("Testing…"));
|
||||
else if (out) line.push(out.ok ? t("Reachable, {ms} ms", { ms: out.ms }) : t("Unreachable: {error}", { error: out.error || "" }));
|
||||
else if (out) line.push(out.ok ? t("Reachable, {ms} ms", { ms: out.ms }) : t("Unreachable: {error}", { error: proxyFailed(out) }));
|
||||
if (p.uses?.length) line.push(t("Used by {n}", { n: p.uses.length }));
|
||||
sub.textContent = sub.title = line.join(" · ");
|
||||
sub.classList.toggle("err", !!out && !out.ok && !chk?.busy);
|
||||
const val = el("div", "val");
|
||||
const test = el("button", "text", chk?.busy ? t("Testing…") : t("Test"));
|
||||
test.disabled = !!chk?.busy;
|
||||
test.onclick = () => {
|
||||
proxyChecks[p.id] = { busy: true };
|
||||
renderSettings();
|
||||
api("proxies/test", { id: p.id })
|
||||
.then((o) => { proxyChecks[p.id] = { out: o }; })
|
||||
.catch((e) => { proxyChecks[p.id] = { out: { ok: false, error: t(e.message) } }; })
|
||||
.finally(renderSettings);
|
||||
};
|
||||
test.onclick = () => testSavedProxy(p.id);
|
||||
const edit = el("button", "text", t("Edit"));
|
||||
edit.onclick = () => { proxyForm = { id: p.id, name: p.name, url: p.url, user: p.user || "", hasPass: !!p.hasPass }; renderSettings(); };
|
||||
edit.onclick = () => {
|
||||
proxyForm = { id: p.id, kind: ssh ? "ssh" : "proxy", name: p.name, url: addr, user: p.user || "", hasPass: !!p.hasPass, hasKey: !!p.hasKey, hostKey: p.hostKey || "" };
|
||||
renderSettings();
|
||||
};
|
||||
const del = el("button", "text", t("Delete"));
|
||||
del.disabled = !!p.uses?.length;
|
||||
del.onclick = () => writingPrefs(api("proxies/delete", { id: p.id })).then(done).catch(statusTErr);
|
||||
del.onclick = () => writingPrefs(api("proxies/delete", { id: p.id })).then((ns) => done(ns)).catch(statusTErr);
|
||||
val.append(test, edit, del);
|
||||
r.append(who, val);
|
||||
box.append(r);
|
||||
@@ -45,7 +70,7 @@ window.renderSavedProxies = function (s) {
|
||||
else if (!proxyForm) {
|
||||
const r = el("div", "row pref");
|
||||
const add = el("button", "text", t("Add proxy"));
|
||||
add.onclick = () => { proxyForm = { id: "", name: "", url: "", user: "", hasPass: false }; renderSettings(); };
|
||||
add.onclick = () => { proxyForm = { id: "", kind: "proxy", name: "", url: "", user: "", hasPass: false }; renderSettings(); };
|
||||
r.append(el("div", "who", ""), el("div", "val"));
|
||||
r.lastChild.append(add);
|
||||
box.append(r);
|
||||
@@ -53,28 +78,52 @@ window.renderSavedProxies = function (s) {
|
||||
};
|
||||
function proxyFormRow(done) {
|
||||
const f = proxyForm;
|
||||
const r = el("div", "row pref proxy-form");
|
||||
const ssh = f.kind === "ssh";
|
||||
const r = el("div", "row pref proxy-form" + (ssh ? " ssh" : ""));
|
||||
const name = input(f.name, t("Name"));
|
||||
const url = input(f.url, "http://127.0.0.1:7890");
|
||||
const user = input(f.user, t("Username (optional)"));
|
||||
const pass = input("", f.hasPass ? "••••••••" : t("Password (optional)"), "password");
|
||||
const url = input(f.url, ssh ? "203.0.113.5:22" : "http://127.0.0.1:7890");
|
||||
const userText = ssh ? t("User") : t("Username (optional)");
|
||||
const passText = ssh ? t("Password") : t("Password (optional)");
|
||||
const user = input(f.user, userText);
|
||||
const pass = input("", f.hasPass ? "••••••••" : passText, "password");
|
||||
name.setAttribute("aria-label", t("Name"));
|
||||
url.setAttribute("aria-label", t("Proxy address"));
|
||||
user.setAttribute("aria-label", t("Username (optional)"));
|
||||
pass.setAttribute("aria-label", t("Password (optional)"));
|
||||
url.setAttribute("aria-label", ssh ? t("SSH server") : t("Proxy address"));
|
||||
user.setAttribute("aria-label", userText);
|
||||
pass.setAttribute("aria-label", passText);
|
||||
const err = el("div", "sub err", f.err || "");
|
||||
const save = el("button", "text", t("Save"));
|
||||
const save = el("button", "text", f.busy ? t("Logging in…") : t("Save"));
|
||||
save.disabled = !!f.busy;
|
||||
const cancel = el("button", "text", t("Cancel"));
|
||||
// what is typed so far, kept when the kind or Advanced redraws the form
|
||||
const keep = () => Object.assign(f, { name: name.value, url: url.value, user: user.value });
|
||||
// a proxy or an SSH server: an SSH server is logged in to, and magpie
|
||||
// carries the requests through it itself (@laiuuui on X: a VPS gives
|
||||
// only SSH)
|
||||
const kind = segs([["proxy", t("Proxy")], ["ssh", "SSH"]], f.kind, (k) => { keep(); f.kind = k; f.err = ""; renderSettings(); });
|
||||
kind.classList.add("proxy-kind");
|
||||
let key = null;
|
||||
const body = () => {
|
||||
const b = { id: f.id, name: name.value.trim(), url: url.value.trim(), user: user.value.trim() };
|
||||
if (pass.value) b.pass = pass.value; // blank keeps the saved password
|
||||
if (ssh) {
|
||||
if (!isSSH(b.url)) b.url = "ssh://" + b.url;
|
||||
if (key?.value.trim()) b.key = key.value; // blank keeps the saved key
|
||||
if (f.trust) b.trustNewKey = true;
|
||||
}
|
||||
return b;
|
||||
};
|
||||
save.onclick = () => {
|
||||
if (!name.value.trim() || !url.value.trim()) return (name.value.trim() ? url : name).focus();
|
||||
const need = [name, url, ...(ssh ? [user] : [])].find((x) => !x.value.trim());
|
||||
if (need) return need.focus();
|
||||
const b = body();
|
||||
Object.assign(f, { name: b.name, url: b.url, user: b.user });
|
||||
writingPrefs(api("proxies/save", b)).then(done).catch((e) => { f.err = t(e.message); renderSettings(); });
|
||||
keep();
|
||||
// an SSH server is logged in to before it is kept, which takes a moment
|
||||
f.busy = ssh;
|
||||
if (ssh) renderSettings();
|
||||
let id = f.id;
|
||||
writingPrefs(api("proxies/save", b, (h) => { id = h.get("X-Magpie-Proxy") || id; }))
|
||||
.then((ns) => done(ns, id))
|
||||
.catch((e) => { f.busy = false; f.err = e.proxy ? proxyWhy(e.proxy) : t(e.message); renderSettings(); });
|
||||
};
|
||||
cancel.onclick = () => { proxyForm = null; renderSettings(); };
|
||||
for (const x of [name, url, user, pass]) {
|
||||
@@ -83,7 +132,37 @@ function proxyFormRow(done) {
|
||||
}
|
||||
const val = el("div", "proxy-controls");
|
||||
val.append(name, url, user, pass, cancel, save);
|
||||
r.append(val, err);
|
||||
r.append(kind, val);
|
||||
if (ssh) {
|
||||
// the key and the server's trusted host key: set by few, so folded
|
||||
const adv = el("details", "more advanced proxy-advanced");
|
||||
adv.open = !!f.adv;
|
||||
adv.ontoggle = () => { f.adv = adv.open; };
|
||||
adv.append(el("summary", "", t("Advanced")));
|
||||
const inner = el("div", "inner");
|
||||
key = el("textarea", "words proxy-key");
|
||||
key.placeholder = f.hasKey ? t("A private key is saved; paste another to replace it") : t("Private key (instead of or with the password)");
|
||||
key.setAttribute("aria-label", t("Private key"));
|
||||
key.spellcheck = false;
|
||||
key.rows = 3;
|
||||
key.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancel.onclick(); };
|
||||
inner.append(key);
|
||||
if (f.hostKey) {
|
||||
const hk = el("div", "proxy-hostkey");
|
||||
const fp = el("div", "sub", f.trust ? t("The key the server shows next is trusted") : t("Host key {fingerprint}", { fingerprint: f.hostKey }));
|
||||
fp.title = f.hostKey;
|
||||
hk.append(fp);
|
||||
if (!f.trust) {
|
||||
const again = el("button", "text", t("Trust a new key"));
|
||||
again.onclick = () => { keep(); f.trust = true; renderSettings(); };
|
||||
hk.append(again);
|
||||
}
|
||||
inner.append(hk);
|
||||
}
|
||||
adv.append(inner);
|
||||
r.append(adv);
|
||||
}
|
||||
r.append(err);
|
||||
err.hidden = !f.err;
|
||||
return r;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
+159
-28
@@ -3,6 +3,7 @@ package gui
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -26,6 +27,10 @@ type savedProxyJSON struct {
|
||||
URL string `json:"url"`
|
||||
User string `json:"user,omitempty"`
|
||||
HasPass bool `json:"hasPass,omitempty"`
|
||||
// an SSH server's: whether a private key is kept, and the SHA256
|
||||
// fingerprint of the host key trusted for it
|
||||
HasKey bool `json:"hasKey,omitempty"`
|
||||
HostKey string `json:"hostKey,omitempty"`
|
||||
// Uses is where it is chosen: Settings' own two, then providers,
|
||||
// accounts and keys
|
||||
Uses []proxyUseJSON `json:"uses,omitempty"`
|
||||
@@ -39,16 +44,40 @@ type proxyUseJSON struct {
|
||||
}
|
||||
|
||||
// proxyTestJSON is one connectivity check: whether a request got through
|
||||
// the proxy, how long it took, and where it left from.
|
||||
// the proxy, how long it took, and where it left from. A failure magpie
|
||||
// can explain has its reason in Why (netproxy.Why: a sentence the page
|
||||
// translates, its slots filled from Addr, Was and Now) and Go's words in
|
||||
// Error.
|
||||
type proxyTestJSON struct {
|
||||
OK bool `json:"ok"`
|
||||
Ms int64 `json:"ms,omitempty"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
Loc string `json:"loc,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Why string `json:"why,omitempty"`
|
||||
Addr string `json:"addr,omitempty"`
|
||||
Was string `json:"was,omitempty"`
|
||||
Now string `json:"now,omitempty"`
|
||||
At int64 `json:"at"`
|
||||
}
|
||||
|
||||
// failed is a check that failed with err, its reason in Why when it is
|
||||
// one magpie can say.
|
||||
func (o proxyTestJSON) failed(err error) proxyTestJSON {
|
||||
o.OK = false
|
||||
var w *netproxy.Why
|
||||
if errors.As(err, &w) {
|
||||
o.Why, o.Addr, o.Was, o.Now = w.Why, w.Addr, w.Was, w.Now
|
||||
o.Error = ""
|
||||
if w.Err != nil {
|
||||
o.Error = redactProxyErr(w.Err.Error())
|
||||
}
|
||||
return o
|
||||
}
|
||||
o.Error = redactProxyErr(err.Error())
|
||||
return o
|
||||
}
|
||||
|
||||
// proxyTestClient makes the check's request; a test swaps its own.
|
||||
var proxyTestClient = http.DefaultClient
|
||||
|
||||
@@ -64,7 +93,10 @@ func savedProxies() []savedProxyJSON {
|
||||
defer proxyTestsMu.Unlock()
|
||||
for _, p := range cur.Proxies {
|
||||
ref := settings.ProxyRef(p.ID)
|
||||
row := savedProxyJSON{ID: p.ID, Name: p.Name, URL: p.URL, User: p.User, HasPass: p.Pass != ""}
|
||||
row := savedProxyJSON{ID: p.ID, Name: p.Name, URL: p.URL, User: p.User, HasPass: p.Pass != "", HasKey: p.Key != ""}
|
||||
if p.HostKey != "" {
|
||||
row.HostKey = netproxy.HostKeyFingerprint(p.HostKey)
|
||||
}
|
||||
if strings.TrimSpace(cur.Proxy) == ref {
|
||||
row.Uses = append(row.Uses, proxyUseJSON{Where: "global"})
|
||||
}
|
||||
@@ -86,30 +118,55 @@ func savedProxies() []savedProxyJSON {
|
||||
return out
|
||||
}
|
||||
|
||||
// proxyIn is what the page sends to save or test a proxy. A nil Pass keeps
|
||||
// the saved password (an edit that left it blank).
|
||||
// proxyIn is what the page sends to save or test a proxy. A nil Pass or
|
||||
// Key keeps the saved one (an edit that left it blank). Trust drops the
|
||||
// SSH host key trusted for it, so the one the server presents now is
|
||||
// trusted instead.
|
||||
type proxyIn struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
User string `json:"user"`
|
||||
Pass *string `json:"pass"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
User string `json:"user"`
|
||||
Pass *string `json:"pass"`
|
||||
Key *string `json:"key"`
|
||||
Trust bool `json:"trustNewKey"`
|
||||
}
|
||||
|
||||
func (in proxyIn) named(cur []settings.NamedProxy) settings.NamedProxy {
|
||||
p := settings.NamedProxy{ID: strings.TrimSpace(in.ID), Name: in.Name, URL: in.URL, User: strings.TrimSpace(in.User)}
|
||||
p := settings.NamedProxy{ID: strings.TrimSpace(in.ID), Name: in.Name, URL: strings.TrimSpace(in.URL), User: strings.TrimSpace(in.User)}
|
||||
var old settings.NamedProxy
|
||||
for _, c := range cur {
|
||||
if c.ID == p.ID && p.ID != "" {
|
||||
old = c
|
||||
}
|
||||
}
|
||||
if in.Pass != nil {
|
||||
p.Pass = *in.Pass
|
||||
} else {
|
||||
for _, c := range cur {
|
||||
if c.ID == p.ID {
|
||||
p.Pass = c.Pass
|
||||
}
|
||||
p.Pass = old.Pass
|
||||
}
|
||||
if in.Key != nil {
|
||||
p.Key = strings.TrimSpace(*in.Key)
|
||||
if p.Key != "" {
|
||||
p.Key += "\n" // a PEM's last line ends in one
|
||||
}
|
||||
} else {
|
||||
p.Key = old.Key
|
||||
}
|
||||
// a host key is the server's: it goes with the address it was
|
||||
// trusted at
|
||||
if !in.Trust && old.URL == p.URL {
|
||||
p.HostKey = old.HostKey
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// sshLogin is whether saving p changes how its SSH server is logged in
|
||||
// to, from old: then the login is tried before the save.
|
||||
func sshLogin(p, old settings.NamedProxy) bool {
|
||||
return p.URL != old.URL || p.User != old.User || p.Pass != old.Pass || p.Key != old.Key || p.HostKey == ""
|
||||
}
|
||||
|
||||
func handleProxySave(rw http.ResponseWriter, r *http.Request) {
|
||||
var in proxyIn
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
@@ -119,11 +176,30 @@ func handleProxySave(rw http.ResponseWriter, r *http.Request) {
|
||||
s := settings.Load()
|
||||
p := in.named(s.Proxies)
|
||||
found := false
|
||||
var old settings.NamedProxy
|
||||
for _, c := range s.Proxies {
|
||||
if c.ID == p.ID && p.ID != "" {
|
||||
old = c
|
||||
}
|
||||
}
|
||||
if p.IsSSH() {
|
||||
if err := settings.CheckSSHProxy(p); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if sshLogin(p, old) {
|
||||
// logged in to once before it is kept: a refused login says
|
||||
// why here, and the server's key is trusted from now on
|
||||
key, err := netproxy.CheckSSH(r.Context(), p)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
p.HostKey = key
|
||||
}
|
||||
}
|
||||
if p.ID == "" {
|
||||
p.ID = settings.NewProxyID()
|
||||
if in.Pass == nil {
|
||||
p.Pass = ""
|
||||
}
|
||||
}
|
||||
for i := range s.Proxies {
|
||||
if s.Proxies[i].ID == p.ID {
|
||||
@@ -137,11 +213,13 @@ func handleProxySave(rw http.ResponseWriter, r *http.Request) {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
provider.ProxyEdited() // Claude Code's env holds an address, not the name
|
||||
netproxy.CloseSSH(p.ID) // its tunnel logs in again, as saved
|
||||
provider.ProxyEdited() // Claude Code's env holds an address, not the name
|
||||
// what it was checked as no longer says anything about it
|
||||
proxyTestsMu.Lock()
|
||||
delete(proxyTests, p.ID)
|
||||
proxyTestsMu.Unlock()
|
||||
rw.Header().Set("X-Magpie-Proxy", p.ID) // the page tests what it saved
|
||||
writeJSON(rw, settingsState())
|
||||
}
|
||||
|
||||
@@ -177,6 +255,7 @@ func handleProxyDelete(rw http.ResponseWriter, r *http.Request) {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
netproxy.CloseSSH(in.ID)
|
||||
proxyTestsMu.Lock()
|
||||
delete(proxyTests, in.ID)
|
||||
proxyTestsMu.Unlock()
|
||||
@@ -210,17 +289,23 @@ func handleProxyTest(rw http.ResponseWriter, r *http.Request) {
|
||||
p = in.named(cur)
|
||||
p.Name = "test"
|
||||
}
|
||||
addr, err := p.Address()
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
saved := strings.TrimSpace(in.ID) != "" && strings.TrimSpace(in.URL) == ""
|
||||
var out proxyTestJSON
|
||||
if p.IsSSH() {
|
||||
out = testSSH(r.Context(), p, saved)
|
||||
} else {
|
||||
addr, err := p.Address()
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
// a typed address is checked as saving would
|
||||
if err := settings.CheckProxy(addr); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
out = testProxy(r.Context(), addr)
|
||||
}
|
||||
// a typed address is checked as saving would
|
||||
if err := settings.CheckProxy(addr); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
out := testProxy(r.Context(), addr)
|
||||
if in.ID != "" && strings.TrimSpace(in.URL) == "" {
|
||||
proxyTestsMu.Lock()
|
||||
proxyTests[p.ID] = out
|
||||
@@ -229,12 +314,58 @@ func handleProxyTest(rw http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(rw, out)
|
||||
}
|
||||
|
||||
// testSSH is the check of an SSH proxy: a login first, which says why it
|
||||
// failed where a request through the tunnel would say only that SOCKS
|
||||
// did, then the request. A saved one is checked through the tunnel its
|
||||
// requests take; one being typed through a tunnel of its own, closed
|
||||
// after.
|
||||
func testSSH(ctx context.Context, p settings.NamedProxy, saved bool) proxyTestJSON {
|
||||
out := proxyTestJSON{At: time.Now().Unix()}
|
||||
if saved {
|
||||
if err := netproxy.SSHReady(ctx, p); err != nil {
|
||||
return out.failed(err)
|
||||
}
|
||||
addr, err := p.Address()
|
||||
if err != nil {
|
||||
return out.failed(err)
|
||||
}
|
||||
return sshTested(p, testProxy(ctx, addr))
|
||||
}
|
||||
key, err := netproxy.CheckSSH(ctx, p)
|
||||
if err != nil {
|
||||
return out.failed(err)
|
||||
}
|
||||
p.HostKey = key
|
||||
addr, done, err := netproxy.OpenSSH(p)
|
||||
if err != nil {
|
||||
return out.failed(err)
|
||||
}
|
||||
defer done()
|
||||
return sshTested(p, testProxy(ctx, addr))
|
||||
}
|
||||
|
||||
// sshTested says a failed check through an SSH tunnel about the SSH
|
||||
// server: the tunnel's own local address is nothing the user can check.
|
||||
func sshTested(p settings.NamedProxy, out proxyTestJSON) proxyTestJSON {
|
||||
if out.OK || out.Error == "" {
|
||||
return out
|
||||
}
|
||||
out.Why, out.Addr, out.Was, out.Now = "", "", "", ""
|
||||
if w := netproxy.SSHForwardWhy(p, out.Error); w != nil {
|
||||
out.Why, out.Addr = w.Why, w.Addr
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func testProxy(ctx context.Context, addr string) proxyTestJSON {
|
||||
leg := throughLeg(netproxy.With(ctx, addr), proxyTestClient)
|
||||
out := proxyTestJSON{Ms: leg.Ms, IP: leg.IP, Loc: leg.Loc, At: time.Now().Unix()}
|
||||
switch {
|
||||
case leg.Error != "":
|
||||
out.Error = redactProxyErr(leg.Error)
|
||||
if w := netproxy.ExplainServer(ctx, addr, out.Error); w != nil {
|
||||
out.Why, out.Addr = w.Why, w.Addr
|
||||
}
|
||||
case !leg.Proxied:
|
||||
out.Error = "the request didn't go to the proxy"
|
||||
default:
|
||||
|
||||
@@ -2,12 +2,16 @@ package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/netproxy/sshtest"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -136,3 +140,92 @@ func TestSavedProxyTest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An SSH server is saved from its host, user and password: the save logs
|
||||
// in first, so a refused login is said there and nothing is kept, and a
|
||||
// kept one shows the host key it trusts. Its test goes through the
|
||||
// server; the page is never sent the password.
|
||||
func TestSavedSSHProxyAPI(t *testing.T) {
|
||||
call, state := proxiesRig(t)
|
||||
client, _, _ := proxyCheckRig(t)
|
||||
old := proxyTestClient
|
||||
proxyTestClient = client
|
||||
t.Cleanup(func() { proxyTestClient = old })
|
||||
srv := sshtest.Start(t, sshtest.Options{User: "root", Pass: "s3cret", Handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(rw, "fl=1\nip=192.0.2.44\nloc=JP\n")
|
||||
})})
|
||||
|
||||
code, body := call("/api/proxies/save", `{"name":"VPS","url":"`+srv.URL+`","user":"root","pass":"wrong","key":""}`)
|
||||
var refused map[string]string
|
||||
json.Unmarshal([]byte(body), &refused)
|
||||
if code != 400 || refused["code"] != "proxy_why" || !strings.Contains(refused["why"], "turned the login away") || refused["addr"] != srv.Addr {
|
||||
t.Fatalf("a refused login: %d %s", code, body)
|
||||
}
|
||||
if len(state().SavedProxies) != 0 {
|
||||
t.Fatal("a proxy whose login was refused was kept")
|
||||
}
|
||||
|
||||
code, body = call("/api/proxies/save", `{"name":"VPS","url":"`+srv.URL+`","user":"root","pass":"s3cret","key":""}`)
|
||||
if code != 200 || strings.Contains(body, "s3cret") {
|
||||
t.Fatalf("save: %d %s", code, body)
|
||||
}
|
||||
ps := state().SavedProxies
|
||||
if len(ps) != 1 || !strings.HasPrefix(ps[0].HostKey, "SHA256:") || !ps[0].HasPass {
|
||||
t.Fatalf("state: %+v", ps)
|
||||
}
|
||||
t.Cleanup(func() { netproxy.CloseSSH(ps[0].ID) })
|
||||
_, body = call("/api/proxies/test", `{"id":"`+ps[0].ID+`"}`)
|
||||
var out proxyTestJSON
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil || !out.OK || out.IP != "192.0.2.44" {
|
||||
t.Fatalf("test through the SSH server: %s", body)
|
||||
}
|
||||
if got := srv.Targets(); len(got) == 0 || got[len(got)-1] != "trace.example.invalid:80" {
|
||||
t.Fatalf("the server was asked for %v", got)
|
||||
}
|
||||
|
||||
// typed where an HTTP proxy goes, the same server says what it is
|
||||
_, body = call("/api/proxies/test", `{"url":"http://`+srv.Addr+`"}`)
|
||||
out = proxyTestJSON{}
|
||||
json.Unmarshal([]byte(body), &out)
|
||||
if out.OK || !strings.Contains(out.Why, "is an SSH server") || out.Addr != srv.Addr {
|
||||
t.Fatalf("an SSH server as an HTTP proxy: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
// A server that lets magpie log in but won't forward says so about the
|
||||
// server, not about the tunnel's local port: OpenSSH with
|
||||
// AllowTcpForwarding no refuses the channel, and macOS 27's sshd hangs up
|
||||
// the whole connection.
|
||||
func TestSavedSSHProxyThatWontForward(t *testing.T) {
|
||||
call, state := proxiesRig(t)
|
||||
client, _, _ := proxyCheckRig(t)
|
||||
old := proxyTestClient
|
||||
proxyTestClient = client
|
||||
t.Cleanup(func() { proxyTestClient = old })
|
||||
for _, how := range []string{"prohibit", "hangup"} {
|
||||
srv := sshtest.Start(t, sshtest.Options{User: "root", Pass: "pw", Forward: how})
|
||||
if code, body := call("/api/proxies/save", `{"name":"`+how+`","url":"`+srv.URL+`","user":"root","pass":"pw"}`); code != 200 {
|
||||
t.Fatalf("%s: save %d %s", how, code, body)
|
||||
}
|
||||
var id string
|
||||
for _, p := range state().SavedProxies {
|
||||
if p.Name == how {
|
||||
id = p.ID
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { netproxy.CloseSSH(id) })
|
||||
_, body := call("/api/proxies/test", `{"id":"`+id+`"}`)
|
||||
var out proxyTestJSON
|
||||
json.Unmarshal([]byte(body), &out)
|
||||
if out.OK || !strings.Contains(out.Why, "won't forward") || out.Addr != srv.Addr {
|
||||
t.Errorf("%s: %s", how, body)
|
||||
}
|
||||
// the same before it is saved
|
||||
_, body = call("/api/proxies/test", `{"url":"`+srv.URL+`","user":"root","pass":"pw"}`)
|
||||
out = proxyTestJSON{}
|
||||
json.Unmarshal([]byte(body), &out)
|
||||
if out.OK || !strings.Contains(out.Why, "won't forward") || out.Addr != srv.Addr {
|
||||
t.Errorf("%s, unsaved: %s", how, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// An SSH server as a saved proxy (@laiuuui on X: a VPS gives only SSH, an
|
||||
// IP, port, user and password). Add proxy › SSH takes its host, user and
|
||||
// password; a refused login says why in the reader's language and keeps
|
||||
// what was typed; a kept one is tested at once. The private key and the
|
||||
// trusted host key wait under a closed Advanced.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const FP = "SHA256:Zx9bR4uE0oKp2m3Yd5qVw7nLs8tGh1jC6aF0eI2xQ4k";
|
||||
function server(lang, posts) {
|
||||
let cur = {
|
||||
theme: "light", lang, tray: "panel", currency: "usd", textSize: 100,
|
||||
proxy: "", proxyNow: "", proxySource: "off", pluginProxy: "",
|
||||
trayUsageEvery: 3, version: "test", dir: "/test", lanURLs: [],
|
||||
visionModels: [], imageGenModels: [], workbuddyCheckins: [],
|
||||
proxies: [{ id: "px2", name: "Home", url: "socks5://192.168.1.2:1080" }],
|
||||
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
|
||||
};
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data, status = 200, headers = {}) => route.fulfill({ status, headers, json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang, theme: "light", web: true })};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: cur.fx });
|
||||
if (url.pathname === "/api/settings") return json(cur);
|
||||
if (url.pathname === "/api/proxies/test") {
|
||||
const b = req.postDataJSON();
|
||||
posts.push({ test: b.id });
|
||||
return json({ ok: true, ms: 42, ip: "203.0.113.5", loc: "JP", at: 1 });
|
||||
}
|
||||
if (url.pathname === "/api/proxies/save") {
|
||||
const b = req.postDataJSON();
|
||||
posts.push({ save: b });
|
||||
// the server's words for a refused login (netproxy.sshWhy)
|
||||
if (b.pass === "wrong") return json({ error: "refused", code: "proxy_why", why: "the SSH server at {addr} turned the login away: check the user and the password or key", addr: "203.0.113.5:22", detail: "ssh: unable to authenticate" }, 400);
|
||||
const row = { id: "px3", name: b.name, url: b.url, user: b.user, hasPass: true, hostKey: FP };
|
||||
cur = { ...cur, proxies: [...cur.proxies.filter((p) => p.id !== "px3"), row] };
|
||||
return json(cur, 200, { "X-Magpie-Proxy": "px3" });
|
||||
}
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
return route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const labels = {
|
||||
en: { add: "Add proxy", name: "Name", save: "Save", edit: "Edit", host: "SSH server", user: "User", pass: "Password", refused: "turned the login away", ok: "Reachable, 42 ms", adv: "Advanced", key: "Private key", trust: "Trust a new key", trusted: "The key the server shows next is trusted" },
|
||||
zh: { add: "添加代理", name: "名称", save: "保存", edit: "编辑", host: "SSH 服务器", user: "用户", pass: "密码", refused: "拒绝登录", ok: "可连接,42 毫秒", adv: "高级", key: "私钥", trust: "信任新密钥", trusted: "将信任服务器下次出示的密钥" },
|
||||
"zh-TW": { add: "新增代理", name: "名稱", save: "儲存", edit: "編輯", host: "SSH 伺服器", user: "使用者", pass: "密碼", refused: "拒絕登入", ok: "可連線,42 毫秒", adv: "進階", key: "私鑰", trust: "信任新金鑰", trusted: "將信任伺服器下次出示的金鑰" },
|
||||
ja: { add: "プロキシを追加", name: "名前", save: "保存", edit: "編集", host: "SSH サーバー", user: "ユーザー", pass: "パスワード", refused: "ログインを拒否しました", ok: "接続できます、42 ms", adv: "詳細設定", key: "秘密鍵", trust: "新しい鍵を信頼", trusted: "サーバーが次に示す鍵を信頼します" },
|
||||
de: { add: "Proxy hinzufügen", name: "Name", save: "Speichern", edit: "Bearbeiten", host: "SSH-Server", user: "Benutzer", pass: "Passwort", refused: "hat die Anmeldung abgelehnt", ok: "Erreichbar, 42 ms", adv: "Erweitert", key: "Privater Schlüssel", trust: "Neuem Schlüssel vertrauen", trusted: "Der Schlüssel, den der Server als Nächstes zeigt, wird vertraut" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(labels)) {
|
||||
const l = labels[lang];
|
||||
for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}px: an SSH server is added as a saved proxy`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(4000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const posts = [], errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=settings&tab=network");
|
||||
const list = page.locator("#proxiesList");
|
||||
await list.getByText("Home", { exact: true }).waitFor();
|
||||
|
||||
await list.getByRole("button", { name: l.add, exact: true }).click();
|
||||
await list.getByRole("button", { name: "SSH", exact: true }).click();
|
||||
// the key waits under a closed Advanced
|
||||
const adv = list.locator("details.proxy-advanced");
|
||||
assert.equal(await adv.evaluate((d) => d.open), false);
|
||||
assert.equal(await list.getByLabel(l.key, { exact: true }).isVisible(), false);
|
||||
await list.getByLabel(l.name, { exact: true }).fill("VPS");
|
||||
await list.getByLabel(l.host, { exact: true }).fill("203.0.113.5:22");
|
||||
await list.getByLabel(l.user, { exact: true }).fill("root");
|
||||
await list.getByLabel(l.pass, { exact: true }).fill("wrong");
|
||||
await list.getByRole("button", { name: l.save, exact: true }).click();
|
||||
|
||||
// a refused login says why, translated, and keeps what was typed
|
||||
await list.locator(".proxy-form .sub.err").getByText(l.refused, { exact: false }).waitFor();
|
||||
const said = await list.locator(".proxy-form .sub.err").textContent();
|
||||
assert(said.includes("203.0.113.5:22") && said.includes("ssh: unable to authenticate"), said);
|
||||
assert.equal(await list.getByLabel(l.user, { exact: true }).inputValue(), "root");
|
||||
assert.equal(await list.getByLabel(l.host, { exact: true }).inputValue(), "203.0.113.5:22");
|
||||
|
||||
await list.getByLabel(l.pass, { exact: true }).fill("s3cret");
|
||||
await list.getByRole("button", { name: l.save, exact: true }).click();
|
||||
const row = list.locator(".saved-proxy").filter({ hasText: "VPS" });
|
||||
await row.getByText("SSH root@203.0.113.5:22", { exact: false }).waitFor();
|
||||
// tested at once
|
||||
await row.getByText(l.ok, { exact: false }).waitFor();
|
||||
const saves = posts.filter((p) => p.save).map((p) => p.save);
|
||||
assert.deepEqual([saves.at(-1).url, saves.at(-1).user, saves.at(-1).pass], ["ssh://203.0.113.5:22", "root", "s3cret"]);
|
||||
assert.equal(posts.filter((p) => p.test).at(-1).test, "px3");
|
||||
assert.equal(await page.evaluate(() => document.body.textContent.includes("s3cret")), false, "the password is never shown");
|
||||
|
||||
// the trusted host key, and trusting a new one
|
||||
await row.getByRole("button", { name: l.edit, exact: true }).click();
|
||||
await list.locator("details.proxy-advanced summary").click();
|
||||
await list.getByText(FP, { exact: false }).waitFor();
|
||||
await list.getByRole("button", { name: l.trust, exact: true }).click();
|
||||
await list.getByText(l.trusted, { exact: true }).waitFor();
|
||||
await list.getByRole("button", { name: l.save, exact: true }).click();
|
||||
await list.locator(".proxy-form").waitFor({ state: "detached" });
|
||||
const last = posts.filter((p) => p.save).at(-1).save;
|
||||
assert.equal(last.trustNewKey, true);
|
||||
assert.equal("pass" in last, false, "a blank password keeps the saved one");
|
||||
|
||||
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
|
||||
assert(over <= 0, `the page scrolls sideways by ${over}px`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -558,6 +558,9 @@ func Redact(raw string) string {
|
||||
return ""
|
||||
}
|
||||
if settings.IsProxyRef(raw) {
|
||||
if a := sshShown(raw); a != "" {
|
||||
return a
|
||||
}
|
||||
// a saved proxy shown as its address, with no login
|
||||
u.User = nil
|
||||
return u.String()
|
||||
@@ -573,6 +576,18 @@ func Redact(raw string) string {
|
||||
return address
|
||||
}
|
||||
|
||||
// sshShown is how a saved SSH proxy (a reference) is shown: its server's
|
||||
// address, not the tunnel's on loopback; "" for any other proxy.
|
||||
func sshShown(ref string) string {
|
||||
id := settings.ProxyID(ref)
|
||||
for _, p := range settings.Shared().Proxies {
|
||||
if p.ID == id && p.IsSSH() {
|
||||
return strings.TrimSpace(p.URL)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// fromEnv is the proxy the environment names for u: HTTPS_PROXY or
|
||||
// HTTP_PROXY as Go reads them, else ALL_PROXY (curl's, which Go doesn't
|
||||
// read: a shell with only ALL_PROXY=socks5://… set has curl go through it,
|
||||
|
||||
@@ -0,0 +1,596 @@
|
||||
package netproxy
|
||||
|
||||
// SSH proxies (@laiuuui on X: a VPS gives only SSH, an address, a port and
|
||||
// a password or key). A saved proxy whose address is ssh://host:port is
|
||||
// carried as `ssh -D` carries it, with no ssh command on the computer:
|
||||
// magpie logs in with golang.org/x/crypto/ssh and stands a SOCKS5 proxy on
|
||||
// loopback, with a login of its own, whose connections it opens as
|
||||
// channels of that SSH connection. The saved proxy resolves to that SOCKS
|
||||
// address (settings.SSHAddress), so every path a SOCKS proxy takes (a
|
||||
// transport, a CLI's *_PROXY, Bun's HTTP bridge) takes it too, and the
|
||||
// destination's name is resolved at the server's end.
|
||||
//
|
||||
// The server's key is trusted on first use and written into the saved
|
||||
// proxy (HostKey); after that a server presenting another key is refused,
|
||||
// until the user trusts it again from the proxy's editor.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
func init() { settings.SSHAddress = sshAddress }
|
||||
|
||||
// SSHTimeout bounds an SSH login: the TCP connection, the handshake and
|
||||
// the authentication together.
|
||||
var SSHTimeout = 15 * time.Second
|
||||
|
||||
// sshKeepAlive is how often an idle SSH connection is asked whether it is
|
||||
// still there; one that doesn't answer in SSHTimeout is dropped, and the
|
||||
// next request logs in again.
|
||||
var sshKeepAlive = 20 * time.Second
|
||||
|
||||
// HostKeyChangedError is an SSH server presenting a key other than the one
|
||||
// trusted for it.
|
||||
type HostKeyChangedError struct{ Was, Now string }
|
||||
|
||||
func (e *HostKeyChangedError) Error() string {
|
||||
return fmt.Sprintf("ssh: host key changed: was %s, now %s", e.Was, e.Now)
|
||||
}
|
||||
|
||||
// HostKeyFingerprint is the SHA256 fingerprint of a key in authorized_keys
|
||||
// form, as `ssh-keygen -l` prints it; "" for one that doesn't parse.
|
||||
func HostKeyFingerprint(authorized string) string {
|
||||
k, _, _, _, err := ssh.ParseAuthorizedKey([]byte(authorized))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return ssh.FingerprintSHA256(k)
|
||||
}
|
||||
|
||||
type sshTunnel struct {
|
||||
ln net.Listener
|
||||
addr string // socks5h://user:pass@127.0.0.1:port
|
||||
user, pass string
|
||||
save bool // a key trusted on first use is written into settings
|
||||
|
||||
mu sync.Mutex
|
||||
cfg settings.NamedProxy
|
||||
client *ssh.Client
|
||||
lastErr error
|
||||
closed bool
|
||||
|
||||
connMu sync.Mutex // one login at a time
|
||||
}
|
||||
|
||||
var (
|
||||
tunnelsMu sync.Mutex
|
||||
tunnels = map[string]*sshTunnel{} // by saved proxy id
|
||||
)
|
||||
|
||||
// sshAddress is the SOCKS address of the saved SSH proxy p, a tunnel stood
|
||||
// up for it the first time it is asked for. The SSH login happens when a
|
||||
// request first goes through it, not here: this runs for every request.
|
||||
func sshAddress(p settings.NamedProxy) (string, error) {
|
||||
tunnelsMu.Lock()
|
||||
defer tunnelsMu.Unlock()
|
||||
if t := tunnels[p.ID]; t != nil {
|
||||
if t.same(p) {
|
||||
return t.addr, nil
|
||||
}
|
||||
t.Close()
|
||||
delete(tunnels, p.ID)
|
||||
}
|
||||
t, err := openTunnel(p, p.ID != "")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if p.ID != "" {
|
||||
tunnels[p.ID] = t
|
||||
}
|
||||
return t.addr, nil
|
||||
}
|
||||
|
||||
// CloseSSH ends the tunnel of the saved proxy id: it was deleted, or its
|
||||
// host key is to be learnt again.
|
||||
func CloseSSH(id string) {
|
||||
tunnelsMu.Lock()
|
||||
defer tunnelsMu.Unlock()
|
||||
if t := tunnels[id]; t != nil {
|
||||
t.Close()
|
||||
delete(tunnels, id)
|
||||
}
|
||||
}
|
||||
|
||||
// SSHReady logs in to the saved SSH proxy p through the tunnel requests
|
||||
// take (nil when it is logged in already), so a check can say why it
|
||||
// can't carry them: a refused login reaches a request only as a SOCKS
|
||||
// failure.
|
||||
func SSHReady(ctx context.Context, p settings.NamedProxy) error {
|
||||
if _, err := sshAddress(p); err != nil {
|
||||
return err
|
||||
}
|
||||
tunnelsMu.Lock()
|
||||
t := tunnels[p.ID]
|
||||
tunnelsMu.Unlock()
|
||||
if t == nil {
|
||||
return errors.New("the SSH proxy isn't saved")
|
||||
}
|
||||
_, err := t.conn(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// OpenSSH stands a tunnel for an SSH proxy not saved yet (a check of what
|
||||
// is being typed): its address, and a func that ends it. A key it trusts
|
||||
// on first use is kept in it alone.
|
||||
func OpenSSH(p settings.NamedProxy) (string, func(), error) {
|
||||
t, err := openTunnel(p, false)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return t.addr, t.Close, nil
|
||||
}
|
||||
|
||||
// CheckSSH logs in to the SSH server of p once, and says the key it
|
||||
// presented (authorized_keys form): the one to trust, when p trusts none
|
||||
// yet. A server whose key differs from the trusted one is refused
|
||||
// (HostKeyChangedError).
|
||||
func CheckSSH(ctx context.Context, p settings.NamedProxy) (string, error) {
|
||||
t := &sshTunnel{cfg: p}
|
||||
c, err := t.login(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
c.Close()
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.cfg.HostKey, nil
|
||||
}
|
||||
|
||||
func openTunnel(p settings.NamedProxy, save bool) (*sshTunnel, error) {
|
||||
if _, _, err := sshTarget(p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the SSH proxy's local end didn't start: %w", err)
|
||||
}
|
||||
t := &sshTunnel{ln: ln, cfg: p, user: "magpie", pass: randomHex(16), save: save}
|
||||
t.addr = (&url.URL{Scheme: "socks5h", User: url.UserPassword(t.user, t.pass), Host: ln.Addr().String()}).String()
|
||||
go func() {
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go t.serve(c)
|
||||
}
|
||||
}()
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func randomHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// same is whether the tunnel carries the saved proxy p as it is now. A
|
||||
// host key the tunnel learnt itself and p doesn't hold yet (being written)
|
||||
// is the same; one p trusts that differs is not.
|
||||
func (t *sshTunnel) same(p settings.NamedProxy) bool {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
c := t.cfg
|
||||
if c.URL != p.URL || c.User != p.User || c.Pass != p.Pass || c.Key != p.Key {
|
||||
return false
|
||||
}
|
||||
return p.HostKey == "" || p.HostKey == c.HostKey
|
||||
}
|
||||
|
||||
// Close ends the tunnel: its listener and its SSH connection.
|
||||
func (t *sshTunnel) Close() {
|
||||
t.mu.Lock()
|
||||
t.closed = true
|
||||
c := t.client
|
||||
t.client = nil
|
||||
t.mu.Unlock()
|
||||
if t.ln != nil {
|
||||
t.ln.Close()
|
||||
}
|
||||
if c != nil {
|
||||
c.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// sshTarget is the host:port of p's server and its login.
|
||||
func sshTarget(p settings.NamedProxy) (string, *ssh.ClientConfig, error) {
|
||||
u, err := url.Parse(strings.TrimSpace(p.URL))
|
||||
if err != nil || u.Hostname() == "" {
|
||||
return "", nil, &Why{Why: "an SSH server looks like 203.0.113.5:22"}
|
||||
}
|
||||
port := u.Port()
|
||||
if port == "" {
|
||||
port = "22"
|
||||
}
|
||||
var auth []ssh.AuthMethod
|
||||
if strings.TrimSpace(p.Key) != "" {
|
||||
signer, err := ssh.ParsePrivateKey([]byte(p.Key))
|
||||
var missing *ssh.PassphraseMissingError
|
||||
if errors.As(err, &missing) {
|
||||
if p.Pass == "" {
|
||||
return "", nil, &Why{Why: "the private key has a passphrase: type it in the password field"}
|
||||
}
|
||||
signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(p.Key), []byte(p.Pass))
|
||||
if err != nil {
|
||||
return "", nil, &Why{Why: "the private key's passphrase is wrong"}
|
||||
}
|
||||
} else if err != nil {
|
||||
return "", nil, &Why{Why: "the private key can't be read: paste the whole file, from its BEGIN line to its END line", Err: err}
|
||||
}
|
||||
auth = append(auth, ssh.PublicKeys(signer))
|
||||
}
|
||||
if p.Pass != "" {
|
||||
pass := p.Pass
|
||||
auth = append(auth, ssh.Password(pass), ssh.KeyboardInteractive(func(_, _ string, qs []string, _ []bool) ([]string, error) {
|
||||
out := make([]string, len(qs))
|
||||
for i := range out {
|
||||
out[i] = pass
|
||||
}
|
||||
return out, nil
|
||||
}))
|
||||
}
|
||||
if len(auth) == 0 {
|
||||
return "", nil, &Why{Why: "an SSH server needs a password or a private key"}
|
||||
}
|
||||
cfg := &ssh.ClientConfig{User: strings.TrimSpace(p.User), Auth: auth, Timeout: SSHTimeout}
|
||||
if k, _, _, _, err := ssh.ParseAuthorizedKey([]byte(p.HostKey)); err == nil {
|
||||
// the server is asked for the kind of key trusted, which it may
|
||||
// hold beside others: offered another kind, it would look changed
|
||||
cfg.HostKeyAlgorithms = hostKeyAlgorithms(k.Type())
|
||||
}
|
||||
return net.JoinHostPort(u.Hostname(), port), cfg, nil
|
||||
}
|
||||
|
||||
func hostKeyAlgorithms(keyType string) []string {
|
||||
if keyType == ssh.KeyAlgoRSA {
|
||||
return []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA}
|
||||
}
|
||||
return []string{keyType}
|
||||
}
|
||||
|
||||
// login opens an SSH connection to the tunnel's server, checking its key
|
||||
// against the trusted one, or trusting it when there is none.
|
||||
func (t *sshTunnel) login(ctx context.Context) (*ssh.Client, error) {
|
||||
t.mu.Lock()
|
||||
p := t.cfg
|
||||
t.mu.Unlock()
|
||||
addr, cfg, err := sshTarget(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var learnt string
|
||||
cfg.HostKeyCallback = func(_ string, _ net.Addr, key ssh.PublicKey) error {
|
||||
got := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key)))
|
||||
if p.HostKey == "" {
|
||||
learnt = got
|
||||
return nil
|
||||
}
|
||||
want, _, _, _, err := ssh.ParseAuthorizedKey([]byte(p.HostKey))
|
||||
if err == nil && bytes.Equal(want.Marshal(), key.Marshal()) {
|
||||
return nil
|
||||
}
|
||||
was := HostKeyFingerprint(p.HostKey)
|
||||
if was == "" {
|
||||
was = "unreadable"
|
||||
}
|
||||
return &HostKeyChangedError{Was: was, Now: ssh.FingerprintSHA256(key)}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, SSHTimeout)
|
||||
defer cancel()
|
||||
raw, err := (&net.Dialer{}).DialContext(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
return nil, sshWhy(addr, err)
|
||||
}
|
||||
if d, ok := ctx.Deadline(); ok {
|
||||
_ = raw.SetDeadline(d)
|
||||
}
|
||||
// a context ended mid-handshake ends it
|
||||
stop := context.AfterFunc(ctx, func() { _ = raw.SetDeadline(time.Unix(1, 0)) })
|
||||
conn, chans, reqs, err := ssh.NewClientConn(raw, addr, cfg)
|
||||
stop()
|
||||
if err != nil {
|
||||
raw.Close()
|
||||
return nil, sshWhy(addr, err)
|
||||
}
|
||||
_ = raw.SetDeadline(time.Time{})
|
||||
if learnt != "" {
|
||||
t.mu.Lock()
|
||||
if t.cfg.HostKey == "" {
|
||||
t.cfg.HostKey = learnt
|
||||
}
|
||||
t.mu.Unlock()
|
||||
if t.save {
|
||||
saveHostKey(p, learnt)
|
||||
}
|
||||
}
|
||||
return ssh.NewClient(conn, chans, reqs), nil
|
||||
}
|
||||
|
||||
// saveHostKey writes the key trusted on first use into the saved proxy, if
|
||||
// it is still the one logged in to and trusts none.
|
||||
func saveHostKey(p settings.NamedProxy, key string) {
|
||||
s := settings.Load()
|
||||
for i := range s.Proxies {
|
||||
q := &s.Proxies[i]
|
||||
if q.ID == p.ID && q.URL == p.URL && q.HostKey == "" {
|
||||
q.HostKey = key
|
||||
_ = settings.Save(s)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SSHForwardWhy is why a request through a logged-in SSH proxy failed,
|
||||
// from the error its local SOCKS end gave: the server's own address, not
|
||||
// the tunnel's, is the one to check. nil when the error says nothing an
|
||||
// SSH server is known for.
|
||||
func SSHForwardWhy(p settings.NamedProxy, msg string) *Why {
|
||||
addr, _, err := sshTarget(p)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
w := &Why{Addr: addr, Err: textErr(msg)}
|
||||
switch {
|
||||
case strings.Contains(msg, "not allowed by ruleset"):
|
||||
w.Why = "the SSH server at {addr} let magpie log in but won't forward connections: its sshd_config needs AllowTcpForwarding yes"
|
||||
case strings.Contains(msg, "connection refused"), strings.Contains(msg, "unreachable"):
|
||||
w.Why = "the SSH server at {addr} couldn't reach the site: check that the server itself reaches the internet"
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// sshWhy is an SSH login's failure said as Why: what to check, the
|
||||
// library's words beside it.
|
||||
func sshWhy(addr string, err error) error {
|
||||
w := &Why{Addr: addr, Err: err}
|
||||
var changed *HostKeyChangedError
|
||||
msg := err.Error()
|
||||
switch {
|
||||
case errors.As(err, &changed):
|
||||
w.Why, w.Was, w.Now = "the SSH server's host key changed: it was {was} and is now {now}. If the server was reinstalled, trust the new key under Advanced", changed.Was, changed.Now
|
||||
case strings.Contains(msg, "unable to authenticate"), strings.Contains(msg, "unexpected message type 51 "):
|
||||
// 51 is a refused login: OpenSSH without PAM refuses
|
||||
// keyboard-interactive at once, where the library waits for its
|
||||
// questions (60), after the password was turned away
|
||||
w.Why = "the SSH server at {addr} turned the login away: check the user and the password or key"
|
||||
case strings.Contains(msg, "connection refused"):
|
||||
w.Why = "nothing answers SSH at {addr}: check the address and port"
|
||||
case strings.Contains(msg, "no such host"):
|
||||
w.Why = "the SSH server's name doesn't resolve"
|
||||
case strings.Contains(msg, "i/o timeout"), strings.Contains(msg, "deadline exceeded"):
|
||||
w.Why = "no answer from {addr} in time: check the address, and that the server's firewall lets SSH in"
|
||||
case strings.Contains(msg, "handshake failed"), strings.Contains(msg, "EOF"):
|
||||
w.Why = "{addr} doesn't speak SSH, or hung up"
|
||||
default:
|
||||
w.Why = "SSH to {addr} failed"
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// conn is the tunnel's SSH connection, logged in to now if it has none.
|
||||
func (t *sshTunnel) conn(ctx context.Context) (*ssh.Client, error) {
|
||||
t.connMu.Lock()
|
||||
defer t.connMu.Unlock()
|
||||
t.mu.Lock()
|
||||
if c := t.client; c != nil || t.closed {
|
||||
t.mu.Unlock()
|
||||
if c == nil {
|
||||
return nil, errors.New("the SSH proxy was closed")
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
t.mu.Unlock()
|
||||
c, err := t.login(ctx)
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.lastErr = err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if t.closed {
|
||||
c.Close()
|
||||
return nil, errors.New("the SSH proxy was closed")
|
||||
}
|
||||
t.client = c
|
||||
go t.watch(c)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// watch drops c from the tunnel when it ends, or stops answering, so the
|
||||
// next request logs in again instead of waiting on a dead connection.
|
||||
func (t *sshTunnel) watch(c *ssh.Client) {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
_ = c.Wait()
|
||||
close(done)
|
||||
}()
|
||||
tick := time.NewTicker(sshKeepAlive)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
t.drop(c)
|
||||
return
|
||||
case <-tick.C:
|
||||
answered := make(chan error, 1)
|
||||
go func() { _, _, err := c.SendRequest("keepalive@openssh.com", true, nil); answered <- err }()
|
||||
select {
|
||||
case err := <-answered:
|
||||
if err != nil {
|
||||
c.Close()
|
||||
}
|
||||
case <-time.After(SSHTimeout):
|
||||
c.Close()
|
||||
case <-done:
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *sshTunnel) drop(c *ssh.Client) {
|
||||
t.mu.Lock()
|
||||
if t.client == c {
|
||||
t.client = nil
|
||||
}
|
||||
t.mu.Unlock()
|
||||
c.Close()
|
||||
}
|
||||
|
||||
// dial opens addr through the SSH server, logging in again once when the
|
||||
// connection it had turned out to be gone.
|
||||
func (t *sshTunnel) dial(ctx context.Context, addr string) (net.Conn, error) {
|
||||
c, err := t.conn(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
up, err := c.DialContext(ctx, "tcp", addr)
|
||||
var open *ssh.OpenChannelError
|
||||
if err == nil || errors.As(err, &open) || ctx.Err() != nil {
|
||||
return up, err
|
||||
}
|
||||
t.drop(c)
|
||||
if c, err = t.conn(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.DialContext(ctx, "tcp", addr)
|
||||
}
|
||||
|
||||
// serve is one SOCKS5 client of the tunnel: its login checked, then one
|
||||
// CONNECT carried through the SSH server.
|
||||
func (t *sshTunnel) serve(c net.Conn) {
|
||||
defer c.Close()
|
||||
_ = c.SetDeadline(time.Now().Add(SSHTimeout + 15*time.Second))
|
||||
var b [2]byte
|
||||
if _, err := io.ReadFull(c, b[:]); err != nil || b[0] != 5 {
|
||||
return
|
||||
}
|
||||
methods := make([]byte, b[1])
|
||||
if _, err := io.ReadFull(c, methods); err != nil {
|
||||
return
|
||||
}
|
||||
if !bytes.Contains(methods, []byte{2}) {
|
||||
_, _ = c.Write([]byte{5, 0xff})
|
||||
return
|
||||
}
|
||||
if _, err := c.Write([]byte{5, 2}); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := io.ReadFull(c, b[:]); err != nil || b[0] != 1 {
|
||||
return
|
||||
}
|
||||
user := make([]byte, b[1])
|
||||
if _, err := io.ReadFull(c, user); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := io.ReadFull(c, b[:1]); err != nil {
|
||||
return
|
||||
}
|
||||
pass := make([]byte, b[0])
|
||||
if _, err := io.ReadFull(c, pass); err != nil {
|
||||
return
|
||||
}
|
||||
if subtle.ConstantTimeCompare(user, []byte(t.user)) != 1 || subtle.ConstantTimeCompare(pass, []byte(t.pass)) != 1 {
|
||||
_, _ = c.Write([]byte{1, 1})
|
||||
return
|
||||
}
|
||||
if _, err := c.Write([]byte{1, 0}); err != nil {
|
||||
return
|
||||
}
|
||||
var h [4]byte
|
||||
if _, err := io.ReadFull(c, h[:]); err != nil || h[0] != 5 {
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch h[3] {
|
||||
case 1, 4:
|
||||
ip := make([]byte, map[byte]int{1: 4, 4: 16}[h[3]])
|
||||
if _, err := io.ReadFull(c, ip); err != nil {
|
||||
return
|
||||
}
|
||||
host = net.IP(ip).String()
|
||||
case 3:
|
||||
if _, err := io.ReadFull(c, b[:1]); err != nil {
|
||||
return
|
||||
}
|
||||
name := make([]byte, b[0])
|
||||
if _, err := io.ReadFull(c, name); err != nil {
|
||||
return
|
||||
}
|
||||
host = string(name)
|
||||
default:
|
||||
socksReply(c, 8)
|
||||
return
|
||||
}
|
||||
if _, err := io.ReadFull(c, b[:]); err != nil {
|
||||
return
|
||||
}
|
||||
if h[1] != 1 { // CONNECT only
|
||||
socksReply(c, 7)
|
||||
return
|
||||
}
|
||||
addr := net.JoinHostPort(host, strconv.Itoa(int(binary.BigEndian.Uint16(b[:]))))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), SSHTimeout+15*time.Second)
|
||||
up, err := t.dial(ctx, addr)
|
||||
cancel()
|
||||
if err != nil {
|
||||
var open *ssh.OpenChannelError
|
||||
code := byte(1)
|
||||
if errors.As(err, &open) {
|
||||
code = 5
|
||||
if open.Reason == ssh.Prohibited {
|
||||
code = 2
|
||||
}
|
||||
} else if strings.Contains(err.Error(), "in response to channel open") {
|
||||
// the server hung up on the forward, as macOS 27's sshd
|
||||
// does: it won't forward, like a refusal
|
||||
code = 2
|
||||
}
|
||||
socksReply(c, code)
|
||||
return
|
||||
}
|
||||
defer up.Close()
|
||||
if !socksReply(c, 0) {
|
||||
return
|
||||
}
|
||||
_ = c.SetDeadline(time.Time{})
|
||||
done := make(chan struct{}, 2)
|
||||
go func() { _, _ = io.Copy(up, c); closeWrite(up); done <- struct{}{} }()
|
||||
go func() { _, _ = io.Copy(c, up); closeWrite(c); done <- struct{}{} }()
|
||||
<-done
|
||||
<-done
|
||||
}
|
||||
|
||||
func socksReply(c net.Conn, code byte) bool {
|
||||
_, err := c.Write([]byte{5, code, 0, 1, 0, 0, 0, 0, 0, 0})
|
||||
return err == nil
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/netproxy/sshtest"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// sshVia gets target with the proxy choice, as a vendor request takes it.
|
||||
func sshVia(t *testing.T, choice, target string) (string, error) {
|
||||
t.Helper()
|
||||
base := &http.Transport{Proxy: Func}
|
||||
defer base.CloseIdleConnections()
|
||||
req, _ := http.NewRequestWithContext(With(context.Background(), choice), http.MethodGet, target, nil)
|
||||
res, err := Dispatch(base).RoundTrip(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
func saveProxies(t *testing.T, ps ...settings.NamedProxy) {
|
||||
t.Helper()
|
||||
if err := settings.Save(settings.Settings{Proxies: ps}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range ps {
|
||||
id := p.ID
|
||||
t.Cleanup(func() { CloseSSH(id) })
|
||||
}
|
||||
}
|
||||
|
||||
func savedProxy(t *testing.T, id string) settings.NamedProxy {
|
||||
t.Helper()
|
||||
for _, p := range settings.Load().Proxies {
|
||||
if p.ID == id {
|
||||
return p
|
||||
}
|
||||
}
|
||||
t.Fatalf("no saved proxy %s", id)
|
||||
return settings.NamedProxy{}
|
||||
}
|
||||
|
||||
// A saved SSH server carries a request as ssh -D would, with no ssh
|
||||
// command: the user's host, user and password are all it takes
|
||||
// (@laiuuui on X, whose VPS gives only SSH). The host key is trusted on
|
||||
// first use and kept; the request reaches the vendor's name through the
|
||||
// server, which resolves it (socks5h), and the login happens once.
|
||||
func TestSSHProxyCarriesRequests(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
srv := sshtest.Start(t, sshtest.Options{User: "root", Pass: "pw:@/ #1"})
|
||||
saveProxies(t, settings.NamedProxy{ID: "pxssh", Name: "VPS", URL: srv.URL, User: "root", Pass: "pw:@/ #1"})
|
||||
for range 2 {
|
||||
got, err := sshVia(t, "@pxssh", "http://vendor.example/v1/models")
|
||||
if err != nil || got != "carried vendor.example/v1/models" {
|
||||
t.Fatalf("through the SSH server: %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
if got := srv.Targets(); len(got) == 0 || got[0] != "vendor.example:80" {
|
||||
t.Fatalf("the server was asked for %v, want vendor.example:80 by name", got)
|
||||
}
|
||||
if n := srv.Logins(); n != 1 {
|
||||
t.Fatalf("%d logins for two requests, want 1", n)
|
||||
}
|
||||
if hk := savedProxy(t, "pxssh").HostKey; hk != srv.HostKey {
|
||||
t.Fatalf("host key kept %q, want %q", hk, srv.HostKey)
|
||||
}
|
||||
// the address a request is shown with is the server, never the
|
||||
// tunnel's own login
|
||||
if got := Redact("@pxssh"); got != srv.URL {
|
||||
t.Fatalf("Redact(@pxssh) = %q, want %q", got, srv.URL)
|
||||
}
|
||||
}
|
||||
|
||||
// A private key logs in as a password does, and one with a passphrase
|
||||
// takes it from the password field.
|
||||
func TestSSHProxyKeyLogin(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
signer, pemKey := sshtest.NewKey(t)
|
||||
srv := sshtest.Start(t, sshtest.Options{User: "deploy", Key: signer.PublicKey()})
|
||||
saveProxies(t, settings.NamedProxy{ID: "pxkey", Name: "VPS", URL: srv.URL, User: "deploy", Key: pemKey})
|
||||
if got, err := sshVia(t, "@pxkey", "http://vendor.example/k"); err != nil || got != "carried vendor.example/k" {
|
||||
t.Fatalf("with a key: %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A server whose host key isn't the trusted one is refused, and the
|
||||
// failure says what changed; nothing goes through it.
|
||||
func TestSSHProxyRefusesAChangedHostKey(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
srv := sshtest.Start(t, sshtest.Options{User: "root", Pass: "pw"})
|
||||
other := sshtest.Start(t, sshtest.Options{User: "root", Pass: "pw"})
|
||||
p := settings.NamedProxy{ID: "pxmitm", Name: "VPS", URL: srv.URL, User: "root", Pass: "pw", HostKey: other.HostKey}
|
||||
saveProxies(t, p)
|
||||
if got, err := sshVia(t, "@pxmitm", "http://vendor.example/x"); err == nil {
|
||||
t.Fatalf("a changed host key carried the request: %q", got)
|
||||
}
|
||||
err := SSHReady(context.Background(), p)
|
||||
var changed *HostKeyChangedError
|
||||
var why *Why
|
||||
if !errors.As(err, &changed) || !errors.As(err, &why) || !strings.Contains(why.Why, "host key changed") || why.Now == "" || why.Was == why.Now {
|
||||
t.Fatalf("SSHReady = %v, want a host key change said", err)
|
||||
}
|
||||
if len(srv.Targets()) != 0 {
|
||||
t.Fatalf("a channel was opened through the server: %v", srv.Targets())
|
||||
}
|
||||
if hk := savedProxy(t, "pxmitm").HostKey; hk != other.HostKey {
|
||||
t.Fatalf("the trusted key was written over: %q", hk)
|
||||
}
|
||||
}
|
||||
|
||||
// A refused login, a port with no server and a server that isn't SSH each
|
||||
// say why, in words the page translates.
|
||||
func TestSSHProxySaysWhyItFailed(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
srv := sshtest.Start(t, sshtest.Options{User: "root", Pass: "pw"})
|
||||
pam := sshtest.Start(t, sshtest.Options{User: "root", Pass: "pw", Interactive: true})
|
||||
notSSH := fakeHTTPProxy(t, "u", "p")
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
p settings.NamedProxy
|
||||
want string
|
||||
}{
|
||||
{"wrong password", settings.NamedProxy{URL: srv.URL, User: "root", Pass: "nope"}, "turned the login away"},
|
||||
// a real Ubuntu sshd with UsePAM no answers keyboard-interactive
|
||||
// with 51 where the library waits for 60
|
||||
{"wrong password, keyboard-interactive refused", settings.NamedProxy{URL: pam.URL, User: "root", Pass: "nope"}, "turned the login away"},
|
||||
// port 1: a freed test port can be handed to anything next
|
||||
{"nothing listens", settings.NamedProxy{URL: "ssh://127.0.0.1:1", User: "root", Pass: "pw"}, "nothing answers SSH"},
|
||||
{"not SSH", settings.NamedProxy{URL: "ssh://" + strings.TrimPrefix(notSSH.URL, "http://"), User: "root", Pass: "pw"}, "doesn't speak SSH"},
|
||||
{"no login", settings.NamedProxy{URL: srv.URL, User: "root"}, "needs a password or a private key"},
|
||||
{"bad key", settings.NamedProxy{URL: srv.URL, User: "root", Key: "-----BEGIN OPENSSH PRIVATE KEY-----\nnope\n"}, "can't be read"},
|
||||
} {
|
||||
_, err := CheckSSH(context.Background(), c.p)
|
||||
var why *Why
|
||||
if !errors.As(err, &why) || !strings.Contains(why.Why, c.want) {
|
||||
t.Errorf("%s: %v, want a Why with %q", c.name, err, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The tunnel's SOCKS end takes only magpie's own login: another program
|
||||
// on this computer can't send through the user's server.
|
||||
func TestSSHProxyLocalEndNeedsItsLogin(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
srv := sshtest.Start(t, sshtest.Options{User: "root", Pass: "pw"})
|
||||
saveProxies(t, settings.NamedProxy{ID: "pxlocal", Name: "VPS", URL: srv.URL, User: "root", Pass: "pw"})
|
||||
addr, ok := settings.ResolveProxy("@pxlocal")
|
||||
u, err := url.Parse(addr)
|
||||
if !ok || err != nil || u.Scheme != "socks5h" || u.User == nil {
|
||||
t.Fatalf("resolved to %q (%v)", addr, err)
|
||||
}
|
||||
if c, err := DialSOCKS(context.Background(), u, "vendor.example:80"); err != nil {
|
||||
t.Fatalf("with its login: %v", err)
|
||||
} else {
|
||||
c.Close()
|
||||
}
|
||||
for _, who := range []*url.Userinfo{nil, url.UserPassword("magpie", "guess")} {
|
||||
bad := *u
|
||||
bad.User = who
|
||||
if c, err := DialSOCKS(context.Background(), &bad, "vendor.example:80"); err == nil {
|
||||
c.Close()
|
||||
t.Fatalf("the SOCKS end let %v in", who)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An SSH server typed where an HTTP or SOCKS proxy goes says so, from
|
||||
// the bytes a real check reads off it. A real OpenSSH's banner has a
|
||||
// space, which Go reads as an HTTP status line with a bad code; the
|
||||
// check then reads the server's first bytes.
|
||||
func TestProxyFailureNamesAnSSHServer(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
for _, version := range []string{"", "SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20"} {
|
||||
srv := sshtest.Start(t, sshtest.Options{User: "root", Pass: "pw", Version: version})
|
||||
for _, scheme := range []string{"http", "socks5"} {
|
||||
addr := scheme + "://" + srv.Addr
|
||||
_, err := sshVia(t, addr, "http://vendor.example/x")
|
||||
if err == nil {
|
||||
t.Fatalf("%s: an SSH server carried a request", scheme)
|
||||
}
|
||||
w := ExplainServer(context.Background(), addr, err.Error())
|
||||
if w == nil || !strings.Contains(w.Why, "is an SSH server") || w.Addr != srv.Addr {
|
||||
t.Errorf("%s, banner %q: %q explained as %+v", scheme, version, err, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
// an HTTP server that answers nonsense isn't called SSH
|
||||
junk := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
c, buf, _ := rw.(http.Hijacker).Hijack()
|
||||
buf.WriteString("HTTP/1.1 abc\r\n\r\n")
|
||||
buf.Flush()
|
||||
c.Close()
|
||||
}))
|
||||
t.Cleanup(junk.Close)
|
||||
addr := "http://" + strings.TrimPrefix(junk.URL, "http://")
|
||||
_, err := sshVia(t, addr, "http://vendor.example/x")
|
||||
if err == nil {
|
||||
t.Fatal("junk carried a request")
|
||||
}
|
||||
if w := ExplainServer(context.Background(), addr, err.Error()); w == nil || strings.Contains(w.Why, "SSH server") {
|
||||
t.Errorf("an HTTP server answering junk: %+v", w)
|
||||
}
|
||||
}
|
||||
|
||||
// An ssh:// address can't be a choice by itself: its login goes with a
|
||||
// saved proxy.
|
||||
func TestInlineSSHAddressRefused(t *testing.T) {
|
||||
if err := settings.CheckProxy("ssh://203.0.113.5:22"); err == nil || !strings.Contains(err.Error(), "saved proxy") {
|
||||
t.Fatalf("CheckProxy(ssh://) = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A backup without keys leaves an SSH proxy's password and private key
|
||||
// out; a sync without keys keeps this computer's.
|
||||
func TestSSHSecretsStayHome(t *testing.T) {
|
||||
p := settings.NamedProxy{ID: "px1", Name: "VPS", URL: "ssh://203.0.113.5:22", User: "root", Pass: "pw", Key: "KEY", HostKey: "ssh-ed25519 AAAA"}
|
||||
out := settings.WithoutProxyPasswords([]settings.NamedProxy{p})[0]
|
||||
if out.Pass != "" || out.Key != "" || out.HostKey != p.HostKey {
|
||||
t.Fatalf("stripped: %+v", out)
|
||||
}
|
||||
merged := settings.MergeProxies([]settings.NamedProxy{p}, []settings.NamedProxy{out}, false)[0]
|
||||
if merged.Pass != "pw" || merged.Key != "KEY" {
|
||||
t.Fatalf("a sync without keys lost them: %+v", merged)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
// Package sshtest is an SSH server on loopback for tests of magpie's SSH
|
||||
// proxy: it logs a user in by password or key and answers each
|
||||
// direct-tcpip channel (ssh -D's CONNECT) with an http.Handler of its
|
||||
// own, so nothing a test sends through it leaves the machine.
|
||||
package sshtest
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"encoding/pem"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// Server is one SSH server a test stood up; it ends with the test.
|
||||
type Server struct {
|
||||
Addr string // host:port
|
||||
URL string // ssh://host:port
|
||||
HostKey string // its host key, authorized_keys form
|
||||
signer ssh.Signer
|
||||
ln net.Listener
|
||||
|
||||
mu sync.Mutex
|
||||
targets []string // host:port of each channel opened, in order
|
||||
logins int
|
||||
}
|
||||
|
||||
// Options are who may log in and what a channel opened through the
|
||||
// server answers. A nil Handler answers "carried <host><path>".
|
||||
type Options struct {
|
||||
User, Pass string
|
||||
Key ssh.PublicKey // a key the user may log in with
|
||||
Handler http.Handler
|
||||
HostSigner ssh.Signer // the server's host key; a new one when nil
|
||||
// Version is the banner, "SSH-2.0-Go" when empty; a real OpenSSH's
|
||||
// has a space ("SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20")
|
||||
Version string
|
||||
// Interactive offers keyboard-interactive and refuses it at once, as
|
||||
// OpenSSH without PAM does
|
||||
Interactive bool
|
||||
// Forward is how a forward is answered: "" carries it, "prohibit"
|
||||
// refuses it as AllowTcpForwarding no does, "hangup" ends the whole
|
||||
// connection as macOS 27's sshd does
|
||||
Forward string
|
||||
}
|
||||
|
||||
// NewKey is a new ed25519 private key: the signer, and the key as an
|
||||
// OpenSSH PEM a user would paste.
|
||||
func NewKey(t testing.TB) (ssh.Signer, string) {
|
||||
t.Helper()
|
||||
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := ssh.NewSignerFromKey(priv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := ssh.MarshalPrivateKey(priv, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, string(pem.EncodeToMemory(b))
|
||||
}
|
||||
|
||||
// Start stands the server up on 127.0.0.1.
|
||||
func Start(t testing.TB, o Options) *Server {
|
||||
t.Helper()
|
||||
host := o.HostSigner
|
||||
if host == nil {
|
||||
host, _ = NewKey(t)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &Server{Addr: ln.Addr().String(), signer: host, ln: ln}
|
||||
s.URL = "ssh://" + s.Addr
|
||||
s.HostKey = strings.TrimSpace(string(ssh.MarshalAuthorizedKey(host.PublicKey())))
|
||||
cfg := &ssh.ServerConfig{ServerVersion: o.Version}
|
||||
if o.Interactive {
|
||||
cfg.KeyboardInteractiveCallback = func(ssh.ConnMetadata, ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
|
||||
return nil, errRefused
|
||||
}
|
||||
}
|
||||
if o.Pass != "" {
|
||||
cfg.PasswordCallback = func(m ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
|
||||
if m.User() == o.User && string(pass) == o.Pass {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errRefused
|
||||
}
|
||||
}
|
||||
if o.Key != nil {
|
||||
want := o.Key.Marshal()
|
||||
cfg.PublicKeyCallback = func(m ssh.ConnMetadata, k ssh.PublicKey) (*ssh.Permissions, error) {
|
||||
if m.User() == o.User && string(k.Marshal()) == string(want) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errRefused
|
||||
}
|
||||
}
|
||||
cfg.AddHostKey(host)
|
||||
h := o.Handler
|
||||
if h == nil {
|
||||
h = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
_, _ = rw.Write([]byte("carried " + r.Host + r.URL.Path))
|
||||
})
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
conns := map[net.Conn]bool{}
|
||||
var connsMu sync.Mutex
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
connsMu.Lock()
|
||||
conns[c] = true
|
||||
connsMu.Unlock()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.serve(c, cfg, h, o.Forward)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
ln.Close()
|
||||
connsMu.Lock()
|
||||
for c := range conns {
|
||||
c.Close()
|
||||
}
|
||||
connsMu.Unlock()
|
||||
wg.Wait()
|
||||
})
|
||||
return s
|
||||
}
|
||||
|
||||
// Close ends the server's listener and leaves its connections up: a
|
||||
// test of what a tunnel does when the server goes away.
|
||||
func (s *Server) Close() { s.ln.Close() }
|
||||
|
||||
// Targets is the host:port of every channel opened through the server.
|
||||
func (s *Server) Targets() []string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]string(nil), s.targets...)
|
||||
}
|
||||
|
||||
// Logins is how many logins the server let in.
|
||||
func (s *Server) Logins() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.logins
|
||||
}
|
||||
|
||||
type refused struct{}
|
||||
|
||||
func (refused) Error() string { return "refused" }
|
||||
|
||||
var errRefused = refused{}
|
||||
|
||||
func (s *Server) serve(c net.Conn, cfg *ssh.ServerConfig, h http.Handler, forward string) {
|
||||
defer c.Close()
|
||||
conn, chans, reqs, err := ssh.NewServerConn(c, cfg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
s.mu.Lock()
|
||||
s.logins++
|
||||
s.mu.Unlock()
|
||||
// keepalive@openssh.com and the rest: answered, never acted on
|
||||
go ssh.DiscardRequests(reqs)
|
||||
var wg sync.WaitGroup
|
||||
defer wg.Wait()
|
||||
for nc := range chans {
|
||||
if nc.ChannelType() != "direct-tcpip" {
|
||||
_ = nc.Reject(ssh.UnknownChannelType, "only direct-tcpip")
|
||||
continue
|
||||
}
|
||||
target, ok := directTarget(nc.ExtraData())
|
||||
if !ok {
|
||||
_ = nc.Reject(ssh.ConnectionFailed, "bad payload")
|
||||
continue
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.targets = append(s.targets, target)
|
||||
s.mu.Unlock()
|
||||
switch forward {
|
||||
case "prohibit":
|
||||
_ = nc.Reject(ssh.Prohibited, "open failed")
|
||||
continue
|
||||
case "hangup":
|
||||
conn.Close()
|
||||
continue
|
||||
}
|
||||
ch, creqs, err := nc.Accept()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
go ssh.DiscardRequests(creqs)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer ch.Close()
|
||||
br := bufio.NewReader(ch)
|
||||
for {
|
||||
req, err := http.ReadRequest(br)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
res := rec.Result()
|
||||
res.ContentLength = int64(rec.Body.Len())
|
||||
if res.Write(ch) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// directTarget reads a direct-tcpip channel's host and port (RFC 4254
|
||||
// 7.2).
|
||||
func directTarget(b []byte) (string, bool) {
|
||||
str := func() (string, bool) {
|
||||
if len(b) < 4 {
|
||||
return "", false
|
||||
}
|
||||
n := binary.BigEndian.Uint32(b)
|
||||
if uint32(len(b)-4) < n {
|
||||
return "", false
|
||||
}
|
||||
s := string(b[4 : 4+n])
|
||||
b = b[4+n:]
|
||||
return s, true
|
||||
}
|
||||
host, ok := str()
|
||||
if !ok || len(b) < 4 {
|
||||
return "", false
|
||||
}
|
||||
port := binary.BigEndian.Uint32(b)
|
||||
return net.JoinHostPort(host, strconv.Itoa(int(port))), true
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Why is a proxy's failure said so the user can act on it: Why is an
|
||||
// English sentence the page translates, its {addr}, {was} and {now} filled
|
||||
// from the fields, and Err the error it explains, shown beside it. A
|
||||
// failed check of a saved proxy said only Go's words before ("malformed
|
||||
// HTTP response "SSH-2.0-OpenSSH_9.6"" for an SSH server typed as a
|
||||
// proxy, @laiuuui on X).
|
||||
type Why struct {
|
||||
Why, Addr, Was, Now string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (w *Why) Error() string {
|
||||
s := strings.NewReplacer("{addr}", w.Addr, "{was}", w.Was, "{now}", w.Now).Replace(w.Why)
|
||||
if w.Err == nil {
|
||||
return s
|
||||
}
|
||||
return s + " (" + w.Err.Error() + ")"
|
||||
}
|
||||
|
||||
func (w *Why) Unwrap() error { return w.Err }
|
||||
|
||||
type textErr string
|
||||
|
||||
func (e textErr) Error() string { return string(e) }
|
||||
|
||||
// Explain is why a request through the proxy at address (http://,
|
||||
// https://, socks5://, as Parse reads it) failed with msg, said as Why;
|
||||
// nil when msg is nothing it knows. msg is Go's error text, its proxy
|
||||
// login already taken out.
|
||||
func Explain(address, msg string) *Why {
|
||||
addr := address
|
||||
if u, err := Parse(address); err == nil && u.Host != "" {
|
||||
addr = u.Host
|
||||
if u.Port() == "" {
|
||||
addr = net.JoinHostPort(u.Hostname(), map[string]string{"http": "80", "https": "443", "socks5": "1080", "socks5h": "1080"}[u.Scheme])
|
||||
}
|
||||
}
|
||||
w := &Why{Addr: addr, Err: textErr(msg)}
|
||||
switch {
|
||||
case strings.Contains(msg, `"SSH-`), strings.Contains(msg, "unexpected protocol version 83"):
|
||||
// an HTTP proxy's CONNECT answered with an SSH banner, or a SOCKS
|
||||
// greeting with its "S"
|
||||
w.Why = "{addr} is an SSH server, not a proxy: add it as SSH, with its user and password"
|
||||
// readLoopPeekFailLocked: the server spoke before the request went
|
||||
// out, as an SSH server's banner does over a plain http:// proxy
|
||||
case strings.Contains(msg, "malformed HTTP"), strings.Contains(msg, "unexpected protocol version"), strings.Contains(msg, "readLoopPeekFailLocked"):
|
||||
w.Why = "{addr} answered, but not as this kind of proxy: check whether it is HTTP, SOCKS5 or SSH"
|
||||
case strings.Contains(msg, "first record does not look like a TLS handshake"):
|
||||
w.Why = "{addr} doesn't speak TLS: write http:// instead of https://"
|
||||
case strings.Contains(msg, "Proxy Authentication Required"), strings.Contains(msg, "HTTP 407"):
|
||||
w.Why = "{addr} wants a username and password, or turned these away"
|
||||
case strings.Contains(msg, "username/password authentication failed"):
|
||||
w.Why = "{addr} turned the username and password away"
|
||||
case strings.Contains(msg, "no acceptable authentication methods"):
|
||||
w.Why = "{addr} wants a username and password"
|
||||
case strings.Contains(msg, "connection refused"):
|
||||
w.Why = "nothing answers at {addr}: check the address and port, and that the proxy is running"
|
||||
case strings.Contains(msg, "no such host"):
|
||||
w.Why = "the proxy's host name doesn't resolve"
|
||||
case strings.Contains(msg, "i/o timeout"), strings.Contains(msg, "deadline exceeded"), strings.Contains(msg, "Client.Timeout"):
|
||||
w.Why = "no answer through {addr} in time: check the address, and that a firewall lets magpie reach it"
|
||||
case strings.Contains(msg, "connection reset"), strings.Contains(msg, "EOF"):
|
||||
w.Why = "{addr} hung up: check whether it is HTTP, SOCKS5 or SSH, and its login"
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// ExplainServer is Explain, and when the error text can't tell what
|
||||
// answered (Go reads a real OpenSSH banner, "SSH-2.0-OpenSSH_9.6p1
|
||||
// Ubuntu-3ubuntu13.20", as an HTTP status line with a malformed code),
|
||||
// it reads the first bytes the server sends: an SSH server says "SSH-"
|
||||
// before anything is sent to it. Only a check the user asked for calls
|
||||
// this, never a request.
|
||||
func ExplainServer(ctx context.Context, address, msg string) *Why {
|
||||
w := Explain(address, msg)
|
||||
if w == nil || strings.HasPrefix(w.Why, "{addr} is an SSH server") || !strings.Contains(msg, "malformed HTTP") && !strings.Contains(msg, "unexpected protocol version") && !strings.Contains(msg, "readLoopPeekFailLocked") && !strings.Contains(msg, "EOF") && !strings.Contains(msg, "connection reset") {
|
||||
return w
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
c, err := (&net.Dialer{}).DialContext(ctx, "tcp", w.Addr)
|
||||
if err != nil {
|
||||
return w
|
||||
}
|
||||
defer c.Close()
|
||||
d, _ := ctx.Deadline()
|
||||
_ = c.SetReadDeadline(d)
|
||||
b := make([]byte, 4)
|
||||
n := 0
|
||||
for n < len(b) {
|
||||
k, err := c.Read(b[n:])
|
||||
n += k
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if bytes.Equal(b[:n], []byte("SSH-")) {
|
||||
w.Why = "{addr} is an SSH server, not a proxy: add it as SSH, with its user and password"
|
||||
}
|
||||
return w
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -16,14 +17,47 @@ import (
|
||||
// login in it; User and Pass are kept apart, in settings.json (0600) as
|
||||
// GitHubToken is, and the page is never sent the password. This computer's
|
||||
// own (KeepOwn), left out of a backup, as Proxy is.
|
||||
//
|
||||
// An ssh:// one is a server the user logs in to (a VPS that offers only
|
||||
// SSH, @laiuuui on X): magpie logs in itself and carries requests through
|
||||
// it as `ssh -D` would (netproxy's SSH tunnel). User is its login, Pass
|
||||
// its password or, with Key, the key's passphrase; Key is a private key,
|
||||
// kept as Pass is. HostKey is the server's key in authorized_keys form,
|
||||
// trusted on first use and checked on every login after.
|
||||
type NamedProxy struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
// URL is http://, https:// or socks5:// (host:port means http), with
|
||||
// no user and password in it.
|
||||
URL string `json:"url"`
|
||||
User string `json:"user,omitempty"`
|
||||
Pass string `json:"pass,omitempty"`
|
||||
// URL is http://, https://, socks5:// or ssh:// (host:port means
|
||||
// http), with no user and password in it.
|
||||
URL string `json:"url"`
|
||||
User string `json:"user,omitempty"`
|
||||
Pass string `json:"pass,omitempty"`
|
||||
Key string `json:"key,omitempty"`
|
||||
HostKey string `json:"hostKey,omitempty"`
|
||||
}
|
||||
|
||||
// IsSSH is whether the proxy is an SSH server magpie tunnels through.
|
||||
func (p NamedProxy) IsSSH() bool { return IsSSHAddress(p.URL) }
|
||||
|
||||
// IsSSHAddress is whether a proxy address is an ssh:// one.
|
||||
func IsSSHAddress(raw string) bool {
|
||||
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(raw)), "ssh://")
|
||||
}
|
||||
|
||||
// SSHAddress is the address an SSH proxy is reached by: a SOCKS5 proxy
|
||||
// on loopback in front of the SSH connection. netproxy sets it; nil means
|
||||
// nothing in this program can carry an SSH proxy.
|
||||
var SSHAddress func(NamedProxy) (string, error)
|
||||
|
||||
// KeepSecretsOf has p keep old's password and key where it was sent none:
|
||||
// what a sync or an edit that left them blank does.
|
||||
func (p *NamedProxy) KeepSecretsOf(old NamedProxy) {
|
||||
if p.Pass == "" {
|
||||
p.Pass = old.Pass
|
||||
}
|
||||
if p.Key == "" {
|
||||
p.Key = old.Key
|
||||
}
|
||||
}
|
||||
|
||||
// ProxyRefPrefix starts a proxy choice that names a NamedProxy by its id.
|
||||
@@ -50,6 +84,12 @@ func ProxyID(choice string) string {
|
||||
// Address is the proxy as a request takes it, with its login in it. Never
|
||||
// shown or logged: netproxy.Redact is what a line of text may carry.
|
||||
func (p NamedProxy) Address() (string, error) {
|
||||
if p.IsSSH() {
|
||||
if SSHAddress == nil {
|
||||
return "", fmt.Errorf("proxy %q is an SSH server, which this program can't carry", p.Name)
|
||||
}
|
||||
return SSHAddress(p)
|
||||
}
|
||||
u, err := url.Parse(withScheme(strings.TrimSpace(p.URL)))
|
||||
if err != nil || u.Host == "" {
|
||||
return "", fmt.Errorf("proxy %q has no usable address", p.Name)
|
||||
@@ -128,6 +168,12 @@ func checkProxies(ps []NamedProxy) error {
|
||||
if p.URL == "direct" || strings.HasPrefix(p.URL, ProxyRefPrefix) {
|
||||
return fmt.Errorf("proxy %q: type its address, like http://127.0.0.1:7890", p.Name)
|
||||
}
|
||||
if p.IsSSH() {
|
||||
if err := CheckSSHProxy(*p); err != nil {
|
||||
return fmt.Errorf("proxy %q: %w", p.Name, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := checkAddress(p.URL); err != nil {
|
||||
return fmt.Errorf("proxy %q: %w", p.Name, err)
|
||||
}
|
||||
@@ -138,6 +184,24 @@ func checkProxies(ps []NamedProxy) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckSSHProxy refuses an SSH proxy magpie couldn't log in to: no host, a
|
||||
// port that isn't one, or no user.
|
||||
func CheckSSHProxy(p NamedProxy) error {
|
||||
u, err := url.Parse(strings.TrimSpace(p.URL))
|
||||
if err != nil || u.Hostname() == "" || u.User != nil || (u.Path != "" && u.Path != "/") {
|
||||
return fmt.Errorf("an SSH server looks like 203.0.113.5:22")
|
||||
}
|
||||
if port := u.Port(); port != "" {
|
||||
if n, err := strconv.Atoi(port); err != nil || n < 1 || n > 65535 {
|
||||
return fmt.Errorf("an SSH server looks like 203.0.113.5:22")
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(p.User) == "" {
|
||||
return fmt.Errorf("an SSH server needs the user to log in as")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func withScheme(raw string) string {
|
||||
if !strings.Contains(raw, "://") {
|
||||
return "http://" + raw
|
||||
@@ -192,12 +256,12 @@ func rememberProxyNames(m map[string]string, ps []NamedProxy) map[string]string
|
||||
return m
|
||||
}
|
||||
|
||||
// WithoutProxyPasswords is ps with each password left out: what goes
|
||||
// where credentials don't.
|
||||
// WithoutProxyPasswords is ps with each password and SSH key left out:
|
||||
// what goes where credentials don't.
|
||||
func WithoutProxyPasswords(ps []NamedProxy) []NamedProxy {
|
||||
out := slices.Clone(ps)
|
||||
for i := range out {
|
||||
out[i].Pass = ""
|
||||
out[i].Pass, out[i].Key = "", ""
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -217,7 +281,7 @@ func MergeProxies(cur, in []NamedProxy, keys bool) []NamedProxy {
|
||||
if i := slices.IndexFunc(out, func(p NamedProxy) bool { return p.ID == n.ID }); i >= 0 {
|
||||
old := out[i]
|
||||
if !keys {
|
||||
n.Pass = old.Pass
|
||||
n.Pass, n.Key = old.Pass, old.Key
|
||||
}
|
||||
if !strings.EqualFold(old.Name, n.Name) && taken[strings.ToLower(n.Name)] {
|
||||
n.Name = old.Name
|
||||
@@ -226,7 +290,7 @@ func MergeProxies(cur, in []NamedProxy, keys bool) []NamedProxy {
|
||||
continue
|
||||
}
|
||||
if !keys {
|
||||
n.Pass = ""
|
||||
n.Pass, n.Key = "", ""
|
||||
}
|
||||
base, k := n.Name, 2
|
||||
for taken[strings.ToLower(n.Name)] {
|
||||
|
||||
@@ -2223,6 +2223,10 @@ func CheckProxy(p string) error {
|
||||
if !strings.Contains(raw, "://") {
|
||||
raw = "http://" + raw
|
||||
}
|
||||
if IsSSHAddress(raw) {
|
||||
// a login goes with it, which an address alone can't hold
|
||||
return fmt.Errorf("an SSH server is added as a saved proxy: Settings › Network › Add proxy › SSH")
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Host == "" || !slices.Contains([]string{"http", "https", "socks5", "socks5h"}, u.Scheme) {
|
||||
return fmt.Errorf("proxy must look like http://127.0.0.1:7890 or socks5://127.0.0.1:1080")
|
||||
|
||||
Reference in New Issue
Block a user