Debian Codegraph @

crypto/attachment/attachments.go

raw
1 // Copyright (c) 2022 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 attachment
8
9 import (
10 "crypto/aes"
11 "crypto/cipher"
12 "crypto/sha256"
13 "encoding/base64"
14 "errors"
15 "hash"
16 "io"
17
18 "maunium.net/go/mautrix/crypto/utils"
19 )
20
21 var (
22 HashMismatch = errors.New("mismatching SHA-256 digest")
23 UnsupportedVersion = errors.New("unsupported Matrix file encryption version")
24 UnsupportedAlgorithm = errors.New("unsupported JWK encryption algorithm")
25 InvalidKey = errors.New("failed to decode key")
26 InvalidInitVector = errors.New("failed to decode initialization vector")
27 InvalidHash = errors.New("failed to decode SHA-256 hash")
28 ReaderClosed = errors.New("encrypting reader was already closed")
29 )
30
31 var (
32 keyBase64Length = base64.RawURLEncoding.EncodedLen(utils.AESCTRKeyLength)
33 ivBase64Length = base64.RawStdEncoding.EncodedLen(utils.AESCTRIVLength)
34 hashBase64Length = base64.RawStdEncoding.EncodedLen(utils.SHAHashLength)
35 )
36
37 type JSONWebKey struct {
38 Key string `json:"k"`
39 Algorithm string `json:"alg"`
40 Extractable bool `json:"ext"`
41 KeyType string `json:"kty"`
42 KeyOps []string `json:"key_ops"`
43 }
44
45 type EncryptedFileHashes struct {
46 SHA256 string `json:"sha256"`
47 }
48
49 type decodedKeys struct {
50 key [utils.AESCTRKeyLength]byte
51 iv [utils.AESCTRIVLength]byte
52
53 sha256 [utils.SHAHashLength]byte
54 }
55
56 type EncryptedFile struct {
57 Key JSONWebKey `json:"key"`
58 InitVector string `json:"iv"`
59 Hashes EncryptedFileHashes `json:"hashes"`
60 Version string `json:"v"`
61
62 decoded *decodedKeys
63 }
64
65 func NewEncryptedFile() *EncryptedFile {
66 key, iv := utils.GenAttachmentA256CTR()
67 return &EncryptedFile{
68 Key: JSONWebKey{
69 Key: base64.RawURLEncoding.EncodeToString(key[:]),
70 Algorithm: "A256CTR",
71 Extractable: true,
72 KeyType: "oct",
73 KeyOps: []string{"encrypt", "decrypt"},
74 },
75 InitVector: base64.RawStdEncoding.EncodeToString(iv[:]),
76 Version: "v2",
77
78 decoded: &decodedKeys{key: key, iv: iv},
79 }
80 }
81
82 func (ef *EncryptedFile) decodeKeys(includeHash bool) error {
83 if ef.decoded != nil {
84 return nil
85 } else if len(ef.Key.Key) != keyBase64Length {
86 return InvalidKey
87 } else if len(ef.InitVector) != ivBase64Length {
88 return InvalidInitVector
89 } else if includeHash && len(ef.Hashes.SHA256) != hashBase64Length {
90 return InvalidHash
91 }
92 ef.decoded = &decodedKeys{}
93 _, err := base64.RawURLEncoding.Decode(ef.decoded.key[:], []byte(ef.Key.Key))
94 if err != nil {
95 return InvalidKey
96 }
97 _, err = base64.RawStdEncoding.Decode(ef.decoded.iv[:], []byte(ef.InitVector))
98 if err != nil {
99 return InvalidInitVector
100 }
101 if includeHash {
102 _, err = base64.RawStdEncoding.Decode(ef.decoded.sha256[:], []byte(ef.Hashes.SHA256))
103 if err != nil {
104 return InvalidHash
105 }
106 }
107 return nil
108 }
109
110 // Encrypt encrypts the given data, updates the SHA256 hash in the EncryptedFile struct and returns the ciphertext.
111 //
112 // Deprecated: this makes a copy for the ciphertext, which means 2x memory usage. EncryptInPlace is recommended.
113 func (ef *EncryptedFile) Encrypt(plaintext []byte) []byte {
114 ciphertext := make([]byte, len(plaintext))
115 copy(ciphertext, plaintext)
116 ef.EncryptInPlace(ciphertext)
117 return ciphertext
118 }
119
120 // EncryptInPlace encrypts the given data in-place (i.e. the provided data is overridden with the ciphertext)
121 // and updates the SHA256 hash in the EncryptedFile struct.
122 func (ef *EncryptedFile) EncryptInPlace(data []byte) {
123 ef.decodeKeys(false)
124 utils.XorA256CTR(data, ef.decoded.key, ef.decoded.iv)
125 checksum := sha256.Sum256(data)
126 ef.Hashes.SHA256 = base64.RawStdEncoding.EncodeToString(checksum[:])
127 }
128
129 type encryptingReader struct {
130 stream cipher.Stream
131 hash hash.Hash
132 source io.Reader
133 file *EncryptedFile
134 closed bool
135
136 isDecrypting bool
137 }
138
139 func (r *encryptingReader) Read(dst []byte) (n int, err error) {
140 if r.closed {
141 return 0, ReaderClosed
142 } else if r.isDecrypting && r.file.decoded == nil {
143 if err = r.file.PrepareForDecryption(); err != nil {
144 return
145 }
146 }
147 n, err = r.source.Read(dst)
148 r.stream.XORKeyStream(dst[:n], dst[:n])
149 r.hash.Write(dst[:n])
150 return
151 }
152
153 func (r *encryptingReader) Close() (err error) {
154 closer, ok := r.source.(io.ReadCloser)
155 if ok {
156 err = closer.Close()
157 }
158 if r.isDecrypting {
159 var downloadedChecksum [utils.SHAHashLength]byte
160 r.hash.Sum(downloadedChecksum[:])
161 if downloadedChecksum != r.file.decoded.sha256 {
162 return HashMismatch
163 }
164 } else {
165 r.file.Hashes.SHA256 = base64.RawStdEncoding.EncodeToString(r.hash.Sum(nil))
166 }
167 r.closed = true
168 return
169 }
170
171 // EncryptStream wraps the given io.Reader in order to encrypt the data.
172 //
173 // The Close() method of the returned io.ReadCloser must be called for the SHA256 hash
174 // in the EncryptedFile struct to be updated. The metadata is not valid before the hash
175 // is filled.
176 func (ef *EncryptedFile) EncryptStream(reader io.Reader) io.ReadCloser {
177 ef.decodeKeys(false)
178 block, _ := aes.NewCipher(ef.decoded.key[:])
179 return &encryptingReader{
180 stream: cipher.NewCTR(block, ef.decoded.iv[:]),
181 hash: sha256.New(),
182 source: reader,
183 file: ef,
184 }
185 }
186
187 // Decrypt decrypts the given data and returns the plaintext.
188 //
189 // Deprecated: this makes a copy for the plaintext data, which means 2x memory usage. DecryptInPlace is recommended.
190 func (ef *EncryptedFile) Decrypt(ciphertext []byte) ([]byte, error) {
191 plaintext := make([]byte, len(ciphertext))
192 copy(plaintext, ciphertext)
193 return plaintext, ef.DecryptInPlace(plaintext)
194 }
195
196 // PrepareForDecryption checks that the version and algorithm are supported and decodes the base64 keys
197 //
198 // DecryptStream will call this with the first Read() call if this hasn't been called manually.
199 //
200 // DecryptInPlace will always call this automatically, so calling this manually is not necessary when using that function.
201 func (ef *EncryptedFile) PrepareForDecryption() error {
202 if ef.Version != "v2" {
203 return UnsupportedVersion
204 } else if ef.Key.Algorithm != "A256CTR" {
205 return UnsupportedAlgorithm
206 } else if err := ef.decodeKeys(true); err != nil {
207 return err
208 }
209 return nil
210 }
211
212 // DecryptInPlace decrypts the given data in-place (i.e. the provided data is overridden with the plaintext).
213 func (ef *EncryptedFile) DecryptInPlace(data []byte) error {
214 if err := ef.PrepareForDecryption(); err != nil {
215 return err
216 } else if ef.decoded.sha256 != sha256.Sum256(data) {
217 return HashMismatch
218 } else {
219 utils.XorA256CTR(data, ef.decoded.key, ef.decoded.iv)
220 return nil
221 }
222 }
223
224 // DecryptStream wraps the given io.Reader in order to decrypt the data.
225 //
226 // The first Read call will check the algorithm and decode keys, so it might return an error before actually reading anything.
227 // If you want to validate the file before opening the stream, call PrepareForDecryption manually and check for errors.
228 //
229 // The Close call will validate the hash and return an error if it doesn't match.
230 // In this case, the written data should be considered compromised and should not be used further.
231 func (ef *EncryptedFile) DecryptStream(reader io.Reader) io.ReadCloser {
232 block, _ := aes.NewCipher(ef.decoded.key[:])
233 return &encryptingReader{
234 stream: cipher.NewCTR(block, ef.decoded.iv[:]),
235 hash: sha256.New(),
236 source: reader,
237 file: ef,
238 }
239 }