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