| 1 | // gomuks - A terminal Matrix client written in Go. |
| 2 | // Copyright (C) 2020 Tulir Asokan |
| 3 | // |
| 4 | // This program is free software: you can redistribute it and/or modify |
| 5 | // it under the terms of the GNU Affero General Public License as published by |
| 6 | // the Free Software Foundation, either version 3 of the License, or |
| 7 | // (at your option) any later version. |
| 8 | // |
| 9 | // This program is distributed in the hope that it will be useful, |
| 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | // GNU Affero General Public License for more details. |
| 13 | // |
| 14 | // You should have received a copy of the GNU Affero General Public License |
| 15 | // along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | |
| 17 | //go:build cgo |
| 18 | |
| 19 | package ui |
| 20 | |
| 21 | import ( |
| 22 | "errors" |
| 23 | "fmt" |
| 24 | "io/ioutil" |
| 25 | "path/filepath" |
| 26 | "strings" |
| 27 | "time" |
| 28 | "unicode" |
| 29 | |
| 30 | "maunium.net/go/mautrix" |
| 31 | "maunium.net/go/mautrix/crypto" |
| 32 | "maunium.net/go/mautrix/crypto/ssss" |
| 33 | "maunium.net/go/mautrix/id" |
| 34 | |
| 35 | ifc "maunium.net/go/gomuks/interface" |
| 36 | ) |
| 37 | |
| 38 | func autocompleteDeviceUserID(cmd *CommandAutocomplete) (completions []string, newText string) { |
| 39 | userCompletions := cmd.Room.AutocompleteUser(cmd.Args[0]) |
| 40 | if len(userCompletions) == 1 { |
| 41 | newText = fmt.Sprintf("/%s %s ", cmd.OrigCommand, userCompletions[0].id) |
| 42 | } else { |
| 43 | completions = make([]string, len(userCompletions)) |
| 44 | for i, completion := range userCompletions { |
| 45 | completions[i] = completion.id |
| 46 | } |
| 47 | } |
| 48 | return |
| 49 | } |
| 50 | |
| 51 | func autocompleteDeviceDeviceID(cmd *CommandAutocomplete) (completions []string, newText string) { |
| 52 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 53 | devices, err := mach.CryptoStore.GetDevices(id.UserID(cmd.Args[0])) |
| 54 | if len(devices) == 0 || err != nil { |
| 55 | return |
| 56 | } |
| 57 | var completedDeviceID id.DeviceID |
| 58 | if len(cmd.Args) > 1 { |
| 59 | existingID := strings.ToUpper(cmd.Args[1]) |
| 60 | for _, device := range devices { |
| 61 | deviceIDStr := string(device.DeviceID) |
| 62 | if deviceIDStr == existingID { |
| 63 | // We don't want to do any autocompletion if there's already a full device ID there. |
| 64 | return []string{}, "" |
| 65 | } else if strings.HasPrefix(strings.ToUpper(device.Name), existingID) || strings.HasPrefix(deviceIDStr, existingID) { |
| 66 | completedDeviceID = device.DeviceID |
| 67 | completions = append(completions, fmt.Sprintf("%s (%s)", device.DeviceID, device.Name)) |
| 68 | } |
| 69 | } |
| 70 | } else { |
| 71 | completions = make([]string, len(devices)) |
| 72 | i := 0 |
| 73 | for _, device := range devices { |
| 74 | completedDeviceID = device.DeviceID |
| 75 | completions[i] = fmt.Sprintf("%s (%s)", device.DeviceID, device.Name) |
| 76 | i++ |
| 77 | } |
| 78 | } |
| 79 | if len(completions) == 1 { |
| 80 | newText = fmt.Sprintf("/%s %s %s ", cmd.OrigCommand, cmd.Args[0], completedDeviceID) |
| 81 | } |
| 82 | return |
| 83 | } |
| 84 | |
| 85 | func autocompleteUser(cmd *CommandAutocomplete) ([]string, string) { |
| 86 | if len(cmd.Args) == 1 && !unicode.IsSpace(rune(cmd.RawArgs[len(cmd.RawArgs)-1])) { |
| 87 | return autocompleteDeviceUserID(cmd) |
| 88 | } |
| 89 | return []string{}, "" |
| 90 | } |
| 91 | |
| 92 | func autocompleteDevice(cmd *CommandAutocomplete) ([]string, string) { |
| 93 | if len(cmd.Args) == 0 { |
| 94 | return []string{}, "" |
| 95 | } else if len(cmd.Args) == 1 && !unicode.IsSpace(rune(cmd.RawArgs[len(cmd.RawArgs)-1])) { |
| 96 | return autocompleteDeviceUserID(cmd) |
| 97 | } |
| 98 | return autocompleteDeviceDeviceID(cmd) |
| 99 | } |
| 100 | |
| 101 | func getDevice(cmd *Command) *crypto.DeviceIdentity { |
| 102 | if len(cmd.Args) < 2 { |
| 103 | cmd.Reply("Usage: /%s <user id> <device id> [fingerprint]", cmd.Command) |
| 104 | return nil |
| 105 | } |
| 106 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 107 | device, err := mach.GetOrFetchDevice(id.UserID(cmd.Args[0]), id.DeviceID(cmd.Args[1])) |
| 108 | if err != nil { |
| 109 | cmd.Reply("Failed to get device: %v", err) |
| 110 | return nil |
| 111 | } |
| 112 | return device |
| 113 | } |
| 114 | |
| 115 | func putDevice(cmd *Command, device *crypto.DeviceIdentity, action string) { |
| 116 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 117 | err := mach.CryptoStore.PutDevice(device.UserID, device) |
| 118 | if err != nil { |
| 119 | cmd.Reply("Failed to save device: %v", err) |
| 120 | } else { |
| 121 | cmd.Reply("Successfully %s %s/%s (%s)", action, device.UserID, device.DeviceID, device.Name) |
| 122 | } |
| 123 | mach.OnDevicesChanged(device.UserID) |
| 124 | } |
| 125 | |
| 126 | func cmdDevices(cmd *Command) { |
| 127 | if len(cmd.Args) == 0 { |
| 128 | cmd.Reply("Usage: /devices <user id>") |
| 129 | return |
| 130 | } |
| 131 | userID := id.UserID(cmd.Args[0]) |
| 132 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 133 | devices, err := mach.CryptoStore.GetDevices(userID) |
| 134 | if err != nil { |
| 135 | cmd.Reply("Failed to get device list: %v", err) |
| 136 | } |
| 137 | if len(devices) == 0 { |
| 138 | cmd.Reply("Fetching device list from server...") |
| 139 | devices = mach.LoadDevices(userID) |
| 140 | } |
| 141 | if len(devices) == 0 { |
| 142 | cmd.Reply("No devices found for %s", userID) |
| 143 | return |
| 144 | } |
| 145 | var buf strings.Builder |
| 146 | for _, device := range devices { |
| 147 | trust := device.Trust.String() |
| 148 | if device.Trust == crypto.TrustStateUnset && mach.IsDeviceTrusted(device) { |
| 149 | trust = "verified (transitive)" |
| 150 | } |
| 151 | _, _ = fmt.Fprintf(&buf, "%s (%s) - %s\n Fingerprint: %s\n", device.DeviceID, device.Name, trust, device.Fingerprint()) |
| 152 | } |
| 153 | resp := buf.String() |
| 154 | cmd.Reply("%s", resp[:len(resp)-1]) |
| 155 | } |
| 156 | |
| 157 | func cmdDevice(cmd *Command) { |
| 158 | device := getDevice(cmd) |
| 159 | if device == nil { |
| 160 | return |
| 161 | } |
| 162 | deviceType := "Device" |
| 163 | if device.Deleted { |
| 164 | deviceType = "Deleted device" |
| 165 | } |
| 166 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 167 | trustState := device.Trust.String() |
| 168 | if device.Trust == crypto.TrustStateUnset && mach.IsDeviceTrusted(device) { |
| 169 | trustState = "verified (transitive)" |
| 170 | } |
| 171 | cmd.Reply("%s %s of %s\nFingerprint: %s\nIdentity key: %s\nDevice name: %s\nTrust state: %s", |
| 172 | deviceType, device.DeviceID, device.UserID, |
| 173 | device.Fingerprint(), device.IdentityKey, |
| 174 | device.Name, trustState) |
| 175 | } |
| 176 | |
| 177 | func crossSignDevice(cmd *Command, device *crypto.DeviceIdentity) { |
| 178 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 179 | err := mach.SignOwnDevice(device) |
| 180 | if err != nil { |
| 181 | cmd.Reply("Failed to upload cross-signing signature: %v", err) |
| 182 | } else { |
| 183 | cmd.Reply("Successfully cross-signed %s (%s)", device.DeviceID, device.Name) |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | func cmdVerifyDevice(cmd *Command) { |
| 188 | device := getDevice(cmd) |
| 189 | if device == nil { |
| 190 | return |
| 191 | } |
| 192 | if device.Trust == crypto.TrustStateVerified { |
| 193 | cmd.Reply("That device is already verified") |
| 194 | return |
| 195 | } |
| 196 | if len(cmd.Args) == 2 { |
| 197 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 198 | mach.DefaultSASTimeout = 120 * time.Second |
| 199 | modal := NewVerificationModal(cmd.MainView, device, mach.DefaultSASTimeout) |
| 200 | cmd.MainView.ShowModal(modal) |
| 201 | _, err := mach.NewSimpleSASVerificationWith(device, modal) |
| 202 | if err != nil { |
| 203 | cmd.Reply("Failed to start interactive verification: %v", err) |
| 204 | return |
| 205 | } |
| 206 | } else { |
| 207 | fingerprint := strings.Join(cmd.Args[2:], "") |
| 208 | if string(device.SigningKey) != fingerprint { |
| 209 | cmd.Reply("Mismatching fingerprint") |
| 210 | return |
| 211 | } |
| 212 | action := "verified" |
| 213 | if device.Trust == crypto.TrustStateBlacklisted { |
| 214 | action = "unblacklisted and verified" |
| 215 | } |
| 216 | if device.UserID == cmd.Matrix.Client().UserID { |
| 217 | crossSignDevice(cmd, device) |
| 218 | device.Trust = crypto.TrustStateVerified |
| 219 | putDevice(cmd, device, action) |
| 220 | } else { |
| 221 | putDevice(cmd, device, action) |
| 222 | cmd.Reply("Warning: verifying individual devices of other users is not synced with cross-signing") |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | func cmdVerify(cmd *Command) { |
| 228 | if len(cmd.Args) < 1 { |
| 229 | cmd.Reply("Usage: /%s <user ID> [--force]", cmd.OrigCommand) |
| 230 | return |
| 231 | } |
| 232 | force := len(cmd.Args) >= 2 && strings.ToLower(cmd.Args[1]) == "--force" |
| 233 | userID := id.UserID(cmd.Args[0]) |
| 234 | room := cmd.Room.Room |
| 235 | if !room.Encrypted { |
| 236 | cmd.Reply("In-room verification is only supported in encrypted rooms") |
| 237 | return |
| 238 | } |
| 239 | if (!room.IsDirect || room.OtherUser != userID) && !force { |
| 240 | cmd.Reply("This doesn't seem to be a direct chat. Either switch to a direct chat with %s, "+ |
| 241 | "or use `--force` to start the verification anyway.", userID) |
| 242 | return |
| 243 | } |
| 244 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 245 | if mach.CrossSigningKeys == nil && !force { |
| 246 | cmd.Reply("Cross-signing private keys not cached. Generate or fetch cross-signing keys with `/cross-signing`, " + |
| 247 | "or use `--force` to start the verification anyway") |
| 248 | return |
| 249 | } |
| 250 | modal := NewVerificationModal(cmd.MainView, &crypto.DeviceIdentity{UserID: userID}, mach.DefaultSASTimeout) |
| 251 | _, err := mach.NewInRoomSASVerificationWith(cmd.Room.Room.ID, userID, modal, 120*time.Second) |
| 252 | if err != nil { |
| 253 | cmd.Reply("Failed to start in-room verification: %v", err) |
| 254 | return |
| 255 | } |
| 256 | cmd.MainView.ShowModal(modal) |
| 257 | } |
| 258 | |
| 259 | func cmdUnverify(cmd *Command) { |
| 260 | device := getDevice(cmd) |
| 261 | if device == nil { |
| 262 | return |
| 263 | } |
| 264 | if device.Trust == crypto.TrustStateUnset { |
| 265 | cmd.Reply("That device is already not verified") |
| 266 | return |
| 267 | } |
| 268 | action := "unverified" |
| 269 | if device.Trust == crypto.TrustStateBlacklisted { |
| 270 | action = "unblacklisted" |
| 271 | } |
| 272 | device.Trust = crypto.TrustStateUnset |
| 273 | putDevice(cmd, device, action) |
| 274 | } |
| 275 | |
| 276 | func cmdBlacklist(cmd *Command) { |
| 277 | device := getDevice(cmd) |
| 278 | if device == nil { |
| 279 | return |
| 280 | } |
| 281 | if device.Trust == crypto.TrustStateBlacklisted { |
| 282 | cmd.Reply("That device is already blacklisted") |
| 283 | return |
| 284 | } |
| 285 | action := "blacklisted" |
| 286 | if device.Trust == crypto.TrustStateVerified { |
| 287 | action = "unverified and blacklisted" |
| 288 | } |
| 289 | device.Trust = crypto.TrustStateBlacklisted |
| 290 | putDevice(cmd, device, action) |
| 291 | } |
| 292 | |
| 293 | func cmdResetSession(cmd *Command) { |
| 294 | err := cmd.Matrix.Crypto().(*crypto.OlmMachine).CryptoStore.RemoveOutboundGroupSession(cmd.Room.Room.ID) |
| 295 | if err != nil { |
| 296 | cmd.Reply("Failed to remove outbound group session: %v", err) |
| 297 | } else { |
| 298 | cmd.Reply("Removed outbound group session for this room") |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | func cmdImportKeys(cmd *Command) { |
| 303 | path, err := filepath.Abs(cmd.RawArgs) |
| 304 | if err != nil { |
| 305 | cmd.Reply("Failed to get absolute path: %v", err) |
| 306 | return |
| 307 | } |
| 308 | data, err := ioutil.ReadFile(path) |
| 309 | if err != nil { |
| 310 | cmd.Reply("Failed to read %s: %v", path, err) |
| 311 | return |
| 312 | } |
| 313 | passphrase, ok := cmd.MainView.AskPassword("Key import", "passphrase", "", false) |
| 314 | if !ok { |
| 315 | cmd.Reply("Passphrase entry cancelled") |
| 316 | return |
| 317 | } |
| 318 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 319 | imported, total, err := mach.ImportKeys(passphrase, data) |
| 320 | if err != nil { |
| 321 | cmd.Reply("Failed to import sessions: %v", err) |
| 322 | } else { |
| 323 | cmd.Reply("Successfully imported %d/%d sessions", imported, total) |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | func exportKeys(cmd *Command, sessions []*crypto.InboundGroupSession) { |
| 328 | path, err := filepath.Abs(cmd.RawArgs) |
| 329 | if err != nil { |
| 330 | cmd.Reply("Failed to get absolute path: %v", err) |
| 331 | return |
| 332 | } |
| 333 | passphrase, ok := cmd.MainView.AskPassword("Key export", "passphrase", "", true) |
| 334 | if !ok { |
| 335 | cmd.Reply("Passphrase entry cancelled") |
| 336 | return |
| 337 | } |
| 338 | export, err := crypto.ExportKeys(passphrase, sessions) |
| 339 | if err != nil { |
| 340 | cmd.Reply("Failed to export sessions: %v", err) |
| 341 | } |
| 342 | err = ioutil.WriteFile(path, export, 0400) |
| 343 | if err != nil { |
| 344 | cmd.Reply("Failed to write sessions to %s: %v", path, err) |
| 345 | } else { |
| 346 | cmd.Reply("Successfully exported %d sessions to %s", len(sessions), path) |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | func cmdExportKeys(cmd *Command) { |
| 351 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 352 | sessions, err := mach.CryptoStore.GetAllGroupSessions() |
| 353 | if err != nil { |
| 354 | cmd.Reply("Failed to get sessions to export: %v", err) |
| 355 | return |
| 356 | } |
| 357 | exportKeys(cmd, sessions) |
| 358 | } |
| 359 | |
| 360 | func cmdExportRoomKeys(cmd *Command) { |
| 361 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 362 | sessions, err := mach.CryptoStore.GetGroupSessionsForRoom(cmd.Room.MxRoom().ID) |
| 363 | if err != nil { |
| 364 | cmd.Reply("Failed to get sessions to export: %v", err) |
| 365 | return |
| 366 | } |
| 367 | exportKeys(cmd, sessions) |
| 368 | } |
| 369 | |
| 370 | const ssssHelp = `Usage: /%s <subcommand> [...] |
| 371 | |
| 372 | Subcommands: |
| 373 | * status [key ID] - Check the status of your SSSS. |
| 374 | * generate [--set-default] - Generate a SSSS key and optionally set it as the default. |
| 375 | * set-default <key ID> - Set a SSSS key as the default.` |
| 376 | |
| 377 | func cmdSSSS(cmd *Command) { |
| 378 | if len(cmd.Args) == 0 { |
| 379 | cmd.Reply(ssssHelp, cmd.OrigCommand) |
| 380 | return |
| 381 | } |
| 382 | |
| 383 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 384 | |
| 385 | switch strings.ToLower(cmd.Args[0]) { |
| 386 | case "status": |
| 387 | keyID := "" |
| 388 | if len(cmd.Args) > 1 { |
| 389 | keyID = cmd.Args[1] |
| 390 | } |
| 391 | cmdS4Status(cmd, mach, keyID) |
| 392 | case "generate": |
| 393 | setDefault := len(cmd.Args) > 1 && strings.ToLower(cmd.Args[1]) == "--set-default" |
| 394 | cmdS4Generate(cmd, mach, setDefault) |
| 395 | case "set-default": |
| 396 | if len(cmd.Args) < 2 { |
| 397 | cmd.Reply("Usage: /%s set-default <key ID>", cmd.OrigCommand) |
| 398 | return |
| 399 | } |
| 400 | cmdS4SetDefault(cmd, mach, cmd.Args[1]) |
| 401 | default: |
| 402 | cmd.Reply(ssssHelp, cmd.OrigCommand) |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | func cmdS4Status(cmd *Command, mach *crypto.OlmMachine, keyID string) { |
| 407 | var keyData *ssss.KeyMetadata |
| 408 | var err error |
| 409 | if len(keyID) == 0 { |
| 410 | keyID, keyData, err = mach.SSSS.GetDefaultKeyData() |
| 411 | } else { |
| 412 | keyData, err = mach.SSSS.GetKeyData(keyID) |
| 413 | } |
| 414 | if errors.Is(err, ssss.ErrNoDefaultKeyAccountDataEvent) { |
| 415 | cmd.Reply("SSSS is not set up: no default key set") |
| 416 | return |
| 417 | } else if err != nil { |
| 418 | cmd.Reply("Failed to get key data: %v", err) |
| 419 | return |
| 420 | } |
| 421 | hasPassphrase := "no" |
| 422 | if keyData.Passphrase != nil { |
| 423 | hasPassphrase = fmt.Sprintf("yes (alg=%s,bits=%d,iter=%d)", keyData.Passphrase.Algorithm, keyData.Passphrase.Bits, keyData.Passphrase.Iterations) |
| 424 | } |
| 425 | algorithm := keyData.Algorithm |
| 426 | if algorithm != ssss.AlgorithmAESHMACSHA2 { |
| 427 | algorithm += " (not supported!)" |
| 428 | } |
| 429 | cmd.Reply("Default key is set.\n Key ID: %s\n Has passphrase: %s\n Algorithm: %s", keyID, hasPassphrase, algorithm) |
| 430 | } |
| 431 | |
| 432 | func cmdS4Generate(cmd *Command, mach *crypto.OlmMachine, setDefault bool) { |
| 433 | passphrase, ok := cmd.MainView.AskPassword("Passphrase", "", "", true) |
| 434 | if !ok { |
| 435 | return |
| 436 | } |
| 437 | |
| 438 | key, err := ssss.NewKey(passphrase) |
| 439 | if err != nil { |
| 440 | cmd.Reply("Failed to generate new key: %v", err) |
| 441 | return |
| 442 | } |
| 443 | |
| 444 | err = mach.SSSS.SetKeyData(key.ID, key.Metadata) |
| 445 | if err != nil { |
| 446 | cmd.Reply("Failed to upload key metadata: %v", err) |
| 447 | return |
| 448 | } |
| 449 | |
| 450 | // TODO if we start persisting command replies, the recovery key needs to be moved into a popup |
| 451 | cmd.Reply("Successfully generated key %s\nRecovery key: %s", key.ID, key.RecoveryKey()) |
| 452 | |
| 453 | if setDefault { |
| 454 | err = mach.SSSS.SetDefaultKeyID(key.ID) |
| 455 | if err != nil { |
| 456 | cmd.Reply("Failed to set key as default: %v", err) |
| 457 | } |
| 458 | } else { |
| 459 | cmd.Reply("You can use `/%s set-default %s` to set it as the default", cmd.OrigCommand, key.ID) |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | func cmdS4SetDefault(cmd *Command, mach *crypto.OlmMachine, keyID string) { |
| 464 | _, err := mach.SSSS.GetKeyData(keyID) |
| 465 | if err != nil { |
| 466 | if errors.Is(err, mautrix.MNotFound) { |
| 467 | cmd.Reply("Couldn't find key data on server") |
| 468 | } else { |
| 469 | cmd.Reply("Failed to fetch key data: %v", err) |
| 470 | } |
| 471 | return |
| 472 | } |
| 473 | |
| 474 | err = mach.SSSS.SetDefaultKeyID(keyID) |
| 475 | if err != nil { |
| 476 | cmd.Reply("Failed to set key as default: %v", err) |
| 477 | } else { |
| 478 | cmd.Reply("Successfully set key %s as default", keyID) |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | const crossSigningHelp = `Usage: /%s <subcommand> [...] |
| 483 | |
| 484 | Subcommands: |
| 485 | * status |
| 486 | Check the status of your own cross-signing keys. |
| 487 | * generate [--force] |
| 488 | Generate and upload new cross-signing keys. |
| 489 | This will prompt you to enter your account password. |
| 490 | If you already have existing keys, --force is required. |
| 491 | * self-sign |
| 492 | Sign the current device with cached cross-signing keys. |
| 493 | * fetch [--save-to-disk] |
| 494 | Fetch your cross-signing keys from SSSS and decrypt them. |
| 495 | If --save-to-disk is specified, the keys are saved to disk. |
| 496 | * upload |
| 497 | Upload your cross-signing keys to SSSS.` |
| 498 | |
| 499 | func cmdCrossSigning(cmd *Command) { |
| 500 | if len(cmd.Args) == 0 { |
| 501 | cmd.Reply(crossSigningHelp, cmd.OrigCommand) |
| 502 | return |
| 503 | } |
| 504 | |
| 505 | client := cmd.Matrix.Client() |
| 506 | mach := cmd.Matrix.Crypto().(*crypto.OlmMachine) |
| 507 | |
| 508 | switch strings.ToLower(cmd.Args[0]) { |
| 509 | case "status": |
| 510 | cmdCrossSigningStatus(cmd, mach) |
| 511 | case "generate": |
| 512 | force := len(cmd.Args) > 1 && strings.ToLower(cmd.Args[1]) == "--force" |
| 513 | cmdCrossSigningGenerate(cmd, cmd.Matrix, mach, client, force) |
| 514 | case "fetch": |
| 515 | saveToDisk := len(cmd.Args) > 1 && strings.ToLower(cmd.Args[1]) == "--save-to-disk" |
| 516 | cmdCrossSigningFetch(cmd, mach, saveToDisk) |
| 517 | case "upload": |
| 518 | cmdCrossSigningUpload(cmd, mach) |
| 519 | case "self-sign": |
| 520 | cmdCrossSigningSelfSign(cmd, mach) |
| 521 | default: |
| 522 | cmd.Reply(crossSigningHelp, cmd.OrigCommand) |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | func cmdCrossSigningStatus(cmd *Command, mach *crypto.OlmMachine) { |
| 527 | keys := mach.GetOwnCrossSigningPublicKeys() |
| 528 | if keys == nil { |
| 529 | if mach.CrossSigningKeys != nil { |
| 530 | cmd.Reply("Cross-signing keys are cached, but not published") |
| 531 | } else { |
| 532 | cmd.Reply("Didn't find published cross-signing keys") |
| 533 | } |
| 534 | return |
| 535 | } |
| 536 | if mach.CrossSigningKeys != nil { |
| 537 | cmd.Reply("Cross-signing keys are published and private keys are cached") |
| 538 | } else { |
| 539 | cmd.Reply("Cross-signing keys are published, but private keys are not cached") |
| 540 | } |
| 541 | cmd.Reply("Master key: %s", keys.MasterKey) |
| 542 | cmd.Reply("User signing key: %s", keys.UserSigningKey) |
| 543 | cmd.Reply("Self-signing key: %s", keys.SelfSigningKey) |
| 544 | } |
| 545 | |
| 546 | func cmdCrossSigningFetch(cmd *Command, mach *crypto.OlmMachine, saveToDisk bool) { |
| 547 | key := getSSSS(cmd, mach) |
| 548 | if key == nil { |
| 549 | return |
| 550 | } |
| 551 | |
| 552 | err := mach.FetchCrossSigningKeysFromSSSS(key) |
| 553 | if err != nil { |
| 554 | cmd.Reply("Error fetching cross-signing keys: %v", err) |
| 555 | return |
| 556 | } |
| 557 | if saveToDisk { |
| 558 | cmd.Reply("Saving keys to disk is not yet implemented") |
| 559 | } |
| 560 | cmd.Reply("Successfully unlocked cross-signing keys") |
| 561 | } |
| 562 | |
| 563 | func cmdCrossSigningGenerate(cmd *Command, container ifc.MatrixContainer, mach *crypto.OlmMachine, client *mautrix.Client, force bool) { |
| 564 | if !force { |
| 565 | existingKeys := mach.GetOwnCrossSigningPublicKeys() |
| 566 | if existingKeys != nil { |
| 567 | cmd.Reply("Found existing cross-signing keys. Use `--force` if you want to overwrite them.") |
| 568 | return |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | keys, err := mach.GenerateCrossSigningKeys() |
| 573 | if err != nil { |
| 574 | cmd.Reply("Failed to generate cross-signing keys: %v", err) |
| 575 | return |
| 576 | } |
| 577 | |
| 578 | err = mach.PublishCrossSigningKeys(keys, func(uia *mautrix.RespUserInteractive) interface{} { |
| 579 | if !uia.HasSingleStageFlow(mautrix.AuthTypePassword) { |
| 580 | for _, flow := range uia.Flows { |
| 581 | if len(flow.Stages) != 1 { |
| 582 | return nil |
| 583 | } |
| 584 | cmd.Reply("Opening browser for authentication") |
| 585 | err := container.UIAFallback(flow.Stages[0], uia.Session) |
| 586 | if err != nil { |
| 587 | cmd.Reply("Authentication failed: %v", err) |
| 588 | return nil |
| 589 | } |
| 590 | return &mautrix.ReqUIAuthFallback{ |
| 591 | Session: uia.Session, |
| 592 | User: mach.Client.UserID.String(), |
| 593 | } |
| 594 | } |
| 595 | cmd.Reply("No supported authentication mechanisms found") |
| 596 | return nil |
| 597 | } |
| 598 | password, ok := cmd.MainView.AskPassword("Account password", "", "correct horse battery staple", false) |
| 599 | if !ok { |
| 600 | return nil |
| 601 | } |
| 602 | return &mautrix.ReqUIAuthLogin{ |
| 603 | BaseAuthData: mautrix.BaseAuthData{ |
| 604 | Type: mautrix.AuthTypePassword, |
| 605 | Session: uia.Session, |
| 606 | }, |
| 607 | User: mach.Client.UserID.String(), |
| 608 | Password: password, |
| 609 | } |
| 610 | }) |
| 611 | if err != nil { |
| 612 | cmd.Reply("Failed to publish cross-signing keys: %v", err) |
| 613 | return |
| 614 | } |
| 615 | cmd.Reply("Successfully generated and published cross-signing keys") |
| 616 | |
| 617 | err = mach.SignOwnMasterKey() |
| 618 | if err != nil { |
| 619 | cmd.Reply("Failed to sign master key with device key: %v", err) |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | func getSSSS(cmd *Command, mach *crypto.OlmMachine) *ssss.Key { |
| 624 | _, keyData, err := mach.SSSS.GetDefaultKeyData() |
| 625 | if err != nil { |
| 626 | if errors.Is(err, mautrix.MNotFound) { |
| 627 | cmd.Reply("SSSS not set up, use `!ssss generate --set-default` first") |
| 628 | } else { |
| 629 | cmd.Reply("Failed to fetch default SSSS key data: %v", err) |
| 630 | } |
| 631 | return nil |
| 632 | } |
| 633 | |
| 634 | var key *ssss.Key |
| 635 | if keyData.Passphrase != nil && keyData.Passphrase.Algorithm == ssss.PassphraseAlgorithmPBKDF2 { |
| 636 | passphrase, ok := cmd.MainView.AskPassword("Passphrase", "", "correct horse battery staple", false) |
| 637 | if !ok { |
| 638 | return nil |
| 639 | } |
| 640 | key, err = keyData.VerifyPassphrase(passphrase) |
| 641 | if errors.Is(err, ssss.ErrIncorrectSSSSKey) { |
| 642 | cmd.Reply("Incorrect passphrase") |
| 643 | return nil |
| 644 | } |
| 645 | } else { |
| 646 | recoveryKey, ok := cmd.MainView.AskPassword("Recovery key", "", "tDAK LMRH PiYE bdzi maCe xLX5 wV6P Nmfd c5mC wLef 15Fs VVSc", false) |
| 647 | if !ok { |
| 648 | return nil |
| 649 | } |
| 650 | key, err = keyData.VerifyRecoveryKey(recoveryKey) |
| 651 | if errors.Is(err, ssss.ErrInvalidRecoveryKey) { |
| 652 | cmd.Reply("Malformed recovery key") |
| 653 | return nil |
| 654 | } else if errors.Is(err, ssss.ErrIncorrectSSSSKey) { |
| 655 | cmd.Reply("Incorrect recovery key") |
| 656 | return nil |
| 657 | } |
| 658 | } |
| 659 | // All the errors should already be handled above, this is just for backup |
| 660 | if err != nil { |
| 661 | cmd.Reply("Failed to get SSSS key: %v", err) |
| 662 | return nil |
| 663 | } |
| 664 | return key |
| 665 | } |
| 666 | |
| 667 | func cmdCrossSigningUpload(cmd *Command, mach *crypto.OlmMachine) { |
| 668 | if mach.CrossSigningKeys == nil { |
| 669 | cmd.Reply("Cross-signing keys not cached, use `!%s generate` first", cmd.OrigCommand) |
| 670 | return |
| 671 | } |
| 672 | |
| 673 | key := getSSSS(cmd, mach) |
| 674 | if key == nil { |
| 675 | return |
| 676 | } |
| 677 | |
| 678 | err := mach.UploadCrossSigningKeysToSSSS(key, mach.CrossSigningKeys) |
| 679 | if err != nil { |
| 680 | cmd.Reply("Failed to upload keys to SSSS: %v", err) |
| 681 | } else { |
| 682 | cmd.Reply("Successfully uploaded cross-signing keys to SSSS") |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | func cmdCrossSigningSelfSign(cmd *Command, mach *crypto.OlmMachine) { |
| 687 | if mach.CrossSigningKeys == nil { |
| 688 | cmd.Reply("Cross-signing keys not cached") |
| 689 | return |
| 690 | } |
| 691 | |
| 692 | err := mach.SignOwnDevice(mach.OwnIdentity()) |
| 693 | if err != nil { |
| 694 | cmd.Reply("Failed to self-sign: %v", err) |
| 695 | } else { |
| 696 | cmd.Reply("Successfully self-signed. This device is now trusted by other devices") |
| 697 | } |
| 698 | } |