-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdecrypt.go
342 lines (309 loc) · 8.61 KB
/
decrypt.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
package gitcrypt
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"github.com/jbuchbinder/go-git-crypt/gpg"
"golang.org/x/crypto/openpgp"
)
/*
// Decrypt decrypts a git-crypt encrypted file, given a key and a data
// stream
func (g *GitCrypt) Decrypt(key []byte, data []byte) ([]byte, error) {
var out []byte
block, err := aes.NewCipher(key)
if err != nil {
return out, err
}
h := hmac.New(sha1.New, key)
block.Decrypt(data, out)
_, err = h.Write(out)
if err != nil {
return out, err
}
return out, nil
}
*/
// DecryptRepoKey decrypts a repository key, given:
// - keyring: A GPG keyring to use for the decryption.
// - keyName: Name of the key set being used. Empty defaults to "default".
// - keyVersion: Version of the git-crypt keys.
// - secretKeys: Array of private keys to attempt to decrypt
// - keysPath: Root path to the repository key directory (should be $REPOPATH/.git-crypt/keys)
func (g *GitCrypt) DecryptRepoKey(keyring openpgp.EntityList, keyName string, keyVersion uint32, secretKeys []string, keysPath string) (Key, error) {
//var err error
keyFile := Key{}
for _, seckey := range secretKeys {
path := keysPath + string(os.PathSeparator)
if keyName == "" {
path += "default"
} else {
path += keyName
}
path += string(os.PathSeparator) + fmt.Sprintf("%d", keyVersion) + string(os.PathSeparator) + seckey + ".gpg"
if g.fileExists(path) {
log.Printf("Decrypting key %v in path %s", keyring, path)
decryptedContents, err := g.GpgDecryptFromFile(keyring, path)
if err != nil {
log.Printf("decryption of file %s : %s", path, err.Error())
continue
}
if len(decryptedContents) == 0 {
log.Printf("")
continue
}
var thisVersionKeyFile Key
br := bytes.NewBuffer(decryptedContents)
err = thisVersionKeyFile.Load(br)
thisVersionEntry, err := thisVersionKeyFile.Get(keyVersion)
if err != nil {
return keyFile, fmt.Errorf("GPG-encrypted keyfile is malformed because it does not contain expected key version")
}
if strings.Compare(keyName, thisVersionKeyFile.KeyName) != 0 {
return keyFile, fmt.Errorf("GPG-encrypted keyfile is malformed because it does not contain expected key name")
}
keyFile.Entries = append(keyFile.Entries, thisVersionEntry)
return keyFile, nil
}
}
return keyFile, errors.New("no secret keys")
}
// DecryptRepoKeys decrypts all available repository keys, given a GPG key
func (g *GitCrypt) DecryptRepoKeys(keyring openpgp.EntityList, keyVersion uint32, secretKeys []string, keysPath string) ([]Key, error) {
successful := false
dirents := make([]string, 0)
keyFiles := make([]Key, 0)
if g.fileExists(keysPath) {
if g.Vfs == nil {
fp, err := os.Open(keysPath)
if err != nil {
return keyFiles, err
}
defer fp.Close()
entries, err := fp.ReadDir(0)
if err != nil {
return keyFiles, err
}
for _, entry := range entries {
dirents = append(dirents, entry.Name())
}
} else {
entries, err := g.Vfs.ReadDir(keysPath)
if err != nil {
return keyFiles, err
}
for _, entry := range entries {
dirents = append(dirents, entry.Name())
}
}
}
for _, dirent := range dirents {
log.Printf("decryptRepoKeys : %s", dirent)
keyName := ""
if strings.Compare(dirent, "default") != 0 {
if err := validateKeyName(dirent); err != nil {
continue
}
keyName = dirent
}
keyFile, err := g.DecryptRepoKey(keyring, keyName, keyVersion, secretKeys, keysPath)
if err == nil {
keyFiles = append(keyFiles, keyFile)
successful = true
}
}
if !successful {
return keyFiles, fmt.Errorf("unsuccessful")
}
return keyFiles, nil
}
// ReadFileHeaderFromFile fetches the git-crypt file header from an unopened
// file
func (g *GitCrypt) ReadFileHeaderFromFile(filename string) ([]byte, error) {
header := make([]byte, 10+aesEncryptorNonceLen)
fp, err := os.Open(filename)
if err != nil {
return header, err
}
defer fp.Close()
n, err := fp.Read(header)
if g.Debug {
log.Printf("readFileHeaderFromFile : read %d bytes : %s", n, header)
}
return header, err
}
// ReadFileHeader fetches the git-crypt file header from an open seekable
// file
func (g *GitCrypt) ReadFileHeader(fp io.ReadSeekCloser) ([]byte, error) {
header := make([]byte, 10+aesEncryptorNonceLen)
_, err := fp.Seek(0, io.SeekStart)
if err != nil {
return header, err
}
n, err := fp.Read(header)
if g.Debug {
log.Printf("readFileHeader : read %d bytes : %#v", n, header)
}
if err != nil {
return header, err
}
pos, err := fp.Seek(10+aesEncryptorNonceLen, io.SeekStart)
if g.Debug {
log.Printf("readFileHeader : seek'd to %d: err = %#v", pos, err)
}
return header, err
}
// IsGitCrypted returns whether or not a file has been encrypted in
// the git-crypt encryption format. Supports optional Vfs methods.
func (g *GitCrypt) IsGitCrypted(fn string) bool {
var err error
if g.Vfs != nil {
_, err = g.Vfs.Stat(fn)
} else {
_, err = os.Stat(fn)
}
if err != nil {
// If we can't open the file, skip git-crypting
log.Printf("ERR: %s", err.Error())
return false
}
var n int
b := make([]byte, 10)
if g.Vfs != nil {
fp, err := g.Vfs.Open(fn)
if err != nil {
// If we can't open the file, skip git-crypting
log.Printf("ERR: %s", err.Error())
return false
}
defer fp.Close()
_, err = fp.Seek(0, io.SeekStart)
if err != nil {
log.Printf("ERR: %s", err.Error())
return false
}
n, err = fp.Read(b)
if err != nil {
log.Printf("ERR: %s", err.Error())
return false
}
} else {
fp, err := os.Open(fn)
if err != nil {
// If we can't open the file, skip git-crypting
log.Printf("ERR: %s", err.Error())
return false
}
defer fp.Close()
n, err = fp.ReadAt(b, 0)
if err != nil {
log.Printf("ERR: %s", err.Error())
return false
}
}
if n < 10 {
log.Printf("ERR: only read %d bytes", n)
return false
}
return bytes.Compare(b[0:9], gitCryptHeader) == 0
}
// DecryptStream decrypts a stream of encrypted git-crypt format data
// given a key file and header
func (g *GitCrypt) DecryptStream(keyFile Key, header []byte, in io.ReadSeeker, out io.Writer) error {
if g.Debug {
log.Printf("header: %#v", header)
}
nonce := header[10:]
if g.Debug {
log.Printf("nonce: %#v", nonce)
}
keyVersion := keyFile.Version
key, err := keyFile.Get(keyVersion)
if err != nil {
return fmt.Errorf("git-crypt: error: key version %d not available - please unlock with the latest version of the key", keyVersion)
}
// Attempt to detect if we've read anything already; if we haven't, ignore
// the header bytes, if not, keep going
currentPos, err := in.Seek(0, io.SeekCurrent)
if err != nil {
return err
}
if currentPos == 0 {
// Skip past the header before we begin calculations
ignore := make([]byte, len(header))
_, err = in.Read(ignore)
if err != nil {
return fmt.Errorf("git-crypt: unable to read header: %s", err.Error())
}
}
aes := NewAesCtrEncryptor(key.AesKey, nonce)
h := NewHMac(key.HmacKey)
counter := 0
for {
ibuf := make([]byte, 1024)
obuf := make([]byte, 1024)
n, err := in.Read(ibuf)
if err != nil {
//log.Printf("ERR: %s", err.Error())
break
}
if g.Debug {
log.Printf("size = %d, ibuf = %x", n, ibuf)
}
err = aes.process(ibuf, obuf, uint32(n))
if err != nil {
return err
}
if g.Debug {
log.Printf("input : %x", string(ibuf))
log.Printf("output : %x", string(obuf))
}
// Only iterate to number of read bytes to avoid ending nulls
for i := 0; i < n; i++ {
out.Write([]byte{obuf[i]})
h.Write([]byte{obuf[i]})
}
counter++
}
// HMAC checksumming
digest := h.Result()
if g.Debug {
log.Printf("digest = %#v, nonce = %#v, len = %d", digest, nonce, aesEncryptorNonceLen)
}
if !leaklessEquals(digest, nonce, aesEncryptorNonceLen) {
return fmt.Errorf("git-crypt: error: encrypted file has been tampered with")
// Although we've already written the tampered file to stdout, exiting
// with a non-zero status will tell git the file has not been filtered,
// so git will not replace it.
}
return nil
}
// GpgDecryptFromFile decrypts a file using a PGP/GPG key
func (g *GitCrypt) GpgDecryptFromFile(keyring openpgp.EntityList, path string) ([]byte, error) {
var filedata []byte
var err error
if g.Vfs == nil {
filedata, err = ioutil.ReadFile(path)
} else {
fp, err := g.Vfs.Open(path)
if err != nil {
return filedata, err
}
defer fp.Close()
filedata, err = io.ReadAll(fp)
}
if err != nil {
log.Printf("GpgDecryptFromFile(%#v, %s): ERR: %s", keyring, path, err.Error())
return []byte{}, err
}
out, err := gpg.Decrypt(filedata, keyring)
if err != nil {
log.Printf("GpgDecryptFromFile(%#v, %s): ERR: %s", keyring, path, err.Error())
}
return out, err
}