Add --keyfile-offset and --new-keyfile-offset to cryptsetup.
[platform/upstream/cryptsetup.git] / lib / luks1 / keymanage.c
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <netinet/in.h>
23 #include <fcntl.h>
24 #include <errno.h>
25 #include <unistd.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <assert.h>
31 #include <uuid/uuid.h>
32
33 #include "luks.h"
34 #include "af.h"
35 #include "pbkdf.h"
36 #include "internal.h"
37
38 #define div_round_up(a,b) ({           \
39         typeof(a) __a = (a);          \
40         typeof(b) __b = (b);          \
41         (__a - 1) / __b + 1;        \
42 })
43
44 static inline int round_up_modulo(int x, int m) {
45         return div_round_up(x, m) * m;
46 }
47
48 /* Get size of struct luks_phrd with all keyslots material space */
49 static uint64_t LUKS_device_sectors(size_t keyLen, unsigned int stripes)
50 {
51         uint64_t keyslot_sectors, sector;
52         int i;
53
54         keyslot_sectors = div_round_up(keyLen * stripes, SECTOR_SIZE);
55         sector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
56
57         for (i = 0; i < LUKS_NUMKEYS; i++) {
58                 sector = round_up_modulo(sector, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
59                 sector += keyslot_sectors;
60         }
61
62         return sector;
63 }
64
65 static int LUKS_check_device_size(const char *device,
66                                   uint64_t min_sectors,
67                                   size_t keyLength)
68 {
69         uint64_t dev_size, req_sectors;
70
71         req_sectors = LUKS_device_sectors(keyLength, LUKS_STRIPES);
72         if (min_sectors > req_sectors)
73                 req_sectors = min_sectors;
74
75         if(device_size(device, &dev_size)) {
76                 log_dbg("Cannot get device size for device %s.", device);
77                 return -EIO;
78         }
79
80         return (req_sectors > (dev_size >> SECTOR_SHIFT));
81 }
82
83 /* Check keyslot to prevent access outside of header and keyslot area */
84 static int LUKS_check_keyslot_size(const struct luks_phdr *phdr, unsigned int keyIndex)
85 {
86         uint32_t secs_per_stripes;
87
88         /* First sectors is the header itself */
89         if (phdr->keyblock[keyIndex].keyMaterialOffset * SECTOR_SIZE < LUKS_ALIGN_KEYSLOTS) {
90                 log_dbg("Invalid offset %u in keyslot %u.",
91                         phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex);
92                 return 1;
93         }
94
95         /* Ignore following check for detached header where offset can be zero. */
96         if (phdr->payloadOffset == 0)
97                 return 0;
98
99         if (phdr->payloadOffset <= phdr->keyblock[keyIndex].keyMaterialOffset) {
100                 log_dbg("Invalid offset %u in keyslot %u (beyond data area offset %u).",
101                         phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex,
102                         phdr->payloadOffset);
103                 return 1;
104         }
105
106         secs_per_stripes = div_round_up(phdr->keyBytes * phdr->keyblock[keyIndex].stripes, SECTOR_SIZE);
107
108         if (phdr->payloadOffset < (phdr->keyblock[keyIndex].keyMaterialOffset + secs_per_stripes)) {
109                 log_dbg("Invalid keyslot size %u (offset %u, stripes %u) in "
110                         "keyslot %u (beyond data area offset %u).",
111                         secs_per_stripes,
112                         phdr->keyblock[keyIndex].keyMaterialOffset,
113                         phdr->keyblock[keyIndex].stripes,
114                         keyIndex, phdr->payloadOffset);
115                 return 1;
116         }
117
118         return 0;
119 }
120
121 static const char *dbg_slot_state(crypt_keyslot_info ki)
122 {
123         switch(ki) {
124         case CRYPT_SLOT_INACTIVE:
125                 return "INACTIVE";
126         case CRYPT_SLOT_ACTIVE:
127                 return "ACTIVE";
128         case CRYPT_SLOT_ACTIVE_LAST:
129                 return "ACTIVE_LAST";
130         case CRYPT_SLOT_INVALID:
131         default:
132                 return "INVALID";
133         }
134 }
135
136 int LUKS_hdr_backup(
137         const char *backup_file,
138         const char *device,
139         struct luks_phdr *hdr,
140         struct crypt_device *ctx)
141 {
142         int r = 0, devfd = -1;
143         ssize_t buffer_size;
144         char *buffer = NULL;
145         struct stat st;
146
147         if(stat(backup_file, &st) == 0) {
148                 log_err(ctx, _("Requested file %s already exist.\n"), backup_file);
149                 return -EINVAL;
150         }
151
152         r = LUKS_read_phdr(device, hdr, 1, ctx);
153         if (r)
154                 return r;
155
156         buffer_size = hdr->payloadOffset << SECTOR_SHIFT;
157         buffer = crypt_safe_alloc(buffer_size);
158         if (!buffer || buffer_size < LUKS_ALIGN_KEYSLOTS) {
159                 r = -ENOMEM;
160                 goto out;
161         }
162
163         log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes).",
164                 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS);
165
166         devfd = open(device, O_RDONLY | O_DIRECT | O_SYNC);
167         if(devfd == -1) {
168                 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
169                 r = -EINVAL;
170                 goto out;
171         }
172
173         if(read_blockwise(devfd, buffer, buffer_size) < buffer_size) {
174                 r = -EIO;
175                 goto out;
176         }
177         close(devfd);
178
179         /* Wipe unused area, so backup cannot contain old signatures */
180         memset(buffer + sizeof(*hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(*hdr));
181
182         devfd = creat(backup_file, S_IRUSR);
183         if(devfd == -1) {
184                 r = -EINVAL;
185                 goto out;
186         }
187         if(write(devfd, buffer, buffer_size) < buffer_size) {
188                 log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
189                 r = -EIO;
190                 goto out;
191         }
192         close(devfd);
193
194         r = 0;
195 out:
196         if (devfd != -1)
197                 close(devfd);
198         crypt_safe_free(buffer);
199         return r;
200 }
201
202 int LUKS_hdr_restore(
203         const char *backup_file,
204         const char *device,
205         struct luks_phdr *hdr,
206         struct crypt_device *ctx)
207 {
208         int r = 0, devfd = -1, diff_uuid = 0;
209         ssize_t buffer_size;
210         char *buffer = NULL, msg[200];
211         struct stat st;
212         struct luks_phdr hdr_file;
213
214         if(stat(backup_file, &st) < 0) {
215                 log_err(ctx, _("Backup file %s doesn't exist.\n"), backup_file);
216                 return -EINVAL;
217         }
218
219         r = LUKS_read_phdr_backup(backup_file, device, &hdr_file, 0, ctx);
220         buffer_size = hdr_file.payloadOffset << SECTOR_SHIFT;
221
222         if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
223                 log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
224                 r = -EINVAL;
225                 goto out;
226         }
227
228         buffer = crypt_safe_alloc(buffer_size);
229         if (!buffer) {
230                 r = -ENOMEM;
231                 goto out;
232         }
233
234         devfd = open(backup_file, O_RDONLY);
235         if(devfd == -1) {
236                 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
237                 r = -EINVAL;
238                 goto out;
239         }
240
241         if(read(devfd, buffer, buffer_size) < buffer_size) {
242                 log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
243                 r = -EIO;
244                 goto out;
245         }
246         close(devfd);
247
248         r = LUKS_read_phdr(device, hdr, 0, ctx);
249         if (r == 0) {
250                 log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device);
251                 if(hdr->payloadOffset != hdr_file.payloadOffset ||
252                    hdr->keyBytes != hdr_file.keyBytes) {
253                         log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
254                         r = -EINVAL;
255                         goto out;
256                 }
257                 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
258                         diff_uuid = 1;
259         }
260
261         if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device,
262                  r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
263                      _("already contains LUKS header. Replacing header will destroy existing keyslots."),
264                      diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
265                 r = -ENOMEM;
266                 goto out;
267         }
268
269         if (!crypt_confirm(ctx, msg)) {
270                 r = -EINVAL;
271                 goto out;
272         }
273
274         log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
275                 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device);
276
277         devfd = open(device, O_WRONLY | O_DIRECT | O_SYNC);
278         if(devfd == -1) {
279                 log_err(ctx, _("Cannot open device %s.\n"), device);
280                 r = -EINVAL;
281                 goto out;
282         }
283
284         if(write_blockwise(devfd, buffer, buffer_size) < buffer_size) {
285                 r = -EIO;
286                 goto out;
287         }
288         close(devfd);
289
290         /* Be sure to reload new data */
291         r = LUKS_read_phdr(device, hdr, 1, ctx);
292 out:
293         if (devfd != -1)
294                 close(devfd);
295         crypt_safe_free(buffer);
296         return r;
297 }
298
299 static int _keyslot_repair(const char *device, struct luks_phdr *phdr, struct crypt_device *ctx)
300 {
301         struct luks_phdr temp_phdr;
302         const unsigned char *sector = (const unsigned char*)phdr;
303         struct volume_key *vk;
304         uint64_t PBKDF2_per_sec = 1;
305         int i, bad;
306
307         // FIXME check keyBytes
308         vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
309
310         // FIXME check cipher, cipher_mode, hash, uuid, payloadOffset
311         LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
312                                phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
313                                phdr->payloadOffset, 0,
314                                1, &PBKDF2_per_sec,
315                                "/dev/null", ctx);
316
317         for(i = 0; i < LUKS_NUMKEYS; ++i) {
318                 bad = 0;
319                 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
320                         log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
321                                 (unsigned)phdr->keyblock[i].keyMaterialOffset,
322                                 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
323                         phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
324                         bad = 1;
325                 }
326
327                 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
328                         log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
329                                 (unsigned)phdr->keyblock[i].stripes,
330                                 (unsigned)temp_phdr.keyblock[i].stripes);
331                         phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
332                         bad = 1;
333                 }
334
335                 /* if enabled, do not try to fix it */
336                 if (phdr->keyblock[i].active != LUKS_KEY_ENABLED) {
337                         /* Known case - MSDOS partition table signature */
338                         if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
339                                 log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
340                                 bad = 1;
341                         }
342
343                         if(bad) {
344                                 log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
345                                 phdr->keyblock[i].active = LUKS_KEY_DISABLED;
346                                 memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
347                                 phdr->keyblock[i].passwordIterations = 0;
348                         }
349                 }
350         }
351
352         crypt_free_volume_key(vk);
353         memset(&temp_phdr, 0, sizeof(temp_phdr));
354
355         return LUKS_write_phdr(device, phdr, ctx);
356 }
357
358 static int _check_and_convert_hdr(const char *device,
359                                   struct luks_phdr *hdr,
360                                   int require_luks_device,
361                                   struct crypt_device *ctx)
362 {
363         int r = 0;
364         unsigned int i;
365         char luksMagic[] = LUKS_MAGIC;
366
367         if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
368                 log_dbg("LUKS header not detected.");
369                 if (require_luks_device)
370                         log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
371                 r = -EINVAL;
372         } else if((hdr->version = ntohs(hdr->version)) != 1) {  /* Convert every uint16/32_t item from network byte order */
373                 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
374                 r = -EINVAL;
375         } else if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
376                 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
377                 r = -EINVAL;
378         } else {
379                 hdr->payloadOffset      = ntohl(hdr->payloadOffset);
380                 hdr->keyBytes           = ntohl(hdr->keyBytes);
381                 hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
382
383                 for(i = 0; i < LUKS_NUMKEYS; ++i) {
384                         hdr->keyblock[i].active             = ntohl(hdr->keyblock[i].active);
385                         hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
386                         hdr->keyblock[i].keyMaterialOffset  = ntohl(hdr->keyblock[i].keyMaterialOffset);
387                         hdr->keyblock[i].stripes            = ntohl(hdr->keyblock[i].stripes);
388                         if (LUKS_check_keyslot_size(hdr, i)) {
389                                 log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
390                                 r = -EINVAL;
391                         }
392                 }
393
394                 /* Avoid unterminated strings */
395                 hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
396                 hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
397                 hdr->uuid[UUID_STRING_L - 1] = '\0';
398 #if 0
399                 if (r == -EINVAL) {
400                         log_err(ctx, _("Repairing keyslots.\n"));
401                         r = _keyslot_repair(device, hdr, ctx);
402                 }
403 #endif
404         }
405
406         return r;
407 }
408
409 static void _to_lower(char *str, unsigned max_len)
410 {
411         for(; *str && max_len; str++, max_len--)
412                 if (isupper(*str))
413                         *str = tolower(*str);
414 }
415
416 static void LUKS_fix_header_compatible(struct luks_phdr *header)
417 {
418         /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
419          * so always convert hash to lower case in header */
420         _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
421 }
422
423 int LUKS_read_phdr_backup(const char *backup_file,
424                           const char *device,
425                           struct luks_phdr *hdr,
426                           int require_luks_device,
427                           struct crypt_device *ctx)
428 {
429         ssize_t hdr_size = sizeof(struct luks_phdr);
430         int devfd = 0, r = 0;
431
432         log_dbg("Reading LUKS header of size %d from backup file %s",
433                 (int)hdr_size, backup_file);
434
435         devfd = open(backup_file, O_RDONLY);
436         if(-1 == devfd) {
437                 log_err(ctx, _("Cannot open file %s.\n"), device);
438                 return -EINVAL;
439         }
440
441         if (read(devfd, hdr, hdr_size) < hdr_size)
442                 r = -EIO;
443         else {
444                 LUKS_fix_header_compatible(hdr);
445                 r = _check_and_convert_hdr(backup_file, hdr, require_luks_device, ctx);
446         }
447
448         close(devfd);
449         return r;
450 }
451
452 int LUKS_read_phdr(const char *device,
453                    struct luks_phdr *hdr,
454                    int require_luks_device,
455                    struct crypt_device *ctx)
456 {
457         ssize_t hdr_size = sizeof(struct luks_phdr);
458         int devfd = 0, r = 0;
459
460         log_dbg("Reading LUKS header of size %d from device %s",
461                 hdr_size, device);
462
463         devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC);
464         if(-1 == devfd) {
465                 log_err(ctx, _("Cannot open device %s.\n"), device);
466                 return -EINVAL;
467         }
468
469         if (read_blockwise(devfd, hdr, hdr_size) < hdr_size)
470                 r = -EIO;
471         else
472                 r = _check_and_convert_hdr(device, hdr, require_luks_device, ctx);
473
474         close(devfd);
475         return r;
476 }
477
478 int LUKS_write_phdr(const char *device,
479                     struct luks_phdr *hdr,
480                     struct crypt_device *ctx)
481 {
482         ssize_t hdr_size = sizeof(struct luks_phdr);
483         int devfd = 0;
484         unsigned int i;
485         struct luks_phdr convHdr;
486         int r;
487
488         log_dbg("Updating LUKS header of size %d on device %s",
489                 sizeof(struct luks_phdr), device);
490
491         if (LUKS_check_device_size(device, hdr->payloadOffset, hdr->keyBytes)) {
492                 log_err(ctx, _("Device %s is too small.\n"), device);
493                 return -EINVAL;
494         }
495
496         devfd = open(device,O_RDWR | O_DIRECT | O_SYNC);
497         if(-1 == devfd) {
498                 log_err(ctx, _("Cannot open device %s.\n"), device);
499                 return -EINVAL;
500         }
501
502         memcpy(&convHdr, hdr, hdr_size);
503         memset(&convHdr._padding, 0, sizeof(convHdr._padding));
504
505         /* Convert every uint16/32_t item to network byte order */
506         convHdr.version            = htons(hdr->version);
507         convHdr.payloadOffset      = htonl(hdr->payloadOffset);
508         convHdr.keyBytes           = htonl(hdr->keyBytes);
509         convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
510         for(i = 0; i < LUKS_NUMKEYS; ++i) {
511                 convHdr.keyblock[i].active             = htonl(hdr->keyblock[i].active);
512                 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
513                 convHdr.keyblock[i].keyMaterialOffset  = htonl(hdr->keyblock[i].keyMaterialOffset);
514                 convHdr.keyblock[i].stripes            = htonl(hdr->keyblock[i].stripes);
515         }
516
517         r = write_blockwise(devfd, &convHdr, hdr_size) < hdr_size ? -EIO : 0;
518         if (r)
519                 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device);
520         close(devfd);
521
522         /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
523         if (!r) {
524                 r = LUKS_read_phdr(device, hdr, 1, ctx);
525                 if (r)
526                         log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device);
527         }
528
529         return r;
530 }
531
532 static int LUKS_PBKDF2_performance_check(const char *hashSpec,
533                                          uint64_t *PBKDF2_per_sec,
534                                          struct crypt_device *ctx)
535 {
536         if (!*PBKDF2_per_sec) {
537                 if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
538                         log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
539                         return -EINVAL;
540                 }
541                 log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
542         }
543
544         return 0;
545 }
546
547 int LUKS_generate_phdr(struct luks_phdr *header,
548                        const struct volume_key *vk,
549                        const char *cipherName, const char *cipherMode, const char *hashSpec,
550                        const char *uuid, unsigned int stripes,
551                        unsigned int alignPayload,
552                        unsigned int alignOffset,
553                        uint32_t iteration_time_ms,
554                        uint64_t *PBKDF2_per_sec,
555                        const char *metadata_device,
556                        struct crypt_device *ctx)
557 {
558         unsigned int i=0;
559         unsigned int blocksPerStripeSet = div_round_up(vk->keylength*stripes,SECTOR_SIZE);
560         int r;
561         uuid_t partitionUuid;
562         int currentSector;
563         char luksMagic[] = LUKS_MAGIC;
564
565         /* For separate metadata device allow zero alignment */
566         if (alignPayload == 0 && !metadata_device)
567                 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
568
569         if (PBKDF2_HMAC_ready(hashSpec) < 0) {
570                 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
571                 return -EINVAL;
572         }
573
574         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
575                 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
576                 return -EINVAL;
577         }
578         if (!uuid)
579                 uuid_generate(partitionUuid);
580
581         memset(header,0,sizeof(struct luks_phdr));
582
583         /* Set Magic */
584         memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
585         header->version=1;
586         strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
587         strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
588         strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
589
590         header->keyBytes=vk->keylength;
591
592         LUKS_fix_header_compatible(header);
593
594         log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
595                 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
596                 header->keyBytes);
597
598         r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_NORMAL);
599         if(r < 0) {
600                 log_err(ctx,  _("Cannot create LUKS header: reading random salt failed.\n"));
601                 return r;
602         }
603
604         if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
605                 return r;
606
607         /* Compute master key digest */
608         iteration_time_ms /= 8;
609         header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
610                                               LUKS_MKD_ITERATIONS_MIN);
611
612         r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength,
613                         header->mkDigestSalt,LUKS_SALTSIZE,
614                         header->mkDigestIterations,
615                         header->mkDigest,LUKS_DIGESTSIZE);
616         if(r < 0) {
617                 log_err(ctx,  _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
618                         header->hashSpec);
619                 return r;
620         }
621
622         currentSector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
623         for(i = 0; i < LUKS_NUMKEYS; ++i) {
624                 header->keyblock[i].active = LUKS_KEY_DISABLED;
625                 header->keyblock[i].keyMaterialOffset = currentSector;
626                 header->keyblock[i].stripes = stripes;
627                 currentSector = round_up_modulo(currentSector + blocksPerStripeSet,
628                                                 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
629         }
630
631         if (metadata_device) {
632                 /* for separate metadata device use alignPayload directly */
633                 header->payloadOffset = alignPayload;
634         } else {
635                 /* alignOffset - offset from natural device alignment provided by topology info */
636                 currentSector = round_up_modulo(currentSector, alignPayload);
637                 header->payloadOffset = currentSector + alignOffset;
638         }
639
640         uuid_unparse(partitionUuid, header->uuid);
641
642         log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
643                 header->payloadOffset, header->uuid, header->mkDigestIterations);
644
645         return 0;
646 }
647
648 int LUKS_hdr_uuid_set(
649         const char *device,
650         struct luks_phdr *hdr,
651         const char *uuid,
652         struct crypt_device *ctx)
653 {
654         uuid_t partitionUuid;
655
656         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
657                 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
658                 return -EINVAL;
659         }
660         if (!uuid)
661                 uuid_generate(partitionUuid);
662
663         uuid_unparse(partitionUuid, hdr->uuid);
664
665         return LUKS_write_phdr(device, hdr, ctx);
666 }
667
668 int LUKS_set_key(const char *device, unsigned int keyIndex,
669                  const char *password, size_t passwordLen,
670                  struct luks_phdr *hdr, struct volume_key *vk,
671                  uint32_t iteration_time_ms,
672                  uint64_t *PBKDF2_per_sec,
673                  struct crypt_device *ctx)
674 {
675         struct volume_key *derived_key;
676         char *AfKey = NULL;
677         unsigned int AFEKSize;
678         uint64_t PBKDF2_temp;
679         int r;
680
681         if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
682                 log_err(ctx,  _("Key slot %d active, purge first.\n"), keyIndex);
683                 return -EINVAL;
684         }
685
686         if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
687                 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
688                         keyIndex);
689                  return -EINVAL;
690         }
691
692         log_dbg("Calculating data for key slot %d", keyIndex);
693
694         if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
695                 return r;
696
697         /*
698          * Avoid floating point operation
699          * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
700          */
701         PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
702         PBKDF2_temp /= 1024;
703         if (PBKDF2_temp > UINT32_MAX)
704                 PBKDF2_temp = UINT32_MAX;
705         hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
706                                                               LUKS_SLOT_ITERATIONS_MIN);
707
708         log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
709
710         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
711         if (!derived_key)
712                 return -ENOMEM;
713
714         r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
715                        LUKS_SALTSIZE, CRYPT_RND_NORMAL);
716         if (r < 0)
717                 return r;
718
719         r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
720                         hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
721                         hdr->keyblock[keyIndex].passwordIterations,
722                         derived_key->key, hdr->keyBytes);
723         if (r < 0)
724                 goto out;
725
726         /*
727          * AF splitting, the masterkey stored in vk->key is split to AfKey
728          */
729         assert(vk->keylength == hdr->keyBytes);
730         AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
731         AfKey = crypt_safe_alloc(AFEKSize);
732         if (!AfKey) {
733                 r = -ENOMEM;
734                 goto out;
735         }
736
737         log_dbg("Using hash %s for AF in key slot %d, %d stripes",
738                 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
739         r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
740         if (r < 0)
741                 goto out;
742
743         log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
744                 hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
745         /* Encryption via dm */
746         r = LUKS_encrypt_to_storage(AfKey,
747                                     AFEKSize,
748                                     hdr,
749                                     derived_key,
750                                     device,
751                                     hdr->keyblock[keyIndex].keyMaterialOffset,
752                                     ctx);
753         if (r < 0) {
754                 log_err(ctx, _("Failed to write to key storage.\n"));
755                 goto out;
756         }
757
758         /* Mark the key as active in phdr */
759         r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
760         if (r < 0)
761                 goto out;
762
763         r = LUKS_write_phdr(device, hdr, ctx);
764         if (r < 0)
765                 goto out;
766
767         r = 0;
768 out:
769         crypt_safe_free(AfKey);
770         crypt_free_volume_key(derived_key);
771         return r;
772 }
773
774 /* Check whether a volume key is invalid. */
775 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
776                            const struct volume_key *vk)
777 {
778         char checkHashBuf[LUKS_DIGESTSIZE];
779
780         if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength,
781                         hdr->mkDigestSalt, LUKS_SALTSIZE,
782                         hdr->mkDigestIterations, checkHashBuf,
783                         LUKS_DIGESTSIZE) < 0)
784                 return -EINVAL;
785
786         if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
787                 return -EPERM;
788
789         return 0;
790 }
791
792 /* Try to open a particular key slot */
793 static int LUKS_open_key(const char *device,
794                   unsigned int keyIndex,
795                   const char *password,
796                   size_t passwordLen,
797                   struct luks_phdr *hdr,
798                   struct volume_key *vk,
799                   struct crypt_device *ctx)
800 {
801         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
802         struct volume_key *derived_key;
803         char *AfKey;
804         size_t AFEKSize;
805         int r;
806
807         log_dbg("Trying to open key slot %d [%s].", keyIndex,
808                 dbg_slot_state(ki));
809
810         if (ki < CRYPT_SLOT_ACTIVE)
811                 return -ENOENT;
812
813         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
814         if (!derived_key)
815                 return -ENOMEM;
816
817         assert(vk->keylength == hdr->keyBytes);
818         AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
819         AfKey = crypt_safe_alloc(AFEKSize);
820         if (!AfKey)
821                 return -ENOMEM;
822
823         r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
824                         hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
825                         hdr->keyblock[keyIndex].passwordIterations,
826                         derived_key->key, hdr->keyBytes);
827         if (r < 0)
828                 goto out;
829
830         log_dbg("Reading key slot %d area.", keyIndex);
831         r = LUKS_decrypt_from_storage(AfKey,
832                                       AFEKSize,
833                                       hdr,
834                                       derived_key,
835                                       device,
836                                       hdr->keyblock[keyIndex].keyMaterialOffset,
837                                       ctx);
838         if (r < 0) {
839                 log_err(ctx, _("Failed to read from key storage.\n"));
840                 goto out;
841         }
842
843         r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
844         if (r < 0)
845                 goto out;
846
847         r = LUKS_verify_volume_key(hdr, vk);
848         if (!r)
849                 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
850 out:
851         crypt_safe_free(AfKey);
852         crypt_free_volume_key(derived_key);
853         return r;
854 }
855
856 int LUKS_open_key_with_hdr(const char *device,
857                            int keyIndex,
858                            const char *password,
859                            size_t passwordLen,
860                            struct luks_phdr *hdr,
861                            struct volume_key **vk,
862                            struct crypt_device *ctx)
863 {
864         unsigned int i;
865         int r;
866
867         *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
868
869         if (keyIndex >= 0) {
870                 r = LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *vk, ctx);
871                 return (r < 0) ? r : keyIndex;
872         }
873
874         for(i = 0; i < LUKS_NUMKEYS; i++) {
875                 r = LUKS_open_key(device, i, password, passwordLen, hdr, *vk, ctx);
876                 if(r == 0)
877                         return i;
878
879                 /* Do not retry for errors that are no -EPERM or -ENOENT,
880                    former meaning password wrong, latter key slot inactive */
881                 if ((r != -EPERM) && (r != -ENOENT))
882                         return r;
883         }
884         /* Warning, early returns above */
885         log_err(ctx, _("No key available with this passphrase.\n"));
886         return -EPERM;
887 }
888
889 int LUKS_del_key(const char *device,
890                  unsigned int keyIndex,
891                  struct luks_phdr *hdr,
892                  struct crypt_device *ctx)
893 {
894         unsigned int startOffset, endOffset, stripesLen;
895         int r;
896
897         r = LUKS_read_phdr(device, hdr, 1, ctx);
898         if (r)
899                 return r;
900
901         r = LUKS_keyslot_set(hdr, keyIndex, 0);
902         if (r) {
903                 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
904                         keyIndex, LUKS_NUMKEYS - 1);
905                 return r;
906         }
907
908         /* secure deletion of key material */
909         startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
910         stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
911         endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
912
913         r = crypt_wipe(device, startOffset * SECTOR_SIZE,
914                        (endOffset - startOffset) * SECTOR_SIZE,
915                        CRYPT_WIPE_DISK, 0);
916         if (r) {
917                 log_err(ctx, _("Cannot wipe device %s.\n"), device);
918                 return r;
919         }
920
921         /* Wipe keyslot info */
922         memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
923         hdr->keyblock[keyIndex].passwordIterations = 0;
924
925         r = LUKS_write_phdr(device, hdr, ctx);
926
927         return r;
928 }
929
930 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
931 {
932         int i;
933
934         if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
935                 return CRYPT_SLOT_INVALID;
936
937         if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
938                 return CRYPT_SLOT_INACTIVE;
939
940         if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
941                 return CRYPT_SLOT_INVALID;
942
943         for(i = 0; i < LUKS_NUMKEYS; i++)
944                 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
945                         return CRYPT_SLOT_ACTIVE;
946
947         return CRYPT_SLOT_ACTIVE_LAST;
948 }
949
950 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
951 {
952         int i;
953
954         for (i = 0; i < LUKS_NUMKEYS; i++)
955                 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
956                         break;
957
958         if (i == LUKS_NUMKEYS)
959                 return -EINVAL;
960
961         return i;
962 }
963
964 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
965 {
966         int i, num = 0;
967
968         for (i = 0; i < LUKS_NUMKEYS; i++)
969                 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
970                         num++;
971
972         return num;
973 }
974
975 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
976 {
977         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
978
979         if (ki == CRYPT_SLOT_INVALID)
980                 return -EINVAL;
981
982         hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
983         log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
984         return 0;
985 }
986
987 int LUKS1_activate(struct crypt_device *cd,
988                    const char *name,
989                    struct volume_key *vk,
990                    uint32_t flags)
991 {
992         int r;
993         char *dm_cipher = NULL;
994         struct crypt_dm_active_device dmd = {
995                 .device = crypt_get_device_name(cd),
996                 .cipher = NULL,
997                 .uuid   = crypt_get_uuid(cd),
998                 .vk    = vk,
999                 .offset = crypt_get_data_offset(cd),
1000                 .iv_offset = 0,
1001                 .size   = 0,
1002                 .flags  = flags
1003         };
1004
1005         r = device_check_and_adjust(cd, dmd.device, DEV_EXCL,
1006                                     &dmd.size, &dmd.offset, &flags);
1007         if (r)
1008                 return r;
1009
1010         r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
1011         if (r < 0)
1012                 return -ENOMEM;
1013
1014         dmd.cipher = dm_cipher;
1015         r = dm_create_device(name, CRYPT_LUKS1, &dmd, 0);
1016
1017         free(dm_cipher);
1018         return r;
1019 }