"Fossies" - the Fresh Open Source Software Archive

Member "cryptsetup-2.1.0/lib/luks1/keymanage.c" (8 Feb 2019, 35773 Bytes) of package /linux/misc/cryptsetup-2.1.0.tar.xz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "keymanage.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.0.6_vs_2.1.0.

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