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