~ubuntu-core-dev/cryptsetup/ubuntu

« back to all changes in this revision

Viewing changes to luks/keymanage.c

  • Committer: Martin Pitt
  • Date: 2012-03-08 06:28:43 UTC
  • Revision ID: martin.pitt@canonical.com-20120308062843-38i53w859o8t6p2p
merge with Debian 2:1.4.1-2

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 * LUKS - Linux Unified Key Setup 
3
 
 *
4
 
 * Copyright (C) 2004-2006, Clemens Fruhwirth <clemens@endorphin.org>
5
 
 *
6
 
 * This program is free software; you can redistribute it and/or
7
 
 * modify it under the terms of the GNU General Public License
8
 
 * version 2 as published by the Free Software Foundation.
9
 
 *
10
 
 * This program is distributed in the hope that it will be useful,
11
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 
 * GNU General Public License for more details.
14
 
 *
15
 
 * You should have received a copy of the GNU General Public License
16
 
 * along with this program; if not, write to the Free Software
17
 
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 
 */
19
 
 
20
 
#include <sys/types.h>
21
 
#include <sys/stat.h>
22
 
#include <sys/ioctl.h>
23
 
#include <linux/fs.h>
24
 
#include <netinet/in.h>
25
 
#include <fcntl.h>
26
 
#include <errno.h>
27
 
#include <unistd.h>
28
 
#include <stdio.h>
29
 
#include <stdlib.h>
30
 
#include <string.h>
31
 
#include <ctype.h>
32
 
 
33
 
#include "luks.h"
34
 
#include "af.h"
35
 
#include "pbkdf.h"
36
 
#include "random.h"
37
 
#include <uuid/uuid.h>
38
 
#include <../lib/internal.h>
39
 
 
40
 
#define div_round_up(a,b) ({           \
41
 
        typeof(a) __a = (a);          \
42
 
        typeof(b) __b = (b);          \
43
 
        (__a - 1) / __b + 1;        \
44
 
})
45
 
 
46
 
static inline int round_up_modulo(int x, int m) {
47
 
        return div_round_up(x, m) * m;
48
 
}
49
 
 
50
 
struct luks_masterkey *LUKS_alloc_masterkey(int keylength, const char *key)
51
 
52
 
        struct luks_masterkey *mk=malloc(sizeof(*mk) + keylength);
53
 
        if(NULL == mk) return NULL;
54
 
        mk->keyLength=keylength;
55
 
        if (key)
56
 
                memcpy(&mk->key, key, keylength);
57
 
        return mk;
58
 
}
59
 
 
60
 
void LUKS_dealloc_masterkey(struct luks_masterkey *mk)
61
 
{
62
 
        if(NULL != mk) {
63
 
                memset(mk->key,0,mk->keyLength);
64
 
                mk->keyLength=0;
65
 
                free(mk);
66
 
        }
67
 
}
68
 
 
69
 
struct luks_masterkey *LUKS_generate_masterkey(int keylength)
70
 
{
71
 
        struct luks_masterkey *mk=LUKS_alloc_masterkey(keylength, NULL);
72
 
        if(NULL == mk) return NULL;
73
 
 
74
 
        int r = getRandom(mk->key,keylength);
75
 
        if(r < 0) {
76
 
                LUKS_dealloc_masterkey(mk);
77
 
                return NULL;
78
 
        }
79
 
        return mk;
80
 
}
81
 
 
82
 
int LUKS_hdr_backup(
83
 
        const char *backup_file,
84
 
        const char *device,
85
 
        struct luks_phdr *hdr,
86
 
        struct crypt_device *ctx)
87
 
{
88
 
        int r = 0, devfd = -1;
89
 
        size_t buffer_size;
90
 
        char *buffer = NULL;
91
 
        struct stat st;
92
 
 
93
 
        if(stat(backup_file, &st) == 0) {
94
 
                log_err(ctx, _("Requested file %s already exist.\n"), backup_file);
95
 
                return -EINVAL;
96
 
        }
97
 
 
98
 
        r = LUKS_read_phdr(device, hdr, 0, ctx);
99
 
        if (r)
100
 
                return r;
101
 
 
102
 
        buffer_size = hdr->payloadOffset << SECTOR_SHIFT;
103
 
        buffer = safe_alloc(buffer_size);
104
 
        if (!buffer || buffer_size < LUKS_ALIGN_KEYSLOTS) {
105
 
                r = -ENOMEM;
106
 
                goto out;
107
 
        }
108
 
 
109
 
        log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes).",
