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:
1 parent
f5dc3bd8f5
commit
dcdbe2b603
19 files changed
+846
-71
No files matched your search
+107
-12
@@ -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()
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
@@ -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{}) {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user