Add broken in-room verification and other stuff

This commit is contained in:
Tulir Asokan 2020-09-13 00:13:08 +03:00
parent c6d1c62b65
commit 5f999121f4
9 changed files with 131 additions and 84 deletions

2
go.mod
View File

@ -29,4 +29,4 @@ require (
) )
//replace maunium.net/go/mautrix => ../mautrix-go //replace maunium.net/go/mautrix => ../mautrix-go
replace maunium.net/go/mautrix => github.com/nikofil/mautrix-go v0.5.2-0.20200911234625-a585557b3750 replace maunium.net/go/mautrix => github.com/nikofil/mautrix-go v0.5.2-0.20200912211003-156aad4c3f86

2
go.sum
View File

@ -56,6 +56,8 @@ github.com/nikofil/mautrix-go v0.5.2-0.20200911232449-6010305aed05 h1:WFyJHdXasA
github.com/nikofil/mautrix-go v0.5.2-0.20200911232449-6010305aed05/go.mod h1:xd0D0ekVts/UDBbjeDSs4wGlBfcarJDg0MMhVgHbxhs= github.com/nikofil/mautrix-go v0.5.2-0.20200911232449-6010305aed05/go.mod h1:xd0D0ekVts/UDBbjeDSs4wGlBfcarJDg0MMhVgHbxhs=
github.com/nikofil/mautrix-go v0.5.2-0.20200911234625-a585557b3750 h1:3eUgrAhYHnI0HidL2uO1uga8dpnqpAXIN0DB7uWc95Y= github.com/nikofil/mautrix-go v0.5.2-0.20200911234625-a585557b3750 h1:3eUgrAhYHnI0HidL2uO1uga8dpnqpAXIN0DB7uWc95Y=
github.com/nikofil/mautrix-go v0.5.2-0.20200911234625-a585557b3750/go.mod h1:xd0D0ekVts/UDBbjeDSs4wGlBfcarJDg0MMhVgHbxhs= github.com/nikofil/mautrix-go v0.5.2-0.20200911234625-a585557b3750/go.mod h1:xd0D0ekVts/UDBbjeDSs4wGlBfcarJDg0MMhVgHbxhs=
github.com/nikofil/mautrix-go v0.5.2-0.20200912211003-156aad4c3f86 h1:cVz8JHJyGRwve5EPDN7X6pUsP3/6Dy2c7gj7RCkZa50=
github.com/nikofil/mautrix-go v0.5.2-0.20200912211003-156aad4c3f86/go.mod h1:xd0D0ekVts/UDBbjeDSs4wGlBfcarJDg0MMhVgHbxhs=
github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U= github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=

View File

