-
Notifications
You must be signed in to change notification settings - Fork 9
/
luks2.go
446 lines (380 loc) · 10.9 KB
/
luks2.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
package luks
import (
"bytes"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"hash"
"os"
"strconv"
"strings"
"unsafe"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/crypto/xts"
)
// LUKS v2 format is specified here
// https://habd.as/post/external-backup-drive-encryption/assets/luks2_doc_wip.pdf
type headerV2 struct {
Magic [6]byte
Version uint16
HeaderSize uint64
SequenceID uint64
Label [48]byte
ChecksumAlgorithm [32]byte
Salt [64]byte
UUID [40]byte
SubsystemLabel [48]byte
HeaderOffset uint64
_ [184]byte // padding
Checksum [64]byte
// padding of size 7*512
}
type deviceV2 struct {
path string
f *os.File
hdr *headerV2
meta *metadata
flags []string
}
func initV2Device(path string, f *os.File) (*deviceV2, error) {
var hdr headerV2
if _, err := f.Seek(0, 0); err != nil {
return nil, err
}
if err := binary.Read(f, binary.BigEndian, &hdr); err != nil {
return nil, err
}
hdrSize := hdr.HeaderSize // size of header + JSON metadata
if !isPowerOfTwo(uint(hdrSize)) || hdrSize < 16384 || hdrSize > 4194304 {
return nil, fmt.Errorf("Invalid size of LUKS header: %v", hdrSize)
}
// read the whole header
data := make([]byte, hdrSize)
if _, err := f.ReadAt(data, 0); err != nil {
return nil, err
}
for i := 0; i < 64; i++ {
// clear the checksum
data[int(unsafe.Offsetof(hdr.Checksum))+i] = 0
}
// calculate the checksum of the whole header
var h hash.Hash
algo := fixedArrayToString(hdr.ChecksumAlgorithm[:])
switch algo {
case "sha256":
h = sha256.New()
default:
return nil, fmt.Errorf("Unknown header checksum algorithm: %v", algo)
}
h.Write(data)
checksum := h.Sum(make([]byte, 0))
expectedChecksum := hdr.Checksum[:h.Size()]
if !bytes.Equal(checksum, expectedChecksum) {
return nil, fmt.Errorf("Invalid header checksum")
}
var meta metadata
jsonData := data[4096:]
jsonData = jsonData[:bytes.IndexByte(jsonData, 0)]
if err := json.Unmarshal(jsonData, &meta); err != nil {
return nil, err
}
return &deviceV2{
path: path,
f: f,
hdr: &hdr,
meta: &meta,
flags: meta.Config.Flags,
}, nil
}
func (d *deviceV2) Close() error {
return d.f.Close()
}
func (d *deviceV2) Path() string {
return d.path
}
func (d *deviceV2) Slots() []int {
var normPrio, highPrio []int
for i, k := range d.meta.Keyslots {
if k.Priority != nil && *k.Priority == 2 {
highPrio = append(highPrio, i)
} else if k.Priority == nil || *k.Priority == 1 {
normPrio = append(normPrio, i)
}
}
// first we append high priority slots, then normal priority
return append(highPrio, normPrio...)
}
func (d *deviceV2) Tokens() ([]Token, error) {
var tokens []Token
type tokenNode struct {
Type string
Keyslots []json.Number
}
for i, t := range d.meta.Tokens {
var node tokenNode
if err := json.Unmarshal(t, &node); err != nil {
return nil, err
}
keyslots := make([]int, len(node.Keyslots))
for j, s := range node.Keyslots {
slotID, err := s.Int64()
if err != nil {
return nil, err
}
keyslots[j] = int(slotID)
}
token := Token{
ID: i,
Slots: keyslots,
Type: node.Type,
Payload: t,
}
tokens = append(tokens, token)
}
return tokens, nil
}
func (d *deviceV2) UUID() string {
return fixedArrayToString(d.hdr.UUID[:])
}
func (d *deviceV2) FlagsGet() []string {
return d.flags
}
func (d *deviceV2) FlagsAdd(flags ...string) error {
d.flags = append(d.flags, flags...)
return nil
}
func (d *deviceV2) FlagsClear() {
d.flags = nil
}
func (d *deviceV2) Version() int {
return 2
}
func (d *deviceV2) Unlock(keyslot int, passphrase []byte, dmName string) error {
volume, err := d.UnsealVolume(keyslot, passphrase)
if err != nil {
return err
}
defer clearSlice(volume.key)
return volume.SetupMapper(dmName)
}
func (d *deviceV2) UnlockAny(passphrase []byte, dmName string) error {
for _, s := range d.Slots() {
volume, err := d.UnsealVolume(s, passphrase)
if err == ErrPassphraseDoesNotMatch {
continue
} else if err != nil {
return err
}
return volume.SetupMapper(dmName)
}
return ErrPassphraseDoesNotMatch
}
func (d *deviceV2) UnsealVolume(keyslotIdx int, passphrase []byte) (*Volume, error) {
keyslots := d.meta.Keyslots
keyslot, ok := keyslots[keyslotIdx]
if !ok {
return nil, fmt.Errorf("Unable to get a keyslot with id: %d", keyslotIdx)
}
afKey, err := deriveLuks2AfKey(keyslot.Kdf, keyslotIdx, passphrase, keyslot.Area.KeySize)
if err != nil {
return nil, err
}
defer clearSlice(afKey)
finalKey, err := d.decryptLuks2VolumeKey(keyslotIdx, keyslot, afKey)
if err != nil {
return nil, err
}
// verify with digest
digest := d.findDigestForKeyslot(keyslotIdx)
if digest == nil {
return nil, fmt.Errorf("No digest is found for keyslot %v", keyslotIdx)
}
generatedDigest, err := computeDigestForKey(digest, keyslotIdx, finalKey)
if err != nil {
return nil, err
}
defer clearSlice(generatedDigest)
expectedDigest, err := base64.StdEncoding.DecodeString(digest.Digest)
if err != nil {
return nil, fmt.Errorf("keyslotIdx[%v].digest.Digest base64 parsing failed: %v", keyslotIdx, err)
}
if !bytes.Equal(generatedDigest[0:len(expectedDigest)], expectedDigest) {
return nil, ErrPassphraseDoesNotMatch
}
clearSlice(generatedDigest)
if len(digest.Segments) != 1 {
return nil, fmt.Errorf("LUKS partition expects exactly 1 storage segment, got %+v", len(digest.Segments))
}
seg, err := digest.Segments[0].Int64()
if err != nil {
return nil, err
}
storageSegment := d.meta.Segments[int(seg)]
offset, err := storageSegment.Offset.Int64()
if err != nil {
return nil, err
}
var storageSize uint64
if storageSegment.Size == "dynamic" {
storageSize, err = fileSize(d.f)
if err != nil {
return nil, err
}
if storageSize < uint64(offset) {
return nil, fmt.Errorf("backing file size %d is smaller than LUKS segment offset %d", storageSize, offset)
}
storageSize -= uint64(offset)
} else {
size, err := strconv.Atoi(storageSegment.Size)
if err != nil {
return nil, err
}
if size == 0 {
return nil, fmt.Errorf("invalid segment size: %v", size)
}
storageSize = uint64(size)
}
ivTweak, err := storageSegment.IvTweak.Int64()
if err != nil {
return nil, err
}
v := &Volume{
BackingDevice: d.path,
Flags: d.flags,
UUID: d.UUID(),
key: finalKey,
LuksType: "LUKS2",
StorageSize: storageSize,
StorageOffset: uint64(offset),
StorageEncryption: storageSegment.Encryption,
StorageIvTweak: uint64(ivTweak),
StorageSectorSize: uint64(storageSegment.SectorSize),
}
return v, nil
}
func computeDigestForKey(dig *digest, keyslotIdx int, finalKey []byte) ([]byte, error) {
digSalt, err := base64.StdEncoding.DecodeString(dig.Salt)
if err != nil {
return nil, fmt.Errorf("keyslotIdx[%v].digest.salt base64 parsing failed: %v", keyslotIdx, err)
}
switch dig.Type {
case "pbkdf2":
h, size := getHashAlgo(dig.Hash)
if h == nil {
return nil, fmt.Errorf("Unknown digest hash algorithm: %v", dig.Hash)
}
return pbkdf2.Key(finalKey, digSalt, int(dig.Iterations), size, h), nil
default:
return nil, fmt.Errorf("Unknown digest kdf type: %v", dig.Type)
}
}
func (d *deviceV2) decryptLuks2VolumeKey(keyslotIdx int, keyslot keyslot, afKey []byte) ([]byte, error) {
// this method follows logic at luks2_keyslot_get_key()
area := keyslot.Area
// decrypt keyslotIdx area using the derived key
keyslotSize := keyslot.KeySize * stripesNum
areaSize, err := area.Size.Int64()
if err != nil {
return nil, fmt.Errorf("Invalid keyslotIdx[%v] size value: %v. %v", keyslotIdx, area.Size, err)
}
if int64(keyslotSize) > areaSize {
return nil, fmt.Errorf("keyslot[%v] area size too small, given %v expected at least %v", keyslotIdx, areaSize, keyslotSize)
}
if keyslotSize%storageSectorSize != 0 {
return nil, fmt.Errorf("keyslot[%v] size %v is not multiple of the sector size %v", keyslotIdx, keyslotSize, storageSectorSize)
}
keyData := make([]byte, keyslotSize)
defer clearSlice(keyData)
keyslotOffset, err := area.Offset.Int64()
if err != nil {
return nil, fmt.Errorf("Invalid keyslotIdx[%v] offset: %v. %v", keyslotIdx, area.Offset, err)
}
if keyslotOffset%storageSectorSize != 0 {
return nil, fmt.Errorf("keyslot[%v] offset %v is not aligned to sector size %v", keyslotIdx, keyslotOffset, storageSectorSize)
}
if _, err := d.f.ReadAt(keyData, keyslotOffset); err != nil {
return nil, err
}
ciph, err := buildLuks2AfCipher(area.Encryption, afKey)
if err != nil {
return nil, err
}
for i := 0; i < int(keyslotSize/storageSectorSize); i++ {
block := keyData[i*storageSectorSize : (i+1)*storageSectorSize]
ciph.Decrypt(block, block, uint64(i))
}
// anti-forensic merge
af := keyslot.Af
if af.Stripes != stripesNum {
return nil, fmt.Errorf("LUKS currently supports only af with 4000 stripes")
}
h, _ := getHashAlgo(af.Hash)
if h == nil {
return nil, fmt.Errorf("Unknown af hash algorithm: %v", af.Hash)
}
return afMerge(keyData, int(keyslot.KeySize), int(af.Stripes), h())
}
func buildLuks2AfCipher(encryption string, afKey []byte) (*xts.Cipher, error) {
// parse encryption mode for the keyslot area, see crypt_parse_name_and_mode()
// example of `encryption` value is 'aes-xts-plain64'
encParts := strings.Split(encryption, "-")
if len(encParts) != 3 {
return nil, fmt.Errorf("Unexpected encryption format: %v", encryption)
}
cipherName := encParts[0]
cipherMode := encParts[1]
// ivModeName := encParts[2]
cipherFunc, err := getCipher(cipherName)
if err != nil {
return nil, err
}
switch cipherMode {
case "xts":
return xts.NewCipher(cipherFunc, afKey)
default:
return nil, fmt.Errorf("Unknown encryption mode: %v", cipherMode)
}
}
func deriveLuks2AfKey(kdf kdf, keyslotIdx int, passphrase []byte, keyLength uint) ([]byte, error) {
salt, err := base64.StdEncoding.DecodeString(kdf.Salt)
if err != nil {
return nil, fmt.Errorf("keyslotIdx[%v].kdf.salt base64 parsing failed: %v", keyslotIdx, err)
}
switch kdf.Type {
case "pbkdf2":
var h func() hash.Hash
switch kdf.Hash {
case "sha256":
h = sha256.New
case "sha512":
h = sha512.New
default:
return nil, fmt.Errorf("Unknown keyslotIdx[%v].kdf.hash algorithm: %v", keyslotIdx, kdf.Hash)
}
return pbkdf2.Key(passphrase, salt, int(kdf.Iterations), int(keyLength), h), nil
case "argon2i":
return argon2.Key(passphrase, salt, uint32(kdf.Time), uint32(kdf.Memory), uint8(kdf.Cpus), uint32(keyLength)), nil
case "argon2id":
return argon2.IDKey(passphrase, salt, uint32(kdf.Time), uint32(kdf.Memory), uint8(kdf.Cpus), uint32(keyLength)), nil
default:
return nil, fmt.Errorf("Unknown kdf type: %v", kdf.Type)
}
}
func (d *deviceV2) findDigestForKeyslot(keyslotIdx int) *digest {
for _, dig := range d.meta.Digests {
for _, k := range dig.Keyslots {
k, e := k.Int64()
if e != nil {
continue
}
if int(k) == keyslotIdx {
return &dig
}
}
}
return nil
}