110
 
                sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS);
111
 
 
112
 
        devfd = open(device, O_RDONLY | O_DIRECT | O_SYNC);
113
 
        if(devfd == -1) {
114
 
                log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
115
 
                r = -EINVAL;
116
 
                goto out;
117
 
        }
118
 
 
119
 
        if(read_blockwise(devfd, buffer, buffer_size) < buffer_size) {
120
 
                r = -EIO;
121
 
                goto out;
122
 
        }
123
 
        close(devfd);
124
 
 
125
 
        /* Wipe unused area, so backup cannot contain old signatures */
126
 
        memset(buffer + sizeof(*hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(*hdr));
127
 
 
128
 
        devfd = creat(backup_file, S_IRUSR);
129
 
        if(devfd == -1) {
130
 
                r = -EINVAL;
131
 
                goto out;
132
 
        }
133
 
        if(write(devfd, buffer, buffer_size) < buffer_size) {
134
 
                log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
135
 
                r = -EIO;
136
 
                goto out;
137
 
        }
138
 
        close(devfd);
139
 
 
140
 
        r = 0;
141
 
out:
142
 
        if (devfd != -1)
143
 
                close(devfd);
144
 
        safe_free(buffer);
145
 
        return r;
146
 
}
147
 
 
148
 
int LUKS_hdr_restore(
149
 
        const char *backup_file,
150
 
        const char *device,
151
 
        struct luks_phdr *hdr,
152
 
        struct crypt_device *ctx)
153
 
{
154
 
        int r = 0, devfd = -1, diff_uuid = 0;
155
 
        size_t buffer_size;
156
 
        char *buffer = NULL, msg[200];
157
 
        struct stat st;
158
 
        struct luks_phdr hdr_file;
159
 
 
160
 
        if(stat(backup_file, &st) < 0) {
161
 
                log_err(ctx, _("Backup file %s doesn't exist.\n"), backup_file);
162
 
                return -EINVAL;
163
 
        }
164
 
 
165
 
        r = LUKS_read_phdr_backup(backup_file, device, &hdr_file, 0, ctx);
166
 
        buffer_size = hdr_file.payloadOffset << SECTOR_SHIFT;
167
 
 
168
 
        if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
169
 
                log_err(ctx, _("Backup file do not contain valid LUKS header.\n"));
170
 
                r = -EINVAL;
171
 
                goto out;
172
 
        }
173
 
 
174
 
        buffer = safe_alloc(buffer_size);
175
 
        if (!buffer) {
176
 
                r = -ENOMEM;
177
 
                goto out;
178
 
        }
179
 
 
180
 
        devfd = open(backup_file, O_RDONLY);
181
 
        if(devfd == -1) {
182
 
                log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
183
 
                r = -EINVAL;
184
 
                goto out;
185
 
        }
186
 
 
187
 
        if(read(devfd, buffer, buffer_size) < buffer_size) {
188
 
                log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
189
 
                r = -EIO;
190
 
                goto out;
191
 
        }
192
 
        close(devfd);
193
 
 
194
 
        r = LUKS_read_phdr(device, hdr, 0, ctx);
195
 
        if (r == 0) {
196
 
                log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device);
197
 
                if(hdr->payloadOffset != hdr_file.payloadOffset ||
198
 
                   hdr->keyBytes != hdr_file.keyBytes) {
199
 
                        log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
200
 
                        r = -EINVAL;
201
 
                        goto out;
202
 
                }
203
 
                if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
204
 
                        diff_uuid = 1;
205
 
        }
206
 
 
207
 
        if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device,
208
 
                 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
209
 
                     _("already contains LUKS header. Replacing header will destroy existing keyslots."),
210
 
                     diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
211
 
                r = -ENOMEM;
212
 
                goto out;
213
 
        }
214
 
 
215
 
        if (!crypt_confirm(ctx, msg)) {
216
 
                r = -EINVAL;
217
 
                goto out;
218
 
        }
219
 
 
220
 
        log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
221
 
                sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device);
222
 
 
223
 
        devfd = open(device, O_WRONLY | O_DIRECT | O_SYNC);
