summary refs log tree commit diff
path: root/vendor/maunium.net/go/mautrix/crypto/attachment/attachments.go
blob: cfa1c3e5b51543eb48a89cfd6c5a8937aca7e03f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// Copyright (c) 2022 Tulir Asokan
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package attachment

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"hash"
	"io"

	"maunium.net/go/mautrix/crypto/utils"
)

var (
	HashMismatch         = errors.New("mismatching SHA-256 digest")
	UnsupportedVersion   = errors.New("unsupported Matrix file encryption version")
	UnsupportedAlgorithm = errors.New("unsupported JWK encryption algorithm")
	InvalidKey           = errors.New("failed to decode key")
	InvalidInitVector    = errors.New("failed to decode initialization vector")
	InvalidHash          = errors.New("failed to decode SHA-256 hash")
	ReaderClosed         = errors.New("encrypting reader was already closed")
)

var (
	keyBase64Length  = base64.RawURLEncoding.EncodedLen(utils.AESCTRKeyLength)
	ivBase64Length   = base64.RawStdEncoding.EncodedLen(utils.AESCTRIVLength)
	hashBase64Length = base64.RawStdEncoding.EncodedLen(utils.SHAHashLength)
)

type JSONWebKey struct {
	Key         string   `json:"k"`
	Algorithm   string   `json:"alg"`
	Extractable bool     `json:"ext"`
	KeyType     string   `json:"kty"`
	KeyOps      []string `json:"key_ops"`
}

type EncryptedFileHashes struct {
	SHA256 string `json:"sha256"`
}

type decodedKeys struct {
	key [utils.AESCTRKeyLength]byte
	iv  [utils.AESCTRIVLength]byte

	sha256 [utils.SHAHashLength]byte
}

type EncryptedFile struct {
	Key        JSONWebKey          `json:"key"`
	InitVector string              `json:"iv"`
	Hashes     EncryptedFileHashes `json:"hashes"`
	Version    string              `json:"v"`

	decoded *decodedKeys
}

func NewEncryptedFile() *EncryptedFile {
	key, iv := utils.GenAttachmentA256CTR()
	return &EncryptedFile{
		Key: JSONWebKey{
			Key:         base64.RawURLEncoding.EncodeToString(key[:]),
			Algorithm:   "A256CTR",
			Extractable: true,
			KeyType:     "oct",
			KeyOps:      []string{"encrypt", "decrypt"},
		},
		InitVector: base64.RawStdEncoding.EncodeToString(iv[:]),
		Version:    "v2",

		decoded: &decodedKeys{key: key, iv: iv},
	}
}

func (ef *EncryptedFile) decodeKeys(includeHash bool) error {
	if ef.decoded != nil {
		return nil
	} else if len(ef.Key.Key) != keyBase64Length {
		return InvalidKey
	} else if len(ef.InitVector) != ivBase64Length {
		return InvalidInitVector
	} else if includeHash && len(ef.Hashes.SHA256) != hashBase64Length {
		return InvalidHash
	}
	ef.decoded = &decodedKeys{}
	_, err := base64.RawURLEncoding.Decode(ef.decoded.key[:], []byte(ef.Key.Key))
	if err != nil {
		return InvalidKey
	}
	_, err = base64.RawStdEncoding.Decode(ef.decoded.iv[:], []byte(ef.InitVector))
	if err != nil {
		return InvalidInitVector
	}
	if includeHash {
		_, err = base64.RawStdEncoding.Decode(ef.decoded.sha256[:], []byte(ef.Hashes.SHA256))
		if err != nil {
			return InvalidHash
		}
	}
	return nil
}

// Encrypt encrypts the given data, updates the SHA256 hash in the EncryptedFile struct and returns the ciphertext.
//
// Deprecated: this makes a copy for the ciphertext, which means 2x memory usage. EncryptInPlace is recommended.
func (ef *EncryptedFile) Encrypt(plaintext []byte) []byte {
	ciphertext := make([]byte, len(plaintext))
	copy(ciphertext, plaintext)
	ef.EncryptInPlace(ciphertext)
	return ciphertext
}

// EncryptInPlace encrypts the given data in-place (i.e. the provided data is overridden with the ciphertext)
// and updates the SHA256 hash in the EncryptedFile struct.
func (ef *EncryptedFile) EncryptInPlace(data []byte) {
	ef.decodeKeys(false)
	utils.XorA256CTR(data, ef.decoded.key, ef.decoded.iv)
	checksum := sha256.Sum256(data)
	ef.Hashes.SHA256 = base64.RawStdEncoding.EncodeToString(checksum[:])
}

type ReadWriterAt interface {
	io.WriterAt
	io.Reader
}

// EncryptFile encrypts the given file in-place and updates the SHA256 hash in the EncryptedFile struct.
func (ef *EncryptedFile) EncryptFile(file ReadWriterAt) error {
	err := ef.decodeKeys(false)
	if err != nil {
		return err
	}
	block, _ := aes.NewCipher(ef.decoded.key[:])
	stream := cipher.NewCTR(block, ef.decoded.iv[:])
	hasher := sha256.New()
	buf := make([]byte, 32*1024)
	var writePtr int64
	var n int
	for {
		n, err = file.Read(buf)
		if err != nil && !errors.Is(err, io.EOF) {
			return err
		}
		if n == 0 {
			break
		}
		stream.XORKeyStream(buf[:n], buf[:n])
		_, err = file.WriteAt(buf[:n], writePtr)
		if err != nil {
			return err
		}
		writePtr += int64(n)
		hasher.Write(buf[:n])
	}
	ef.Hashes.SHA256 = base64.RawStdEncoding.EncodeToString(hasher.Sum(nil))
	return nil
}

