| 1 |
// Copyright (c) 2021 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package crypto |
| 8 |
|
| 9 |
import ( |
| 10 |
"encoding/json" |
| 11 |
"errors" |
| 12 |
"fmt" |
| 13 |
"time" |
| 14 |
|
| 15 |
"maunium.net/go/mautrix/event" |
| 16 |
"maunium.net/go/mautrix/id" |
| 17 |
) |
| 18 |
|
| 19 |
var ( |
| 20 |
UnsupportedAlgorithm = errors.New("unsupported event encryption algorithm") |
| 21 |
NotEncryptedForMe = errors.New("olm event doesn't contain ciphertext for this device") |
| 22 |
UnsupportedOlmMessageType = errors.New("unsupported olm message type") |
| 23 |
DecryptionFailedWithMatchingSession = errors.New("decryption failed with matching session") |
| 24 |
DecryptionFailedForNormalMessage = errors.New("decryption failed for normal message") |
| 25 |
SenderMismatch = errors.New("mismatched sender in olm payload") |
| 26 |
RecipientMismatch = errors.New("mismatched recipient in olm payload") |
| 27 |
RecipientKeyMismatch = errors.New("mismatched recipient key in olm payload") |
| 28 |
) |
| 29 |
|
| 30 |
// DecryptedOlmEvent represents an event that was decrypted from an event encrypted with the m.olm.v1.curve25519-aes-sha2 algorithm. |
| 31 |
type DecryptedOlmEvent struct { |
| 32 |
Source *event.Event `json:"-"` |
| 33 |
|
| 34 |
SenderKey id.SenderKey `json:"-"` |
| 35 |
|
| 36 |
Sender id.UserID `json:"sender"` |
| 37 |
SenderDevice id.DeviceID `json:"sender_device"` |
| 38 |
Keys OlmEventKeys `json:"keys"` |
| 39 |
Recipient id.UserID `json:"recipient"` |
| 40 |
RecipientKeys OlmEventKeys `json:"recipient_keys"` |
| 41 |
|
| 42 |
Type event.Type `json:"type"` |
| 43 |
Content event.Content `json:"content"` |
| 44 |
} |
| 45 |
|
| 46 |
func (mach *OlmMachine) decryptOlmEvent(evt *event.Event, traceID string) (*DecryptedOlmEvent, error) { |
| 47 |
content, ok := evt.Content.Parsed.(*event.EncryptedEventContent) |
| 48 |
if !ok { |
| 49 |
return nil, IncorrectEncryptedContentType |
| 50 |
} else if content.Algorithm != id.AlgorithmOlmV1 { |
| 51 |
return nil, UnsupportedAlgorithm |
| 52 |
} |
| 53 |
ownContent, ok := content.OlmCiphertext[mach.account.IdentityKey()] |
| 54 |
if !ok { |
| 55 |
return nil, NotEncryptedForMe |
| 56 |
} |
| 57 |
decrypted, err := mach.decryptAndParseOlmCiphertext(evt.Sender, content.SenderKey, ownContent.Type, ownContent.Body, traceID) |
| 58 |
if err != nil { |
| 59 |
return nil, err |
| 60 |
} |
| 61 |
decrypted.Source = evt |
| 62 |
return decrypted, nil |
| 63 |
} |
| 64 |
|
| 65 |
type OlmEventKeys struct { |
| 66 |
Ed25519 id.Ed25519 `json:"ed25519"` |
| 67 |
} |
| 68 |
|
| 69 |
func (mach *OlmMachine) decryptAndParseOlmCiphertext(sender id.UserID, senderKey id.SenderKey, olmType id.OlmMsgType, ciphertext string, traceID string) (*DecryptedOlmEvent, error) { |
| 70 |
if olmType != id.OlmMsgTypePreKey && olmType != id.OlmMsgTypeMsg { |
| 71 |
return nil, UnsupportedOlmMessageType |
| 72 |
} |
| 73 |
|
| 74 |
endTimeTrace := mach.timeTrace("decrypting olm ciphertext", traceID, 5*time.Second) |
| 75 |
plaintext, err := mach.tryDecryptOlmCiphertext(sender, senderKey, olmType, ciphertext, traceID) |
| 76 |
endTimeTrace() |
| 77 |
if err != nil { |
| 78 |
return nil, err |
| 79 |
} |
| 80 |
|
| 81 |
defer mach.timeTrace("parsing decrypted olm event", traceID, time.Second)() |
| 82 |
|
| 83 |
var olmEvt DecryptedOlmEvent |
| 84 |
err = json.Unmarshal(plaintext, &olmEvt) |
| 85 |
if err != nil { |
| 86 |
return nil, fmt.Errorf("failed to parse olm payload: %w", err) |
| 87 |
} |
| 88 |
if sender != olmEvt.Sender { |
| 89 |
return nil, SenderMismatch |
| 90 |
} else if mach.Client.UserID != olmEvt.Recipient { |
| 91 |
return nil, RecipientMismatch |
| 92 |
} else if mach.account.SigningKey() != olmEvt.RecipientKeys.Ed25519 { |
| 93 |
return nil, RecipientKeyMismatch |
| 94 |
} |
| 95 |
|
| 96 |
err = olmEvt.Content.ParseRaw(olmEvt.Type) |
| 97 |
if err != nil && !event.IsUnsupportedContentType(err) { |
| 98 |
return nil, fmt.Errorf("failed to parse content of olm payload event: %w", err) |
| 99 |
} |
| 100 |
|
| 101 |
olmEvt.SenderKey = senderKey |
| 102 |
|
| 103 |
return &olmEvt, nil |
| 104 |
} |
| 105 |
|
| 106 |
func (mach *OlmMachine) tryDecryptOlmCiphertext(sender id.UserID, senderKey id.SenderKey, olmType id.OlmMsgType, ciphertext string, traceID string) ([]byte, error) { |
| 107 |
endTimeTrace := mach.timeTrace("waiting for olm lock", traceID, 5*time.Second) |
| 108 |
mach.olmLock.Lock() |
| 109 |
endTimeTrace() |
| 110 |
defer mach.olmLock.Unlock() |
| 111 |
|
| 112 |
plaintext, err := mach.tryDecryptOlmCiphertextWithExistingSession(senderKey, olmType, ciphertext, traceID) |
| 113 |
if err != nil { |
| 114 |
if err == DecryptionFailedWithMatchingSession { |
| 115 |
mach.Log.Warn("Found matching session yet decryption failed for sender %s with key %s", sender, senderKey) |
| 116 |
go mach.unwedgeDevice(sender, senderKey) |
| 117 |
} |
| 118 |
return nil, fmt.Errorf("failed to decrypt olm event: %w", err) |
| 119 |
} |
| 120 |
|
| 121 |
if plaintext != nil { |
| 122 |
// Decryption successful |
| 123 |
return plaintext, nil |
| 124 |
} |
| 125 |
|
| 126 |
// Decryption failed with every known session or no known sessions, let's try to create a new session. |
| 127 |
// |
| 128 |
// New sessions can only be created if it's a prekey message, we can't decrypt the message |
| 129 |
// if it isn't one at this point in time anymore, so return early. |
| 130 |
if olmType != id.OlmMsgTypePreKey { |
| 131 |
go mach.unwedgeDevice(sender, senderKey) |
| 132 |
return nil, DecryptionFailedForNormalMessage |
| 133 |
} |
| 134 |
|
| 135 |
mach.Log.Trace("Trying to create inbound session for %s/%s", sender, senderKey) |
| 136 |
endTimeTrace = mach.timeTrace("creating inbound olm session", traceID, time.Second) |
| 137 |
session, err := mach.createInboundSession(senderKey, ciphertext) |
| 138 |
endTimeTrace() |
| 139 |
if err != nil { |
| 140 |
go mach.unwedgeDevice(sender, senderKey) |
| 141 |
return nil, fmt.Errorf("failed to create new session from prekey message: %w", err) |
| 142 |
} |
| 143 |
mach.Log.Debug("Created inbound olm session %s for %s/%s: %s", session.ID(), sender, senderKey, session.Describe()) |
| 144 |
|
| 145 |
endTimeTrace = mach.timeTrace(fmt.Sprintf("decrypting prekey olm message with %s/%s", senderKey, session.ID()), traceID, time.Second) |
| 146 |
plaintext, err = session.Decrypt(ciphertext, olmType) |
| 147 |
endTimeTrace() |
| 148 |
if err != nil { |
| 149 |
go mach.unwedgeDevice(sender, senderKey) |
| 150 |
return nil, fmt.Errorf("failed to decrypt olm event with session created from prekey message: %w", err) |
| 151 |
} |
| 152 |
|
| 153 |
endTimeTrace = mach.timeTrace(fmt.Sprintf("updating new session %s/%s in database", senderKey, session.ID()), traceID, time.Second) |
| 154 |
err = mach.CryptoStore.UpdateSession(senderKey, session) |
| 155 |
endTimeTrace() |
| 156 |
if err != nil { |
| 157 |
mach.Log.Warn("Failed to update new olm session in crypto store after decrypting: %v", err) |
| 158 |
} |
| 159 |
return plaintext, nil |
| 160 |
} |
| 161 |
|
| 162 |
func (mach *OlmMachine) tryDecryptOlmCiphertextWithExistingSession(senderKey id.SenderKey, olmType id.OlmMsgType, ciphertext string, traceID string) ([]byte, error) { |
| 163 |
endTimeTrace := mach.timeTrace(fmt.Sprintf("getting sessions with %s", senderKey), traceID, time.Second) |
| 164 |
sessions, err := mach.CryptoStore.GetSessions(senderKey) |
| 165 |
endTimeTrace() |
| 166 |
if err != nil { |
| 167 |
return nil, fmt.Errorf("failed to get session for %s: %w", senderKey, err) |
| 168 |
} |
| 169 |
|
| 170 |
for _, session := range sessions { |
| 171 |
if olmType == id.OlmMsgTypePreKey { |
| 172 |
endTimeTrace = mach.timeTrace(fmt.Sprintf("checking if prekey olm message matches session %s/%s", senderKey, session.ID()), traceID, time.Second) |
| 173 |
matches, err := session.Internal.MatchesInboundSession(ciphertext) |
| 174 |
endTimeTrace() |
| 175 |
if err != nil { |
| 176 |
return nil, fmt.Errorf("failed to check if ciphertext matches inbound session: %w", err) |
| 177 |
} else if !matches { |
| 178 |
continue |
| 179 |
} |
| 180 |
} |
| 181 |
mach.Log.Trace("Trying to decrypt olm message from %s with session %s: %s", senderKey, session.ID(), session.Describe()) |
| 182 |
endTimeTrace = mach.timeTrace(fmt.Sprintf("decrypting olm message with %s/%s", senderKey, session.ID()), traceID, time.Second) |
| 183 |
plaintext, err := session.Decrypt(ciphertext, olmType) |
| 184 |
endTimeTrace() |
| 185 |
if err != nil { |
| 186 |
if olmType == id.OlmMsgTypePreKey { |
| 187 |
return nil, DecryptionFailedWithMatchingSession |
| 188 |
} |
| 189 |
} else { |
| 190 |
endTimeTrace = mach.timeTrace(fmt.Sprintf("updating session %s/%s in database", senderKey, session.ID()), traceID, time.Second) |
| 191 |
err = mach.CryptoStore.UpdateSession(senderKey, session) |
| 192 |
endTimeTrace() |
| 193 |
if err != nil { |
| 194 |
mach.Log.Warn("Failed to update olm session in crypto store after decrypting: %v", err) |
| 195 |
} |
| 196 |
mach.Log.Trace("Decrypted olm message from %s with session %s", senderKey, session.ID()) |
| 197 |
return plaintext, nil |
| 198 |
} |
| 199 |
} |
| 200 |
return nil, nil |
| 201 |
} |
| 202 |
|
| 203 |
func (mach *OlmMachine) createInboundSession(senderKey id.SenderKey, ciphertext string) (*OlmSession, error) { |
| 204 |
session, err := mach.account.NewInboundSessionFrom(senderKey, ciphertext) |
| 205 |
if err != nil { |
| 206 |
return nil, err |
| 207 |
} |
| 208 |
mach.saveAccount() |
| 209 |
err = mach.CryptoStore.AddSession(senderKey, session) |
| 210 |
if err != nil { |
| 211 |
mach.Log.Error("Failed to store created inbound session: %v", err) |
| 212 |
} |
| 213 |
return session, nil |
| 214 |
} |
| 215 |
|
| 216 |
const MinUnwedgeInterval = 1 * time.Hour |
| 217 |
|
| 218 |
func (mach *OlmMachine) unwedgeDevice(sender id.UserID, senderKey id.SenderKey) { |
| 219 |
mach.recentlyUnwedgedLock.Lock() |
| 220 |
prevUnwedge, ok := mach.recentlyUnwedged[senderKey] |
| 221 |
delta := time.Now().Sub(prevUnwedge) |
| 222 |
if ok && delta < MinUnwedgeInterval { |
| 223 |
mach.Log.Debug("Not creating new Olm session with %s/%s, previous recreation was %s ago", sender, senderKey, delta) |
| 224 |
mach.recentlyUnwedgedLock.Unlock() |
| 225 |
return |
| 226 |
} |
| 227 |
mach.recentlyUnwedged[senderKey] = time.Now() |
| 228 |
mach.recentlyUnwedgedLock.Unlock() |
| 229 |
|
| 230 |
deviceIdentity, err := mach.GetOrFetchDeviceByKey(sender, senderKey) |
| 231 |
if err != nil { |
| 232 |
mach.Log.Error("Failed to find device info by identity key: %v", err) |
| 233 |
return |
| 234 |
} else if deviceIdentity == nil { |
| 235 |
mach.Log.Warn("Didn't find identity of %s/%s, can't unwedge session", sender, senderKey) |
| 236 |
return |
| 237 |
} |
| 238 |
|
| 239 |
mach.Log.Debug("Creating new Olm session with %s/%s (key: %s)", sender, deviceIdentity.DeviceID, senderKey) |
| 240 |
mach.devicesToUnwedgeLock.Lock() |
| 241 |
mach.devicesToUnwedge[senderKey] = true |
| 242 |
mach.devicesToUnwedgeLock.Unlock() |
| 243 |
err = mach.SendEncryptedToDevice(deviceIdentity, event.ToDeviceDummy, event.Content{}) |
| 244 |
if err != nil { |
| 245 |
mach.Log.Error("Failed to send dummy event to unwedge session with %s/%s: %v", sender, senderKey, err) |
| 246 |
} |
| 247 |
} |