224
 
        if(devfd == -1) {
225
 
                log_err(ctx, _("Cannot open device %s.\n"), device);
226
 
                r = -EINVAL;
227
 
                goto out;
228
 
        }
229
 
 
230
 
        if(write_blockwise(devfd, buffer, buffer_size) < buffer_size) {
231
 
                r = -EIO;
232
 
                goto out;
233
 
        }
234
 
        close(devfd);
235
 
 
236
 
        /* Be sure to reload new data */
237
 
        r = LUKS_read_phdr(device, hdr, 0, ctx);
238
 
out:
239
 
        if (devfd != -1)
240
 
                close(devfd);
241
 
        safe_free(buffer);
242
 
        return r;
243
 
}
244
 
 
245
 
static int _check_and_convert_hdr(const char *device,
246
 
                                  struct luks_phdr *hdr,
247
 
                                  int require_luks_device,
248
 
                                  struct crypt_device *ctx)
249
 
{
250
 
        int r = 0;
251
 
        unsigned int i;
252
 
        char luksMagic[] = LUKS_MAGIC;
253
 
 
254
 
        if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
255
 
                log_dbg("LUKS header not detected.");
256
 
                if (require_luks_device)
257
 
                        log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
258
 
                else
259
 
                        set_error(_("Device %s is not a valid LUKS device."), device);
260
 
                r = -EINVAL;
261
 
        } else if((hdr->version = ntohs(hdr->version)) != 1) {  /* Convert every uint16/32_t item from network byte order */
262
 
                log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
263
 
                r = -EINVAL;
264
 
        } else if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
265
 
                log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
266
 
                r = -EINVAL;
267
 
        } else {
268
 
                hdr->payloadOffset      = ntohl(hdr->payloadOffset);
269
 
                hdr->keyBytes           = ntohl(hdr->keyBytes);
270
 
                hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
271
 
 
272
 
                for(i = 0; i < LUKS_NUMKEYS; ++i) {
273
 
                        hdr->keyblock[i].active             = ntohl(hdr->keyblock[i].active);
274
 
                        hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
275
 
                        hdr->keyblock[i].keyMaterialOffset  = ntohl(hdr->keyblock[i].keyMaterialOffset);
276
 
                        hdr->keyblock[i].stripes            = ntohl(hdr->keyblock[i].stripes);
277
 
                }
278
 
        }
279
 
 
280
 
        return r;
281
 
}
282
 
 
283
 
static void _to_lower(char *str, unsigned max_len)
284
 
{
285
 
        for(; *str && max_len; str++, max_len--)
286
 
                if (isupper(*str))
287
 
                        *str = tolower(*str);
288
 
}
289
 
 
290
 
static void LUKS_fix_header_compatible(struct luks_phdr *header)
291
 
{
292
 
        /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
293
 
         * so always convert hash to lower case in header */
294
 
        _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
295
 
}
296
 
 
297
 
int LUKS_read_phdr_backup(const char *backup_file,
298
 
                          const char *device,
299
 
                          struct luks_phdr *hdr,
300
 
                          int require_luks_device,
301
 
                          struct crypt_device *ctx)
302
 
{
303
 
        int devfd = 0, r = 0;
304
 
 
305
 
        log_dbg("Reading LUKS header of size %d from backup file %s",
306
 
                sizeof(struct luks_phdr), backup_file);
307
 
 
308
 
        devfd = open(backup_file, O_RDONLY);
309
 
        if(-1 == devfd) {
310
 
                log_err(ctx, _("Cannot open file %s.\n"), device);
311
 
                return -EINVAL;
312
 
        }
313
 
 
314
 
        if(read(devfd, hdr, sizeof(struct luks_phdr)) < sizeof(struct luks_phdr))
315
 
                r = -EIO;
316
 
        else {
317
 
                LUKS_fix_header_compatible(hdr);
318
 
                r = _check_and_convert_hdr(backup_file, hdr, require_luks_device, ctx);
319
 
        }
320
 
 
321
 
        close(devfd);
322
 
        return r;
323
 
}
324
 
 
325
 
int LUKS_read_phdr(const char *device,
326
 
                   struct luks_phdr *hdr,
327
 
                   int require_luks_device,
328
 
                   struct crypt_device *ctx)
329
 
{
330
 
        int devfd = 0, r = 0;
331
 
        uint64_t size;
332
 
 
333
 
        log_dbg("Reading LUKS header of size %d from device %s",
334
 
                sizeof(struct luks_phdr), device);
335
 
 
336
 
        devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC);
