Avoid some clang warnings.
[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         if (!r)
222                 buffer_size = hdr_file.payloadOffset << SECTOR_SHIFT;
223
224         if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
225                 log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
226                 r = -EINVAL;
227                 goto out;
228         }
229
230         buffer = crypt_safe_alloc(buffer_size);
231         if (!buffer) {
232                 r = -ENOMEM;
233                 goto out;
234         }
235
236         devfd = open(backup_file, O_RDONLY);
237         if(devfd == -1) {
238                 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
239                 r = -EINVAL;
240                 goto out;
241         }
242
243         if(read(devfd, buffer, buffer_size) < buffer_size) {
244                 log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
245                 r = -EIO;
246                 goto out;
247         }
248         close(devfd);
249
250         r = LUKS_read_phdr(device, hdr, 0, 0, ctx);
251         if (r == 0) {
252                 log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device);
253                 if(hdr->payloadOffset != hdr_file.payloadOffset ||
254                    hdr->keyBytes != hdr_file.keyBytes) {
255                         log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
256                         r = -EINVAL;
257                         goto out;
258                 }
259                 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
260                         diff_uuid = 1;
261         }
262
263         if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device,
264                  r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
265                      _("already contains LUKS header. Replacing header will destroy existing keyslots."),
266                      diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
267                 r = -ENOMEM;
268                 goto out;
269         }
270
271         if (!crypt_confirm(ctx, msg)) {
272                 r = -EINVAL;
273                 goto out;
274         }
275
276         log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
277                 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device);
278
279         devfd = open(device, O_WRONLY | O_DIRECT | O_SYNC);
280         if(devfd == -1) {
281                 log_err(ctx, _("Cannot open device %s.\n"), device);
282                 r = -EINVAL;
283                 goto out;
284         }
285
286         if(write_blockwise(devfd, buffer, buffer_size) < buffer_size) {
287                 r = -EIO;
288                 goto out;
289         }
290         close(devfd);
291
292         /* Be sure to reload new data */
293         r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
294 out:
295         if (devfd != -1)
296                 close(devfd);
297         crypt_safe_free(buffer);
298         return r;
299 }
300
301 /* This routine should do some just basic recovery for known problems. */
302 static int _keyslot_repair(const char *device, struct luks_phdr *phdr, struct crypt_device *ctx)
303 {
304         struct luks_phdr temp_phdr;
305         const unsigned char *sector = (const unsigned char*)phdr;
306         struct volume_key *vk;
307         uint64_t PBKDF2_per_sec = 1;
308         int i, bad, r, need_write = 0;
309
310         if (phdr->keyBytes != 16 && phdr->keyBytes != 32) {
311                 log_err(ctx, _("Non standard key size, manual repair required.\n"));
312                 return -EINVAL;
313         }
314         /* cryptsetup 1.0 did not align to 4k, cannot repair this one */
315         if (phdr->keyblock[0].keyMaterialOffset < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
316                 log_err(ctx, _("Non standard keyslots alignment, manual repair required.\n"));
317                 return -EINVAL;
318         }
319
320         vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
321
322         log_verbose(ctx, _("Repairing keyslots.\n"));
323
324         log_dbg("Generating second header with the same parameters for check.");
325         /* cipherName, cipherMode, hashSpec, uuid are already null terminated */
326         /* payloadOffset - cannot check */
327         r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
328                                phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
329                                phdr->payloadOffset, 0,
330                                1, &PBKDF2_per_sec,
331                                "/dev/null", ctx);
332         if (r < 0) {
333                 log_err(ctx, _("Repair failed."));
334                 goto out;
335         }
336
337         for(i = 0; i < LUKS_NUMKEYS; ++i) {
338                 if (phdr->keyblock[i].active == LUKS_KEY_ENABLED)  {
339                         log_dbg("Skipping repair for active keyslot %i.", i);
340                         continue;
341                 }
342
343                 bad = 0;
344                 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
345                         log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
346                                 (unsigned)phdr->keyblock[i].keyMaterialOffset,
347                                 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
348                         phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
349                         bad = 1;
350                 }
351
352                 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
353                         log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
354                                 (unsigned)phdr->keyblock[i].stripes,
355                                 (unsigned)temp_phdr.keyblock[i].stripes);
356                         phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
357                         bad = 1;
358                 }
359
360                 /* Known case - MSDOS partition table signature */
361                 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
362                         log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
363                         bad = 1;
364                 }
365
366                 if(bad) {
367                         log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
368                         phdr->keyblock[i].active = LUKS_KEY_DISABLED;
369                         memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
370                         phdr->keyblock[i].passwordIterations = 0;
371                 }
372
373                 if (bad)
374                         need_write = 1;
375         }
376
377         if (need_write) {
378                 log_verbose(ctx, _("Writing LUKS header to disk.\n"));
379                 r = LUKS_write_phdr(device, phdr, ctx);
380         }
381 out:
382         crypt_free_volume_key(vk);
383         memset(&temp_phdr, 0, sizeof(temp_phdr));
384         return r;
385 }
386
387 static int _check_and_convert_hdr(const char *device,
388                                   struct luks_phdr *hdr,
389                                   int require_luks_device,
390                                   int repair,
391                                   struct crypt_device *ctx)
392 {
393         int r = 0;
394         unsigned int i;
395         char luksMagic[] = LUKS_MAGIC;
396
397         if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
398                 log_dbg("LUKS header not detected.");
399                 if (require_luks_device)
400                         log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
401                 return -EINVAL;
402         } else if((hdr->version = ntohs(hdr->version)) != 1) {  /* Convert every uint16/32_t item from network byte order */
403                 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
404                 return -EINVAL;
405         }
406
407         hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
408         if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
409                 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
410                 return -EINVAL;
411         }
412
413         /* Header detected */
414         hdr->payloadOffset      = ntohl(hdr->payloadOffset);
415         hdr->keyBytes           = ntohl(hdr->keyBytes);
416         hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
417
418         for(i = 0; i < LUKS_NUMKEYS; ++i) {
419                 hdr->keyblock[i].active             = ntohl(hdr->keyblock[i].active);
420                 hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
421                 hdr->keyblock[i].keyMaterialOffset  = ntohl(hdr->keyblock[i].keyMaterialOffset);
422                 hdr->keyblock[i].stripes            = ntohl(hdr->keyblock[i].stripes);
423                 if (LUKS_check_keyslot_size(hdr, i)) {
424                         log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
425                         r = -EINVAL;
426                 }
427         }
428
429         /* Avoid unterminated strings */
430         hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
431         hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
432         hdr->uuid[UUID_STRING_L - 1] = '\0';
433
434         if (repair) {
435                 if (r == -EINVAL)
436                         r = _keyslot_repair(device, hdr, ctx);
437                 else
438                         log_verbose(ctx, _("No known problems detected for LUKS header.\n"));
439         }
440
441         return r;
442 }
443
444 static void _to_lower(char *str, unsigned max_len)
445 {
446         for(; *str && max_len; str++, max_len--)
447                 if (isupper(*str))
448                         *str = tolower(*str);
449 }
450
451 static void LUKS_fix_header_compatible(struct luks_phdr *header)
452 {
453         /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
454          * so always convert hash to lower case in header */
455         _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
456 }
457
458 int LUKS_read_phdr_backup(const char *backup_file,
459                           const char *device,
460                           struct luks_phdr *hdr,
461                           int require_luks_device,
462                           struct crypt_device *ctx)
463 {
464         ssize_t hdr_size = sizeof(struct luks_phdr);
465         int devfd = 0, r = 0;
466
467         log_dbg("Reading LUKS header of size %d from backup file %s",
468                 (int)hdr_size, backup_file);
469
470         devfd = open(backup_file, O_RDONLY);
471         if(-1 == devfd) {
472                 log_err(ctx, _("Cannot open file %s.\n"), device);
473                 return -EINVAL;
474         }
475
476         if (read(devfd, hdr, hdr_size) < hdr_size)
477                 r = -EIO;
478         else {
479                 LUKS_fix_header_compatible(hdr);
480                 r = _check_and_convert_hdr(backup_file, hdr,
481                                            require_luks_device, 0, ctx);
482         }
483
484         close(devfd);
485         return r;
486 }
487
488 int LUKS_read_phdr(const char *device,
489                    struct luks_phdr *hdr,
490                    int require_luks_device,
491                    int repair,
492                    struct crypt_device *ctx)
493 {
494         ssize_t hdr_size = sizeof(struct luks_phdr);
495         int devfd = 0, r = 0;
496
497         if (repair && !require_luks_device)
498                 return -EINVAL;
499
500         log_dbg("Reading LUKS header of size %d from device %s",
501                 hdr_size, device);
502
503         devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC);
504         if(-1 == devfd) {
505                 log_err(ctx, _("Cannot open device %s.\n"), device);
506                 return -EINVAL;
507         }
508
509         if (read_blockwise(devfd, hdr, hdr_size) < hdr_size)
510                 r = -EIO;
511         else
512                 r = _check_and_convert_hdr(device, hdr, require_luks_device,
513                                            repair, ctx);
514
515         close(devfd);
516         return r;
517 }
518
519 int LUKS_write_phdr(const char *device,
520                     struct luks_phdr *hdr,
521                     struct crypt_device *ctx)
522 {
523         ssize_t hdr_size = sizeof(struct luks_phdr);
524         int devfd = 0;
525         unsigned int i;
526         struct luks_phdr convHdr;
527         int r;
528
529         log_dbg("Updating LUKS header of size %d on device %s",
530                 sizeof(struct luks_phdr), device);
531
532         if (LUKS_check_device_size(device, hdr->payloadOffset, hdr->keyBytes)) {
533                 log_err(ctx, _("Device %s is too small.\n"), device);
534                 return -EINVAL;
535         }
536
537         devfd = open(device,O_RDWR | O_DIRECT | O_SYNC);
538         if(-1 == devfd) {
539                 log_err(ctx, _("Cannot open device %s.\n"), device);
540                 return -EINVAL;
541         }
542
543         memcpy(&convHdr, hdr, hdr_size);
544         memset(&convHdr._padding, 0, sizeof(convHdr._padding));
545
546         /* Convert every uint16/32_t item to network byte order */
547         convHdr.version            = htons(hdr->version);
548         convHdr.payloadOffset      = htonl(hdr->payloadOffset);
549         convHdr.keyBytes           = htonl(hdr->keyBytes);
550         convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
551         for(i = 0; i < LUKS_NUMKEYS; ++i) {
552                 convHdr.keyblock[i].active             = htonl(hdr->keyblock[i].active);
553                 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
554                 convHdr.keyblock[i].keyMaterialOffset  = htonl(hdr->keyblock[i].keyMaterialOffset);
555                 convHdr.keyblock[i].stripes            = htonl(hdr->keyblock[i].stripes);
556         }
557
558         r = write_blockwise(devfd, &convHdr, hdr_size) < hdr_size ? -EIO : 0;
559         if (r)
560                 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device);
561         close(devfd);
562
563         /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
564         if (!r) {
565                 r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
566                 if (r)
567                         log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device);
568         }
569
570         return r;
571 }
572
573 static int LUKS_PBKDF2_performance_check(const char *hashSpec,
574                                          uint64_t *PBKDF2_per_sec,
575                                          struct crypt_device *ctx)
576 {
577         if (!*PBKDF2_per_sec) {
578                 if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
579                         log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
580                         return -EINVAL;
581                 }
582                 log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
583         }
584
585         return 0;
586 }
587
588 int LUKS_generate_phdr(struct luks_phdr *header,
589                        const struct volume_key *vk,
590                        const char *cipherName, const char *cipherMode, const char *hashSpec,
591                        const char *uuid, unsigned int stripes,
592                        unsigned int alignPayload,
593                        unsigned int alignOffset,
594                        uint32_t iteration_time_ms,
595                        uint64_t *PBKDF2_per_sec,
596                        const char *metadata_device,
597                        struct crypt_device *ctx)
598 {
599         unsigned int i=0;
600         unsigned int blocksPerStripeSet = div_round_up(vk->keylength*stripes,SECTOR_SIZE);
601         int r;
602         uuid_t partitionUuid;
603         int currentSector;
604         char luksMagic[] = LUKS_MAGIC;
605
606         /* For separate metadata device allow zero alignment */
607         if (alignPayload == 0 && !metadata_device)
608                 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
609
610         if (PBKDF2_HMAC_ready(hashSpec) < 0) {
611                 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
612                 return -EINVAL;
613         }
614
615         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
616                 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
617                 return -EINVAL;
618         }
619         if (!uuid)
620                 uuid_generate(partitionUuid);
621
622         memset(header,0,sizeof(struct luks_phdr));
623
624         /* Set Magic */
625         memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
626         header->version=1;
627         strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
628         strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
629         strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
630
631         header->keyBytes=vk->keylength;
632
633         LUKS_fix_header_compatible(header);
634
635         log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
636                 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
637                 header->keyBytes);
638
639         r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
640         if(r < 0) {
641                 log_err(ctx,  _("Cannot create LUKS header: reading random salt failed.\n"));
642                 return r;
643         }
644
645         if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
646                 return r;
647
648         /* Compute master key digest */
649         iteration_time_ms /= 8;
650         header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
651                                               LUKS_MKD_ITERATIONS_MIN);
652
653         r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength,
654                         header->mkDigestSalt,LUKS_SALTSIZE,
655                         header->mkDigestIterations,
656                         header->mkDigest,LUKS_DIGESTSIZE);
657         if(r < 0) {
658                 log_err(ctx,  _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
659                         header->hashSpec);
660                 return r;
661         }
662
663         currentSector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
664         for(i = 0; i < LUKS_NUMKEYS; ++i) {
665                 header->keyblock[i].active = LUKS_KEY_DISABLED;
666                 header->keyblock[i].keyMaterialOffset = currentSector;
667                 header->keyblock[i].stripes = stripes;
668                 currentSector = round_up_modulo(currentSector + blocksPerStripeSet,
669                                                 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
670         }
671
672         if (metadata_device) {
673                 /* for separate metadata device use alignPayload directly */
674                 header->payloadOffset = alignPayload;
675         } else {
676                 /* alignOffset - offset from natural device alignment provided by topology info */
677                 currentSector = round_up_modulo(currentSector, alignPayload);
678                 header->payloadOffset = currentSector + alignOffset;
679         }
680
681         uuid_unparse(partitionUuid, header->uuid);
682
683         log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
684                 header->payloadOffset, header->uuid, header->mkDigestIterations);
685
686         return 0;
687 }
688
689 int LUKS_hdr_uuid_set(
690         const char *device,
691         struct luks_phdr *hdr,
692         const char *uuid,
693         struct crypt_device *ctx)
694 {
695         uuid_t partitionUuid;
696
697         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
698                 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
699                 return -EINVAL;
700         }
701         if (!uuid)
702                 uuid_generate(partitionUuid);
703
704         uuid_unparse(partitionUuid, hdr->uuid);
705
706         return LUKS_write_phdr(device, hdr, ctx);
707 }
708
709 int LUKS_set_key(const char *device, unsigned int keyIndex,
710                  const char *password, size_t passwordLen,
711                  struct luks_phdr *hdr, struct volume_key *vk,
712                  uint32_t iteration_time_ms,
713                  uint64_t *PBKDF2_per_sec,
714                  struct crypt_device *ctx)
715 {
716         struct volume_key *derived_key;
717         char *AfKey = NULL;
718         unsigned int AFEKSize;
719         uint64_t PBKDF2_temp;
720         int r;
721
722         if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
723                 log_err(ctx,  _("Key slot %d active, purge first.\n"), keyIndex);
724                 return -EINVAL;
725         }
726
727         if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
728                 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
729                         keyIndex);
730                  return -EINVAL;
731         }
732
733         log_dbg("Calculating data for key slot %d", keyIndex);
734
735         if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
736                 return r;
737
738         /*
739          * Avoid floating point operation
740          * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
741          */
742         PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
743         PBKDF2_temp /= 1024;
744         if (PBKDF2_temp > UINT32_MAX)
745                 PBKDF2_temp = UINT32_MAX;
746         hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
747                                                               LUKS_SLOT_ITERATIONS_MIN);
748
749         log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
750
751         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
752         if (!derived_key)
753                 return -ENOMEM;
754
755         r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
756                        LUKS_SALTSIZE, CRYPT_RND_SALT);
757         if (r < 0)
758                 return r;
759
760         r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
761                         hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
762                         hdr->keyblock[keyIndex].passwordIterations,
763                         derived_key->key, hdr->keyBytes);
764         if (r < 0)
765                 goto out;
766
767         /*
768          * AF splitting, the masterkey stored in vk->key is split to AfKey
769          */
770         assert(vk->keylength == hdr->keyBytes);
771         AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
772         AfKey = crypt_safe_alloc(AFEKSize);
773         if (!AfKey) {
774                 r = -ENOMEM;
775                 goto out;
776         }
777
778         log_dbg("Using hash %s for AF in key slot %d, %d stripes",
779                 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
780         r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
781         if (r < 0)
782                 goto out;
783
784         log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
785                 hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
786         /* Encryption via dm */
787         r = LUKS_encrypt_to_storage(AfKey,
788                                     AFEKSize,
789                                     hdr,
790                                     derived_key,
791                                     device,
792                                     hdr->keyblock[keyIndex].keyMaterialOffset,
793                                     ctx);
794         if (r < 0) {
795                 log_err(ctx, _("Failed to write to key storage.\n"));
796                 goto out;
797         }
798
799         /* Mark the key as active in phdr */
800         r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
801         if (r < 0)
802                 goto out;
803
804         r = LUKS_write_phdr(device, hdr, ctx);
805         if (r < 0)
806                 goto out;
807
808         r = 0;
809 out:
810         crypt_safe_free(AfKey);
811         crypt_free_volume_key(derived_key);
812         return r;
813 }
814
815 /* Check whether a volume key is invalid. */
816 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
817                            const struct volume_key *vk)
818 {
819         char checkHashBuf[LUKS_DIGESTSIZE];
820
821         if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength,
822                         hdr->mkDigestSalt, LUKS_SALTSIZE,
823                         hdr->mkDigestIterations, checkHashBuf,
824                         LUKS_DIGESTSIZE) < 0)
825                 return -EINVAL;
826
827         if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
828                 return -EPERM;
829
830         return 0;
831 }
832
833 /* Try to open a particular key slot */
834 static int LUKS_open_key(const char *device,
835                   unsigned int keyIndex,
836                   const char *password,
837                   size_t passwordLen,
838                   struct luks_phdr *hdr,
839                   struct volume_key *vk,
840                   struct crypt_device *ctx)
841 {
842         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
843         struct volume_key *derived_key;
844         char *AfKey;
845         size_t AFEKSize;
846         int r;
847
848         log_dbg("Trying to open key slot %d [%s].", keyIndex,
849                 dbg_slot_state(ki));
850
851         if (ki < CRYPT_SLOT_ACTIVE)
852                 return -ENOENT;
853
854         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
855         if (!derived_key)
856                 return -ENOMEM;
857
858         assert(vk->keylength == hdr->keyBytes);
859         AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
860         AfKey = crypt_safe_alloc(AFEKSize);
861         if (!AfKey)
862                 return -ENOMEM;
863
864         r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
865                         hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
866                         hdr->keyblock[keyIndex].passwordIterations,
867                         derived_key->key, hdr->keyBytes);
868         if (r < 0)
869                 goto out;
870
871         log_dbg("Reading key slot %d area.", keyIndex);
872         r = LUKS_decrypt_from_storage(AfKey,
873                                       AFEKSize,
874                                       hdr,
875                                       derived_key,
876                                       device,
877                                       hdr->keyblock[keyIndex].keyMaterialOffset,
878                                       ctx);
879         if (r < 0) {
880                 log_err(ctx, _("Failed to read from key storage.\n"));
881                 goto out;
882         }
883
884         r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
885         if (r < 0)
886                 goto out;
887
888         r = LUKS_verify_volume_key(hdr, vk);
889         if (!r)
890                 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
891 out:
892         crypt_safe_free(AfKey);
893         crypt_free_volume_key(derived_key);
894         return r;
895 }
896
897 int LUKS_open_key_with_hdr(const char *device,
898                            int keyIndex,
899                            const char *password,
900                            size_t passwordLen,
901                            struct luks_phdr *hdr,
902                            struct volume_key **vk,
903                            struct crypt_device *ctx)
904 {
905         unsigned int i;
906         int r;
907
908         *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
909
910         if (keyIndex >= 0) {
911                 r = LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *vk, ctx);
912                 return (r < 0) ? r : keyIndex;
913         }
914
915         for(i = 0; i < LUKS_NUMKEYS; i++) {
916                 r = LUKS_open_key(device, i, password, passwordLen, hdr, *vk, ctx);
917                 if(r == 0)
918                         return i;
919
920                 /* Do not retry for errors that are no -EPERM or -ENOENT,
921                    former meaning password wrong, latter key slot inactive */
922                 if ((r != -EPERM) && (r != -ENOENT))
923                         return r;
924         }
925         /* Warning, early returns above */
926         log_err(ctx, _("No key available with this passphrase.\n"));
927         return -EPERM;
928 }
929
930 int LUKS_del_key(const char *device,
931                  unsigned int keyIndex,
932                  struct luks_phdr *hdr,
933                  struct crypt_device *ctx)
934 {
935         unsigned int startOffset, endOffset, stripesLen;
936         int r;
937
938         r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
939         if (r)
940                 return r;
941
942         r = LUKS_keyslot_set(hdr, keyIndex, 0);
943         if (r) {
944                 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
945                         keyIndex, LUKS_NUMKEYS - 1);
946                 return r;
947         }
948
949         /* secure deletion of key material */
950         startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
951         stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
952         endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
953
954         r = crypt_wipe(device, startOffset * SECTOR_SIZE,
955                        (endOffset - startOffset) * SECTOR_SIZE,
956                        CRYPT_WIPE_DISK, 0);
957         if (r) {
958                 log_err(ctx, _("Cannot wipe device %s.\n"), device);
959                 return r;
960         }
961
962         /* Wipe keyslot info */
963         memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
964         hdr->keyblock[keyIndex].passwordIterations = 0;
965
966         r = LUKS_write_phdr(device, hdr, ctx);
967
968         return r;
969 }
970
971 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
972 {
973         int i;
974
975         if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
976                 return CRYPT_SLOT_INVALID;
977
978         if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
979                 return CRYPT_SLOT_INACTIVE;
980
981         if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
982                 return CRYPT_SLOT_INVALID;
983
984         for(i = 0; i < LUKS_NUMKEYS; i++)
985                 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
986                         return CRYPT_SLOT_ACTIVE;
987
988         return CRYPT_SLOT_ACTIVE_LAST;
989 }
990
991 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
992 {
993         int i;
994
995         for (i = 0; i < LUKS_NUMKEYS; i++)
996                 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
997                         break;
998
999         if (i == LUKS_NUMKEYS)
1000                 return -EINVAL;
1001
1002         return i;
1003 }
1004
1005 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1006 {
1007         int i, num = 0;
1008
1009         for (i = 0; i < LUKS_NUMKEYS; i++)
1010                 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1011                         num++;
1012
1013         return num;
1014 }
1015
1016 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
1017 {
1018         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
1019
1020         if (ki == CRYPT_SLOT_INVALID)
1021                 return -EINVAL;
1022
1023         hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
1024         log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
1025         return 0;
1026 }
1027
1028 int LUKS1_activate(struct crypt_device *cd,
1029                    const char *name,
1030                    struct volume_key *vk,
1031                    uint32_t flags)
1032 {
1033         int r;
1034         char *dm_cipher = NULL;
1035         enum devcheck device_check;
1036         struct crypt_dm_active_device dmd = {
1037                 .target = DM_CRYPT,
1038                 .uuid   = crypt_get_uuid(cd),
1039                 .flags  = flags,
1040                 .size   = 0,
1041                 .data_device = crypt_get_device_name(cd),
1042                 .u.crypt = {
1043                         .cipher = NULL,
1044                         .vk     = vk,
1045                         .offset = crypt_get_data_offset(cd),
1046                         .iv_offset = 0,
1047                 }
1048         };
1049
1050         if (dmd.flags & CRYPT_ACTIVATE_SHARED)
1051                 device_check = DEV_SHARED;
1052         else
1053                 device_check = DEV_EXCL;
1054
1055         r = device_check_and_adjust(cd, dmd.data_device, device_check,
1056                                     &dmd.size, &dmd.u.crypt.offset,
1057                                     &dmd.flags);
1058         if (r)
1059                 return r;
1060
1061         r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
1062         if (r < 0)
1063                 return -ENOMEM;
1064
1065         dmd.u.crypt.cipher = dm_cipher;
1066         r = dm_create_device(name, CRYPT_LUKS1, &dmd, 0);
1067
1068         free(dm_cipher);
1069         return r;
1070 }