/
v1.go
316 lines (283 loc) · 8.63 KB
/
v1.go
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package v1 implements the first version of encryption for drive
// It uses AES-256 in CTR mode for encryption and uses authenticates
// with an HMAC using SHA-512.
//
// This package should always be able to decrypt files that were encrypted
// using this package. If there is a change that needs to be made that would
// prevent decryption of old files, it should be done in a new version.
package v1
import (
"bufio"
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"encoding/binary"
"errors"
"hash"
"io"
"os"
"github.com/odeke-em/go-utils/tmpfile"
"golang.org/x/crypto/scrypt"
)
const (
// The size of the HMAC sum.
hmacSize = sha512.Size
// The size of the HMAC key.
hmacKeySize = 32 // 256 bits
// The size of the random salt.
saltSize = 32 // 256 bits
// The size of the AES key.
aesKeySize = 32 // 256 bits
// The size of the AES block.
blockSize = aes.BlockSize
// The number of iterations to use in for key generation
// See N value in https://godoc.org/golang.org/x/crypto/scrypt#Key
// Must be a power of 2.
scryptIterations int32 = 262144 // 2^18
)
const _16KB = 16 * 1024
var (
// The underlying hash function to use for HMAC.
hashFunc = sha512.New
// The amount of key material we need.
keySize = hmacKeySize + aesKeySize
// The size of the Header.
HeaderSize = 4 + saltSize + blockSize
// The overhead added to the file by using this library.
// Overhead + len(plaintext) == len(ciphertext)
Overhead = HeaderSize + hmacSize
)
var DecryptErr = errors.New("message corrupt or incorrect password")
// randBytes returns random bytes in a byte slice of size.
func randBytes(size int) ([]byte, error) {
b := make([]byte, size)
_, err := rand.Read(b)
return b, err
}
// keys derives AES and HMAC keys from a password and salt.
func keys(pass, salt []byte, iterations int) (aesKey, hmacKey []byte, err error) {
key, err := scrypt.Key(pass, salt, iterations, 8, 1, keySize)
if err != nil {
return nil, nil, err
}
aesKey = append(aesKey, key[:aesKeySize]...)
hmacKey = append(hmacKey, key[aesKeySize:keySize]...)
return aesKey, hmacKey, nil
}
// Make sure we implement io.ReadWriter.
var _ io.ReadWriter = &hashReadWriter{}
// hashReadWriter hashes on write and on read finalizes the hash and returns it.
// Writes after a Read will return an error.
type hashReadWriter struct {
hash hash.Hash
done bool
sum io.Reader
}
// Write implements io.Writer
func (h *hashReadWriter) Write(p []byte) (int, error) {
if h.done {
return 0, errors.New("writing to hashReadWriter after read is not allowed")
}
return h.hash.Write(p)
}
// Read implements io.Reader.
func (h *hashReadWriter) Read(p []byte) (int, error) {
if !h.done {
h.done = true
h.sum = bytes.NewReader(h.hash.Sum(nil))
}
return h.sum.Read(p)
}
// encInt32 will encode a int32 in to a byte slice.
func encInt32(i int32) ([]byte, error) {
buf := new(bytes.Buffer)
if err := binary.Write(buf, binary.LittleEndian, i); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// decInt32 will read an int32 from a reader and return the byte slice and the int32.
func decInt32(r io.Reader) (b []byte, i int32, err error) {
buf := new(bytes.Buffer)
tr := io.TeeReader(r, buf)
err = binary.Read(tr, binary.LittleEndian, &i)
return buf.Bytes(), i, err
}
// NewEncryptReader returns an io.Reader wrapping the provided io.Reader.
// It uses a user provided password and a random salt to derive keys.
// If the key is provided interactively, it should be verified since there
// is no recovery.
func NewEncryptReader(r io.Reader, pass []byte) (io.Reader, error) {
salt, err := randBytes(saltSize)
if err != nil {
return nil, err
}
return newEncryptReader(r, pass, salt, scryptIterations)
}
// newEncryptReader returns a encryptReader wrapping an io.Reader.
// It uses a user provided password and the provided salt iterated the
// provided number of times to derive keys.
func newEncryptReader(r io.Reader, pass, salt []byte, iterations int32) (io.Reader, error) {
itersAsBytes, err := encInt32(iterations)
if err != nil {
return nil, err
}
aesKey, hmacKey, err := keys(pass, salt, int(iterations))
if err != nil {
return nil, err
}
iv, err := randBytes(blockSize)
if err != nil {
return nil, err
}
var header []byte
header = append(header, itersAsBytes...)
header = append(header, salt...)
header = append(header, iv...)
return encrypter(r, aesKey, hmacKey, iv, header)
}
// encrypter returns the encrypted reader passed on the keys and IV provided.
func encrypter(r io.Reader, aesKey, hmacKey, iv, header []byte) (io.Reader, error) {
b, err := aes.NewCipher(aesKey)
if err != nil {
return nil, err
}
h := hmac.New(hashFunc, hmacKey)
hr := &hashReadWriter{hash: h}
sr := &cipher.StreamReader{R: r, S: cipher.NewCTR(b, iv)}
return io.MultiReader(io.TeeReader(io.MultiReader(bytes.NewReader(header), sr), hr), hr), nil
}
// decodeHeader decodes the header of the reader.
// It returns the keys, IV, and original header using the password and iterations in the reader.
func decodeHeader(r io.Reader, password []byte) (aesKey, hmacKey, iv, header []byte, err error) {
itersAsBytes, iterations, err := decInt32(r)
if err != nil {
return nil, nil, nil, nil, err
}
salt := make([]byte, saltSize)
iv = make([]byte, blockSize)
_, err = io.ReadFull(r, salt)
if err != nil {
return nil, nil, nil, nil, err
}
_, err = io.ReadFull(r, iv)
if err != nil {
return nil, nil, nil, nil, err
}
aesKey, hmacKey, err = keys(password, salt, int(iterations))
if err != nil {
return nil, nil, nil, nil, err
}
header = append(header, itersAsBytes...)
header = append(header, salt...)
header = append(header, iv...)
return aesKey, hmacKey, iv, header, err
}
// decryptReader wraps a io.Reader decrypting its content.
type decryptReader struct {
tmpFile *tmpfile.TmpFile
sReader *cipher.StreamReader
}
// NewDecryptReader creates an io.ReadCloser wrapping an io.Reader.
// It has to read the entire io.Reader to disk using a temp file so that it can
// hash the contents to verify that it is safe to decrypt.
// If the file is athenticated, the DecryptReader will be returned and
// the resulting bytes will be the plaintext.
func NewDecryptReader(r io.Reader, pass []byte) (d io.ReadCloser, err error) {
mac := make([]byte, hmacSize)
aesKey, hmacKey, iv, header, err := decodeHeader(r, pass)
h := hmac.New(hashFunc, hmacKey)
h.Write(header)
if err != nil {
return nil, err
}
dst, err := tmpfile.New(&tmpfile.Context{
Dir: os.TempDir(),
Suffix: "drive-encrypted-",
})
if err != nil {
return nil, err
}
// If there is an error, try to delete the temp file.
defer func() {
if err != nil {
dst.Done()
}
}()
b, err := aes.NewCipher(aesKey)
if err != nil {
return nil, err
}
d = &decryptReader{
tmpFile: dst,
sReader: &cipher.StreamReader{R: dst, S: cipher.NewCTR(b, iv)},
}
w := io.MultiWriter(h, dst)
buf := bufio.NewReaderSize(r, _16KB)
for {
b, err := buf.Peek(_16KB)
if err != nil && err != io.EOF {
return nil, err
}
if err == io.EOF {
left := buf.Buffered()
if left < hmacSize {
return nil, DecryptErr
}
copy(mac, b[left-hmacSize:left])
_, err = io.CopyN(w, buf, int64(left-hmacSize))
if err != nil {
return nil, err
}
break
}
_, err = io.CopyN(w, buf, _16KB-hmacSize)
if err != nil {
return nil, err
}
}
if !hmac.Equal(mac, h.Sum(nil)) {
return nil, DecryptErr
}
dst.Seek(0, 0)
return d, nil
}
// Read implements io.Reader.
func (d *decryptReader) Read(dst []byte) (int, error) {
return d.sReader.Read(dst)
}
// Close implements io.Closer.
func (d *decryptReader) Close() error {
return d.tmpFile.Done()
}
// Hash hashes the plaintext based on the header of the encrypted file and returns the hash Sum.
func Hash(plainTextR io.Reader, headerR io.Reader, password []byte, h hash.Hash) ([]byte, error) {
aesKey, hmacKey, iv, eHeader, err := decodeHeader(headerR, password)
if err != nil {
return nil, err
}
encReader, err := encrypter(plainTextR, aesKey, hmacKey, iv, eHeader)
if err != nil {
return nil, err
}
if _, err := io.Copy(h, encReader); err != nil {
return nil, err
}
return h.Sum(nil), nil
}