forked from yeka/zip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
485 lines (443 loc) · 11.5 KB
/
crypto.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package zip
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/subtle"
"errors"
"hash"
"io"
"time"
"golang.org/x/crypto/pbkdf2"
)
type EncryptionMethod int
const (
StandardEncryption EncryptionMethod = 1
AES128Encryption EncryptionMethod = 2
AES192Encryption EncryptionMethod = 3
AES256Encryption EncryptionMethod = 4
// AES key lengths
aes128 = 16
aes192 = 24
aes256 = 32
)
func aesKeyLen(strength byte) int {
switch strength {
case 1:
return aes128
case 2:
return aes192
case 3:
return aes256
default:
return 0
}
}
// Encryption/Decryption Errors
var (
ErrDecryption = errors.New("zip: decryption error")
ErrPassword = errors.New("zip: invalid password")
ErrAuthentication = errors.New("zip: authentication failed")
)
// Counter (CTR) mode.
// CTR converts a block cipher into a stream cipher by
// repeatedly encrypting an incrementing counter and
// xoring the resulting stream of data with the input.
// This is a re-implementation of Go's CTR mode to allow
// for a little-endian, left-aligned uint32 counter, which
// is required for WinZip AES encryption. Go's cipher.NewCTR
// follows the NIST Standard SP 800-38A, pp 13-15
// which has a big-endian, right-aligned counter.
type ctr struct {
b cipher.Block
ctr []byte
out []byte
outUsed int
}
const streamBufferSize = 512
// NewWinZipCTR returns a Stream which encrypts/decrypts using the given Block in
// counter mode. The counter is initially set to 1 per WinZip AES.
func newWinZipCTR(block cipher.Block) cipher.Stream {
bufSize := streamBufferSize
if bufSize < block.BlockSize() {
bufSize = block.BlockSize()
}
// Set the IV (counter) to 1
iv := make([]byte, block.BlockSize())
iv[0] = 1
return &ctr{
b: block,
ctr: iv,
out: make([]byte, 0, bufSize),
outUsed: 0,
}
}
func (x *ctr) refill() {
remain := len(x.out) - x.outUsed
if remain > x.outUsed {
return
}
copy(x.out, x.out[x.outUsed:])
x.out = x.out[:cap(x.out)]
bs := x.b.BlockSize()
for remain < len(x.out)-bs {
x.b.Encrypt(x.out[remain:], x.ctr)
remain += bs
// Increment counter
// for i := len(x.ctr) - 1; i >= 0; i-- {
// x.ctr[i]++
// if x.ctr[i] != 0 {
// break
// }
// }
// Change to allow for little-endian,
// left-aligned counter
for i := 0; i < len(x.ctr); i++ {
x.ctr[i]++
if x.ctr[i] != 0 {
break
}
}
}
x.out = x.out[:remain]
x.outUsed = 0
}
func (x *ctr) XORKeyStream(dst, src []byte) {
for len(src) > 0 {
if x.outUsed >= len(x.out)-x.b.BlockSize() {
x.refill()
}
n := xorBytes(dst, src, x.out[x.outUsed:])
dst = dst[n:]
src = src[n:]
x.outUsed += n
}
}
func xorBytes(dst, a, b []byte) int {
n := len(a)
if len(b) < n {
n = len(b)
}
for i := 0; i < n; i++ {
dst[i] = a[i] ^ b[i]
}
return n
}
// newAuthReader returns either a buffered or streaming authentication reader.
// Buffered authentication is recommended. Streaming authentication is only
// recommended if: 1. you buffer the data yourself and wait for authentication
// before streaming to another source such as the network, or 2. you just don't
// care about authenticating unknown ciphertext before use :).
func newAuthReader(akey []byte, data, adata io.Reader, streaming bool) io.Reader {
ar := authReader{
data: data,
adata: adata,
mac: hmac.New(sha1.New, akey),
err: nil,
auth: false,
}
if streaming {
return &ar
}
return &bufferedAuthReader{
ar,
new(bytes.Buffer),
}
}
// Streaming authentication
type authReader struct {
data io.Reader // data to be authenticated
adata io.Reader // the authentication code to read
mac hash.Hash // hmac hash
err error
auth bool
}
func (a *authReader) Read(p []byte) (int, error) {
if a.err != nil {
return 0, a.err
}
end := false
// read underlying data
n, err := a.data.Read(p)
if err != nil && err != io.EOF {
a.err = err
return n, a.err
} else if err == io.EOF {
// if we are at the end, calculate the mac
end = true
a.err = err
}
// write any data to mac
_, err = a.mac.Write(p[:n])
if err != nil {
a.err = err
return n, a.err
}
if end {
ab := new(bytes.Buffer)
_, err = io.Copy(ab, a.adata)
if err != nil || ab.Len() != 10 {
a.err = ErrDecryption
return n, a.err
}
if !a.checkAuthentication(ab.Bytes()) {
a.err = ErrAuthentication
return n, a.err
}
}
return n, a.err
}
// buffered authentication
type bufferedAuthReader struct {
authReader
buf *bytes.Buffer // buffer to store data to authenticate
}
func (a *bufferedAuthReader) Read(b []byte) (int, error) {
// check for sticky error
if a.err != nil {
return 0, a.err
}
// make sure we have auth'ed before we send any data
if !a.auth {
_, err := io.Copy(a.buf, a.data)
if err != nil {
a.err = err
return 0, a.err
}
ab := new(bytes.Buffer)
nn, err := io.Copy(ab, a.adata)
if err != nil {
a.err = err
return 0, a.err
} else if nn != 10 {
a.err = ErrDecryption
return 0, a.err
}
_, err = a.mac.Write(a.buf.Bytes())
if err != nil {
a.err = err
return 0, a.err
}
if !a.checkAuthentication(ab.Bytes()) {
a.err = ErrAuthentication
return 0, a.err
}
}
// so we've authenticated the data, now just pass it on.
n, err := a.buf.Read(b)
if err != nil {
a.err = err
}
return n, a.err
}
func (a *authReader) checkAuthentication(authcode []byte) bool {
expectedAuthCode := a.mac.Sum(nil)
// Truncate at the first 10 bytes
expectedAuthCode = expectedAuthCode[:10]
a.auth = subtle.ConstantTimeCompare(expectedAuthCode, authcode) > 0
return a.auth
}
func checkPasswordVerification(pwvv, pwv []byte) bool {
b := subtle.ConstantTimeCompare(pwvv, pwv) > 0
return b
}
func generateKeys(password, salt []byte, keySize int) (encKey, authKey, pwv []byte) {
totalSize := (keySize * 2) + 2 // enc + auth + pv sizes
key := pbkdf2.Key(password, salt, 1000, totalSize, sha1.New)
encKey = key[:keySize]
authKey = key[keySize : keySize*2]
pwv = key[keySize*2:]
return
}
// newDecryptionReader returns an authenticated, decryption reader
func newDecryptionReader(r *io.SectionReader, f *File) (io.Reader, error) {
keyLen := aesKeyLen(f.aesStrength)
saltLen := keyLen / 2 // salt is half of key len
if saltLen == 0 {
return nil, ErrDecryption
}
// grab the salt and pwvv
saltpwvv := make([]byte, saltLen+2)
if _, err := r.Read(saltpwvv); err != nil {
return nil, err
}
salt := saltpwvv[:saltLen]
pwvv := saltpwvv[saltLen : saltLen+2]
// generate keys only if we have a password
if f.password == nil {
return nil, ErrPassword
}
decKey, authKey, pwv := generateKeys(f.password(), salt, keyLen)
if !checkPasswordVerification(pwv, pwvv) {
return nil, ErrPassword
}
dataOff := int64(saltLen + 2)
dataLen := int64(f.CompressedSize64 - uint64(saltLen) - 2 - 10)
// // TODO(alex): Should the compressed sizes be fixed?
// // Not the ideal place to do this.
// f.CompressedSize64 = uint64(dataLen)
// f.CompressedSize = uint32(dataLen)
data := io.NewSectionReader(r, dataOff, dataLen)
authOff := dataOff + dataLen
authcode := io.NewSectionReader(r, authOff, 10)
ar := newAuthReader(authKey, data, authcode, f.DeferAuth)
dr := decryptStream(decKey, ar)
if dr == nil {
return nil, ErrDecryption
}
return dr, nil
}
func decryptStream(key []byte, ciphertext io.Reader) io.Reader {
block, err := aes.NewCipher(key)
if err != nil {
return nil
}
stream := newWinZipCTR(block)
reader := &cipher.StreamReader{S: stream, R: ciphertext}
return reader
}
// writes encrypted data to hmac as it passes through
type authWriter struct {
hmac hash.Hash // from fw.hmac
w io.Writer // this will be the compCount writer
}
func (aw *authWriter) Write(p []byte) (int, error) {
_, err := aw.hmac.Write(p)
if err != nil {
return 0, err
}
return aw.w.Write(p)
}
// writes out the salt, pwv, and then the encrypted file data
type encryptionWriter struct {
pwv []byte
salt []byte
w io.Writer // where to write the salt + pwv
es io.Writer // where to write plaintext
first bool // first write
err error
}
func (ew *encryptionWriter) Write(p []byte) (int, error) {
if ew.err != nil {
return 0, ew.err
}
if ew.first {
// if our first time writing
// must write out the salt and pwv first unencrypted
_, err1 := ew.w.Write(ew.salt)
_, err2 := ew.w.Write(ew.pwv)
if err1 != nil || err2 != nil {
ew.err = errors.New("zip: error writing salt or pwv")
return 0, ew.err
}
ew.first = false
}
// now just pass on to the encryption stream
return ew.es.Write(p)
}
func encryptStream(key []byte, w io.Writer) (io.Writer, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
stream := newWinZipCTR(block)
writer := &cipher.StreamWriter{S: stream, W: w}
return writer, nil
}
// newEncryptionWriter returns an io.Writer that when written to, 1. writes
// out the salt, 2. writes out pwv, and 3. writes out authenticated, encrypted
// data. The authcode will be written out in fileWriter.close().
func newEncryptionWriter(w io.Writer, password passwordFn, fw *fileWriter, aesstrength byte) (io.Writer, error) {
keysize := aesKeyLen(aesstrength)
salt := make([]byte, keysize/2)
_, err := rand.Read(salt[:])
if err != nil {
return nil, errors.New("zip: unable to generate random salt")
}
ekey, akey, pwv := generateKeys(password(), salt[:], keysize)
fw.hmac = hmac.New(sha1.New, akey)
aw := &authWriter{
hmac: fw.hmac,
w: w,
}
es, err := encryptStream(ekey, aw)
if err != nil {
return nil, err
}
ew := &encryptionWriter{
pwv: pwv,
salt: salt[:],
w: w,
es: es,
first: true,
}
return ew, nil
}
// IsEncrypted indicates whether this file's data is encrypted.
func (h *FileHeader) IsEncrypted() bool {
return h.Flags&0x1 == 1
}
// WinZip AE-2 specifies that no CRC value is written and
// should be skipped when reading.
func (h *FileHeader) isAE2() bool {
return h.ae == 2
}
func (h *FileHeader) writeWinZipExtra() {
// total size is 11 bytes
var buf [11]byte
eb := writeBuf(buf[:])
eb.uint16(winzipAesExtraId) // 0x9901
eb.uint16(7) // following data size is 7
eb.uint16(2) // ae 2
eb.uint16(0x4541) // "AE"
eb.uint8(h.aesStrength) // aes256
eb.uint16(h.Method) // original compression method
h.Extra = append(h.Extra, buf[:]...)
}
func (h *FileHeader) setEncryptionMethod(enc EncryptionMethod) {
h.encryption = enc
switch enc {
case AES128Encryption:
h.aesStrength = 1
case AES192Encryption:
h.aesStrength = 2
case AES256Encryption:
h.aesStrength = 3
}
}
func (h *FileHeader) setEncryptionBit() {
h.Flags |= 0x1
}
// SetPassword sets the password used for encryption/decryption.
func (h *FileHeader) SetPassword(password string) {
if !h.IsEncrypted() {
h.setEncryptionBit()
}
h.password = func() []byte {
return []byte(password)
}
}
// PasswordFn is a function that returns the password
// as a byte slice
type passwordFn func() []byte
// Encrypt adds a file to the zip file using the provided name.
// It returns a Writer to which the file contents should be written. File
// contents will be encrypted with AES-256 using the given password. The
// file's contents must be written to the io.Writer before the next call
// to Create, CreateHeader, or Close.
func (w *Writer) Encrypt(name string, password string, enc EncryptionMethod) (io.Writer, error) {
fh := &FileHeader{
Name: name,
Method: Deflate,
}
fh.SetModTime(time.Now())
fh.SetPassword(password)
fh.setEncryptionMethod(enc)
return w.CreateHeader(fh)
}