337
 
        if(-1 == devfd) {
338
 
                log_err(ctx, _("Cannot open device %s.\n"), device);
339
 
                return -EINVAL;
340
 
        }
341
 
 
342
 
        if(read_blockwise(devfd, hdr, sizeof(struct luks_phdr)) < sizeof(struct luks_phdr))
343
 
                r = -EIO;
344
 
        else
345
 
                r = _check_and_convert_hdr(device, hdr, require_luks_device, ctx);
346
 
 
347
 
#ifdef BLKGETSIZE64
348
 
        if (r == 0 && (ioctl(devfd, BLKGETSIZE64, &size) < 0 ||
349
 
            size < (uint64_t)hdr->payloadOffset)) {
350
 
                log_err(ctx, _("LUKS header detected but device %s is too small.\n"), device);
351
 
                r = -EINVAL;
352
 
        }
353
 
#endif
354
 
        close(devfd);
355
 
 
356
 
        return r;
357
 
}
358
 
 
359
 
int LUKS_write_phdr(const char *device,
360
 
                    struct luks_phdr *hdr,
361
 
                    struct crypt_device *ctx)
362
 
{
363
 
        int devfd = 0; 
364
 
        unsigned int i; 
365
 
        struct luks_phdr convHdr;
366
 
        int r;
367
 
 
368
 
        log_dbg("Updating LUKS header of size %d on device %s",
369
 
                sizeof(struct luks_phdr), device);
370
 
 
371
 
        devfd = open(device,O_RDWR | O_DIRECT | O_SYNC);
372
 
        if(-1 == devfd) { 
373
 
                log_err(ctx, _("Cannot open device %s.\n"), device);
374
 
                return -EINVAL;
375
 
        }
376
 
 
377
 
        memcpy(&convHdr, hdr, sizeof(struct luks_phdr));
378
 
        memset(&convHdr._padding, 0, sizeof(convHdr._padding));
379
 
 
380
 
        /* Convert every uint16/32_t item to network byte order */
381
 
        convHdr.version            = htons(hdr->version);
382
 
        convHdr.payloadOffset      = htonl(hdr->payloadOffset);
383
 
        convHdr.keyBytes           = htonl(hdr->keyBytes);
384
 
        convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
385
 
        for(i = 0; i < LUKS_NUMKEYS; ++i) {
386
 
                convHdr.keyblock[i].active             = htonl(hdr->keyblock[i].active);
387
 
                convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
388
 
                convHdr.keyblock[i].keyMaterialOffset  = htonl(hdr->keyblock[i].keyMaterialOffset);
389
 
                convHdr.keyblock[i].stripes            = htonl(hdr->keyblock[i].stripes);
390
 
        }
391
 
 
392
 
        r = write_blockwise(devfd, &convHdr, sizeof(struct luks_phdr)) < sizeof(struct luks_phdr) ? -EIO : 0;
393
 
        if (r)
394
 
                log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device);
395
 
        close(devfd);
396
 
 
397
 
        /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
398
 
        if (!r) {
399
 
                r = LUKS_read_phdr(device, hdr, 1, ctx);
400
 
                if (r)
401
 
                        log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device);
402
 
        }
403
 
 
404
 
        return r;
405
 
}
406
 
 
407
 
static int LUKS_PBKDF2_performance_check(const char *hashSpec,
408
 
                                         uint64_t *PBKDF2_per_sec,
409
 
                                         struct crypt_device *ctx)
410
 
{
411
 
        if (!*PBKDF2_per_sec) {
412
 
                if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
413
 
                        log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
414
 
                        return -EINVAL;
415
 
                }
416
 
                log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
417
 
        }
418
 
 
419
 
        return 0;
420
 
}
421
 
 
422
 
int LUKS_generate_phdr(struct luks_phdr *header,
423
 
                       const struct luks_masterkey *mk,
424
 
                       const char *cipherName, const char *cipherMode, const char *hashSpec,
425
 
                       const char *uuid, unsigned int stripes,
426
 
                       unsigned int alignPayload,
427
 
                       unsigned int alignOffset,
428
 
                       uint32_t iteration_time_ms,
429
 
                       uint64_t *PBKDF2_per_sec,
430
 
                       struct crypt_device *ctx)
