| 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/rand" |
| 15 |
"crypto/sha256" |
| 16 |
"crypto/sha512" |
| 17 |
"encoding/base64" |
| 18 |
"encoding/binary" |
| 19 |
"encoding/json" |
| 20 |
"fmt" |
| 21 |
"math" |
| 22 |
|
| 23 |
"golang.org/x/crypto/pbkdf2" |
| 24 |
|
| 25 |
"maunium.net/go/mautrix/crypto/olm" |
| 26 |
"maunium.net/go/mautrix/id" |
| 27 |
) |
| 28 |
|
| 29 |
type SenderClaimedKeys struct { |
| 30 |
Ed25519 id.Ed25519 `json:"ed25519"` |
| 31 |
} |
| 32 |
|
| 33 |
type ExportedSession struct { |
| 34 |
Algorithm id.Algorithm `json:"algorithm"` |
| 35 |
ForwardingChains []string `json:"forwarding_curve25519_key_chain"` |
| 36 |
RoomID id.RoomID `json:"room_id"` |
| 37 |
SenderKey id.SenderKey `json:"sender_key"` |
| 38 |
SenderClaimedKeys SenderClaimedKeys `json:"sender_claimed_keys"` |
| 39 |
SessionID id.SessionID `json:"session_id"` |
| 40 |
SessionKey string `json:"session_key"` |
| 41 |
} |
| 42 |
|
| 43 |
// The default number of pbkdf2 rounds to use when exporting keys |
| 44 |
const defaultPassphraseRounds = 100000 |
| 45 |
|
| 46 |
const exportPrefix = "-----BEGIN MEGOLM SESSION DATA-----\n" |
| 47 |
const exportSuffix = "-----END MEGOLM SESSION DATA-----\n" |
| 48 |
|
| 49 |
// Only version 0x01 is currently specified in the spec |
| 50 |
const exportVersion1 = 0x01 |
| 51 |
|
| 52 |
// The standard for wrapping base64 is 76 bytes |
| 53 |
const exportLineLengthLimit = 76 |
| 54 |
|
| 55 |
// Byte count for version + salt + iv + number of rounds |
| 56 |
const exportHeaderLength = 1 + 16 + 16 + 4 |
| 57 |
|
| 58 |
// SHA-256 hash length |
| 59 |
const exportHashLength = 32 |
| 60 |
|
| 61 |
func computeKey(passphrase string, salt []byte, rounds int) (encryptionKey, hashKey []byte) { |
| 62 |
key := pbkdf2.Key([]byte(passphrase), salt, rounds, 64, sha512.New) |
| 63 |
encryptionKey = key[:32] |
| 64 |
hashKey = key[32:] |
| 65 |
return |
| 66 |
} |
| 67 |
|
| 68 |
func makeExportIV() []byte { |
| 69 |
iv := make([]byte, 16) |
| 70 |
_, err := rand.Read(iv) |
| 71 |
if err != nil { |
| 72 |
panic(olm.NotEnoughGoRandom) |
| 73 |
} |
| 74 |
// Set bit 63 to zero |
| 75 |
iv[7] &= 0b11111110 |
| 76 |
return iv |
| 77 |
} |
| 78 |
|
| 79 |
func makeExportKeys(passphrase string) (encryptionKey, hashKey, salt, iv []byte) { |
| 80 |
salt = make([]byte, 16) |
| 81 |
_, err := rand.Read(salt) |
| 82 |
if err != nil { |
| 83 |
panic(olm.NotEnoughGoRandom) |
| 84 |
} |
| 85 |
|
| 86 |
encryptionKey, hashKey = computeKey(passphrase, salt, defaultPassphraseRounds) |
| 87 |
|
| 88 |
iv = makeExportIV() |
| 89 |
return |
| 90 |
} |
| 91 |
|
| 92 |
func exportSessions(sessions []*InboundGroupSession) ([]ExportedSession, error) { |
| 93 |
export := make([]ExportedSession, len(sessions)) |
| 94 |
for i, session := range sessions { |
| 95 |
key, err := session.Internal.Export(session.Internal.FirstKnownIndex()) |
| 96 |
if err != nil { |
| 97 |
return nil, fmt.Errorf("failed to export session: %w", err) |
| 98 |
} |
| 99 |
export[i] = ExportedSession{ |
| 100 |
Algorithm: id.AlgorithmMegolmV1, |
| 101 |
ForwardingChains: session.ForwardingChains, |
| 102 |
RoomID: session.RoomID, |
| 103 |
SenderKey: session.SenderKey, |
| 104 |
SenderClaimedKeys: SenderClaimedKeys{}, |
| 105 |
SessionID: session.ID(), |
| 106 |
SessionKey: key, |
| 107 |
} |
| 108 |
} |
| 109 |
return export, nil |
| 110 |
} |
| 111 |
|
| 112 |
func exportSessionsJSON(sessions []*InboundGroupSession) ([]byte, error) { |
| 113 |
exportedSessions, err := exportSessions(sessions) |
| 114 |
if err != nil { |
| 115 |
return nil, err |
| 116 |
} |
| 117 |
return json.Marshal(exportedSessions) |
| 118 |
} |
| 119 |
|
| 120 |
func min(a, b int) int { |
| 121 |
if a > b { |
| 122 |
return b |
| 123 |
} |
| 124 |
return a |
| 125 |
} |
| 126 |
|
| 127 |
func formatKeyExportData(data []byte) []byte { |
| 128 |
base64Data := make([]byte, base64.StdEncoding.EncodedLen(len(data))) |
| 129 |
base64.StdEncoding.Encode(base64Data, data) |
| 130 |
|
| 131 |
// Prefix + data and newline for each 76 characters of data + suffix |
| 132 |
outputLength := len(exportPrefix) + |
| 133 |
len(base64Data) + int(math.Ceil(float64(len(base64Data))/exportLineLengthLimit)) + |
| 134 |
len(exportSuffix) |
| 135 |
|
| 136 |
var buf bytes.Buffer |
| 137 |
buf.Grow(outputLength) |
| 138 |
buf.WriteString(exportPrefix) |
| 139 |
for ptr := 0; ptr < len(base64Data); ptr += exportLineLengthLimit { |
| 140 |
buf.Write(base64Data[ptr:min(ptr+exportLineLengthLimit, len(base64Data))]) |
| 141 |
buf.WriteRune('\n') |
| 142 |
} |
| 143 |
buf.WriteString(exportSuffix) |
| 144 |
if buf.Len() != buf.Cap() || buf.Len() != outputLength { |
| 145 |
panic(fmt.Errorf("unexpected length %d / %d / %d", buf.Len(), buf.Cap(), outputLength)) |
| 146 |
} |
| 147 |
return buf.Bytes() |
| 148 |
} |
| 149 |
|
| 150 |
// ExportKeys exports the given Megolm sessions with the format specified in the Matrix spec. |
| 151 |
// See https://spec.matrix.org/v1.2/client-server-api/#key-exports |
| 152 |
func ExportKeys(passphrase string, sessions []*InboundGroupSession) ([]byte, error) { |
| 153 |
// Make all the keys necessary for exporting |
| 154 |
encryptionKey, hashKey, salt, iv := makeExportKeys(passphrase) |
| 155 |
// Export all the given sessions and put them in JSON |
| 156 |
unencryptedData, err := exportSessionsJSON(sessions) |
| 157 |
if err != nil { |
| 158 |
return nil, err |
| 159 |
} |
| 160 |
|
| 161 |
// The export data consists of: |
| 162 |
// 1 byte of export format version |
| 163 |
// 16 bytes of salt |
| 164 |
// 16 bytes of IV (initialization vector) |
| 165 |
// 4 bytes of the number of rounds |
| 166 |
// the encrypted export data |
| 167 |
// 32 bytes of the hash of all the data above |
| 168 |
|
| 169 |
exportData := make([]byte, exportHeaderLength+len(unencryptedData)+exportHashLength) |
| 170 |
dataWithoutHashLength := len(exportData) - exportHashLength |
| 171 |
|
| 172 |
// Create the header for the export data |
| 173 |
exportData[0] = exportVersion1 |
| 174 |
copy(exportData[1:17], salt) |
| 175 |
copy(exportData[17:33], iv) |
| 176 |
binary.BigEndian.PutUint32(exportData[33:37], defaultPassphraseRounds) |
| 177 |
|
| 178 |
// Encrypt data with AES-256-CTR |
| 179 |
block, _ := aes.NewCipher(encryptionKey) |
| 180 |
cipher.NewCTR(block, iv).XORKeyStream(exportData[exportHeaderLength:dataWithoutHashLength], unencryptedData) |
| 181 |
|
| 182 |
// Hash all the data with HMAC-SHA256 and put it at the end |
| 183 |
mac := hmac.New(sha256.New, hashKey) |
| 184 |
mac.Write(exportData[:dataWithoutHashLength]) |
| 185 |
mac.Sum(exportData[:dataWithoutHashLength]) |
| 186 |
|
| 187 |
// Format the export (prefix, base64'd exportData, suffix) and return |
| 188 |
return formatKeyExportData(exportData), nil |
| 189 |
} |