type encryptingReader struct {
	stream cipher.Stream
	hash   hash.Hash
	source io.Reader
	file   *EncryptedFile
	closed bool

	isDecrypting bool
}

var _ io.ReadSeekCloser = (*encryptingReader)(nil)

func (r *encryptingReader) Seek(offset int64, whence int) (int64, error) {
	if r.closed {
		return 0, ReaderClosed
	}
	if offset != 0 || whence != io.SeekStart {
		return 0, fmt.Errorf("attachments.EncryptStream: only seeking to the beginning is supported")
	}
	seeker, ok := r.source.(io.ReadSeeker)
	if !ok {
		return 0, fmt.Errorf("attachments.EncryptStream: source reader (%T) is not an io.ReadSeeker", r.source)
	}
	n, err := seeker.Seek(offset, whence)
	if err != nil {
		return 0, err
	}
	block, _ := aes.NewCipher(r.file.decoded.key[:])
	r.stream = cipher.NewCTR(block, r.file.decoded.iv[:])
	r.hash.Reset()
	return n, nil
}

func (r *encryptingReader) Read(dst []byte) (n int, err error) {
	if r.closed {
		return 0, ReaderClosed
	} else if r.isDecrypting && r.file.decoded == nil {
		if err = r.file.PrepareForDecryption(); err != nil {
			return
		}
	}
	n, err = r.source.Read(dst)
	r.stream.XORKeyStream(dst[:n], dst[:n])
	r.hash.Write(dst[:n])
	return
}

func (r *encryptingReader) Close() (err error) {
	closer, ok := r.source.(io.ReadCloser)
	if ok {
		err = closer.Close()
	}
	if r.isDecrypting {
		var downloadedChecksum [utils.SHAHashLength]byte
		r.hash.Sum(downloadedChecksum[:])
		if downloadedChecksum != r.file.decoded.sha256 {
			return HashMismatch
		}
	} else {
		r.file.Hashes.SHA256 = base64.RawStdEncoding.EncodeToString(r.hash.Sum(nil))
	}
	r.closed = true
	return
}

// EncryptStream wraps the given io.Reader in order to encrypt the data.
//
// The Close() method of the returned io.ReadCloser must be called for the SHA256 hash
// in the EncryptedFile struct to be updated. The metadata is not valid before the hash
// is filled.
func (ef *EncryptedFile) EncryptStream(reader io.Reader) io.ReadSeekCloser {
	ef.decodeKeys(false)
	block, _ := aes.NewCipher(ef.decoded.key[:])
	return &encryptingReader{
		stream: cipher.NewCTR(block, ef.decoded.iv[:]),
		hash:   sha256.New(),
		source: reader,
		file:   ef,
	}
}

// Decrypt decrypts the given data and returns the plaintext.
//
// Deprecated: this makes a copy for the plaintext data, which means 2x memory usage. DecryptInPlace is recommended.
func (ef *EncryptedFile) Decrypt(ciphertext []byte) ([]byte, error) {
	plaintext := make([]byte, len(ciphertext))
	copy(plaintext, ciphertext)
	return plaintext, ef.DecryptInPlace(plaintext)
}

// PrepareForDecryption checks that the version and algorithm are supported and decodes the base64 keys
//
// DecryptStream will call this with the first Read() call if this hasn't been called manually.
//
// DecryptInPlace will always call this automatically, so calling this manually is not necessary when using that function.
func (ef *EncryptedFile) PrepareForDecryption() error {
	if ef.Version != "v2" {
		return UnsupportedVersion
	} else if ef.Key.Algorithm != "A256CTR" {
		return UnsupportedAlgorithm
	} else if err := ef.decodeKeys(true); err != nil {
		return err
	}
	return nil
}

// DecryptInPlace decrypts the given data in-place (i.e. the provided data is overridden with the plaintext).
func (ef *EncryptedFile) DecryptInPlace(data []byte) error {
	if err := ef.PrepareForDecryption(); err != nil {
		return err
	} else if ef.decoded.sha256 != sha256.Sum256(data) {
		return HashMismatch
	} else {
		utils.XorA256CTR(data, ef.decoded.key, ef.decoded.iv)
		return nil
	}
}

// DecryptStream wraps the given io.Reader in order to decrypt the data.
//
// The first Read call will check the algorithm and decode keys, so it might return an error before actually reading anything.
// If you want to validate the file before opening the stream, call PrepareForDecryption manually and check for errors.
//
// The Close call will validate the hash and return an error if it doesn't match.
// In this case, the written data should be considered compromised and should not be used further.
func (ef *EncryptedFile) DecryptStream(reader io.Reader) io.ReadSeekCloser {
	block, _ := aes.NewCipher(ef.decoded.key[:])
	return &encryptingReader{
		stream: cipher.NewCTR(block, ef.decoded.iv[:]),
		hash:   sha256.New(),
		source: reader,
		file:   ef,
	}
}