Fix FSF address in license text according to
[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 _check_and_convert_hdr(const char *device,
300                                   struct luks_phdr *hdr,
301                                   int require_luks_device,
302                                   struct crypt_device *ctx)
303 {
304         int r = 0;
305         unsigned int i;
306         char luksMagic[] = LUKS_MAGIC;
307
308         if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
309                 log_dbg("LUKS header not detected.");
310                 if (require_luks_device)
311                         log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
312                 r = -EINVAL;
313         } else if((hdr->version = ntohs(hdr->version)) != 1) {  /* Convert every uint16/32_t item from network byte order */
314                 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
315                 r = -EINVAL;
316         } else if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
317                 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
318                 r = -EINVAL;
319         } else {
320                 hdr->payloadOffset      = ntohl(hdr->payloadOffset);
321                 hdr->keyBytes           = ntohl(hdr->keyBytes);
322                 hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
323
324                 for(i = 0; i < LUKS_NUMKEYS; ++i) {
325                         hdr->keyblock[i].active             = ntohl(hdr->keyblock[i].active);
326                         hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
327                         hdr->keyblock[i].keyMaterialOffset  = ntohl(hdr->keyblock[i].keyMaterialOffset);
328                         hdr->keyblock[i].stripes            = ntohl(hdr->keyblock[i].stripes);
329                         if (LUKS_check_keyslot_size(hdr, i)) {
330                                 log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
331                                 // FIXME: allow header recovery
332                                 r = -EINVAL;
333                         }
334                 }
335
336                 /* Avoid unterminated strings */
337                 hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
338                 hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
339                 hdr->uuid[UUID_STRING_L - 1] = '\0';
340         }
341
342         return r;
343 }
344
345 static void _to_lower(char *str, unsigned max_len)
346 {
347         for(; *str && max_len; str++, max_len--)
348                 if (isupper(*str))
349                         *str = tolower(*str);
350 }
351
352 static void LUKS_fix_header_compatible(struct luks_phdr *header)
353 {
354         /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
355          * so always convert hash to lower case in header */
356         _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
357 }
358
359 int LUKS_read_phdr_backup(const char *backup_file,
360                           const char *device,
361                           struct luks_phdr *hdr,
362                           int require_luks_device,
363                           struct crypt_device *ctx)
364 {
365         ssize_t hdr_size = sizeof(struct luks_phdr);
366         int devfd = 0, r = 0;
367
368         log_dbg("Reading LUKS header of size %d from backup file %s",
369                 (int)hdr_size, backup_file);
370
371         devfd = open(backup_file, O_RDONLY);
372         if(-1 == devfd) {
373                 log_err(ctx, _("Cannot open file %s.\n"), device);
374                 return -EINVAL;
375         }
376
377         if (read(devfd, hdr, hdr_size) < hdr_size)
378                 r = -EIO;
379         else {
380                 LUKS_fix_header_compatible(hdr);
381                 r = _check_and_convert_hdr(backup_file, hdr, require_luks_device, ctx);
382         }
383
384         close(devfd);
385         return r;
386 }
387
388 int LUKS_read_phdr(const char *device,
389                    struct luks_phdr *hdr,
390                    int require_luks_device,
391                    struct crypt_device *ctx)
392 {
393         ssize_t hdr_size = sizeof(struct luks_phdr);
394         int devfd = 0, r = 0;
395
396         log_dbg("Reading LUKS header of size %d from device %s",
397                 hdr_size, device);
398
399         devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC);
400         if(-1 == devfd) {
401                 log_err(ctx, _("Cannot open device %s.\n"), device);
402                 return -EINVAL;
403         }
404
405         if (read_blockwise(devfd, hdr, hdr_size) < hdr_size)
406                 r = -EIO;
407         else
408                 r = _check_and_convert_hdr(device, hdr, require_luks_device, ctx);
409
410         close(devfd);
411         return r;
412 }
413
414 int LUKS_write_phdr(const char *device,
415                     struct luks_phdr *hdr,
416                     struct crypt_device *ctx)
417 {
418         ssize_t hdr_size = sizeof(struct luks_phdr);
419         int devfd = 0;
420         unsigned int i;
421         struct luks_phdr convHdr;
422         int r;
423
424         log_dbg("Updating LUKS header of size %d on device %s",
425                 sizeof(struct luks_phdr), device);
426
427         if (LUKS_check_device_size(device, hdr->payloadOffset, hdr->keyBytes)) {
428                 log_err(ctx, _("Device %s is too small.\n"), device);
429                 return -EINVAL;
430         }
431
432         devfd = open(device,O_RDWR | O_DIRECT | O_SYNC);
433         if(-1 == devfd) {
434                 log_err(ctx, _("Cannot open device %s.\n"), device);
435                 return -EINVAL;
436         }
437
438         memcpy(&convHdr, hdr, hdr_size);
439         memset(&convHdr._padding, 0, sizeof(convHdr._padding));
440
441         /* Convert every uint16/32_t item to network byte order */
442         convHdr.version            = htons(hdr->version);
443         convHdr.payloadOffset      = htonl(hdr->payloadOffset);
444         convHdr.keyBytes           = htonl(hdr->keyBytes);
445         convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
446         for(i = 0; i < LUKS_NUMKEYS; ++i) {
447                 convHdr.keyblock[i].active             = htonl(hdr->keyblock[i].active);
448                 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
449                 convHdr.keyblock[i].keyMaterialOffset  = htonl(hdr->keyblock[i].keyMaterialOffset);
450                 convHdr.keyblock[i].stripes            = htonl(hdr->keyblock[i].stripes);
451         }
452
453         r = write_blockwise(devfd, &convHdr, hdr_size) < hdr_size ? -EIO : 0;
454         if (r)
455                 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device);
456         close(devfd);
457
458         /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
459         if (!r) {
460                 r = LUKS_read_phdr(device, hdr, 1, ctx);
461                 if (r)
462                         log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device);
463         }
464
465         return r;
466 }
467
468 static int LUKS_PBKDF2_performance_check(const char *hashSpec,
469                                          uint64_t *PBKDF2_per_sec,
470                                          struct crypt_device *ctx)
471 {
472         if (!*PBKDF2_per_sec) {
473                 if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
474                         log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
475                         return -EINVAL;
476                 }
477                 log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
478         }
479
480         return 0;
481 }
482
483 int LUKS_generate_phdr(struct luks_phdr *header,
484                        const struct volume_key *vk,
485                        const char *cipherName, const char *cipherMode, const char *hashSpec,
486                        const char *uuid, unsigned int stripes,
487                        unsigned int alignPayload,
488                        unsigned int alignOffset,
489                        uint32_t iteration_time_ms,
490                        uint64_t *PBKDF2_per_sec,
491                        const char *metadata_device,
492                        struct crypt_device *ctx)
493 {
494         unsigned int i=0;
495         unsigned int blocksPerStripeSet = div_round_up(vk->keylength*stripes,SECTOR_SIZE);
496         int r;
497         uuid_t partitionUuid;
498         int currentSector;
499         char luksMagic[] = LUKS_MAGIC;
500
501         /* For separate metadata device allow zero alignment */
502         if (alignPayload == 0 && !metadata_device)
503                 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
504
505         if (PBKDF2_HMAC_ready(hashSpec) < 0) {
506                 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
507                 return -EINVAL;
508         }
509
510         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
511                 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
512                 return -EINVAL;
513         }
514         if (!uuid)
515                 uuid_generate(partitionUuid);
516
517         memset(header,0,sizeof(struct luks_phdr));
518
519         /* Set Magic */
520         memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
521         header->version=1;
522         strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
523         strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
524         strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
525
526         header->keyBytes=vk->keylength;
527
528         LUKS_fix_header_compatible(header);
529
530         log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
531                 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
532                 header->keyBytes);
533
534         r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_NORMAL);
535         if(r < 0) {
536                 log_err(ctx,  _("Cannot create LUKS header: reading random salt failed.\n"));
537                 return r;
538         }
539
540         if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
541                 return r;
542
543         /* Compute master key digest */
544         iteration_time_ms /= 8;
545         header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
546                                               LUKS_MKD_ITERATIONS_MIN);
547
548         r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength,
549                         header->mkDigestSalt,LUKS_SALTSIZE,
550                         header->mkDigestIterations,
551                         header->mkDigest,LUKS_DIGESTSIZE);
552         if(r < 0) {
553                 log_err(ctx,  _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
554                         header->hashSpec);
555                 return r;
556         }
557
558         currentSector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
559         for(i = 0; i < LUKS_NUMKEYS; ++i) {
560                 header->keyblock[i].active = LUKS_KEY_DISABLED;
561                 header->keyblock[i].keyMaterialOffset = currentSector;
562                 header->keyblock[i].stripes = stripes;
563                 currentSector = round_up_modulo(currentSector + blocksPerStripeSet,
564                                                 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
565         }
566
567         if (metadata_device) {
568                 /* for separate metadata device use alignPayload directly */
569                 header->payloadOffset = alignPayload;
570         } else {
571                 /* alignOffset - offset from natural device alignment provided by topology info */
572                 currentSector = round_up_modulo(currentSector, alignPayload);
573                 header->payloadOffset = currentSector + alignOffset;
574         }
575
576         uuid_unparse(partitionUuid, header->uuid);
577
578         log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
579                 header->payloadOffset, header->uuid, header->mkDigestIterations);
580
581         return 0;
582 }
583
584 int LUKS_hdr_uuid_set(
585         const char *device,
586         struct luks_phdr *hdr,
587         const char *uuid,
588         struct crypt_device *ctx)
589 {
590         uuid_t partitionUuid;
591
592         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
593                 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
594                 return -EINVAL;
595         }
596         if (!uuid)
597                 uuid_generate(partitionUuid);
598
599         uuid_unparse(partitionUuid, hdr->uuid);
600
601         return LUKS_write_phdr(device, hdr, ctx);
602 }
603
604 int LUKS_set_key(const char *device, unsigned int keyIndex,
605                  const char *password, size_t passwordLen,
606                  struct luks_phdr *hdr, struct volume_key *vk,
607                  uint32_t iteration_time_ms,
608                  uint64_t *PBKDF2_per_sec,
609                  struct crypt_device *ctx)
610 {
611         struct volume_key *derived_key;
612         char *AfKey = NULL;
613         unsigned int AFEKSize;
614         uint64_t PBKDF2_temp;
615         int r;
616
617         if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
618                 log_err(ctx,  _("Key slot %d active, purge first.\n"), keyIndex);
619                 return -EINVAL;
620         }
621
622         if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
623                 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
624                         keyIndex);
625                  return -EINVAL;
626         }
627
628         log_dbg("Calculating data for key slot %d", keyIndex);
629
630         if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
631                 return r;
632
633         /*
634          * Avoid floating point operation
635          * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
636          */
637         PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
638         PBKDF2_temp /= 1024;
639         if (PBKDF2_temp > UINT32_MAX)
640                 PBKDF2_temp = UINT32_MAX;
641         hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
642                                                               LUKS_SLOT_ITERATIONS_MIN);
643
644         log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
645
646         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
647         if (!derived_key)
648                 return -ENOMEM;
649
650         r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
651                        LUKS_SALTSIZE, CRYPT_RND_NORMAL);
652         if (r < 0)
653                 return r;
654
655         r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
656                         hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
657                         hdr->keyblock[keyIndex].passwordIterations,
658                         derived_key->key, hdr->keyBytes);
659         if (r < 0)
660                 goto out;
661
662         /*
663          * AF splitting, the masterkey stored in vk->key is split to AfKey
664          */
665         assert(vk->keylength == hdr->keyBytes);
666         AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
667         AfKey = crypt_safe_alloc(AFEKSize);
668         if (!AfKey) {
669                 r = -ENOMEM;
670                 goto out;
671         }
672
673         log_dbg("Using hash %s for AF in key slot %d, %d stripes",
674                 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
675         r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
676         if (r < 0)
677                 goto out;
678
679         log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
680                 hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
681         /* Encryption via dm */
682         r = LUKS_encrypt_to_storage(AfKey,
683                                     AFEKSize,
684                                     hdr,
685                                     derived_key,
686                                     device,
687                                     hdr->keyblock[keyIndex].keyMaterialOffset,
688                                     ctx);
689         if (r < 0) {
690                 log_err(ctx, _("Failed to write to key storage.\n"));
691                 goto out;
692         }
693
694         /* Mark the key as active in phdr */
695         r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
696         if (r < 0)
697                 goto out;
698
699         r = LUKS_write_phdr(device, hdr, ctx);
700         if (r < 0)
701                 goto out;
702
703         r = 0;
704 out:
705         crypt_safe_free(AfKey);
706         crypt_free_volume_key(derived_key);
707         return r;
708 }
709
710 /* Check whether a volume key is invalid. */
711 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
712                            const struct volume_key *vk)
713 {
714         char checkHashBuf[LUKS_DIGESTSIZE];
715
716         if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength,
717                         hdr->mkDigestSalt, LUKS_SALTSIZE,
718                         hdr->mkDigestIterations, checkHashBuf,
719                         LUKS_DIGESTSIZE) < 0)
720                 return -EINVAL;
721
722         if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
723                 return -EPERM;
724
725         return 0;
726 }
727
728 /* Try to open a particular key slot */
729 static int LUKS_open_key(const char *device,
730                   unsigned int keyIndex,
731                   const char *password,
732                   size_t passwordLen,
733                   struct luks_phdr *hdr,
734                   struct volume_key *vk,
735                   struct crypt_device *ctx)
736 {
737         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
738         struct volume_key *derived_key;
739         char *AfKey;
740         size_t AFEKSize;
741         int r;
742
743         log_dbg("Trying to open key slot %d [%s].", keyIndex,
744                 dbg_slot_state(ki));
745
746         if (ki < CRYPT_SLOT_ACTIVE)
747                 return -ENOENT;
748
749         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
750         if (!derived_key)
751                 return -ENOMEM;
752
753         assert(vk->keylength == hdr->keyBytes);
754         AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
755         AfKey = crypt_safe_alloc(AFEKSize);
756         if (!AfKey)
757                 return -ENOMEM;
758
759         r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
760                         hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
761                         hdr->keyblock[keyIndex].passwordIterations,
762                         derived_key->key, hdr->keyBytes);
763         if (r < 0)
764                 goto out;
765
766         log_dbg("Reading key slot %d area.", keyIndex);
767         r = LUKS_decrypt_from_storage(AfKey,
768                                       AFEKSize,
769                                       hdr,
770                                       derived_key,
771                                       device,
772                                       hdr->keyblock[keyIndex].keyMaterialOffset,
773                                       ctx);
774         if (r < 0) {
775                 log_err(ctx, _("Failed to read from key storage.\n"));
776                 goto out;
777         }
778
779         r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
780         if (r < 0)
781                 goto out;
782
783         r = LUKS_verify_volume_key(hdr, vk);
784         if (!r)
785                 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
786 out:
787         crypt_safe_free(AfKey);
788         crypt_free_volume_key(derived_key);
789         return r;
790 }
791
792 int LUKS_open_key_with_hdr(const char *device,
793                            int keyIndex,
794                            const char *password,
795                            size_t passwordLen,
796                            struct luks_phdr *hdr,
797                            struct volume_key **vk,
798                            struct crypt_device *ctx)
799 {
800         unsigned int i;
801         int r;
802
803         *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
804
805         if (keyIndex >= 0) {
806                 r = LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *vk, ctx);
807                 return (r < 0) ? r : keyIndex;
808         }
809
810         for(i = 0; i < LUKS_NUMKEYS; i++) {
811                 r = LUKS_open_key(device, i, password, passwordLen, hdr, *vk, ctx);
812                 if(r == 0)
813                         return i;
814
815                 /* Do not retry for errors that are no -EPERM or -ENOENT,
816                    former meaning password wrong, latter key slot inactive */
817                 if ((r != -EPERM) && (r != -ENOENT))
818                         return r;
819         }
820         /* Warning, early returns above */
821         log_err(ctx, _("No key available with this passphrase.\n"));
822         return -EPERM;
823 }
824
825 int LUKS_del_key(const char *device,
826                  unsigned int keyIndex,
827                  struct luks_phdr *hdr,
828                  struct crypt_device *ctx)
829 {
830         unsigned int startOffset, endOffset, stripesLen;
831         int r;
832
833         r = LUKS_read_phdr(device, hdr, 1, ctx);
834         if (r)
835                 return r;
836
837         r = LUKS_keyslot_set(hdr, keyIndex, 0);
838         if (r) {
839                 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
840                         keyIndex, LUKS_NUMKEYS - 1);
841                 return r;
842         }
843
844         /* secure deletion of key material */
845         startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
846         stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
847         endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
848
849         r = crypt_wipe(device, startOffset * SECTOR_SIZE,
850                        (endOffset - startOffset) * SECTOR_SIZE,
851                        CRYPT_WIPE_DISK, 0);
852         if (r) {
853                 log_err(ctx, _("Cannot wipe device %s.\n"), device);
854                 return r;
855         }
856
857         /* Wipe keyslot info */
858         memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
859         hdr->keyblock[keyIndex].passwordIterations = 0;
860
861         r = LUKS_write_phdr(device, hdr, ctx);
862
863         return r;
864 }
865
866 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
867 {
868         int i;
869
870         if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
871                 return CRYPT_SLOT_INVALID;
872
873         if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
874                 return CRYPT_SLOT_INACTIVE;
875
876         if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
877                 return CRYPT_SLOT_INVALID;
878
879         for(i = 0; i < LUKS_NUMKEYS; i++)
880                 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
881                         return CRYPT_SLOT_ACTIVE;
882
883         return CRYPT_SLOT_ACTIVE_LAST;
884 }
885
886 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
887 {
888         int i;
889
890         for (i = 0; i < LUKS_NUMKEYS; i++)
891                 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
892                         break;
893
894         if (i == LUKS_NUMKEYS)
895                 return -EINVAL;
896
897         return i;
898 }
899
900 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
901 {
902         int i, num = 0;
903
904         for (i = 0; i < LUKS_NUMKEYS; i++)
905                 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
906                         num++;
907
908         return num;
909 }
910
911 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
912 {
913         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
914
915         if (ki == CRYPT_SLOT_INVALID)
916                 return -EINVAL;
917
918         hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
919         log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
920         return 0;
921 }
922
923 int LUKS1_activate(struct crypt_device *cd,
924                    const char *name,
925                    struct volume_key *vk,
926                    uint32_t flags)
927 {
928         int r;
929         char *dm_cipher = NULL;
930         struct crypt_dm_active_device dmd = {
931                 .device = crypt_get_device_name(cd),
932                 .cipher = NULL,
933                 .uuid   = crypt_get_uuid(cd),
934                 .vk    = vk,
935                 .offset = crypt_get_data_offset(cd),
936                 .iv_offset = 0,
937                 .size   = 0,
938                 .flags  = flags
939         };
940
941         r = device_check_and_adjust(cd, dmd.device, DEV_EXCL,
942                                     &dmd.size, &dmd.offset, &flags);
943         if (r)
944                 return r;
945
946         r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
947         if (r < 0)
948                 return -ENOMEM;
949
950         dmd.cipher = dm_cipher;
951         r = dm_create_device(name, CRYPT_LUKS1, &dmd, 0);
952
953         free(dm_cipher);
954         return r;
955 }