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