431
 
{
432
 
        unsigned int i=0;
433
 
        unsigned int blocksPerStripeSet = div_round_up(mk->keyLength*stripes,SECTOR_SIZE);
434
 
        int r;
435
 
        char luksMagic[] = LUKS_MAGIC;
436
 
        uuid_t partitionUuid;
437
 
        int currentSector;
438
 
        int alignSectors = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
439
 
        if (alignPayload == 0)
440
 
                alignPayload = alignSectors;
441
 
 
442
 
        memset(header,0,sizeof(struct luks_phdr));
443
 
 
444
 
        /* Set Magic */
445
 
        memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
446
 
        header->version=1;
447
 
        strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
448
 
        strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
449
 
        strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
450
 
 
451
 
        header->keyBytes=mk->keyLength;
452
 
 
453
 
        LUKS_fix_header_compatible(header);
454
 
 
455
 
        log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
456
 
                header->version, header->hashSpec ,header->cipherName, header->cipherMode,
457
 
                header->keyBytes);
458
 
 
459
 
        r = getRandom(header->mkDigestSalt,LUKS_SALTSIZE);
460
 
        if(r < 0) {
461
 
                log_err(ctx,  _("Cannot create LUKS header: reading random salt failed.\n"));
462
 
                return r;
463
 
        }
464
 
 
465
 
        if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
466
 
                return r;
467
 
 
468
 
        /* Compute master key digest */
469
 
        iteration_time_ms /= 8;
470
 
        header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
471
 
                                              LUKS_MKD_ITERATIONS_MIN);
472
 
 
473
 
        r = PBKDF2_HMAC(header->hashSpec,mk->key,mk->keyLength,
474
 
                        header->mkDigestSalt,LUKS_SALTSIZE,
475
 
                        header->mkDigestIterations,
476
 
                        header->mkDigest,LUKS_DIGESTSIZE);
477
 
        if(r < 0) {
478
 
                log_err(ctx,  _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
479
 
                        header->hashSpec);
480
 
                return r;
481
 
        }
482
 
 
483
 
        currentSector = round_up_modulo(LUKS_PHDR_SIZE, alignSectors);
484
 
        for(i = 0; i < LUKS_NUMKEYS; ++i) {
485
 
                header->keyblock[i].active = LUKS_KEY_DISABLED;
486
 
                header->keyblock[i].keyMaterialOffset = currentSector;
487
 
                header->keyblock[i].stripes = stripes;
488
 
                currentSector = round_up_modulo(currentSector + blocksPerStripeSet, alignSectors);
489
 
        }
490
 
        currentSector = round_up_modulo(currentSector, alignPayload);
491
 
 
492
 
        /* alignOffset - offset from natural device alignment provided by topology info */
493
 
        header->payloadOffset = currentSector + alignOffset;
494
 
 
495
 
        if (uuid && !uuid_parse(uuid, partitionUuid)) {
496
 
                log_err(ctx, _("Wrong UUID format provided, generating new one.\n"));
497
 
                uuid = NULL;
498
 
        }
499
 
        if (!uuid)
500
 
                uuid_generate(partitionUuid);
501
 
        uuid_unparse(partitionUuid, header->uuid);
502
 
 
503
 
        log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
504
 
                header->payloadOffset, header->uuid, header->mkDigestIterations);
505
 
 
506
 
        return 0;
507
 
}
508
 
 
509
 
int LUKS_set_key(const char *device, unsigned int keyIndex,
510
 
                 const char *password, size_t passwordLen,
511
 
                 struct luks_phdr *hdr, struct luks_masterkey *mk,
512
 
                 uint32_t iteration_time_ms,
513
 
                 uint64_t *PBKDF2_per_sec,
514
 
                 struct crypt_device *ctx)
515
 
{
516
 
        char derivedKey[hdr->keyBytes];
517
 
        char *AfKey;
518
 
        unsigned int AFEKSize;
519
 
        uint64_t PBKDF2_temp;
520
 
        int r;
521
 
 
522
 
        if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
523
 
                log_err(ctx,  _("Key slot %d active, purge first.\n"), keyIndex);
524
 
                return -EINVAL;
525
 
        }
526
 
 
527
 
        if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
528
 
                log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
529
 
                        keyIndex);
530
 
                 return -EINVAL;
531
 
        }
