Prepare Remote 0.1.2 with Orca key handling and remembered connections

Apply the four-patch Remote series: accept Orca-style Shift and unflagged extended keys, add browser/media mappings, review untrusted certificate fingerprints during explicit Connect, and retain recent successful connections in private storage.

Report history-write failures without ending live connections, add failure/storage/trust regressions, and document the required reader revision and remaining live accessibility acceptance.

Validated with make check, the complete Remote race suite, private Xorg capture and key-helper cleanup checks, and publisher tests. Linux amd64/arm64 archives reproduce byte-for-byte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chase CichorzandClaude Opus 5.5 authored and Storm Dragon committed 2026-11-06 21:19:39 -05:00
1 parent f5dc3bd8f5
commit dcdbe2b603
19 files changed
+846 -71

No files matched your search

+3 -3
View File
@@ -20,10 +20,10 @@ Native packages are available from the
Battery Status 0.1.0 packages are available from the
[Battery Status release page](https://git.stormux.org/storm/cthulhu-tentacles/releases/tag/battery-status-v0.1.0).
It uses Cthulhu+Shift+B and requires the UPower system service.
Remote 0.1.1 test packages are available from the
[Remote release page](https://git.stormux.org/storm/cthulhu-tentacles/releases/tag/remote-v0.1.1).
Remote 0.1.2 test packages are available from the
[Remote release page](https://git.stormux.org/storm/cthulhu-tentacles/releases/tag/remote-v0.1.2).
It uses Cthulhu+Ctrl+Shift+R and requires the matching experimental reader;
see [installation and live checks](remote/README.md#install-and-test-011).
see [installation and live checks](remote/README.md#install-and-test-012).
Local build artifacts live in the ignored `dist/` directory.
The discovery source URL is
`https://git.stormux.org/storm/cthulhu-tentacles`.
+35
View File
@@ -1005,6 +1005,41 @@ suites on a private D-Bus session, the private native input and native key
harnesses, the Remote race suite and `make check`. Live acceptance is next; use
the procedures in [command.md](remote/command.md) and section 12 below.
Forty-ninth and fiftieth implementation increments (2026-11-06): key
interoperability with Linux controllers derived from Orca Remote. A controlled
Cthulhu now treats generic `VK_SHIFT` with an absent or zero scan code as left
Shift, and accepts Print Screen, the Windows keys, Menu, keypad divide and Num
Lock with or without the extended flag; other generic-Shift scan codes and flag
combinations stay rejected. The eighteen browser, volume, media and launch keys
map to Windows VK 0xA6-0xB7 (launch app 1 and 2 as My Computer and Calculator),
sent extended and accepted either way. Reader `Allow Remote browser, volume and
media keys` adds these names to the Remote key vocabulary; an older reader
rejects them. Both were applied on top of Remote 0.1.1 and reader `bf4a236`;
the earlier NVDA-style dialog layout was dropped because 0.1.1's single
Mode/Host/Key form supersedes it. Checks: reader `internal/input`,
`internal/tentaclewire` and Xorg package tests (native capture cases skipped
without Xvfb), the Remote race suite and `make check`. The keys were also
exercised against the cthulhu-nvda-remote port through an NVDA-style test
relay; no physical keyboard or live NVDA/Orca peer was used.
Fifty-first implementation increment (2026-11-06): recent connections and
automatic fingerprint review. When Connect's key-free TLS check fails on the
certificate, Remote now fetches the relay's leaf certificate on a separate
key-free connection and shows its SHA-256 fingerprint; Trust once or Trust and
remember continues the same Connect through a re-verified check to reader
approval, and Cancel returns to options. Network failures still return to the
form. The connection form gains Recent connections (up to ten host, port, mode,
key and remembered-pin entries in a private `recent.toml`, newest first) and a
Remember this host and key checkbox, checked by default; an entry is saved only
after a successful join. Enter on an entry fills Mode and Host; an empty Key
then uses that entry's key. Remembered pins are looked up from recent entries
too, so switching relays keeps trust. More options adds Forget recent
connections. The reader's actual-host test now permits that one checkbox while
still rejecting duplicated permission controls. Checks: new store, selection
and full untrusted-certificate-to-join tests over a private TLS relay, the
Remote race suite and `make check`. No live relay, NVDA peer or physical
desktop was used.
## 1. Intended result and recommended approach
Build a native Go Tentacle named **Remote**, with package ID `remote`, in this
+27 -12
View File
@@ -1,18 +1,19 @@
# Remote 0.1.1 — experimental test release
# Remote 0.1.2 — experimental test release
Remote connects Cthulhu to an NVDA Remote protocol-v2 relay, as either a
controller or a controlled computer, with relay/role selection, reader-owned
consent, connection controls, speech, keyboard, clipboard text and Braille.
Version 0.1.1 simplifies the connection UI and remains a release for live
testing. Physical keyboard recovery, audible speech/masking, physical Braille and NVDA/Orca interoperability
Version 0.1.2 adds Orca-style Shift handling, browser and media keys, untrusted
certificate fingerprint review, and remembered connections. It remains a release
for live testing. Physical keyboard recovery, audible speech/masking, physical Braille and NVDA/Orca interoperability
have not yet passed live acceptance. ARM64 is cross-built and has not been run
on ARM64 hardware.
## Install and test 0.1.1
## Install and test 0.1.2
Use the matching experimental Cthulhu reader from `testing` revision
`bf4a23645eafa3efbd4321e6f95fe13a011ced7a` or a compatible later revision.
It must support optional Remote grants and polling form transitions; see the
`6867d90` or a compatible later revision.
It must support Remote browser/media keys, optional grants and polling form transitions; see the
reader's `docs/testing/remote-ui.md`. Older readers cannot run this workflow.
Keyboard control requires its `cthulhu-input-helper`; Braille requires
`cthulhu-braille`. Keyboard capture/injection requires Xorg. Installing this
@@ -22,23 +23,33 @@ In global Cthulhu Preferences → Tentacles, add or refresh
`https://git.stormux.org/storm/cthulhu-tentacles`, select **Remote**, review its
version and requested access, and choose **Install and enable**. Packages for
Linux amd64 and arm64 and their SHA-256 checksums are on the
[0.1.1 release page](https://git.stormux.org/storm/cthulhu-tentacles/releases/tag/remote-v0.1.1).
[0.1.2 release page](https://git.stormux.org/storm/cthulhu-tentacles/releases/tag/remote-v0.1.2).
Press **Cthulhu+Ctrl+Shift+R**. Choose Mode, enter Host and Key, then
choose Connect. Host accepts `relay.example:7000`; the default port is 6837.
The key is masked and is never saved automatically. More options contains
The key is masked. With **Remember this host and key** checked (the default),
a successful join adds the host, mode, key and any remembered certificate to
**Recent connections** (up to ten, newest first). Press Enter on a recent
entry to fill Mode and Host; leave Key empty to use its saved key. The list
never shows or speaks a key. More options contains Forget recent connections,
explicit saved-key actions, certificate inspection and keyboard mapping.
Uncheck Remember before connecting to keep a new key out of history. If saving
fails, Remote reports the failure and keeps the connection active.
The certificate is verified before the reader asks you to select access.
If it cannot be verified, Remote fetches the relay certificate on a separate
connection that sends no key and shows its SHA-256 fingerprint. Choose Trust
once or remember it for this host and port, and the connection continues to
the reader's access selection; Cancel returns to the options form.
Only installed permissions are offered; all start unchecked. Select speech,
keyboard, clipboard or Braille as needed and choose **Allow selected access and
connect**. The form closes automatically after joining the relay. Reopen Remote
for status and Disconnect; Close or Escape keeps a live connection.
If certificate verification fails, use **Inspect relay certificate** in the
options form. Check its fingerprint with the relay operator and choose Trust
once or remember it for this host and port. Inspection sends no key; trust
alone never connects. Choose Connect again to review access and join.
Check the fingerprint with the relay operator before trusting it. A remembered
fingerprint travels with that host's recent connections. **Inspect relay
certificate** in the options form shows it on demand; trust chosen there does
not connect by itself.
| Keys | Action |
| --- | --- |
@@ -59,6 +70,10 @@ Follow [the physical keyboard, speech, clipboard and Braille checks](command.md)
on both desktops. Check disconnect/lock/handoff with modifiers held, local
typing after F11, password/key masking and ordinary reading. Recheck Hello
World, Wormhole and Battery Status because they share the host interaction path.
With an Orca-style controller, check uppercase typing and Shift+Tab, then media
and browser keys. Verify both Trust once and remembered trust, Cancel on a bad
certificate, reuse of a recent connection, and unchecked Remember followed by
Forget recent connections; see [command.md](command.md).
Record reader/peer versions, role, layout, actual speech/key/Braille results and
recovery behavior. Automated tests do not establish those results.
+21 -7
View File
@@ -2,15 +2,29 @@
Remote uses Cthulhu+Ctrl+Shift+R to open a compact Mode, Host and masked Key
form. Host accepts an optional port. Cancel starts focused and works with empty
entries. More options opens explicit saved-key, certificate and keyboard-map
controls. Only relay address, mode and explicitly remembered trust are ordinary
saved settings; the channel key is saved or loaded only by explicit action.
entries. More options opens recent-connection, saved-key, certificate and
keyboard-map controls. Relay address, mode and explicitly remembered trust are
ordinary saved settings. A channel key is saved by an explicit saved-key action
or, when Remember this host and key is checked, as a recent connection after a
successful join; abandoned, refused or failed attempts are never remembered.
Recent connections appears after Mode when any exist: up to ten host, port and
mode entries, newest first, in a private file with their keys and any
remembered certificate pin. Enter on an entry fills Mode and Host, and the
current selection is listed first. Connect with an empty Key uses the key saved
for that host, port and mode. Labels never contain a key. Forget recent
connections removes them all; it is not secure erasure.
Connect performs a normal verified TLS handshake without application data before
requesting reader consent. An untrusted relay returns to options for explicit
certificate inspection and fingerprint review. Trust is bound to the immutable
host/port and certificate and does not connect. The actual join uses a new TLS
connection and verifies trust again before sending the key.
requesting reader consent. If that fails on the certificate (not on a network
error), a separate key-free inspection fetches the leaf certificate and shows
its SHA-256 fingerprint for review. Trust once or Trust and remember continues
this Connect: the handshake is verified again against the new pin before the
reader asks for access. Cancel returns to options. Nothing is trusted without
that choice. Trust is bound to the immutable host/port and certificate;
remembered trust is also recorded on that host's recent connections. The
actual join uses a new TLS connection and verifies trust again before sending
the key.
The reader makes the only permission decision. Required speech access and
optional keyboard, clipboard and Braille are offered within installation grants;
+4 -2
View File
@@ -1,8 +1,10 @@
# Remote connection UI
The current user workflow and validation steps are in [command.md](command.md).
Mode, Host and masked Key share one connection form. More options holds
certificate, saved-key and keyboard-map controls. Services are selected only in
Mode, Recent connections (when any exist), Host, masked Key and Remember this
host and key share one connection form. More options holds recent-connection,
certificate, saved-key and keyboard-map controls. An untrusted certificate on
Connect opens the SHA-256 fingerprint review automatically. Services are selected only in
the reader-owned local approval form, constrained by installation grants.
The connection workflow owns pre-approval credentials and asynchronous verified
+14 -5
View File
@@ -19,6 +19,10 @@ Construct an immutable map with an explicit profile:
left/right Shift, Control, Alt and Super, Menu, Caps Lock, Num Lock, Scroll
Lock, Pause, Print, Backspace, Tab, Escape, Space, Return, and keypad and
navigation keys. `Prior`/`Next` and their keypad forms are accepted aliases.
It also includes the eighteen browser, volume, media and launch keys, VK
0xA6–0xB7 (`XF86Back` through `XF86Calculator`; see `mediaKeys` in
`src/keyboard.go`). These are layout independent and sent extended, as
Windows does.
- `us`: the same keys plus the eleven US OEM punctuation key identities.
This requires an explicit US-layout agreement; it is never an automatic
fallback. OEM meanings on other layouts remain unsupported.
@@ -36,14 +40,19 @@ emitted explicitly; right Shift is **not** an extended key. Scan codes are never
fabricated from X keycodes or keysyms.
Incoming generic Control/Alt use the extended flag for side selection. Generic
Shift requires scan `0x2a` or `0x36`; absent or unknown scan information is
rejected. Side-specific VKs determine identity directly; other scan information
is range-checked but does not override the identity or become an X keycode.
Unsupported extended/VK combinations are rejected. The same conversion applies
Shift uses scan `0x2a` (left) or `0x36` (right); an absent or zero scan code,
as sent by Linux controllers derived from Orca Remote, means left Shift, and
other scan codes are rejected. Side-specific VKs determine identity directly;
other scan information is range-checked but does not override the identity or
become an X keycode. Print Screen, the Windows keys, Menu, keypad divide and
Num Lock, and the media keys, are always extended on Windows but are accepted without the flag,
which those controllers omit. Other unsupported extended/VK combinations are
rejected. The same conversion applies
to both press and release, and outgoing press state survives the JSON codec.
AltGr (`ISO_Level3_Shift`), level-five modifiers, IME/dead keys, other OEM
profiles, OEM102, multimedia keys and unsupported VKs remain unavailable.
profiles, OEM102, other XF86 keys (such as power and eject) and unsupported
VKs remain unavailable.
In particular, no implicit Control press is generated to emulate Windows AltGr.
Unknown profiles, key names and wire identities return one constant error with
no input text or partial key. The maps retain no caller input, held-key state,
+7
View File
@@ -6,6 +6,13 @@ capture. It adds explicit persistent-pin Remember/Forget. The original library
increment below remains its historical verification record; physical-source
acceptance and desktop services are still pending.
Remote 0.1.2 also opens fingerprint review after Connect fails certificate
verification. This uses a separate inspection connection with no channel key.
Trust once or Trust and remember resumes that explicit Connect through a fresh
verified handshake and reader-owned access selection. Cancel returns to options.
Inspection from More options still requires a separate Connect. The following
original increment describes the earlier explicit-inspection workflow.
Implemented as a source-library increment on 2026-11-03, on Tentacles `master`
at `63e84e9` with the existing coordinator work preserved. The maintained remote
branch matched that revision when checked. This uses the adjacent reader's
+107 -12
View File
@@ -47,6 +47,9 @@ type connectionCommand struct {
store *settingsStore
selected settings
workflow *connectionWorkflow
// Remembered connections, newest first. Their keys fill an empty Key on
// Connect for the same host, port and mode; they never enter a form.
recent []recentConnection
}
func (command *connectionCommand) commands() []sdk.Command {
@@ -95,23 +98,68 @@ func (command *connectionCommand) commands() []sdk.Command {
return commands
}
func role_label(role string) string {
if role == "controlled" {
return "Allow this computer to be controlled"
}
return "Control another computer"
}
func display_address(host string, port int) string {
if host != "" && port != 6837 {
return net.JoinHostPort(host, strconv.Itoa(port))
}
return host
}
// Reload remembered connections. A read failure hides the list rather than
// failing setup; nothing is connected or trusted from it automatically.
func (command *connectionCommand) load_recent() {
command.recent = nil
if command.store != nil {
if entries, err := command.store.loadRecent(); err == nil {
command.recent = entries
}
}
}
func (command *connectionCommand) selection_form(notice string) sdk.Interaction {
roles := []sdk.ListItem{{ID: "controller", Label: "Control another computer"}, {ID: "controlled", Label: "Allow this computer to be controlled"}}
roles := []sdk.ListItem{{ID: "controller", Label: role_label("controller")}, {ID: "controlled", Label: role_label("controlled")}}
if command.selected.Role == "controlled" {
roles[0], roles[1] = roles[1], roles[0]
}
host := command.selected.Host
if host != "" && command.selected.Port != 6837 {
host = net.JoinHostPort(host, strconv.Itoa(command.selected.Port))
}
result := sdk.Interaction{Form: &sdk.Form{Title: "Remote", Elements: []sdk.Element{
host := display_address(command.selected.Host, command.selected.Port)
elements := []sdk.Element{
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
{ID: "role", Label: "Mode", Kind: sdk.List, Items: roles},
{ID: "host", Label: "Host", Kind: sdk.Entry, Text: host, MaxLength: 300},
{ID: "channel-key", Label: "Key", Kind: sdk.Entry, Secret: true, MaxLength: 512},
{ID: "connect", Label: "Connect", Kind: sdk.Button},
{ID: "options", Label: "More options", Kind: sdk.Button},
}}, Next: "remote-select"}
}
if len(command.recent) > 0 {
// Like NVDA's host history: choosing an entry fills Mode and Host and
// holds its key; the key itself is never shown or spoken.
items := []sdk.ListItem{{ID: "recent-new", Label: "New connection"}}
for index, entry := range command.recent {
label := display_address(entry.Host, entry.Port) + ", " + role_label(entry.Role)
if entry.SHA256 != "" {
label += ", remembered certificate"
}
items = append(items, sdk.ListItem{ID: "recent-" + strconv.Itoa(index), Label: label})
}
for index, entry := range command.recent {
if entry.Host == command.selected.Host && entry.Port == command.selected.Port && entry.Role == command.selected.Role {
items[0], items[index+1] = items[index+1], items[0]
break
}
}
elements = append(elements, sdk.Element{ID: "recent", Label: "Recent connections, press Enter to use", Kind: sdk.List, Items: items})
}
elements = append(elements,
sdk.Element{ID: "host", Label: "Host", Kind: sdk.Entry, Text: host, MaxLength: 300},
sdk.Element{ID: "channel-key", Label: "Key", Kind: sdk.Entry, Secret: true, MaxLength: 512},
sdk.Element{ID: "remember", Label: "Remember this host and key", Kind: sdk.CheckBox, Checked: true},
sdk.Element{ID: "connect", Label: "Connect", Kind: sdk.Button},
sdk.Element{ID: "options", Label: "More options", Kind: sdk.Button},
)
result := sdk.Interaction{Form: &sdk.Form{Title: "Remote", Elements: elements}, Next: "remote-select"}
if notice != "" {
result.Presentation = security_message(notice).Presentation
}
@@ -165,6 +213,7 @@ func (command *connectionCommand) open(ctx context.Context, _ json.RawMessage) (
if err := command.refresh_pin(&command.selected); err != nil {
return security_message("Saved relay trust could not be read."), nil
}
command.load_recent()
return command.selection_form(""), nil
}
@@ -179,9 +228,33 @@ func (command *connectionCommand) refresh_pin(selected *settings) error {
if found && stored.Host == selected.Host && stored.Port == selected.Port {
selected.Pin = stored.Pin
}
if selected.Pin == nil {
// Remembered certificates travel with recent connections, so choosing
// another relay does not lose its trust.
entries, err := command.store.loadRecent()
if err != nil {
return err
}
for _, entry := range entries {
if entry.Host == selected.Host && entry.Port == selected.Port && entry.SHA256 != "" {
selected.Pin = &savedPin{Host: entry.Host, Port: entry.Port, SHA256: entry.SHA256}
break
}
}
}
return nil
}
// recent_key finds the remembered key for this host, port and mode.
func (command *connectionCommand) recent_key(selected settings) string {
for _, entry := range command.recent {
if entry.Host == selected.Host && entry.Port == selected.Port && entry.Role == selected.Role {
return entry.Key
}
}
return ""
}
func (command *connectionCommand) select_relay(ctx context.Context, raw json.RawMessage) (any, error) {
command.mu.Lock()
defer command.mu.Unlock()
@@ -195,6 +268,22 @@ func (command *connectionCommand) select_relay(ctx context.Context, raw json.Raw
if command.workflow != nil {
return security_message("Remote setup is already open."), nil
}
if value.Activated == "recent-new" {
command.selected.Host, command.selected.Port, command.selected.Pin = "", 6837, nil
return command.selection_form("New connection. Enter Host and Key."), nil
}
if index, ok := strings.CutPrefix(value.Activated, "recent-"); ok {
position, err := strconv.Atoi(index)
if err != nil || position < 0 || position >= len(command.recent) {
return command.selection_form(""), nil
}
entry := command.recent[position]
command.selected = settings{Version: 1, Role: entry.Role, Host: entry.Host, Port: entry.Port}
if err := command.refresh_pin(&command.selected); err != nil {
return command.selection_form("Saved relay trust could not be read."), nil
}
return command.selection_form("Using " + display_address(entry.Host, entry.Port) + ". Its saved key will be used unless you enter another. Choose Connect."), nil
}
if value.Activated != "connect" && value.Activated != "options" {
return command.selection_form(""), nil
}
@@ -217,7 +306,12 @@ func (command *connectionCommand) select_relay(ctx context.Context, raw json.Raw
return security_message("Remote setup is unavailable."), nil
}
command.workflow = workflow
workflow.key = value.Values["channel-key"].Text
key := value.Values["channel-key"].Text
if key == "" {
key = command.recent_key(selected)
}
workflow.key = key
workflow.remember = value.Values["remember"].Checked
workflow.profile = "portable"
if value.Activated == "connect" {
return workflow.submit(ctx, sdk.Submission{Activated: "connect"})
@@ -259,6 +353,7 @@ func (command *connectionCommand) approved(ctx context.Context, raw json.RawMess
return security_message("Remote mode changed. Start again."), nil
}
w.action = action
w.hold_recent_locked(w.key)
command.coordinator.set_keyboard(w.profile)
if err := command.coordinator.connect(action, w.target, w.key); err != nil {
w.finish_locked()
+2 -2
View File
@@ -20,14 +20,14 @@ func TestRemoteCommandCollectsCredentialsBeforeApproval(t *testing.T) {
store, _, saved := settingsFixture(t)
command := &connectionCommand{coordinator: c, store: store, selected: saved}
form := command.selection_form("")
if len(form.Form.Elements) != 6 {
if len(form.Form.Elements) != 7 {
t.Fatal("connection form has extra controls")
}
for _, element := range form.Form.Elements {
if element.ID == "channel-key" && (!element.Secret || element.Text != "") {
t.Fatal("key is unmasked or prefilled")
}
if element.Kind == sdk.CheckBox {
if element.Kind == sdk.CheckBox && element.ID != "remember" {
t.Fatal("permissions duplicated in connection form")
}
}
+95 -6
View File
@@ -5,6 +5,7 @@ package remote
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"errors"
"net"
@@ -43,6 +44,15 @@ type connectionWorkflow struct {
needsApproval bool
autoBackground bool
lastStatus string
// remember saves host, mode, key and remembered pin as a recent connection
// after a successful join; pendingRecent holds it only until then.
remember bool
pendingRecent *recentConnection
// savedPin is the remembered (not session-only) pin digest for target.
savedPin string
// resume continues an explicit Connect after the user trusts the
// fingerprint shown when certificate verification failed.
resume bool
}
func new_connection_workflow(ctx context.Context, owner *coordinator, action sdk.SessionEvent, target endpoint, store *settingsStore) (*connectionWorkflow, error) {
@@ -95,6 +105,7 @@ func new_connection_workflow(ctx context.Context, owner *coordinator, action sdk
func (w *connectionWorkflow) finish_locked() {
w.mode, w.key, w.review, w.keys = "finished", "", nil, nil
w.pendingRecent, w.resume = nil, false
w.target.pin = nil
w.cancel()
w.owner.disconnect_epoch(w.action.Epoch)
@@ -139,6 +150,7 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
if w.target.pin != nil {
elements = append(elements, sdk.Element{ID: "forget-pin", Label: "Forget this relay's pin and use normal certificate validation", Kind: sdk.Button})
}
elements = append(elements, sdk.Element{ID: "forget-recent", Label: "Forget recent connections and their keys", Kind: sdk.Button})
}
profiles := []sdk.ListItem{{ID: "portable", Label: "Letters, numbers and navigation"}, {ID: "us", Label: "Include US punctuation"}}
if w.profile == "us" {
@@ -147,12 +159,17 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
elements = append(elements, sdk.Element{ID: "key-profile", Label: "Keyboard mapping", Kind: sdk.List, Items: profiles}, sdk.Element{ID: "cancel", Label: "Cancel", Kind: sdk.Button})
result.Form = &sdk.Form{Title: "Remote options", Elements: elements}
case "inspecting", "checking":
details.Items = append(details.Items, sdk.ListItem{ID: "inspection", Label: "Inspecting the certificate without sending a channel key. No connection will start automatically."})
details.Items = append(details.Items, sdk.ListItem{ID: "inspection", Label: "Checking the certificate without sending a channel key. Untrusted certificates require explicit fingerprint approval."})
result.Form = &sdk.Form{Title: "Checking Remote certificate", Elements: []sdk.Element{details,
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
}}
case "certificate":
result = w.review.form()
if w.resume {
result.Form.Title = "Untrusted Remote relay certificate"
intro := sdk.ListItem{ID: "untrusted", Label: "The relay certificate could not be verified. No key was sent. Trust it only if this SHA-256 fingerprint matches the one from the relay operator; the connection then continues."}
result.Form.Elements[0].Items = append([]sdk.ListItem{intro}, result.Form.Elements[0].Items...)
}
if w.store != nil {
result.Form.Elements = append(result.Form.Elements, sdk.Element{ID: "remember-pin", Label: "Trust and remember this certificate for this relay host and port", Kind: sdk.Button})
}
@@ -355,6 +372,16 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
} else {
w.keys, w.mode = keys, "saved-key"
}
case "forget-recent":
if w.store == nil {
break
}
if w.store.forgetRecent() != nil {
w.notice = "Recent connections could not be forgotten."
} else {
w.remember = false
w.notice = "Recent connections and their keys forgotten. This connection will not be remembered."
}
case "forget-pin":
if w.store == nil {
break
@@ -364,6 +391,12 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
selected.Pin = nil
err = w.store.save(selected)
}
if err == nil {
err = w.store.setRecentPin(w.target.host, w.target.port, "")
}
if err == nil {
w.savedPin = ""
}
if err != nil {
w.notice = "The certificate pin update failed. Stored trust may have changed; review it before another connection."
} else {
@@ -372,6 +405,8 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
}
}
case "certificate":
resume := w.resume
w.resume = false
remember := value.Activated == "remember-pin" && w.store != nil
if remember {
value.Activated = "trust-once"
@@ -385,17 +420,26 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
} else if approved.host != "" && remember {
selected := settings{Version: 1, Role: w.role, Host: approved.host, Port: approved.port,
Pin: &savedPin{Host: approved.host, Port: approved.port, SHA256: hex.EncodeToString(approved.pin.sha256[:])}}
if w.store.save(selected) != nil {
if w.store.save(selected) != nil || w.store.setRecentPin(approved.host, approved.port, selected.Pin.SHA256) != nil {
w.notice = "The certificate pin save failed. Stored trust may have changed; review it before another connection."
} else {
w.target = approved
w.target, w.savedPin = approved, selected.Pin.SHA256
w.notice = "Certificate pin remembered for this relay host and port. Choose Connect relay to connect."
if resume && validChannelKey(w.key) {
w.notice = "Certificate pin remembered for this relay host and port."
w.check_locked()
}
}
} else if approved.host != "" {
w.target = approved
w.notice = "Certificate approved for this attempt only. Enter a channel key and choose Connect relay."
if resume && validChannelKey(w.key) {
w.notice = "Certificate approved for this attempt only."
w.check_locked()
}
}
} else {
w.resume = resume
// Rebuild the nested form to retain the optional Remember pin action.
form := w.form_locked()
form.Clipboard = result.Clipboard
@@ -441,6 +485,10 @@ func new_setup_workflow(owner *coordinator, target endpoint, store *settingsStor
}
lifetime, cancel := context.WithCancel(owner.ctx)
w := &connectionWorkflow{ctx: lifetime, cancel: cancel, done: make(chan struct{}), setupCtx: lifetime, owner: owner, target: target, store: store, role: role, mode: "credentials", needsApproval: true}
if target.pin != nil {
// A setup target's pin comes only from remembered trust.
w.savedPin = hex.EncodeToString(target.pin.sha256[:])
}
go func() {
defer close(w.done)
<-lifetime.Done()
@@ -455,8 +503,10 @@ func new_setup_workflow(owner *coordinator, target endpoint, store *settingsStor
return w, nil
}
// A normal verified TLS handshake sends no application bytes. Failed trust
// returns to explicit inspection; it never enables an insecure fallback.
// A normal verified TLS handshake sends no application bytes. A certificate
// failure fetches the relay's SHA-256 fingerprint on a separate key-free
// connection and asks the user; nothing is trusted without that explicit
// choice and there is never an insecure fallback.
func (w *connectionWorkflow) check_locked() {
w.mode, w.notice = "checking", "Checking relay certificate."
done := make(chan struct{})
@@ -476,12 +526,19 @@ func (w *connectionWorkflow) check_locked() {
connection.Close()
}
}
var review *certificateReview
if err != nil && is_certificate_error(err) {
review, _ = probe_certificate(w.ctx, target)
}
w.mu.Lock()
defer w.mu.Unlock()
if w.mode != "checking" || w.ctx.Err() != nil {
return
}
if err != nil {
if review != nil {
review.lifetime = w.setupCtx
w.review, w.mode, w.resume, w.notice = review, "certificate", true, ""
} else if err != nil {
w.mode, w.notice = "credentials", "Could not verify the relay. No key was sent. Check the address or inspect its certificate."
} else {
w.mode, w.notice = "approval", ""
@@ -510,7 +567,11 @@ func (w *connectionWorkflow) poll(ctx context.Context) sdk.Interaction {
if w.autoBackground && status.epoch == w.action.Epoch && (status.state == "waiting" || status.state == "ready") {
if lease, ok := w.owner.background_lease(w.action.Epoch); ok {
w.autoBackground = false
saveErr := w.save_recent_locked()
text := connection_status_text(status)
if saveErr != nil {
text += " This connection could not be remembered."
}
if slices.Contains(w.action.Grants, "keyboard-capture") {
text += " Keyboard remains local. Cthulhu+Alt+Tab switches control."
}
@@ -533,3 +594,31 @@ func (w *connectionWorkflow) poll(ctx context.Context) sdk.Interaction {
return w.form_locked()
}
}
// is_certificate_error separates certificate rejection, which can be reviewed,
// from network failures, which cannot.
func is_certificate_error(err error) bool {
var verification *tls.CertificateVerificationError
var authority x509.UnknownAuthorityError
var hostname x509.HostnameError
var invalid x509.CertificateInvalidError
return errors.Is(err, errTrust) || errors.As(err, &verification) || errors.As(err, &authority) || errors.As(err, &hostname) || errors.As(err, &invalid)
}
// hold_recent_locked keeps the joined host and key until the join succeeds.
func (w *connectionWorkflow) hold_recent_locked(key string) {
w.pendingRecent = nil
if w.remember && w.store != nil && validChannelKey(key) {
w.pendingRecent = &recentConnection{Host: w.target.host, Port: w.target.port, Role: w.role, Key: key, SHA256: w.savedPin}
}
}
// A failed save is reported without ending the already-live connection.
func (w *connectionWorkflow) save_recent_locked() error {
if w.pendingRecent != nil {
err := w.store.rememberRecent(*w.pendingRecent)
w.pendingRecent = nil
return err
}
return nil
}
+38 -4
View File
@@ -15,6 +15,24 @@ type wireKey struct {
var errKeyboard = errors.New("unsupported remote keyboard mapping")
// mediaKeys are VK 0xa6 (browser back) through 0xb7 (launch app 2).
var mediaKeys = []string{
"XF86Back", "XF86Forward", "XF86Reload", "XF86Stop", "XF86Search", "XF86Favorites",
"XF86HomePage", "XF86AudioMute", "XF86AudioLowerVolume", "XF86AudioRaiseVolume",
"XF86AudioNext", "XF86AudioPrev", "XF86AudioStop", "XF86AudioPlay", "XF86Mail",
"XF86AudioMedia", "XF86MyComputer", "XF86Calculator",
}
// alwaysExtended VKs are only ever extended keys on Windows: Print Screen,
// left/right Windows, Menu, keypad divide, Num Lock and the media keys.
var alwaysExtended = func() map[int]bool {
keys := map[int]bool{0x2c: true, 0x5b: true, 0x5c: true, 0x5d: true, 0x6f: true, 0x90: true}
for index := range mediaKeys {
keys[0xa6+index] = true
}
return keys
}()
// keyboardMap is immutable after construction. The caller must supply the
// unshifted, active-layout keysym name, not text generated by a keystroke.
// No profile is inferred from the environment or a relay message.
@@ -98,6 +116,11 @@ func newKeyboardMap(profile string) (*keyboardMap, error) {
add(0xa3, true, "Control_R")
add(0xa4, false, "Alt_L")
add(0xa5, true, "Alt_R")
// Browser, volume, media and launch keys are layout independent and
// always extended on Windows.
for index, name := range mediaKeys {
add(0xa6+index, true, name)
}
if profile == "us" {
// OEM VK meanings depend on the Windows layout. This profile is an
// explicit US-layout contract, not a fallback for other layouts.
@@ -134,14 +157,20 @@ func (m *keyboardMap) fromWire(key keyTransition) (string, error) {
}
identity := wireKey{key.VK, key.Extended}
// Some peers use generic modifier VKs. Control/Alt sides are specified
// by extended; Shift requires an explicit PC scan code to disambiguate.
// by extended. Shift sides need a PC scan code; Linux controllers derived
// from Orca Remote send generic Shift with scan 0 or none, which means
// left Shift, as it does on their side.
switch key.VK {
case 0x10:
if key.Extended || key.Scan == nil {
if key.Extended {
return "", errKeyboard
}
switch *key.Scan {
case 0x2a:
scan := 0
if key.Scan != nil {
scan = *key.Scan
}
switch scan {
case 0, 0x2a:
identity = wireKey{0xa0, false}
case 0x36:
identity = wireKey{0xa1, false}
@@ -160,6 +189,11 @@ func (m *keyboardMap) fromWire(key keyTransition) (string, error) {
}
}
name, ok := m.decode[identity]
if !ok && !identity.extended && alwaysExtended[identity.vk] {
// Windows always marks these extended, but Orca Remote-style peers
// omit the flag. They have no other meaning, so accept either form.
name, ok = m.decode[wireKey{identity.vk, true}]
}
if !ok {
return "", errKeyboard
}
+2 -1
View File
@@ -38,11 +38,12 @@ func TestKeyboardBridgeSDKIdentity(t *testing.T) {
func TestKeyboardBridgeRejectsUnsupportedPayload(t *testing.T) {
mapping := keyboardFixture(t, "portable")
escapeScan := 0x01 // A Shift VK carrying another key's scan code.
for _, message := range []message{
{kind: "speak", payload: keyTransition{VK: 0x41}},
{kind: "key"}, {kind: "key", payload: "anything"},
{kind: "key", payload: keyTransition{VK: 0xba}},
{kind: "key", payload: keyTransition{VK: 0x10}},
{kind: "key", payload: keyTransition{VK: 0x10, Scan: &escapeScan}},
{kind: "key", payload: keyTransition{VK: 0x41, Extended: true}},
} {
if key, err := reader_key(mapping, message); err == nil || key != (sdk.RemoteKey{}) {
+20 -3
View File
@@ -53,6 +53,10 @@ func TestKeyboardWireIdentities(t *testing.T) {
{"Print", 0x2c, true}, {"Pause", 0x13, false},
{"BackSpace", 0x08, false}, {"Tab", 0x09, false},
{"Escape", 0x1b, false}, {"space", 0x20, false},
{"XF86Back", 0xa6, true}, {"XF86HomePage", 0xac, true},
{"XF86AudioMute", 0xad, true}, {"XF86AudioLowerVolume", 0xae, true},
{"XF86AudioRaiseVolume", 0xaf, true}, {"XF86AudioPlay", 0xb3, true},
{"XF86Calculator", 0xb7, true},
} {
t.Run(test.name, func(t *testing.T) {
for _, pressed := range []bool{true, false} {
@@ -95,7 +99,7 @@ func TestKeyboardLettersDigitsAndFunctions(t *testing.T) {
func TestKeyboardGenericModifiers(t *testing.T) {
m := keyboardFixture(t, "portable")
left, right, unknown := 0x2a, 0x36, 0x01
left, right, unknown, zero := 0x2a, 0x36, 0x01, 0
for _, test := range []struct {
key keyTransition
name string
@@ -106,9 +110,22 @@ func TestKeyboardGenericModifiers(t *testing.T) {
{keyTransition{VK: 0x11, Extended: true}, "Control_R"},
{keyTransition{VK: 0x12}, "Alt_L"},
{keyTransition{VK: 0x12, Extended: true}, "Alt_R"},
{keyTransition{VK: 0x10}, ""},
// Orca Remote-style controllers: generic Shift without a side.
{keyTransition{VK: 0x10}, "Shift_L"},
{keyTransition{VK: 0x10, Scan: &zero}, "Shift_L"},
{keyTransition{VK: 0x10, Scan: &unknown}, ""},
{keyTransition{VK: 0x10, Scan: &left, Extended: true}, ""},
// Always-extended keys sent without the flag.
{keyTransition{VK: 0x2c, Scan: &zero}, "Print"},
{keyTransition{VK: 0x5b}, "Super_L"},
{keyTransition{VK: 0x5c}, "Super_R"},
{keyTransition{VK: 0x5d}, "Menu"},
{keyTransition{VK: 0x6f}, "KP_Divide"},
{keyTransition{VK: 0x90}, "Num_Lock"},
{keyTransition{VK: 0xaf}, "XF86AudioRaiseVolume"},
{keyTransition{VK: 0xb3, Extended: true}, "XF86AudioPlay"},
// The fallback does not reach keys whose flag carries meaning.
{keyTransition{VK: 0x6e, Extended: true}, ""},
} {
name, err := m.fromWire(test.key)
if name != test.name || (err != nil) != (test.name == "") {
@@ -155,7 +172,7 @@ func TestKeyboardRejectsUnknownAndAmbiguousInput(t *testing.T) {
}
}
for _, m := range []*keyboardMap{nil, keyboardFixture(t, "portable"), keyboardFixture(t, "us")} {
for _, name := range []string{"", "38", "A", "exclam", "ISO_Left_Tab", "ISO_Level3_Shift", "ISO_Level5_Shift", "dead_acute", "é", "U20AC", "F25", "KP_F1", "XF86AudioMute", strings.Repeat("private", 100)} {
for _, name := range []string{"", "38", "A", "exclam", "ISO_Left_Tab", "ISO_Level3_Shift", "ISO_Level5_Shift", "dead_acute", "é", "U20AC", "F25", "KP_F1", "XF86Eject", "XF86PowerOff", strings.Repeat("private", 100)} {
if key, err := m.toWire(name, true); !errors.Is(err, errKeyboard) || key != (keyTransition{}) {
t.Fatal("unknown input did not fail without a partial key")
}
+301
View File
@@ -0,0 +1,301 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"bufio"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
func TestRecentConnectionsOrderReplaceCapAndForget(t *testing.T) {
store, _, _ := settingsFixture(t)
pin := strings.Repeat("a", 64)
if err := store.rememberRecent(recentConnection{Host: "one.invalid", Port: 6837, Role: "controller", Key: "first", SHA256: pin}); err != nil {
t.Fatal(err)
}
if err := store.rememberRecent(recentConnection{Host: "two.invalid", Port: 7000, Role: "controlled", Key: "second"}); err != nil {
t.Fatal(err)
}
// Reusing a host, port and mode replaces its key, keeps its pin and moves it first.
if err := store.rememberRecent(recentConnection{Host: "one.invalid", Port: 6837, Role: "controller", Key: "replaced"}); err != nil {
t.Fatal(err)
}
entries, err := store.loadRecent()
if err != nil || len(entries) != 2 || entries[0].Key != "replaced" || entries[0].SHA256 != pin || entries[1].Host != "two.invalid" {
t.Fatal("recent connections were not ordered or replaced", entries, err)
}
for index := range maxRecent + 3 {
if err := store.rememberRecent(recentConnection{Host: "host" + strconv.Itoa(index) + ".invalid", Port: 6837, Role: "controller", Key: "k"}); err != nil {
t.Fatal(err)
}
}
entries, _ = store.loadRecent()
if len(entries) != maxRecent || entries[0].Host != "host12.invalid" {
t.Fatal("recent connections were not capped newest first", len(entries))
}
if err := store.rememberRecent(recentConnection{Host: "bad host", Port: 6837, Role: "controller", Key: "k"}); err == nil {
t.Fatal("invalid host remembered")
}
if err := store.rememberRecent(recentConnection{Host: "ok.invalid", Port: 6837, Role: "controller", Key: ""}); err == nil {
t.Fatal("empty key remembered")
}
if err := store.forgetRecent(); err != nil {
t.Fatal(err)
}
if entries, err := store.loadRecent(); err != nil || entries != nil {
t.Fatal("forget kept recent connections")
}
}
func TestRecentPinFollowsHostAcrossSelection(t *testing.T) {
c, _ := fixtureCoordinator(t, nil)
store, _, saved := settingsFixture(t)
pin := strings.Repeat("b", 64)
store.rememberRecent(recentConnection{Host: "pinned.invalid", Port: 7000, Role: "controller", Key: "pinned-key", SHA256: pin})
store.rememberRecent(recentConnection{Host: "plain.invalid", Port: 6837, Role: "controlled", Key: "plain-key"})
command := &connectionCommand{coordinator: c, store: store, selected: saved}
opened, err := command.open(t.Context(), nil)
if err != nil {
t.Fatal(err)
}
form := opened.(sdk.Interaction).Form
var recent *sdk.Element
for index := range form.Elements {
if form.Elements[index].ID == "recent" {
recent = &form.Elements[index]
}
}
if recent == nil || len(recent.Items) != 3 || recent.Items[0].ID != "recent-new" || !strings.Contains(recent.Items[2].Label, "remembered certificate") || strings.Contains(recent.Items[1].Label, "remembered certificate") {
t.Fatal("recent connections list missing", recent)
}
encoded, _ := json.Marshal(form)
if strings.Contains(string(encoded), "pinned-key") || strings.Contains(string(encoded), "plain-key") {
t.Fatal("recent list exposed a key")
}
raw, _ := json.Marshal(sdk.Submission{Activated: "recent-0"})
value, _ := command.select_relay(t.Context(), raw)
if command.selected.Host != "plain.invalid" || command.selected.Role != "controlled" || command.selected.Pin != nil {
t.Fatal("recent entry did not fill the form", command.selected)
}
assertSecretAbsent(t, value.(sdk.Interaction), "plain-key")
raw, _ = json.Marshal(sdk.Submission{Activated: "recent-1"})
command.select_relay(t.Context(), raw)
if command.selected.Host != "pinned.invalid" || command.selected.Port != 7000 || command.selected.Pin == nil || command.selected.Pin.SHA256 != pin {
t.Fatal("remembered pin did not follow the chosen host", command.selected)
}
// Options with an empty key for a known host, port and mode use its key.
raw, _ = json.Marshal(sdk.Submission{Activated: "options", Values: map[string]sdk.Value{"host": {Text: "pinned.invalid:7000"}, "role": {Selected: "controller"}, "remember": {Checked: true}}})
value, _ = command.select_relay(t.Context(), raw)
w := command.workflow
if w == nil || w.key != "pinned-key" || !w.remember || w.savedPin != pin || w.target.pin == nil {
t.Fatal("known host did not reuse its key and pin")
}
assertSecretAbsent(t, value.(sdk.Interaction), "pinned-key")
w.close()
awaitDone(t, w.done)
}
// An untrusted relay certificate on Connect shows its SHA-256 fingerprint
// without sending the key; trusting it continues to reader approval, and the
// joined host, key and pin become a recent connection.
func TestUntrustedConnectShowsFingerprintAndRemembersRecent(t *testing.T) {
for _, saveFailure := range []bool{false, true} {
t.Run(strconv.FormatBool(saveFailure), func(t *testing.T) {
c, f := fixtureCoordinator(t, func(ctx context.Context, method string, params, result any) error {
if method == "remote.open" {
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: params.(sdk.RemoteOpen).Epoch}
}
return nil
})
store, _, saved := settingsFixture(t)
certificate, _ := testCertificate(t, true)
target := testRelay(t, certificate, func(connection net.Conn) {
reader := bufio.NewReader(connection)
greeting, err := reader.ReadString('\n')
if err != nil {
return // Probe and preflight connections send no application bytes.
}
join, _ := reader.ReadString('\n')
if !strings.Contains(greeting, "protocol_version") || !strings.Contains(join, "synthetic-key") {
t.Error("unexpected join", greeting, join)
return
}
io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-key\",\"clients\":[]}\n")
io.Copy(io.Discard, connection)
})
command := &connectionCommand{coordinator: c, store: store, selected: saved}
host := net.JoinHostPort(target.host, strconv.Itoa(target.port))
raw, _ := json.Marshal(sdk.Submission{Activated: "connect", Values: map[string]sdk.Value{"host": {Text: host}, "role": {Selected: "controller"}, "channel-key": {Text: "synthetic-key"}, "remember": {Checked: true}}})
value, err := command.select_relay(t.Context(), raw)
if err != nil || value.(sdk.Interaction).Poll != "remote-poll" {
t.Fatal("connect did not start checking", err)
}
w := command.workflow
awaitDone(t, w.probeDone)
result := w.poll(t.Context())
digest := sha256.Sum256(certificate.Certificate[0])
fingerprint := hex.EncodeToString(digest[:])
encoded, _ := json.Marshal(result)
if result.Form == nil || result.Form.Title != "Untrusted Remote relay certificate" || !strings.Contains(string(encoded), fingerprint) {
t.Fatal("untrusted certificate did not show its SHA-256 fingerprint", string(encoded))
}
assertSecretAbsent(t, result, "synthetic-key")
result = workflowSubmit(t, w, "remember-pin", "")
if result.Poll != "remote-poll" {
t.Fatal("trusting the fingerprint did not continue the connection")
}
awaitDone(t, w.probeDone)
result = w.poll(t.Context())
if result.Remote == nil || result.Next != "remote-approved" {
t.Fatal("pinned relay did not continue to reader approval")
}
f.events <- sdk.SessionEvent{Sequence: 1, Kind: "remote.action", Action: strings.Repeat("a", 32), Epoch: 1, Role: "controller", Grants: []string{"remote-present"}}
raw, _ = json.Marshal(sdk.Submission{Remote: &sdk.SessionEvent{Kind: "remote.action", Epoch: 1, Action: strings.Repeat("a", 32)}})
if _, err := command.approved(t.Context(), raw); err != nil {
t.Fatal(err)
}
if entries, _ := store.loadRecent(); entries != nil {
t.Fatal("recent connection saved before the join succeeded")
}
if saveFailure {
store.close()
}
deadline := time.Now().Add(4 * time.Second)
for {
value, _ = command.poll(t.Context(), nil)
if value.(sdk.Interaction).RemoteBackground != nil {
break
}
if time.Now().After(deadline) {
t.Fatal("connection did not reach the background")
}
time.Sleep(20 * time.Millisecond)
}
if saveFailure {
if !strings.Contains(value.(sdk.Interaction).Presentation.Speech, "could not be remembered") || w.pendingRecent != nil || w.ctx.Err() != nil || c.snapshot().state != "waiting" {
t.Fatal("history failure was not reported while preserving the live connection")
}
return
}
entries, err := store.loadRecent()
if err != nil || len(entries) != 1 || entries[0].Host != target.host || entries[0].Port != target.port || entries[0].Key != "synthetic-key" || entries[0].SHA256 != fingerprint {
t.Fatal("joined connection was not remembered with its pin", entries, err)
}
})
}
}
func TestRecentConnectionNotRememberedWhenUnchecked(t *testing.T) {
c, _ := fixtureCoordinator(t, nil)
store, _, _ := settingsFixture(t)
w, err := new_setup_workflow(c, endpoint{host: "relay.invalid", port: 6837}, store, "controller")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { w.close(); awaitDone(t, w.done) })
w.mu.Lock()
w.hold_recent_locked("synthetic-key")
w.save_recent_locked()
w.remember = true
w.hold_recent_locked("synthetic-key")
w.finish_locked()
w.save_recent_locked()
w.mu.Unlock()
if entries, _ := store.loadRecent(); entries != nil {
t.Fatal("unchecked or abandoned connection was remembered")
}
}
func TestRecentConnectionStorageRejectsUnsafeFiles(t *testing.T) {
for _, variant := range []string{"permissions", "symlink", "hardlink", "oversized"} {
t.Run(variant, func(t *testing.T) {
store, path, _ := settingsFixture(t)
entry := recentConnection{Host: "relay.invalid", Port: 6837, Role: "controller", Key: "synthetic-key"}
if err := store.rememberRecent(entry); err != nil {
t.Fatal(err)
}
recentPath := filepath.Join(path, "recent.toml")
info, err := os.Stat(recentPath)
if err != nil || info.Mode().Perm() != 0600 {
t.Fatal("recent connections are not private", err)
}
switch variant {
case "permissions":
err = os.Chmod(recentPath, 0644)
case "symlink":
if err = os.Rename(recentPath, recentPath+".original"); err == nil {
err = os.Symlink(recentPath+".original", recentPath)
}
case "hardlink":
err = os.Link(recentPath, recentPath+".link")
case "oversized":
err = os.WriteFile(recentPath, []byte(strings.Repeat("x", maxRecentBytes+1)), 0600)
}
if err != nil {
t.Fatal(err)
}
if entries, err := store.loadRecent(); err != errSettings || entries != nil {
t.Fatal("unsafe history was loaded", err)
}
if err := store.rememberRecent(entry); err != errSettings {
t.Fatal("unsafe history was replaced", err)
}
})
}
}
func TestAutomaticCertificateReviewCancelAndTrustOnce(t *testing.T) {
for _, action := range []string{"cancel", "trust-once"} {
t.Run(action, func(t *testing.T) {
c, _ := fixtureCoordinator(t, nil)
store, _, _ := settingsFixture(t)
certificate, _ := testCertificate(t, true)
target := testRelay(t, certificate, func(connection net.Conn) {
data, _ := io.ReadAll(connection)
if len(data) != 0 {
t.Error("certificate checks sent application data")
}
})
w, err := new_setup_workflow(c, target, store, "controller")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { w.close(); awaitDone(t, w.done) })
workflowSubmit(t, w, "connect", "synthetic-key")
awaitDone(t, w.probeDone)
if result := w.poll(t.Context()); result.Form == nil || result.Form.Title != "Untrusted Remote relay certificate" {
t.Fatal("certificate failure did not require explicit review")
}
result := workflowSubmit(t, w, action, "")
if action == "cancel" {
if result.Form == nil || w.mode != "credentials" || w.target.pin != nil {
t.Fatal("cancel approved trust or continued connecting")
}
} else {
awaitDone(t, w.probeDone)
if result = w.poll(t.Context()); result.Remote == nil || w.target.pin == nil || w.savedPin != "" {
t.Fatal("trust once did not reach approval with session-only trust")
}
}
if _, found, err := store.load(); err != nil || found {
t.Fatal("cancel or trust once persisted a certificate", err)
}
if entries, err := store.loadRecent(); err != nil || entries != nil {
t.Fatal("unjoined attempt persisted history", err)
}
})
}
}
+149 -4
View File
@@ -21,6 +21,12 @@ var errSettings = errors.New("remote settings are unavailable or unsafe")
const maxSettingsBytes = 8 * 1024
// Recent connections hold up to maxRecent host/key pairs, newest first.
const (
maxRecent = 10
maxRecentBytes = 16 * 1024
)
// No key, lease, peer, startup-connect or reusable session consent belongs in
// ordinary settings. Saved pins are trust decisions bound to a single endpoint.
type settings struct {
@@ -44,6 +50,31 @@ type savedKey struct {
Key string `toml:"key"`
}
// recentConnection is one previously joined relay and its channel key. It is
// written only after a successful join the user chose to remember. SHA256 is a
// remembered certificate pin for this host and port, never a session-only trust.
type recentConnection struct {
Host string `toml:"host"`
Port int `toml:"port"`
Role string `toml:"role"`
Key string `toml:"key"`
SHA256 string `toml:"sha256,omitempty"`
}
type recentConnections struct {
Version int `toml:"version"`
Entries []recentConnection `toml:"entries"`
}
func (entry recentConnection) valid() bool {
pin := (*savedPin)(nil)
if entry.SHA256 != "" {
pin = &savedPin{Host: entry.Host, Port: entry.Port, SHA256: entry.SHA256}
}
_, err := (settings{Version: 1, Role: entry.Role, Host: entry.Host, Port: entry.Port, Pin: pin}).endpoint()
return err == nil && validChannelKey(entry.Key)
}
func (value settings) endpoint() (endpoint, error) {
e := endpoint{host: value.Host, port: value.Port}
if value.Version != 1 || (value.Role != "controller" && value.Role != "controlled") {
@@ -147,6 +178,10 @@ func (store *settingsStore) lock() (*os.File, error) {
}
func (store *settingsStore) read(name string) ([]byte, error) {
return store.readLimited(name, maxSettingsBytes)
}
func (store *settingsStore) readLimited(name string, limit int) ([]byte, error) {
fd, err := syscall.Openat(int(store.directory.Fd()), name, syscall.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
if err == syscall.ENOENT {
return nil, nil
@@ -159,20 +194,24 @@ func (store *settingsStore) read(name string) ([]byte, error) {
if !privateFile(file, false) {
return nil, errSettings
}
data, err := io.ReadAll(io.LimitReader(file, maxSettingsBytes+1))
if err != nil || len(data) > maxSettingsBytes {
data, err := io.ReadAll(io.LimitReader(file, int64(limit)+1))
if err != nil || len(data) > limit {
return nil, errSettings
}
return data, nil
}
func (store *settingsStore) replace(name string, value any) error {
return store.replaceLimited(name, value, maxSettingsBytes)
}
func (store *settingsStore) replaceLimited(name string, value any, limit int) error {
data, err := toml.Marshal(value)
if err != nil || len(data) > maxSettingsBytes {
if err != nil || len(data) > limit {
return errSettings
}
// Refuse existing links/special files rather than replacing them silently.
if _, err := store.read(name); err != nil {
if _, err := store.readLimited(name, limit); err != nil {
return err
}
var nonce [16]byte
@@ -306,3 +345,109 @@ func (store *settingsStore) forgetKey() error {
}
return nil
}
func (store *settingsStore) readRecent_locked() ([]recentConnection, error) {
data, err := store.readLimited("recent.toml", maxRecentBytes)
if err != nil || data == nil {
return nil, err
}
var value recentConnections
if decodeSettings(data, &value) != nil || value.Version != 1 || len(value.Entries) > maxRecent {
return nil, errSettings
}
for _, entry := range value.Entries {
if !entry.valid() {
return nil, errSettings
}
}
return value.Entries, nil
}
// loadRecent returns remembered connections, newest first. It does no network I/O.
func (store *settingsStore) loadRecent() ([]recentConnection, error) {
store.mu.Lock()
defer store.mu.Unlock()
lock, err := store.lock()
if err != nil {
return nil, err
}
defer lock.Close()
return store.readRecent_locked()
}
// rememberRecent moves entry to the front, replacing the entry for the same
// host, port and mode. An empty SHA256 keeps a pin already remembered there.
func (store *settingsStore) rememberRecent(entry recentConnection) error {
if !entry.valid() {
return errSettings
}
store.mu.Lock()
defer store.mu.Unlock()
lock, err := store.lock()
if err != nil {
return err
}
defer lock.Close()
entries, err := store.readRecent_locked()
if err != nil {
return err
}
next := []recentConnection{entry}
for _, old := range entries {
if old.Host == entry.Host && old.Port == entry.Port && old.Role == entry.Role {
if next[0].SHA256 == "" {
next[0].SHA256 = old.SHA256
}
continue
}
if len(next) < maxRecent {
next = append(next, old)
}
}
return store.replaceLimited("recent.toml", recentConnections{Version: 1, Entries: next}, maxRecentBytes)
}
// setRecentPin records (or with an empty digest removes) the remembered pin on
// every recent entry for this host and port, so switching relays keeps trust.
func (store *settingsStore) setRecentPin(host string, port int, digest string) error {
store.mu.Lock()
defer store.mu.Unlock()
lock, err := store.lock()
if err != nil {
return err
}
defer lock.Close()
entries, err := store.readRecent_locked()
if err != nil || entries == nil {
return err
}
changed := false
for index := range entries {
if entries[index].Host == host && entries[index].Port == port && entries[index].SHA256 != digest {
entries[index].SHA256, changed = digest, true
}
}
if !changed {
return nil
}
return store.replaceLimited("recent.toml", recentConnections{Version: 1, Entries: entries}, maxRecentBytes)
}
// forgetRecent removes every remembered connection. It is not secure erasure.
func (store *settingsStore) forgetRecent() error {
store.mu.Lock()
defer store.mu.Unlock()
lock, err := store.lock()
if err != nil {
return err
}
defer lock.Close()
data, err := store.readLimited("recent.toml", maxRecentBytes)
if err != nil || data == nil {
return err
}
if syscall.Unlinkat(int(store.directory.Fd()), "recent.toml") != nil || store.directory.Sync() != nil {
return errSettings
}
return nil
}
+5 -4
View File
@@ -26,10 +26,11 @@ type certificateReview struct {
finished bool
}
// probe_certificate is an explicit, unauthenticated certificate inspection. It
// takes no channel key and writes no application bytes. Never call it as an
// automatic fallback from connect: CA or pin failure must stop that attempt.
// Normal CA/pin authentication is repeated on a NEW connection after review.
// probe_certificate is an unauthenticated certificate inspection. It takes no
// channel key and writes no application bytes. After a CA or pin failure on
// Connect it only fetches the fingerprint for review; it never approves trust
// and never becomes the relay connection. Normal CA/pin authentication is
// repeated on a NEW connection after the user's explicit review.
func probe_certificate(ctx context.Context, target endpoint) (*certificateReview, error) {
config, err := target.tlsConfig()
if err != nil {
+13 -3
View File
@@ -24,9 +24,19 @@ forgotten. `forgetKey` removes and syncs the credential file and is idempotent.
Removal is not a promise of secure disk erasure. Saving ordinary settings never
saves a key, and there is no saved-key flag that silently triggers a connection.
`recent.toml` separately holds up to ten successfully joined host, port, mode and
key entries, newest first, with any explicitly remembered certificate pin. It is
written only when Remember this host and key is checked for that attempt. The
connection form offers this option checked by default; uncheck it before Connect
to avoid adding a new key to history. An empty Key can reuse the entry matching
the selected endpoint and mode. Labels and presentation never include its key.
Forget recent connections removes this file, independently of the explicit
saved-key slot. No entry restores consent or starts a connection.
Keys use the transport's existing validation: nonempty valid UTF-8, at most 512
bytes, without C0 controls or DEL. The transport and store share that validator.
Settings and credential files are each bounded to 8 KiB on read. Parser errors
Settings and the saved-key slot are each bounded to 8 KiB on read; recent
connections are bounded to 16 KiB. Parser errors
are replaced with a generic error, without the file path, parser excerpt or key.
Ordinary settings can therefore be inspected separately from credential content.
@@ -50,12 +60,12 @@ a nonblocking flock excludes cooperating processes. Temporary files are removed
after normal failures. Abrupt process death can leave an owner-only `.pending-*`
file; it is never read as live settings. A directory-sync failure after rename
can leave the new version present despite an error, so the UI must report the
failure and re-read before claiming which value was saved. The two files are
failure and re-read before claiming which value was saved. These files are
independent atomic records, not a cross-file transaction.
The key is plaintext protected by filesystem ownership and permissions. This is
not encryption, an OS keyring, or protection against malicious same-user code.
No runtime data is added to release archives; Remote still has no package entry.
No runtime data is added to release archives.
Tests use disposable directories and synthetic keys. They cover restart, exact
endpoint scoping, atomic inode replacement, permission modes, temporary-file
+2 -2
View File
@@ -2,7 +2,7 @@ format-version = 1
id = "remote"
name = "Remote"
description = "Control another computer or let a helper access this one over an NVDA Remote compatible relay: speech, keyboard, clipboard text and Braille, each approved per session."
version = "0.1.1"
version = "0.1.2"
authors = ["Storm Dragon"]
license = "GPL-3.0-or-later"
source = "https://git.stormux.org/storm/cthulhu-tentacles"
@@ -18,6 +18,6 @@ major = 1
minor = 1
[requirements]
reader = "Cthulhu testing with optional Remote grants and polling form transitions, including cthulhu-input-helper for keyboard control and cthulhu-braille for Braille"
reader = "Cthulhu testing revision 6867d90 or later with Remote browser and media key support, including cthulhu-input-helper for keyboard control and cthulhu-braille for Braille"
runtime = "Xorg for keyboard capture and injection; an independently hosted NVDA Remote protocol 2 relay"
build = "Go 1.24 or newer and the adjacent cthulhu source checkout"
+1 -1
View File
@@ -38,7 +38,7 @@ def check_metadata(repoRoot):
require(item["manifest"] == f"{name}/tentacle.toml", "Manifest path must match ID")
manifest = read_toml(repoRoot / item["manifest"])
require(manifest["format-version"] == 1 and manifest["id"] == name
and manifest["name"] and manifest["version"] == ({"wormhole":"0.1.2", "remote":"0.1.1"}.get(name, "0.1.0")), "Invalid Tentacle metadata")
and manifest["name"] and manifest["version"] == ({"wormhole":"0.1.2", "remote":"0.1.2"}.get(name, "0.1.0")), "Invalid Tentacle metadata")
expectedGrants = ["presentation"] + (["interaction"] if name in ("wormhole", "battery-status") else [])
if name == "remote":
expectedGrants = ["presentation", "interaction", "output-observe", "remote-present", "keyboard-capture",