| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/rand" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "io" |
| 11 | "log" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "runtime" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/sylvinus/agent-vm/internal/mobilelink" |
| 19 | ) |
| 20 | |
| 21 | |
| 22 | |
| 23 | type connectionFile struct { |
| 24 | Version int `json:"version"` |
| 25 | Relay string `json:"relay"` |
| 26 | LookupToken string `json:"lookup_token"` |
| 27 | HostPin string `json:"host_pin"` |
| 28 | } |
| 29 | |
| 30 | type hostSettings struct { |
| 31 | Relay string `json:"relay"` |
| 32 | AdminFile string `json:"admin_token_file"` |
| 33 | CageBinary string `json:"cage_binary"` |
| 34 | Config string `json:"config"` |
| 35 | } |
| 36 | |
| 37 | type savedHost struct { |
| 38 | Connection connectionFile `json:"connection"` |
| 39 | Settings hostSettings `json:"host"` |
| 40 | PeerPin string `json:"peer_pin"` |
| 41 | } |
| 42 | |
| 43 | func decodePrivateJSON(path string, result any) error { |
| 44 | data, err := readPrivate(path, 16<<10) |
| 45 | if err != nil { |
| 46 | return err |
| 47 | } |
| 48 | defer clear(data) |
| 49 | decoder := json.NewDecoder(bytes.NewReader(data)) |
| 50 | decoder.DisallowUnknownFields() |
| 51 | if decoder.Decode(result) != nil || decoder.Decode(new(any)) != io.EOF { |
| 52 | return errors.New("invalid private connection record") |
| 53 | } |
| 54 | return nil |
| 55 | } |
| 56 | |
| 57 | func (c connectionFile) valid() bool { |
| 58 | raw, err := base64.RawURLEncoding.DecodeString(c.LookupToken) |
| 59 | defer clear(raw) |
| 60 | return c.Version == 1 && mobilelink.ValidRelayOrigin(c.Relay) && validPin(c.HostPin) && err == nil && len(raw) == 32 && base64.RawURLEncoding.EncodeToString(raw) == c.LookupToken |
| 61 | } |
| 62 | |
| 63 | func (s hostSettings) valid() bool { |
| 64 | return mobilelink.ValidRelayOrigin(s.Relay) && (s.AdminFile == "" || filepath.IsAbs(s.AdminFile)) && filepath.IsAbs(s.Config) && filepath.IsAbs(s.CageBinary) |
| 65 | } |
| 66 | |
| 67 | func loadSavedHost(state, hostPin, peerPin string) (savedHost, error) { |
| 68 | var h savedHost |
| 69 | err := decodePrivateJSON(filepath.Join(state, "saved-host.json"), &h) |
| 70 | if err != nil { |
| 71 | return h, err |
| 72 | } |
| 73 | if !h.Connection.valid() || !h.Settings.valid() || h.Connection.Relay != h.Settings.Relay || h.Connection.HostPin != hostPin || h.PeerPin != peerPin { |
| 74 | return savedHost{}, errors.New("saved host settings no longer match this pairing; verify the device state") |
| 75 | } |
| 76 | return h, nil |
| 77 | } |
| 78 | |
| 79 | func configureSavedHost(state, dest, hostPin, peerPin string, settings hostSettings) (savedHost, error) { |
| 80 | var h savedHost |
| 81 | if !settings.valid() { |
| 82 | return h, errors.New("saved host requires a trusted relay and absolute admin token, cage binary and config paths") |
| 83 | } |
| 84 | if info, err := os.Stat(settings.CageBinary); err != nil || !info.Mode().IsRegular() || (runtime.GOOS != "windows" && info.Mode().Perm()&0111 == 0) { |
| 85 | return h, errors.New("saved Cage binary must be an executable file") |
| 86 | } |
| 87 | if _, err := readAdminToken(settings.AdminFile); err != nil { |
| 88 | return h, err |
| 89 | } |
| 90 | path := filepath.Join(state, "saved-host.json") |
| 91 | _, err := os.Lstat(path) |
| 92 | switch { |
| 93 | case err == nil: |
| 94 | h, err = loadSavedHost(state, hostPin, peerPin) |
| 95 | if err != nil { |
| 96 | return h, err |
| 97 | } |
| 98 | if h.Settings != settings { |
| 99 | return h, errors.New("existing saved host settings differ; revoke this pairing before replacing it") |
| 100 | } |
| 101 | case errors.Is(err, os.ErrNotExist): |
| 102 | raw := make([]byte, 32) |
| 103 | _, _ = rand.Read(raw) |
| 104 | h = savedHost{Connection: connectionFile{Version: 1, Relay: settings.Relay, LookupToken: base64.RawURLEncoding.EncodeToString(raw), HostPin: hostPin}, Settings: settings, PeerPin: peerPin} |
| 105 | clear(raw) |
| 106 | data, _ := json.Marshal(h) |
| 107 | err = writeNewPrivate(path, data) |
| 108 | clear(data) |
| 109 | if err != nil { |
| 110 | return savedHost{}, err |
| 111 | } |
| 112 | default: |
| 113 | return h, errors.New("cannot inspect saved host settings") |
| 114 | } |
| 115 | data, _ := json.Marshal(h.Connection) |
| 116 | err = writeNewPrivate(dest, data) |
| 117 | clear(data) |
| 118 | return h, err |
| 119 | } |
| 120 | |
| 121 | func readAdminToken(path string) (string, error) { |
| 122 | if path == "" { |
| 123 | return "", nil |
| 124 | } |
| 125 | raw, err := readPrivate(path, 4098) |
| 126 | if err != nil { |
| 127 | return "", err |
| 128 | } |
| 129 | defer clear(raw) |
| 130 | token := string(raw) |
| 131 | if strings.HasSuffix(token, "\n") { |
| 132 | token = strings.TrimSuffix(strings.TrimSuffix(token, "\n"), "\r") |
| 133 | } |
| 134 | if len(token) < 32 || len(token) > 4096 { |
| 135 | return "", errors.New("invalid protected relay admin token") |
| 136 | } |
| 137 | for i := range len(token) { |
| 138 | if token[i] < 0x21 || token[i] > 0x7e { |
| 139 | return "", errors.New("invalid protected relay admin token") |
| 140 | } |
| 141 | } |
| 142 | return token, nil |
| 143 | } |
| 144 | |
| 145 | func revoke(state string) error { |
| 146 | if _, err := loadIdentity(state); err != nil { |
| 147 | return err |
| 148 | } |
| 149 | |
| 150 | |
| 151 | for _, name := range []string{"trusted-peer", "saved-host.json"} { |
| 152 | if err := os.Remove(filepath.Join(state, name)); err != nil && !errors.Is(err, os.ErrNotExist) { |
| 153 | return errors.New("could not revoke saved device state") |
| 154 | } |
| 155 | } |
| 156 | return nil |
| 157 | } |
| 158 | |
| 159 | var errRevoked = errors.New("saved device trust changed; host bridge closed") |
| 160 | |
| 161 | func verifySaved(state string, h savedHost) bool { |
| 162 | peer, err := trustedPeer(state) |
| 163 | if err != nil || peer != h.PeerPin { |
| 164 | return false |
| 165 | } |
| 166 | current, err := loadSavedHost(state, h.Connection.HostPin, peer) |
| 167 | return err == nil && current == h |
| 168 | } |
| 169 | |
| 170 | func monitorTrust(parent context.Context, verify func() bool) (context.Context, func()) { |
| 171 | ctx, cancel := context.WithCancelCause(parent) |
| 172 | |
| 173 | |
| 174 | go func() { |
| 175 | ticker := time.NewTicker(time.Second) |
| 176 | defer ticker.Stop() |
| 177 | for { |
| 178 | select { |
| 179 | case <-ctx.Done(): |
| 180 | return |
| 181 | case <-ticker.C: |
| 182 | if !verify() { |
| 183 | cancel(errRevoked) |
| 184 | return |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | }() |
| 189 | return ctx, func() { cancel(nil) } |
| 190 | } |
| 191 | |
| 192 | func savedService(parent context.Context, state string, h savedHost, out io.Writer) error { |
| 193 | ctx, stop := monitorTrust(parent, func() bool { return verifySaved(state, h) }) |
| 194 | defer stop() |
| 195 | logger := log.New(out, "", 0) |
| 196 | stopAwake := keepHostAwake(ctx, logger) |
| 197 | defer stopAwake() |
| 198 | delay := time.Second |
| 199 | for ctx.Err() == nil { |
| 200 | if !verifySaved(state, h) { |
| 201 | return errRevoked |
| 202 | } |
| 203 | retry, err := savedRoom(ctx, state, h) |
| 204 | if ctx.Err() != nil { |
| 205 | break |
| 206 | } |
| 207 | if !retry { |
| 208 | return err |
| 209 | } |
| 210 | if err == nil { |
| 211 | delay = time.Second |
| 212 | } else { |
| 213 | logger.Println("Room unavailable; retrying the saved connection in", delay.String()) |
| 214 | } |
| 215 | timer := time.NewTimer(delay) |
| 216 | select { |
| 217 | case <-ctx.Done(): |
| 218 | timer.Stop() |
| 219 | return context.Cause(ctx) |
| 220 | case <-timer.C: |
| 221 | } |
| 222 | if err != nil { |
| 223 | delay = min(30*time.Second, 2*delay) |
| 224 | } |
| 225 | } |
| 226 | return context.Cause(ctx) |
| 227 | } |
| 228 | |
| 229 | func savedRoom(ctx context.Context, state string, h savedHost) (bool, error) { |
| 230 | |
| 231 | |
| 232 | id, err := loadIdentity(state) |
| 233 | if err != nil || id.Pin != h.Connection.HostPin { |
| 234 | return false, errors.New("device identity changed") |
| 235 | } |
| 236 | if info, err := os.Stat(h.Settings.CageBinary); err != nil || !info.Mode().IsRegular() { |
| 237 | return false, errors.New("saved Cage binary unavailable") |
| 238 | } |
| 239 | admin, err := readAdminToken(h.Settings.AdminFile) |
| 240 | if err != nil { |
| 241 | return false, err |
| 242 | } |
| 243 | b, err := localWorkbench(ctx, h.Settings.CageBinary, h.Settings.Config) |
| 244 | if err != nil { |
| 245 | return true, err |
| 246 | } |
| 247 | defer b.Close() |
| 248 | room, err := mobilelink.CreateDiscoverableRoom(ctx, h.Settings.Relay, admin, h.Connection.LookupToken) |
| 249 | if err != nil { |
| 250 | return mobilelink.Retryable(err), err |
| 251 | } |
| 252 | err = mobilelink.ServeHost(ctx, h.Settings.Relay, room.ID, room.HostToken, id, h.PeerPin, b) |
| 253 | if mobilelink.Retryable(err) && !time.Now().Before(room.ExpiresAt) { |
| 254 | |
| 255 | |
| 256 | return true, nil |
| 257 | } |
| 258 | return err == nil || mobilelink.Retryable(err), err |
| 259 | } |
| 260 | |
| 261 | func resolveSaved(ctx context.Context, path, base, peer string) (clientInvitation, error) { |
| 262 | var c connectionFile |
| 263 | if err := decodePrivateJSON(path, &c); err != nil { |
| 264 | return clientInvitation{}, err |
| 265 | } |
| 266 | if !c.valid() || c.Relay != base || c.HostPin != peer { |
| 267 | return clientInvitation{}, errors.New("connection file differs from independently trusted host or relay") |
| 268 | } |
| 269 | found, err := mobilelink.LookupRoom(ctx, base, c.LookupToken) |
| 270 | if err != nil { |
| 271 | return clientInvitation{}, err |
| 272 | } |
| 273 | return clientInvitation{found.ID, found.ClientToken, found.ExpiresAt}, nil |
| 274 | } |