532
 
 
533
 
        log_dbg("Calculating data for key slot %d", keyIndex);
534
 
 
535
 
        if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
536
 
                return r;
537
 
 
538
 
        /*
539
 
         * Avoid floating point operation
540
 
         * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
541
 
         */
542
 
        PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
543
 
        PBKDF2_temp /= 1024;
544
 
        if (PBKDF2_temp > UINT32_MAX)
545
 
                PBKDF2_temp = UINT32_MAX;
546
 
        hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
547
 
                                                              LUKS_SLOT_ITERATIONS_MIN);
548
 
 
549
 
        log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
550
 
 
551
 
        r = getRandom(hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE);
552
 
        if(r < 0) return r;
553
 
 
554
 
//      assert((mk->keyLength % TWOFISH_BLOCKSIZE) == 0); FIXME
555
 
 
556
 
        r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
557
 
                        hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
558
 
                        hdr->keyblock[keyIndex].passwordIterations,
559
 
                        derivedKey, hdr->keyBytes);
560
 
        if(r < 0) return r;
561
 
 
562
 
        /*
563
 
         * AF splitting, the masterkey stored in mk->key is splitted to AfMK
564
 
         */
565
 
        AFEKSize = hdr->keyblock[keyIndex].stripes*mk->keyLength;
566
 
        AfKey = (char *)malloc(AFEKSize);
567
 
        if(AfKey == NULL) return -ENOMEM;
568
 
 
569
 
        log_dbg("Using hash %s for AF in key slot %d, %d stripes",
570
 
                hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
571
 
        r = AF_split(mk->key,AfKey,mk->keyLength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
572
 
        if(r < 0) goto out;
573
 
 
574
 
        log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
575
 
                hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
576
 
        /* Encryption via dm */
577
 
        r = LUKS_encrypt_to_storage(AfKey,
578
 
                                    AFEKSize,
579
 
                                    hdr,
580
 
                                    derivedKey,
581
 
                                    hdr->keyBytes,
582
 
                                    device,
583
 
                                    hdr->keyblock[keyIndex].keyMaterialOffset,
584
 
                                    ctx);
585
 
        if(r < 0) {
586
 
                if(!get_error())
587
 
                        log_err(ctx, _("Failed to write to key storage.\n"));
588
 
                goto out;
589
 
        }
590
 
 
591
 
        /* Mark the key as active in phdr */
592
 
        r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
593
 
        if(r < 0) goto out;
594
 
 
595
 
        r = LUKS_write_phdr(device, hdr, ctx);
596
 
        if(r < 0) goto out;
597
 
 
598
 
        r = 0;
599
 
out:
600
 
        free(AfKey);
601
 
        return r;
602
 
}
603
 
 
604
 
/* Check whether a master key is invalid. */
605
 
int LUKS_verify_master_key(const struct luks_phdr *hdr,
606
 
                           const struct luks_masterkey *mk)
607
 
{
608
 
        char checkHashBuf[LUKS_DIGESTSIZE];
609
 
 
610
 
        if (PBKDF2_HMAC(hdr->hashSpec, mk->key, mk->keyLength,
611
 
                        hdr->mkDigestSalt, LUKS_SALTSIZE,
612
 
                        hdr->mkDigestIterations, checkHashBuf,
613
 
                        LUKS_DIGESTSIZE) < 0)
614
 
                return -EINVAL;
615
 
 
616
 
        if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
617
 
                return -EPERM;
618
 
 
619
 
        return 0;
620
 
}
621
 
 
622
 
/* Try to open a particular key slot */
623
 
static int LUKS_open_key(const char *device,
624
 
                  unsigned int keyIndex,
625
 
                  const char *password,
626
 
                  size_t passwordLen,
627
 
                  struct luks_phdr *hdr,
628
 
                  struct luks_masterkey *mk,
629
 
                  struct crypt_device *ctx)
630
 
{
631
 
        crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
632
 
        char derivedKey[hdr->keyBytes];
633
 
        char *AfKey;
634
 
        size_t AFEKSize;
635
 
        int r;
636
 
 
637
 
        log_dbg("Trying to open key slot %d [%d].", keyIndex, (int)ki);
638
 
 
639
 
        if (ki < CRYPT_SLOT_ACTIVE)
640
 
                return -ENOENT;
641
 
 
642
 
        // assert((mk->keyLength % TWOFISH_BLOCKSIZE) == 0); FIXME
643
 
 
644
 
        AFEKSize = hdr->keyblock[keyIndex].stripes*mk->keyLength;
645
 
        AfKey = (char *)malloc(AFEKSize);
646
 
        if(AfKey == NULL) return -ENOMEM;
647
 
 
648
 
        r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
649
 
                        hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
650
 
                        hdr->keyblock[keyIndex].passwordIterations,
651
 
                        derivedKey, hdr->keyBytes);
652
 
        if(r < 0) goto out;
653
 
 
654
 
        log_dbg("Reading key slot %d area.", keyIndex);
655
 
        r = LUKS_decrypt_from_storage(AfKey,
656
 
                                      AFEKSize,
657
 
                                      hdr,
658
 
                                      derivedKey,
659
 
                                      hdr->keyBytes,
660
 
                                      device,
661
 
                                      hdr->keyblock[keyIndex].keyMaterialOffset,
662
 
                                      ctx);
663
 
        if(r < 0) {
664
 
                log_err(ctx, _("Failed to read from key storage.\n"));
665
 
                goto out;
666
 
        }
667
 
 
668
 
        r = AF_merge(AfKey,mk->key,mk->keyLength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
669
 
        if(r < 0) goto out;
670
 
 
671
 
        r = LUKS_verify_master_key(hdr, mk);
672
 
        if (r >= 0)
673
 
                log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
674
 
out:
675
 
        free(AfKey);
676
 
        return r;
677
 
}
678
 
 
679
 
int LUKS_open_key_with_hdr(const char *device,
680
 
                           int keyIndex,
681
 
                           const char *password,
682
 
                           size_t passwordLen,
683
 
                           struct luks_phdr *hdr,
684
 
                           struct luks_masterkey **mk,
685
 
                           struct crypt_device *ctx)
686
 
{
687
 
        unsigned int i;
688
 
        int r;
689
 
 
690
 
        *mk = LUKS_alloc_masterkey(hdr->keyBytes, NULL);
691
 
 
692
 
        if (keyIndex >= 0)
693
 
                return LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *mk, ctx);
694
 
 
695
 
        for(i = 0; i < LUKS_NUMKEYS; i++) {
696
 
                r = LUKS_open_key(device, i, password, passwordLen, hdr, *mk, ctx);
697
 
                if(r == 0)
698
 
                        return i;
699
 
 
700
 
                /* Do not retry for errors that are no -EPERM or -ENOENT,
701
 
                   former meaning password wrong, latter key slot inactive */
702
 
                if ((r != -EPERM) && (r != -ENOENT)) 
703
 
                        return r;
704
 
        }
705
 
        /* Warning, early returns above */
706
 
        log_err(ctx, _("No key available with this passphrase.\n"));
707
 
        return -EPERM;
708
 
}
709
 
 
710
 