@ -83,6 +83,7 @@ type Crypto interface {
Load() error Load() error
FlushStore() error FlushStore() error
ProcessSyncResponse(resp *mautrix.RespSync, since string) ProcessSyncResponse(resp *mautrix.RespSync, since string)
ProcessInRoomVerification(evt *event.Event) error
HandleMemberEvent(*event.Event) HandleMemberEvent(*event.Event)
DecryptMegolmEvent(*event.Event) (*event.Event, error) DecryptMegolmEvent(*event.Event) (*event.Event, error)
EncryptMegolmEvent(id.RoomID, event.Type, interface{}) (*event.EncryptedEventContent, error) EncryptMegolmEvent(id.RoomID, event.Type, interface{}) (*event.EncryptedEventContent, error)

View File

@ -584,7 +584,16 @@ func (c *Container) HandleEncrypted(source mautrix.EventSource, mxEvent *event.E
c.HandleMessage(source, mxEvent) c.HandleMessage(source, mxEvent)
return return
} }
c.HandleMessage(source, evt) if evt.Type.IsInRoomVerification() {
err := c.crypto.ProcessInRoomVerification(evt)
if err != nil {
debug.Printf("[Crypto/Error] Failed to process in-room verification event %s of type %s: %v", evt.ID, evt.Type.String(), err)
} else {
debug.Printf("[Crypto/Debug] Processed in-room verification event %s of type %s", evt.ID, evt.Type.String())
}
} else {
c.HandleMessage(source, evt)
}
} }
// HandleMessage is the event handler for the m.room.message timeline event. // HandleMessage is the event handler for the m.room.message timeline event.
@ -743,14 +752,14 @@ func (c *Container) HandleReadReceipt(source mautrix.EventSource, evt *event.Eve
} }
} }
func (c *Container) parseDirectChatInfo(evt *event.Event) map[*rooms.Room]bool { func (c *Container) parseDirectChatInfo(evt *event.Event) map[*rooms.Room]id.UserID {
directChats := make(map[*rooms.Room]bool) directChats := make(map[*rooms.Room]id.UserID)
for _, roomIDList := range *evt.Content.AsDirectChats() { for userID, roomIDList := range *evt.Content.AsDirectChats() {
for _, roomID := range roomIDList { for _, roomID := range roomIDList {
// TODO we shouldn't create direct chat rooms that we aren't in // TODO we shouldn't create direct chat rooms that we aren't in
room := c.GetOrCreateRoom(roomID) room := c.GetOrCreateRoom(roomID)
if room != nil && !room.HasLeft { if room != nil && !room.HasLeft {
directChats[room] = true directChats[room] = userID
} }
} }
} }
@ -760,9 +769,10 @@ func (c *Container) parseDirectChatInfo(evt *event.Event) map[*rooms.Room]bool {
func (c *Container) HandleDirectChatInfo(_ mautrix.EventSource, evt *event.Event) { func (c *Container) HandleDirectChatInfo(_ mautrix.EventSource, evt *event.Event) {
directChats := c.parseDirectChatInfo(evt) directChats := c.parseDirectChatInfo(evt)
for _, room := range c.config.Rooms.Map { for _, room := range c.config.Rooms.Map {
shouldBeDirect := directChats[room] userID, isDirect := directChats[room]
if shouldBeDirect != room.IsDirect { if isDirect != room.IsDirect {
room.IsDirect = shouldBeDirect room.IsDirect = isDirect
room.OtherUser = userID
if c.config.AuthCache.InitialSyncDone { if c.config.AuthCache.InitialSyncDone {
c.ui.MainView().UpdateTags(room) c.ui.MainView().UpdateTags(room)
} }

View File

@ -93,7 +93,8 @@ type Room struct {
highlightCache *bool highlightCache *bool
lastMarkedRead id.EventID lastMarkedRead id.EventID
// Whether or not this room is marked as a direct chat. // Whether or not this room is marked as a direct chat.
IsDirect bool IsDirect bool
OtherUser id.UserID
// List of tags given to this room. // List of tags given to this room.
RawTags []RoomTag RawTags []RoomTag

View File

@ -109,17 +109,18 @@ func NewCommandProcessor(parent *MainView) *CommandProcessor {
"cs": {"cross-signing"}, "cs": {"cross-signing"},
}, },
autocompleters: map[string]CommandAutocompleter{ autocompleters: map[string]CommandAutocompleter{
"devices": autocompleteDevice, "devices": autocompleteUser,
"device": autocompleteDevice, "device": autocompleteDevice,
"verify": autocompleteDevice, "verify": autocompleteUser,
"unverify": autocompleteDevice, "verify-device": autocompleteDevice,
"blacklist": autocompleteDevice, "unverify": autocompleteDevice,
"upload": autocompleteFile, "blacklist": autocompleteDevice,
"download": autocompleteFile, "upload": autocompleteFile,
"open": autocompleteFile, "download": autocompleteFile,
"import": autocompleteFile, "open": autocompleteFile,
"export": autocompleteFile, "import": autocompleteFile,
"export-room": autocompleteFile, "export": autocompleteFile,
"export-room": autocompleteFile,
}, },
commands: map[string]CommandHandler{ commands: map[string]CommandHandler{
"unknown-command": cmdUnknownCommand, "unknown-command": cmdUnknownCommand,
@ -167,6 +168,7 @@ func NewCommandProcessor(parent *MainView) *CommandProcessor {
"fingerprint": cmdFingerprint, "fingerprint": cmdFingerprint,
"devices": cmdDevices, "devices": cmdDevices,
"verify-device": cmdVerifyDevice,
"verify": cmdVerify, "verify": cmdVerify,
"device": cmdDevice, "device": cmdDevice,
"unverify": cmdUnverify, "unverify": cmdUnverify,

View File

@ -81,15 +81,20 @@ func autocompleteDeviceDeviceID(cmd *CommandAutocomplete) (completions []string,
return return
} }
func autocompleteUser(cmd *CommandAutocomplete) ([]string, string) {
if len(cmd.Args) == 1 && !unicode.IsSpace(rune(cmd.RawArgs[len(cmd.RawArgs)-1])) {
return autocompleteDeviceUserID(cmd)
}
return []string{}, ""
}
func autocompleteDevice(cmd *CommandAutocomplete) ([]string, string) { func autocompleteDevice(cmd *CommandAutocomplete) ([]string, string) {
if len(cmd.Args) == 0 { if len(cmd.Args) == 0 {
return []string{}, "" return []string{}, ""
} else if len(cmd.Args) == 1 && !unicode.IsSpace(rune(cmd.RawArgs[len(cmd.RawArgs)-1])) { } else if len(cmd.Args) == 1 && !unicode.IsSpace(rune(cmd.RawArgs[len(cmd.RawArgs)-1])) {
return autocompleteDeviceUserID(cmd) return autocompleteDeviceUserID(cmd)
} else if cmd.Command != "devices" {
return autocompleteDeviceDeviceID(cmd)
} }
return []string{}, "" return autocompleteDeviceDeviceID(cmd)
} }
func getDevice(cmd *Command) *crypto.DeviceIdentity { func getDevice(cmd *Command) *crypto.DeviceIdentity {
@ -138,7 +143,11 @@ func cmdDevices(cmd *Command) {
} }
var buf strings.Builder var buf strings.Builder
for _, device := range devices { for _, device := range devices {
_, _ = fmt.Fprintf(&buf, "%s (%s) - %s\n Fingerprint: %s\n", device.DeviceID, device.Name, device.Trust.String(), device.Fingerprint()) trust := device.Trust.String()
if device.Trust == crypto.TrustStateUnset && mach.IsDeviceTrusted(device) {
trust = "verified (transitive)"
}
_, _ = fmt.Fprintf(&buf, "%s (%s) - %s\n Fingerprint: %s\n", device.DeviceID, device.Name, trust, device.Fingerprint())
} }
resp := buf.String() resp := buf.String()
cmd.Reply("%s", resp[:len(resp)-1]) cmd.Reply("%s", resp[:len(resp)-1])
@ -153,13 +162,28 @@ func cmdDevice(cmd *Command) {
if device.Deleted { if device.Deleted {
deviceType = "Deleted device" deviceType = "Deleted device"
} }
mach := cmd.Matrix.Crypto().(*crypto.OlmMachine)
trustState := device.Trust.String()
if device.Trust == crypto.TrustStateUnset && mach.IsDeviceTrusted(device) {
trustState = "verified (transitive)"
}
cmd.Reply("%s %s of %s\nFingerprint: %s\nIdentity key: %s\nDevice name: %s\nTrust state: %s", cmd.Reply("%s %s of %s\nFingerprint: %s\nIdentity key: %s\nDevice name: %s\nTrust state: %s",
deviceType, device.DeviceID, device.UserID, deviceType, device.DeviceID, device.UserID,
device.Fingerprint(), device.IdentityKey, device.Fingerprint(), device.IdentityKey,
device.Name, device.Trust.String()) device.Name, trustState)
} }
func cmdVerify(cmd *Command) { func crossSignDevice(cmd *Command, device *crypto.DeviceIdentity) {
mach := cmd.Matrix.Crypto().(*crypto.OlmMachine)
err := mach.SignOwnDevice(device)
if err != nil {
cmd.Reply("Failed to upload cross-signing signature: %v", err)
} else {
cmd.Reply("Successfully cross-signed %s (%s)", device.DeviceID, device.Name)
}
}
func cmdVerifyDevice(cmd *Command) {
device := getDevice(cmd) device := getDevice(cmd)
if device == nil { if device == nil {
return return
@ -188,11 +212,49 @@ func cmdVerify(cmd *Command) {
if device.Trust == crypto.TrustStateBlacklisted { if device.Trust == crypto.TrustStateBlacklisted {
action = "unblacklisted and verified" action = "unblacklisted and verified"
} }
device.Trust = crypto.TrustStateVerified if device.UserID == cmd.Matrix.Client().UserID {
putDevice(cmd, device, action) crossSignDevice(cmd, device)
device.Trust = crypto.TrustStateVerified
putDevice(cmd, device, action)
} else {
putDevice(cmd, device, action)
cmd.Reply("Warning: verifying individual devices of other users is not synced with cross-signing")
}
} }
} }
func cmdVerify(cmd *Command) {
if len(cmd.Args) < 1 {
cmd.Reply("Usage: /%s <user ID> [--force]", cmd.OrigCommand)
return
}
force := len(cmd.Args) >= 2 && strings.ToLower(cmd.Args[1]) == "--force"
userID := id.UserID(cmd.Args[0])
room := cmd.Room.Room
if !room.Encrypted {
cmd.Reply("In-room verification is only supported in encrypted rooms")
return
}
if (!room.IsDirect || room.OtherUser != userID) && !force {
cmd.Reply("This doesn't seem to be a direct chat. Either switch to a direct chat with %s, "+
"or use `--force` to start the verification anyway.", userID)
return
}
mach := cmd.Matrix.Crypto().(*crypto.OlmMachine)
if mach.CrossSigningKeys == nil && !force {
cmd.Reply("Cross-signing private keys not cached. Generate or fetch cross-signing keys with `/cross-signing`, " +
"or use `--force` to start the verification anyway")
return
}
modal := NewVerificationModal(cmd.MainView, &crypto.DeviceIdentity{UserID: userID}, mach.DefaultSASTimeout)
_, err := mach.NewInRoomSASVerificationWith(cmd.Room.Room.ID, userID, modal, 120*time.Second)
if err != nil {
cmd.Reply("Failed to start in-room verification: %v", err)
return
}
cmd.MainView.ShowModal(modal)
}
func cmdUnverify(cmd *Command) { func cmdUnverify(cmd *Command) {
device := getDevice(cmd) device := getDevice(cmd)
if device == nil { if device == nil {
@ -444,7 +506,7 @@ func cmdCrossSigning(cmd *Command) {
switch strings.ToLower(cmd.Args[0]) { switch strings.ToLower(cmd.Args[0]) {
case "status": case "status":
cmdCrossSigningStatus(cmd, mach, client) cmdCrossSigningStatus(cmd, mach)
case "generate": case "generate":
force := len(cmd.Args) > 1 && strings.ToLower(cmd.Args[1]) == "--force" force := len(cmd.Args) > 1 && strings.ToLower(cmd.Args[1]) == "--force"
cmdCrossSigningGenerate(cmd, cmd.Matrix, mach, client, force) cmdCrossSigningGenerate(cmd, cmd.Matrix, mach, client, force)
@ -460,48 +522,24 @@ func cmdCrossSigning(cmd *Command) {
} }
} }
func parseKeyResp(keys *mautrix.RespQueryKeys, userID id.UserID) (id.Ed25519, id.Ed25519, id.Ed25519, bool) { func cmdCrossSigningStatus(cmd *Command, mach *crypto.OlmMachine) {
masterKeys, ok := keys.MasterKeys[userID] keys := mach.GetOwnCrossSigningPublicKeys()
if !ok { if keys == nil {
return "", "", "", false if mach.CrossSigningKeys != nil {
cmd.Reply("Cross-signing keys are cached, but not published")
} else {
cmd.Reply("Didn't find published cross-signing keys")
}
return
} }
selfSigningKeys, ok := keys.SelfSigningKeys[userID]
if !ok {
return "", "", "", false
}
userSigningKeys, ok := keys.UserSigningKeys[userID]
if !ok {
return masterKeys.FirstKey(), selfSigningKeys.FirstKey(), "", true
}
return masterKeys.FirstKey(), userSigningKeys.FirstKey(), selfSigningKeys.FirstKey(), true
}
func cmdCrossSigningStatus(cmd *Command, mach *crypto.OlmMachine, client *mautrix.Client) {
if mach.CrossSigningKeys != nil { if mach.CrossSigningKeys != nil {
cmd.Reply("Cross-signing is set up and private keys are cached") cmd.Reply("Cross-signing keys are published and private keys are cached")
cmd.Reply("Master key: %s", mach.CrossSigningKeys.MasterKey.PublicKey) } else {
cmd.Reply("User signing key: %s", mach.CrossSigningKeys.UserSigningKey.PublicKey) cmd.Reply("Cross-signing keys are published, but private keys are not cached")
cmd.Reply("Self-signing key: %s", mach.CrossSigningKeys.SelfSigningKey.PublicKey)
return
} }
keys, err := client.QueryKeys(&mautrix.ReqQueryKeys{ cmd.Reply("Master key: %s", keys.MasterKey)
DeviceKeys: mautrix.DeviceKeysRequest{ cmd.Reply("User signing key: %s", keys.UserSigningKey)
client.UserID: mautrix.DeviceIDList{client.DeviceID}, cmd.Reply("Self-signing key: %s", keys.SelfSigningKey)
},
})
if err != nil {
cmd.Reply("Failed to query own keys: %v", err)
return
}
masterKey, selfSigningKey, userSigningKey, ok := parseKeyResp(keys, client.UserID)
if !ok {
cmd.Reply("Didn't find published cross-signing keys")
return
}
cmd.Reply("Cross-signing is set up, but private keys are not cached")
cmd.Reply("Master key: %s", masterKey)
cmd.Reply("User signing key: %s", userSigningKey)
cmd.Reply("Self-signing key: %s", selfSigningKey)
} }
func cmdCrossSigningFetch(cmd *Command, mach *crypto.OlmMachine, saveToDisk bool) { func cmdCrossSigningFetch(cmd *Command, mach *crypto.OlmMachine, saveToDisk bool) {
@ -523,17 +561,10 @@ func cmdCrossSigningFetch(cmd *Command, mach *crypto.OlmMachine, saveToDisk bool
func cmdCrossSigningGenerate(cmd *Command, container ifc.MatrixContainer, mach *crypto.OlmMachine, client *mautrix.Client, force bool) { func cmdCrossSigningGenerate(cmd *Command, container ifc.MatrixContainer, mach *crypto.OlmMachine, client *mautrix.Client, force bool) {
if !force { if !force {
keys, err := client.QueryKeys(&mautrix.ReqQueryKeys{ existingKeys := mach.GetOwnCrossSigningPublicKeys()
DeviceKeys: mautrix.DeviceKeysRequest{ if existingKeys != nil {
client.UserID: mautrix.DeviceIDList{client.DeviceID}, cmd.Reply("Found existing cross-signing keys. Use `--force` if you want to overwrite them.")
}, return
})
if err == nil {
_, _, _, ok := parseKeyResp(keys, client.UserID)
if ok {
cmd.Reply("Found existing cross-signing keys. Use `--force` if you want to overwrite them.")
return
}
} }
} }
@ -557,7 +588,7 @@ func cmdCrossSigningGenerate(cmd *Command, container ifc.MatrixContainer, mach *
} }
return &mautrix.ReqUIAuthFallback{ return &mautrix.ReqUIAuthFallback{
Session: uia.Session, Session: uia.Session,
User: mach.Client.UserID.String(), User: mach.Client.UserID.String(),
} }
} }
cmd.Reply("No supported authentication mechanisms found") cmd.Reply("No supported authentication mechanisms found")
@ -580,8 +611,6 @@ func cmdCrossSigningGenerate(cmd *Command, container ifc.MatrixContainer, mach *
cmd.Reply("Failed to publish cross-signing keys: %v", err) cmd.Reply("Failed to publish cross-signing keys: %v", err)
return return
} }
mach.CrossSigningKeys = keys
cmd.Reply("Successfully generated and published cross-signing keys") cmd.Reply("Successfully generated and published cross-signing keys")
err = mach.SignOwnMasterKey() err = mach.SignOwnMasterKey()

View File

@ -29,6 +29,7 @@ func cmdNoCrypto(cmd *Command) {
var ( var (
cmdDevices = cmdNoCrypto cmdDevices = cmdNoCrypto
cmdDevice = cmdNoCrypto cmdDevice = cmdNoCrypto
cmdVerifyDevice = cmdNoCrypto
cmdVerify = cmdNoCrypto cmdVerify = cmdNoCrypto
cmdUnverify = cmdNoCrypto cmdUnverify = cmdNoCrypto
cmdBlacklist = cmdNoCrypto cmdBlacklist = cmdNoCrypto

View File

@ -148,7 +148,8 @@ func (vm *VerificationModal) VerificationMethods() []crypto.VerificationMethod {
return []crypto.VerificationMethod{crypto.VerificationMethodEmoji{}, crypto.VerificationMethodDecimal{}} return []crypto.VerificationMethod{crypto.VerificationMethodEmoji{}, crypto.VerificationMethodDecimal{}}
} }
func (vm *VerificationModal) VerifySASMatch(_ *crypto.DeviceIdentity, data crypto.SASData) bool { func (vm *VerificationModal) VerifySASMatch(device *crypto.DeviceIdentity, data crypto.SASData) bool {
vm.device = device
var typeName string var typeName string
if data.Type() == event.SASDecimal { if data.Type() == event.SASDecimal {
typeName = "numbers" typeName = "numbers"