Debian Codegraph @

crypto/keyimport.go

raw
1 // Copyright (c) 2020 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 "bytes"
11 "crypto/aes"
12 "crypto/cipher"
13 "crypto/hmac"
14 "crypto/sha256"
15 "encoding/base64"
16 "encoding/binary"
17 "encoding/json"
18 "errors"
19 "fmt"
20
21 "maunium.net/go/mautrix/crypto/olm"
22 "maunium.net/go/mautrix/id"
23 )
24
25 var (
26 ErrMissingExportPrefix = errors.New("invalid Matrix key export: missing prefix")
27 ErrMissingExportSuffix = errors.New("invalid Matrix key export: missing suffix")
28 ErrUnsupportedExportVersion = errors.New("unsupported Matrix key export format version")
29 ErrMismatchingExportHash = errors.New("mismatching hash; incorrect passphrase?")
30 ErrInvalidExportedAlgorithm = errors.New("session has unknown algorithm")
31 ErrMismatchingExportedSessionID = errors.New("imported session has different ID than expected")
32 )
33
34 var exportPrefixBytes, exportSuffixBytes = []byte(exportPrefix), []byte(exportSuffix)
35
36 func decodeKeyExport(data []byte) ([]byte, error) {
37 // If the valid prefix and suffix aren't there, it's probably not a Matrix key export
38 if !bytes.HasPrefix(data, exportPrefixBytes) {
39 return nil, ErrMissingExportPrefix
40 } else if !bytes.HasSuffix(data, exportSuffixBytes) {
41 return nil, ErrMissingExportSuffix
42 }
43 // Remove the prefix and suffix, we don't care about them anymore
44 data = data[len(exportPrefix) : len(data)-len(exportSuffix)]
45
46 // Allocate space for the decoded data. Ignore newlines when counting the length
47 exportData := make([]byte, base64.StdEncoding.DecodedLen(len(data)-bytes.Count(data, []byte{'\n'})))
48 n, err := base64.StdEncoding.Decode(exportData, data)
49 if err != nil {
50 return nil, err
51 }
52
53 return exportData[:n], nil
54 }
55
56 func decryptKeyExport(passphrase string, exportData []byte) ([]ExportedSession, error) {
57 if exportData[0] != exportVersion1 {
58 return nil, ErrUnsupportedExportVersion
59 }
60
61 // Get all the different parts of the export
62 salt := exportData[1:17]
63 iv := exportData[17:33]
64 passphraseRounds := binary.BigEndian.Uint32(exportData[33:37])
65 dataWithoutHashLength := len(exportData) - exportHashLength
66 encryptedData := exportData[exportHeaderLength:dataWithoutHashLength]
67 hash := exportData[dataWithoutHashLength:]
68
69 // Compute the encryption and hash keys from the passphrase and salt
70 encryptionKey, hashKey := computeKey(passphrase, salt, int(passphraseRounds))
71
72 // Compute and verify the hash. If it doesn't match, the passphrase is probably wrong
73 mac := hmac.New(sha256.New, hashKey)
74 mac.Write(exportData[:dataWithoutHashLength])
75 if !bytes.Equal(hash, mac.Sum(nil)) {
76 return nil, ErrMismatchingExportHash
77 }
78
79 // Decrypt the export
80 block, _ := aes.NewCipher(encryptionKey)
81 unencryptedData := make([]byte, len(exportData)-exportHashLength-exportHeaderLength)
82 cipher.NewCTR(block, iv).XORKeyStream(unencryptedData, encryptedData)
83
84 // Parse the decrypted JSON
85 var sessionsJSON []ExportedSession
86 err := json.Unmarshal(unencryptedData, &sessionsJSON)
87 if err != nil {
88 return nil, fmt.Errorf("invalid export json: %w", err)
89 }
90 return sessionsJSON, nil
91 }
92
93 func (mach *OlmMachine) importExportedRoomKey(session ExportedSession) (bool, error) {
94 if session.Algorithm != id.AlgorithmMegolmV1 {
95 return false, ErrInvalidExportedAlgorithm
96 }
97
98 igsInternal, err := olm.InboundGroupSessionImport([]byte(session.SessionKey))
99 if err != nil {
100 return false, fmt.Errorf("failed to import session: %w", err)
101 } else if igsInternal.ID() != session.SessionID {
102 return false, ErrMismatchingExportedSessionID
103 }
104 igs := &InboundGroupSession{
105 Internal: *igsInternal,
106 SigningKey: session.SenderClaimedKeys.Ed25519,
107 SenderKey: session.SenderKey,
108 RoomID: session.RoomID,
109 // TODO should we add something here to mark the signing key as unverified like key requests do?
110 ForwardingChains: session.ForwardingChains,
111 }
112 existingIGS, _ := mach.CryptoStore.GetGroupSession(igs.RoomID, igs.SenderKey, igs.ID())
113 if existingIGS != nil && existingIGS.Internal.FirstKnownIndex() <= igs.Internal.FirstKnownIndex() {
114 // We already have an equivalent or better session in the store, so don't override it.
115 return false, nil
116 }
117 err = mach.CryptoStore.PutGroupSession(igs.RoomID, igs.SenderKey, igs.ID(), igs)
118 if err != nil {
119 return false, fmt.Errorf("failed to store imported session: %w", err)
120 }
121 mach.markSessionReceived(igs.ID())
122 return true, nil
123 }
124
125 // ImportKeys imports data that was exported with the format specified in the Matrix spec.
126 // See https://spec.matrix.org/v1.2/client-server-api/#key-exports
127 func (mach *OlmMachine) ImportKeys(passphrase string, data []byte) (int, int, error) {
128 exportData, err := decodeKeyExport(data)
129 if err != nil {
130 return 0, 0, err
131 }
132 sessions, err := decryptKeyExport(passphrase, exportData)
133 if err != nil {
134 return 0, 0, err
135 }
136
137 count := 0
138 for _, session := range sessions {
139 imported, err := mach.importExportedRoomKey(session)
140 if err != nil {
141 mach.Log.Warn("Failed to import Megolm session %s/%s from file: %v", session.RoomID, session.SessionID, err)
142 } else if imported {
143 mach.Log.Debug("Imported Megolm session %s/%s from file", session.RoomID, session.SessionID)
144 count++
145 } else {
146 mach.Log.Debug("Skipped Megolm session %s/%s: already in store", session.RoomID, session.SessionID)
147 }
148 }
149 return count, len(sessions), nil
150 }