/*
711
 
 * Wipe patterns according to Gutmann's Paper
712
 
 */
713
 
 
714
 
static void wipeSpecial(char *buffer, size_t buffer_size, unsigned int turn)
715
 
{
716
 
        unsigned int i;
717
 
 
718
 
        unsigned char write_modes[][3] = {
719
 
                {"\x55\x55\x55"}, {"\xaa\xaa\xaa"}, {"\x92\x49\x24"},
720
 
                {"\x49\x24\x92"}, {"\x24\x92\x49"}, {"\x00\x00\x00"},
721
 
                {"\x11\x11\x11"}, {"\x22\x22\x22"}, {"\x33\x33\x33"},
722
 
                {"\x44\x44\x44"}, {"\x55\x55\x55"}, {"\x66\x66\x66"},
723
 
                {"\x77\x77\x77"}, {"\x88\x88\x88"}, {"\x99\x99\x99"},
724
 
                {"\xaa\xaa\xaa"}, {"\xbb\xbb\xbb"}, {"\xcc\xcc\xcc"},
725
 
                {"\xdd\xdd\xdd"}, {"\xee\xee\xee"}, {"\xff\xff\xff"},
726
 
                {"\x92\x49\x24"}, {"\x49\x24\x92"}, {"\x24\x92\x49"},
727
 
                {"\x6d\xb6\xdb"}, {"\xb6\xdb\x6d"}, {"\xdb\x6d\xb6"}
728
 
        };
729
 
 
730
 
        for(i = 0; i < buffer_size / 3; ++i) {
731
 
                memcpy(buffer, write_modes[turn], 3);
732
 
                buffer += 3;
733
 
        }
734
 
}
735
 
 
736
 
static int wipe(const char *device, unsigned int from, unsigned int to)
737
 
{
738
 
        int devfd;
739
 
        char *buffer;
740
 
        unsigned int i;
741
 
        unsigned int bufLen = (to - from) * SECTOR_SIZE;
742
 
        int r = 0;
743
 
 
744
 
        devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
745
 
        if(devfd == -1)
746
 
                return -EINVAL;
747
 
 
748
 
        buffer = (char *) malloc(bufLen);
749
 
        if(!buffer) return -ENOMEM;
750
 
 
751
 
        for(i = 0; i < 39; ++i) {
752
 
                if     (i >=  0 && i <  5) getRandom(buffer, bufLen);
753
 
                else if(i >=  5 && i < 32) wipeSpecial(buffer, bufLen, i - 5);
754
 
                else if(i >= 32 && i < 38) getRandom(buffer, bufLen);
755
 
                else if(i >= 38 && i < 39) memset(buffer, 0xFF, bufLen);
756
 
 
757
 
                if(write_lseek_blockwise(devfd, buffer, bufLen, from * SECTOR_SIZE) < 0) {
758
 
                        r = -EIO;
759
 
                        break;
760
 
                }
761
 
        }
762
 
 
763
 
        free(buffer);
764
 
        close(devfd);
765
 
 
766
 
        return r;
767
 
}
768
 
 
769
 
int LUKS_del_key(const char *device,
770
 
                 unsigned int keyIndex,
771
 
                 struct luks_phdr *hdr,
772
 
                 struct crypt_device *ctx)
773
 
{
774
 
        unsigned int startOffset, endOffset, stripesLen;
775
 
        int r;
776
 
 
777
 
        r = LUKS_read_phdr(device, hdr, 1, ctx);
778
 
        if (r)
779
 
                return r;
780
 
 
781
 
        r = LUKS_keyslot_set(hdr, keyIndex, 0);
782
 
        if (r) {
783
 
                log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
784
 
                        keyIndex, LUKS_NUMKEYS - 1);
785
 
                return r;
786
 
        }
787
 
 
788
 
        /* secure deletion of key material */
789
 
        startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
790
 
        stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
791
 
        endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
792
 
 
793
 
        r = wipe(device, startOffset, endOffset);
794
 
        if (r) {
795
 
                log_err(ctx, _("Cannot wipe device %s.\n"), device);
796
 
                return r;
797
 
        }
798
 
 
799
 
        r = LUKS_write_phdr(device, hdr, ctx);
800
 
 
801
 
        return r;
802
 
}
803
 
 
804
 
crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
805
 
{
806
 
        int i;
807
 
 
808
 
        if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
809
 
                return CRYPT_SLOT_INVALID;
810
 
 
811
 
        if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
812
 
                return CRYPT_SLOT_INACTIVE;
813
 
 
814
 
        if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
815
 
                return CRYPT_SLOT_INVALID;
816
 
 
817
 
        for(i = 0; i < LUKS_NUMKEYS; i++)
818
 
                if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
819
 
                        return CRYPT_SLOT_ACTIVE;
820
 
 
821
 
        return CRYPT_SLOT_ACTIVE_LAST;
822
 
}
823
 
 
824
 
int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
825
 
{
826
 
        int i;
827
 
 
828
 
        for (i = 0; i < LUKS_NUMKEYS; i++)
829
 
                if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
830
 
                        break;
831
 
 
832
 
        if (i == LUKS_NUMKEYS)
833
 
                return -EINVAL;
834
 
 
835
 
        return i;
836
 
}
837
 
 
838
 
int LUKS_keyslot_active_count(struct luks_phdr *hdr)
839
 
{
840
 
        int i, num = 0;
841
 
 
842
 
        for (i = 0; i < LUKS_NUMKEYS; i++)
843
 
                if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
844
 
                        num++;
845
 
 
846
 
        return num;
847
 
}
848
 
 
849
 
int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
850
 
{
851
 
        crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
852
 
 
853
 
        if (ki == CRYPT_SLOT_INVALID)
854
 
                return -EINVAL;
855
 
 
856
 
        hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
857
 
        log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
858
 
        return 0;
859
 
}