"Fossies" - the Fresh Open Source Software Archive

Member "cryptsetup-2.4.3/lib/luks2/luks2_disk_metadata.c" (13 Jan 2022, 23377 Bytes) of package /linux/misc/cryptsetup-2.4.3.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 "luks2_disk_metadata.c" see the Fossies "Dox" file reference documentation and the last Fossies "Diffs" side-by-side code changes report: 2.4.1_vs_2.4.2.

    1 /*
    2  * LUKS - Linux Unified Key Setup v2
    3  *
    4  * Copyright (C) 2015-2021 Red Hat, Inc. All rights reserved.
    5  * Copyright (C) 2015-2021 Milan Broz
    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 <assert.h>
   23 
   24 #include "luks2_internal.h"
   25 
   26 /*
   27  * Helper functions
   28  */
   29 static json_object *parse_json_len(struct crypt_device *cd, const char *json_area,
   30                 uint64_t max_length, int *json_len)
   31 {
   32     json_object *jobj;
   33     struct json_tokener *jtok;
   34 
   35      /* INT32_MAX is internal (json-c) json_tokener_parse_ex() limit */
   36     if (!json_area || max_length > INT32_MAX)
   37         return NULL;
   38 
   39     jtok = json_tokener_new();
   40     if (!jtok) {
   41         log_dbg(cd, "ERROR: Failed to init json tokener");
   42         return NULL;
   43     }
   44 
   45     jobj = json_tokener_parse_ex(jtok, json_area, max_length);
   46     if (!jobj)
   47         log_dbg(cd, "ERROR: Failed to parse json data (%d): %s",
   48             json_tokener_get_error(jtok),
   49             json_tokener_error_desc(json_tokener_get_error(jtok)));
   50     else
   51         *json_len = jtok->char_offset;
   52 
   53     json_tokener_free(jtok);
   54 
   55     return jobj;
   56 }
   57 
   58 static void log_dbg_checksum(struct crypt_device *cd,
   59                  const uint8_t *csum, const char *csum_alg, const char *info)
   60 {
   61     char csum_txt[2*LUKS2_CHECKSUM_L+1];
   62     int i;
   63 
   64     for (i = 0; i < crypt_hash_size(csum_alg); i++)
   65         if (snprintf(&csum_txt[i*2], 3, "%02hhx", (const char)csum[i]) != 2)
   66             return;
   67 
   68     log_dbg(cd, "Checksum:%s (%s)", &csum_txt[0], info);
   69 }
   70 
   71 /*
   72  * Calculate hash (checksum) of |LUKS2_bin|LUKS2_JSON_area| from in-memory structs.
   73  * LUKS2 on-disk header contains uniques salt both for primary and secondary header.
   74  * Checksum is always calculated with zeroed checksum field in binary header.
   75  */
   76 static int hdr_checksum_calculate(const char *alg, struct luks2_hdr_disk *hdr_disk,
   77                   const char *json_area, size_t json_len)
   78 {
   79     struct crypt_hash *hd = NULL;
   80     int hash_size, r;
   81 
   82     hash_size = crypt_hash_size(alg);
   83     if (hash_size <= 0 || crypt_hash_init(&hd, alg))
   84         return -EINVAL;
   85 
   86     /* Binary header, csum zeroed. */
   87     r = crypt_hash_write(hd, (char*)hdr_disk, LUKS2_HDR_BIN_LEN);
   88 
   89     /* JSON area (including unused space) */
   90     if (!r)
   91         r = crypt_hash_write(hd, json_area, json_len);
   92 
   93     if (!r)
   94         r = crypt_hash_final(hd, (char*)hdr_disk->csum, (size_t)hash_size);
   95 
   96     crypt_hash_destroy(hd);
   97     return r;
   98 }
   99 
  100 /*
  101  * Compare hash (checksum) of on-disk and in-memory header.
  102  */
  103 static int hdr_checksum_check(struct crypt_device *cd,
  104                   const char *alg, struct luks2_hdr_disk *hdr_disk,
  105                   const char *json_area, size_t json_len)
  106 {
  107     struct luks2_hdr_disk hdr_tmp;
  108     int hash_size, r;
  109 
  110     hash_size = crypt_hash_size(alg);
  111     if (hash_size <= 0)
  112         return -EINVAL;
  113 
  114     /* Copy header and zero checksum. */
  115     memcpy(&hdr_tmp, hdr_disk, LUKS2_HDR_BIN_LEN);
  116     memset(&hdr_tmp.csum, 0, sizeof(hdr_tmp.csum));
  117 
  118     r = hdr_checksum_calculate(alg, &hdr_tmp, json_area, json_len);
  119     if (r < 0)
  120         return r;
  121 
  122     log_dbg_checksum(cd, hdr_disk->csum, alg, "on-disk");
  123     log_dbg_checksum(cd, hdr_tmp.csum, alg, "in-memory");
  124 
  125     if (memcmp(hdr_tmp.csum, hdr_disk->csum, (size_t)hash_size))
  126         return -EINVAL;
  127 
  128     return 0;
  129 }
  130 
  131 /*
  132  * Convert header from on-disk format to in-memory struct
  133  */
  134 static void hdr_from_disk(struct luks2_hdr_disk *hdr_disk1,
  135               struct luks2_hdr_disk *hdr_disk2,
  136               struct luks2_hdr *hdr,
  137               int secondary)
  138 {
  139     hdr->version  = be16_to_cpu(hdr_disk1->version);
  140     hdr->hdr_size = be64_to_cpu(hdr_disk1->hdr_size);
  141     hdr->seqid    = be64_to_cpu(hdr_disk1->seqid);
  142 
  143     memcpy(hdr->label, hdr_disk1->label, LUKS2_LABEL_L);
  144     hdr->label[LUKS2_LABEL_L - 1] = '\0';
  145     memcpy(hdr->subsystem, hdr_disk1->subsystem, LUKS2_LABEL_L);
  146     hdr->subsystem[LUKS2_LABEL_L - 1] = '\0';
  147     memcpy(hdr->checksum_alg, hdr_disk1->checksum_alg, LUKS2_CHECKSUM_ALG_L);
  148     hdr->checksum_alg[LUKS2_CHECKSUM_ALG_L - 1] = '\0';
  149     memcpy(hdr->uuid, hdr_disk1->uuid, LUKS2_UUID_L);
  150     hdr->uuid[LUKS2_UUID_L - 1] = '\0';
  151 
  152     if (secondary) {
  153         memcpy(hdr->salt1, hdr_disk2->salt, LUKS2_SALT_L);
  154         memcpy(hdr->salt2, hdr_disk1->salt, LUKS2_SALT_L);
  155     } else {
  156         memcpy(hdr->salt1, hdr_disk1->salt, LUKS2_SALT_L);
  157         memcpy(hdr->salt2, hdr_disk2->salt, LUKS2_SALT_L);
  158     }
  159 }
  160 
  161 /*
  162  * Convert header from in-memory struct to on-disk format
  163  */
  164 static void hdr_to_disk(struct luks2_hdr *hdr,
  165             struct luks2_hdr_disk *hdr_disk,
  166             int secondary, uint64_t offset)
  167 {
  168     assert(((char*)&(hdr_disk->_padding4096) - (char*)&(hdr_disk->magic)) == 512);
  169 
  170     memset(hdr_disk, 0, LUKS2_HDR_BIN_LEN);
  171 
  172     memcpy(&hdr_disk->magic, secondary ? LUKS2_MAGIC_2ND : LUKS2_MAGIC_1ST, LUKS2_MAGIC_L);
  173     hdr_disk->version     = cpu_to_be16(hdr->version);
  174     hdr_disk->hdr_size    = cpu_to_be64(hdr->hdr_size);
  175     hdr_disk->hdr_offset  = cpu_to_be64(offset);
  176     hdr_disk->seqid       = cpu_to_be64(hdr->seqid);
  177 
  178     memcpy(hdr_disk->label, hdr->label, MIN(strlen(hdr->label), LUKS2_LABEL_L));
  179     hdr_disk->label[LUKS2_LABEL_L - 1] = '\0';
  180     memcpy(hdr_disk->subsystem, hdr->subsystem, MIN(strlen(hdr->subsystem), LUKS2_LABEL_L));
  181     hdr_disk->subsystem[LUKS2_LABEL_L - 1] = '\0';
  182     memcpy(hdr_disk->checksum_alg, hdr->checksum_alg, MIN(strlen(hdr->checksum_alg), LUKS2_CHECKSUM_ALG_L));
  183     hdr_disk->checksum_alg[LUKS2_CHECKSUM_ALG_L - 1] = '\0';
  184     memcpy(hdr_disk->uuid, hdr->uuid, MIN(strlen(hdr->uuid), LUKS2_UUID_L));
  185     hdr_disk->uuid[LUKS2_UUID_L - 1] = '\0';
  186 
  187     memcpy(hdr_disk->salt, secondary ? hdr->salt2 : hdr->salt1, LUKS2_SALT_L);
  188 }
  189 
  190 /*
  191  * Sanity checks before checksum is validated
  192  */
  193 static int hdr_disk_sanity_check_pre(struct crypt_device *cd,
  194                      struct luks2_hdr_disk *hdr,
  195                      size_t *hdr_json_size, int secondary,
  196                      uint64_t offset)
  197 {
  198     uint64_t hdr_size;
  199 
  200     if (memcmp(hdr->magic, secondary ? LUKS2_MAGIC_2ND : LUKS2_MAGIC_1ST, LUKS2_MAGIC_L))
  201         return -EINVAL;
  202 
  203     if (be16_to_cpu(hdr->version) != 2) {
  204         log_dbg(cd, "Unsupported LUKS2 header version %u.", be16_to_cpu(hdr->version));
  205         return -EINVAL;
  206     }
  207 
  208     if (offset != be64_to_cpu(hdr->hdr_offset)) {
  209         log_dbg(cd, "LUKS2 offset 0x%04" PRIx64 " on device differs to expected offset 0x%04" PRIx64 ".",
  210             be64_to_cpu(hdr->hdr_offset), offset);
  211         return -EINVAL;
  212     }
  213 
  214     hdr_size = be64_to_cpu(hdr->hdr_size);
  215 
  216     if (hdr_size < LUKS2_HDR_16K_LEN || hdr_size > LUKS2_HDR_OFFSET_MAX) {
  217         log_dbg(cd, "LUKS2 header has bogus size 0x%04" PRIx64 ".", hdr_size);
  218         return -EINVAL;
  219     }
  220 
  221     if (secondary && (offset != hdr_size)) {
  222         log_dbg(cd, "LUKS2 offset 0x%04" PRIx64 " in secondary header does not match size 0x%04" PRIx64 ".",
  223             offset, hdr_size);
  224         return -EINVAL;
  225     }
  226 
  227     /* FIXME: sanity check checksum alg. */
  228 
  229     log_dbg(cd, "LUKS2 header version %u of size %" PRIu64 " bytes, checksum %s.",
  230         be16_to_cpu(hdr->version), hdr_size,
  231         hdr->checksum_alg);
  232 
  233     *hdr_json_size = hdr_size - LUKS2_HDR_BIN_LEN;
  234     return 0;
  235 }
  236 
  237 /*
  238  * Read LUKS2 header from disk at specific offset.
  239  */
  240 static int hdr_read_disk(struct crypt_device *cd,
  241              struct device *device, struct luks2_hdr_disk *hdr_disk,
  242              char **json_area, uint64_t offset, int secondary)
  243 {
  244     size_t hdr_json_size = 0;
  245     int devfd, r;
  246 
  247     log_dbg(cd, "Trying to read %s LUKS2 header at offset 0x%" PRIx64 ".",
  248         secondary ? "secondary" : "primary", offset);
  249 
  250     devfd = device_open_locked(cd, device, O_RDONLY);
  251     if (devfd < 0)
  252         return devfd == -1 ? -EIO : devfd;
  253 
  254     /*
  255      * Read binary header and run sanity check before reading
  256      * JSON area and validating checksum.
  257      */
  258     if (read_lseek_blockwise(devfd, device_block_size(cd, device),
  259                  device_alignment(device), hdr_disk,
  260                  LUKS2_HDR_BIN_LEN, offset) != LUKS2_HDR_BIN_LEN) {
  261         return -EIO;
  262     }
  263 
  264     /*
  265      * hdr_json_size is validated if this call succeeds
  266      */
  267     r = hdr_disk_sanity_check_pre(cd, hdr_disk, &hdr_json_size, secondary, offset);
  268     if (r < 0)
  269         return r;
  270 
  271     /*
  272      * Allocate and read JSON area. Always the whole area must be read.
  273      */
  274     *json_area = malloc(hdr_json_size);
  275     if (!*json_area)
  276         return -ENOMEM;
  277 
  278     if (read_lseek_blockwise(devfd, device_block_size(cd, device),
  279                  device_alignment(device), *json_area, hdr_json_size,
  280                  offset + LUKS2_HDR_BIN_LEN) != (ssize_t)hdr_json_size) {
  281         free(*json_area);
  282         *json_area = NULL;
  283         return -EIO;
  284     }
  285 
  286     /*
  287      * Calculate and validate checksum and zero it afterwards.
  288      */
  289     if (hdr_checksum_check(cd, hdr_disk->checksum_alg, hdr_disk,
  290                 *json_area, hdr_json_size)) {
  291         log_dbg(cd, "LUKS2 header checksum error (offset %" PRIu64 ").", offset);
  292         free(*json_area);
  293         *json_area = NULL;
  294         r = -EINVAL;
  295     }
  296     memset(hdr_disk->csum, 0, LUKS2_CHECKSUM_L);
  297 
  298     return r;
  299 }
  300 
  301 /*
  302  * Write LUKS2 header to disk at specific offset.
  303  */
  304 static int hdr_write_disk(struct crypt_device *cd,
  305               struct device *device, struct luks2_hdr *hdr,
  306               const char *json_area, int secondary)
  307 {
  308     struct luks2_hdr_disk hdr_disk;
  309     uint64_t offset = secondary ? hdr->hdr_size : 0;
  310     size_t hdr_json_len;
  311     int devfd, r;
  312 
  313     log_dbg(cd, "Trying to write LUKS2 header (%zu bytes) at offset %" PRIu64 ".",
  314         hdr->hdr_size, offset);
  315 
  316     devfd = device_open_locked(cd, device, O_RDWR);
  317     if (devfd < 0)
  318         return devfd == -1 ? -EINVAL : devfd;
  319 
  320     hdr_json_len = hdr->hdr_size - LUKS2_HDR_BIN_LEN;
  321 
  322     hdr_to_disk(hdr, &hdr_disk, secondary, offset);
  323 
  324     /*
  325      * Write header without checksum but with proper seqid.
  326      */
  327     if (write_lseek_blockwise(devfd, device_block_size(cd, device),
  328                   device_alignment(device), (char *)&hdr_disk,
  329                   LUKS2_HDR_BIN_LEN, offset) < (ssize_t)LUKS2_HDR_BIN_LEN) {
  330         return -EIO;
  331     }
  332 
  333     /*
  334      * Write json area.
  335      */
  336     if (write_lseek_blockwise(devfd, device_block_size(cd, device),
  337                   device_alignment(device),
  338                   CONST_CAST(char*)json_area, hdr_json_len,
  339                   LUKS2_HDR_BIN_LEN + offset) < (ssize_t)hdr_json_len) {
  340         return -EIO;
  341     }
  342 
  343     /*
  344      * Calculate checksum and write header with checksum.
  345      */
  346     r = hdr_checksum_calculate(hdr_disk.checksum_alg, &hdr_disk,
  347                    json_area, hdr_json_len);
  348     if (r < 0) {
  349         return r;
  350     }
  351     log_dbg_checksum(cd, hdr_disk.csum, hdr_disk.checksum_alg, "in-memory");
  352 
  353     if (write_lseek_blockwise(devfd, device_block_size(cd, device),
  354                   device_alignment(device), (char *)&hdr_disk,
  355                   LUKS2_HDR_BIN_LEN, offset) < (ssize_t)LUKS2_HDR_BIN_LEN)
  356         r = -EIO;
  357 
  358     device_sync(cd, device);
  359     return r;
  360 }
  361 
  362 static int LUKS2_check_sequence_id(struct crypt_device *cd, struct luks2_hdr *hdr, struct device *device)
  363 {
  364     int devfd;
  365     struct luks2_hdr_disk dhdr;
  366 
  367     if (!hdr)
  368         return -EINVAL;
  369 
  370     devfd = device_open_locked(cd, device, O_RDONLY);
  371     if (devfd < 0)
  372         return devfd == -1 ? -EINVAL : devfd;
  373 
  374     /* we need only first 512 bytes, see luks2_hdr_disk structure */
  375     if ((read_lseek_blockwise(devfd, device_block_size(cd, device),
  376          device_alignment(device), &dhdr, 512, 0) != 512))
  377         return -EIO;
  378 
  379     /* there's nothing to check if there's no LUKS2 header */
  380     if ((be16_to_cpu(dhdr.version) != 2) ||
  381         memcmp(dhdr.magic, LUKS2_MAGIC_1ST, LUKS2_MAGIC_L) ||
  382         strcmp(dhdr.uuid, hdr->uuid))
  383         return 0;
  384 
  385     return hdr->seqid != be64_to_cpu(dhdr.seqid);
  386 }
  387 
  388 int LUKS2_device_write_lock(struct crypt_device *cd, struct luks2_hdr *hdr, struct device *device)
  389 {
  390     int r = device_write_lock(cd, device);
  391 
  392     if (r < 0) {
  393         log_err(cd, _("Failed to acquire write lock on device %s."), device_path(device));
  394         return r;
  395     }
  396 
  397     /* run sequence id check only on first write lock (r == 1) and w/o LUKS2 reencryption in-progress */
  398     if (r == 1 && !crypt_get_luks2_reencrypt(cd)) {
  399         log_dbg(cd, "Checking context sequence id matches value stored on disk.");
  400         if (LUKS2_check_sequence_id(cd, hdr, device)) {
  401             device_write_unlock(cd, device);
  402             log_err(cd, _("Detected attempt for concurrent LUKS2 metadata update. Aborting operation."));
  403             return -EINVAL;
  404         }
  405     }
  406 
  407     return 0;
  408 }
  409 
  410 /*
  411  * Convert in-memory LUKS2 header and write it to disk.
  412  * This will increase sequence id, write both header copies and calculate checksum.
  413  */
  414 int LUKS2_disk_hdr_write(struct crypt_device *cd, struct luks2_hdr *hdr, struct device *device, bool seqid_check)
  415 {
  416     char *json_area;
  417     const char *json_text;
  418     size_t json_area_len;
  419     int r;
  420 
  421     if (hdr->version != 2) {
  422         log_dbg(cd, "Unsupported LUKS2 header version (%u).", hdr->version);
  423         return -EINVAL;
  424     }
  425 
  426     r = device_check_size(cd, crypt_metadata_device(cd), LUKS2_hdr_and_areas_size(hdr), 1);
  427     if (r)
  428         return r;
  429 
  430     /*
  431      * Allocate and zero JSON area (of proper header size).
  432      */
  433     json_area_len = hdr->hdr_size - LUKS2_HDR_BIN_LEN;
  434     json_area = crypt_zalloc(json_area_len);
  435     if (!json_area)
  436         return -ENOMEM;
  437 
  438     /*
  439      * Generate text space-efficient JSON representation to json area.
  440      */
  441     json_text = json_object_to_json_string_ext(hdr->jobj,
  442             JSON_C_TO_STRING_PLAIN | JSON_C_TO_STRING_NOSLASHESCAPE);
  443     if (!json_text || !*json_text) {
  444         log_dbg(cd, "Cannot parse JSON object to text representation.");
  445         free(json_area);
  446         return -ENOMEM;
  447     }
  448     if (strlen(json_text) > (json_area_len - 1)) {
  449         log_dbg(cd, "JSON is too large (%zu > %zu).", strlen(json_text), json_area_len);
  450         free(json_area);
  451         return -EINVAL;
  452     }
  453     strncpy(json_area, json_text, json_area_len);
  454 
  455     if (seqid_check)
  456         r = LUKS2_device_write_lock(cd, hdr, device);
  457     else
  458         r = device_write_lock(cd, device);
  459     if (r < 0) {
  460         free(json_area);
  461         return r;
  462     }
  463 
  464     /* Increase sequence id before writing it to disk. */
  465     hdr->seqid++;
  466 
  467     /* Write primary and secondary header */
  468     r = hdr_write_disk(cd, device, hdr, json_area, 0);
  469     if (!r)
  470         r = hdr_write_disk(cd, device, hdr, json_area, 1);
  471 
  472     if (r)
  473         log_dbg(cd, "LUKS2 header write failed (%d).", r);
  474 
  475     device_write_unlock(cd, device);
  476 
  477     free(json_area);
  478     return r;
  479 }
  480 static int validate_json_area(struct crypt_device *cd, const char *json_area,
  481                   uint64_t json_len, uint64_t max_length)
  482 {
  483     char c;
  484 
  485     /* Enforce there are no needless opening bytes */
  486     if (*json_area != '{') {
  487         log_dbg(cd, "ERROR: Opening character must be left curly bracket: '{'.");
  488         return -EINVAL;
  489     }
  490 
  491     if (json_len >= max_length) {
  492         log_dbg(cd, "ERROR: Missing trailing null byte beyond parsed json data string.");
  493         return -EINVAL;
  494     }
  495 
  496     /*
  497      * TODO:
  498      *  validate there are legal json format characters between
  499      *  'json_area' and 'json_area + json_len'
  500      */
  501 
  502     do {
  503         c = *(json_area + json_len);
  504         if (c != '\0') {
  505             log_dbg(cd, "ERROR: Forbidden ascii code 0x%02hhx found beyond json data string at offset %" PRIu64,
  506                 c, json_len);
  507             return -EINVAL;
  508         }
  509     } while (++json_len < max_length);
  510 
  511     return 0;
  512 }
  513 
  514 static int validate_luks2_json_object(struct crypt_device *cd, json_object *jobj_hdr, uint64_t length)
  515 {
  516     int r;
  517 
  518     /* we require top level object to be of json_type_object */
  519     r = !json_object_is_type(jobj_hdr, json_type_object);
  520     if (r) {
  521         log_dbg(cd, "ERROR: Resulting object is not a json object type");
  522         return r;
  523     }
  524 
  525     r = LUKS2_hdr_validate(cd, jobj_hdr, length);
  526     if (r) {
  527         log_dbg(cd, "Repairing JSON metadata.");
  528         /* try to correct known glitches */
  529         LUKS2_hdr_repair(cd, jobj_hdr);
  530 
  531         /* run validation again */
  532         r = LUKS2_hdr_validate(cd, jobj_hdr, length);
  533     }
  534 
  535     if (r)
  536         log_dbg(cd, "ERROR: LUKS2 validation failed");
  537 
  538     return r;
  539 }
  540 
  541 static json_object *parse_and_validate_json(struct crypt_device *cd,
  542                         const char *json_area, uint64_t max_length)
  543 {
  544     int json_len, r;
  545     json_object *jobj = parse_json_len(cd, json_area, max_length, &json_len);
  546 
  547     if (!jobj)
  548         return NULL;
  549 
  550     /* successful parse_json_len must not return offset <= 0 */
  551     assert(json_len > 0);
  552 
  553     r = validate_json_area(cd, json_area, json_len, max_length);
  554     if (!r)
  555         r = validate_luks2_json_object(cd, jobj, max_length);
  556 
  557     if (r) {
  558         json_object_put(jobj);
  559         jobj = NULL;
  560     }
  561 
  562     return jobj;
  563 }
  564 
  565 static int detect_device_signatures(struct crypt_device *cd, const char *path)
  566 {
  567     blk_probe_status prb_state;
  568     int r;
  569     struct blkid_handle *h;
  570 
  571     if (!blk_supported()) {
  572         log_dbg(cd, "Blkid probing of device signatures disabled.");
  573         return 0;
  574     }
  575 
  576     if ((r = blk_init_by_path(&h, path))) {
  577         log_dbg(cd, "Failed to initialize blkid_handle by path.");
  578         return -EINVAL;
  579     }
  580 
  581     /* We don't care about details. Be fast. */
  582     blk_set_chains_for_fast_detection(h);
  583 
  584     /* Filter out crypto_LUKS. we don't care now */
  585     blk_superblocks_filter_luks(h);
  586 
  587     prb_state = blk_safeprobe(h);
  588 
  589     switch (prb_state) {
  590     case PRB_AMBIGUOUS:
  591         log_dbg(cd, "Blkid probe couldn't decide device type unambiguously.");
  592         /* fall through */
  593     case PRB_FAIL:
  594         log_dbg(cd, "Blkid probe failed.");
  595         r = -EINVAL;
  596         break;
  597     case PRB_OK: /* crypto_LUKS type is filtered out */
  598         r = -EINVAL;
  599 
  600         if (blk_is_partition(h))
  601             log_dbg(cd, "Blkid probe detected partition type '%s'", blk_get_partition_type(h));
  602         else if (blk_is_superblock(h))
  603             log_dbg(cd, "blkid probe detected superblock type '%s'", blk_get_superblock_type(h));
  604         break;
  605     case PRB_EMPTY:
  606         log_dbg(cd, "Blkid probe detected no foreign device signature.");
  607     }
  608     blk_free(h);
  609     return r;
  610 }
  611 
  612 /*
  613  * Read and convert on-disk LUKS2 header to in-memory representation..
  614  * Try to do recovery if on-disk state is not consistent.
  615  */
  616 int LUKS2_disk_hdr_read(struct crypt_device *cd, struct luks2_hdr *hdr,
  617             struct device *device, int do_recovery, int do_blkprobe)
  618 {
  619     enum { HDR_OK, HDR_OBSOLETE, HDR_FAIL, HDR_FAIL_IO } state_hdr1, state_hdr2;
  620     struct luks2_hdr_disk hdr_disk1, hdr_disk2;
  621     char *json_area1 = NULL, *json_area2 = NULL;
  622     json_object *jobj_hdr1 = NULL, *jobj_hdr2 = NULL;
  623     unsigned int i;
  624     int r;
  625     uint64_t hdr_size;
  626     uint64_t hdr2_offsets[] = LUKS2_HDR2_OFFSETS;
  627 
  628     /* Skip auto-recovery if locks are disabled and we're not doing LUKS2 explicit repair */
  629     if (do_recovery && do_blkprobe && !crypt_metadata_locking_enabled()) {
  630         do_recovery = 0;
  631         log_dbg(cd, "Disabling header auto-recovery due to locking being disabled.");
  632     }
  633 
  634     /*
  635      * Read primary LUKS2 header (offset 0).
  636      */
  637     state_hdr1 = HDR_FAIL;
  638     r = hdr_read_disk(cd, device, &hdr_disk1, &json_area1, 0, 0);
  639     if (r == 0) {
  640         jobj_hdr1 = parse_and_validate_json(cd, json_area1, be64_to_cpu(hdr_disk1.hdr_size) - LUKS2_HDR_BIN_LEN);
  641         state_hdr1 = jobj_hdr1 ? HDR_OK : HDR_OBSOLETE;
  642     } else if (r == -EIO)
  643         state_hdr1 = HDR_FAIL_IO;
  644 
  645     /*
  646      * Read secondary LUKS2 header (follows primary).
  647      */
  648     state_hdr2 = HDR_FAIL;
  649     if (state_hdr1 != HDR_FAIL && state_hdr1 != HDR_FAIL_IO) {
  650         r = hdr_read_disk(cd, device, &hdr_disk2, &json_area2, be64_to_cpu(hdr_disk1.hdr_size), 1);
  651         if (r == 0) {
  652             jobj_hdr2 = parse_and_validate_json(cd, json_area2, be64_to_cpu(hdr_disk2.hdr_size) - LUKS2_HDR_BIN_LEN);
  653             state_hdr2 = jobj_hdr2 ? HDR_OK : HDR_OBSOLETE;
  654         } else if (r == -EIO)
  655             state_hdr2 = HDR_FAIL_IO;
  656     } else {
  657         /*
  658          * No header size, check all known offsets.
  659          */
  660         for (r = -EINVAL,i = 0; r < 0 && i < ARRAY_SIZE(hdr2_offsets); i++)
  661             r = hdr_read_disk(cd, device, &hdr_disk2, &json_area2, hdr2_offsets[i], 1);
  662 
  663         if (r == 0) {
  664             jobj_hdr2 = parse_and_validate_json(cd, json_area2, be64_to_cpu(hdr_disk2.hdr_size) - LUKS2_HDR_BIN_LEN);
  665             state_hdr2 = jobj_hdr2 ? HDR_OK : HDR_OBSOLETE;
  666         } else if (r == -EIO)
  667             state_hdr2 = HDR_FAIL_IO;
  668     }
  669 
  670     /*
  671      * Check sequence id if both headers are read correctly.
  672      */
  673     if (state_hdr1 == HDR_OK && state_hdr2 == HDR_OK) {
  674         if (be64_to_cpu(hdr_disk1.seqid) > be64_to_cpu(hdr_disk2.seqid))
  675             state_hdr2 = HDR_OBSOLETE;
  676         else if (be64_to_cpu(hdr_disk1.seqid) < be64_to_cpu(hdr_disk2.seqid))
  677             state_hdr1 = HDR_OBSOLETE;
  678     }
  679 
  680     /* check header with keyslots to fit the device */
  681     if (state_hdr1 == HDR_OK)
  682         hdr_size = LUKS2_hdr_and_areas_size_jobj(jobj_hdr1);
  683     else if (state_hdr2 == HDR_OK)
  684         hdr_size = LUKS2_hdr_and_areas_size_jobj(jobj_hdr2);
  685     else {
  686         r = (state_hdr1 == HDR_FAIL_IO && state_hdr2 == HDR_FAIL_IO) ? -EIO : -EINVAL;
  687         goto err;
  688     }
  689 
  690     r = device_check_size(cd, device, hdr_size, 0);
  691     if (r)
  692         goto err;
  693 
  694     /*
  695      * Try to rewrite (recover) bad header. Always regenerate salt for bad header.
  696      */
  697     if (state_hdr1 == HDR_OK && state_hdr2 != HDR_OK) {
  698         log_dbg(cd, "Secondary LUKS2 header requires recovery.");
  699 
  700         if (do_blkprobe && (r = detect_device_signatures(cd, device_path(device)))) {
  701             log_err(cd, _("Device contains ambiguous signatures, cannot auto-recover LUKS2.\n"
  702                       "Please run \"cryptsetup repair\" for recovery."));
  703             goto err;
  704         }
  705 
  706         if (do_recovery) {
  707             memcpy(&hdr_disk2, &hdr_disk1, LUKS2_HDR_BIN_LEN);
  708             r = crypt_random_get(cd, (char*)hdr_disk2.salt, sizeof(hdr_disk2.salt), CRYPT_RND_SALT);
  709             if (r)
  710                 log_dbg(cd, "Cannot generate master salt.");
  711             else {
  712                 hdr_from_disk(&hdr_disk1, &hdr_disk2, hdr, 0);
  713                 r = hdr_write_disk(cd, device, hdr, json_area1, 1);
  714             }
  715             if (r)
  716                 log_dbg(cd, "Secondary LUKS2 header recovery failed.");
  717         }
  718     } else if (state_hdr1 != HDR_OK && state_hdr2 == HDR_OK) {
  719         log_dbg(cd, "Primary LUKS2 header requires recovery.");
  720 
  721         if (do_blkprobe && (r = detect_device_signatures(cd, device_path(device)))) {
  722             log_err(cd, _("Device contains ambiguous signatures, cannot auto-recover LUKS2.\n"
  723                       "Please run \"cryptsetup repair\" for recovery."));
  724             goto err;
  725         }
  726 
  727         if (do_recovery) {
  728             memcpy(&hdr_disk1, &hdr_disk2, LUKS2_HDR_BIN_LEN);
  729             r = crypt_random_get(cd, (char*)hdr_disk1.salt, sizeof(hdr_disk1.salt), CRYPT_RND_SALT);
  730             if (r)
  731                 log_dbg(cd, "Cannot generate master salt.");
  732             else {
  733                 hdr_from_disk(&hdr_disk2, &hdr_disk1, hdr, 1);
  734                 r = hdr_write_disk(cd, device, hdr, json_area2, 0);
  735             }
  736             if (r)
  737                 log_dbg(cd, "Primary LUKS2 header recovery failed.");
  738         }
  739     }
  740 
  741     free(json_area1);
  742     json_area1 = NULL;
  743     free(json_area2);
  744     json_area2 = NULL;
  745 
  746     /* wrong lock for write mode during recovery attempt */
  747     if (r == -EAGAIN)
  748         goto err;
  749 
  750     /*
  751      * Even if status is failed, the second header includes salt.
  752      */
  753     if (state_hdr1 == HDR_OK) {
  754         hdr_from_disk(&hdr_disk1, &hdr_disk2, hdr, 0);
  755         hdr->jobj = jobj_hdr1;
  756         json_object_put(jobj_hdr2);
  757     } else if (state_hdr2 == HDR_OK) {
  758         hdr_from_disk(&hdr_disk2, &hdr_disk1, hdr, 1);
  759         hdr->jobj = jobj_hdr2;
  760         json_object_put(jobj_hdr1);
  761     }
  762 
  763     /*
  764      * FIXME: should this fail? At least one header was read correctly.
  765      * r = (state_hdr1 == HDR_FAIL_IO || state_hdr2 == HDR_FAIL_IO) ? -EIO : -EINVAL;
  766      */
  767     return 0;
  768 err:
  769     log_dbg(cd, "LUKS2 header read failed (%d).", r);
  770 
  771     free(json_area1);
  772     free(json_area2);
  773     json_object_put(jobj_hdr1);
  774     json_object_put(jobj_hdr2);
  775     hdr->jobj = NULL;
  776     return r;
  777 }
  778 
  779 int LUKS2_hdr_version_unlocked(struct crypt_device *cd, const char *backup_file)
  780 {
  781     struct {
  782         char magic[LUKS2_MAGIC_L];
  783         uint16_t version;
  784     }  __attribute__ ((packed)) hdr;
  785     struct device *device = NULL;
  786     int r = 0, devfd = -1, flags;
  787 
  788     if (!backup_file)
  789         device = crypt_metadata_device(cd);
  790     else if (device_alloc(cd, &device, backup_file) < 0)
  791         return 0;
  792 
  793     if (!device)
  794         return 0;
  795 
  796     flags = O_RDONLY;
  797     if (device_direct_io(device))
  798         flags |= O_DIRECT;
  799 
  800     devfd = open(device_path(device), flags);
  801     if (devfd != -1 && (read_lseek_blockwise(devfd, device_block_size(cd, device),
  802          device_alignment(device), &hdr, sizeof(hdr), 0) == sizeof(hdr)) &&
  803         !memcmp(hdr.magic, LUKS2_MAGIC_1ST, LUKS2_MAGIC_L))
  804         r = (int)be16_to_cpu(hdr.version);
  805 
  806     if (devfd != -1)
  807         close(devfd);
  808 
  809     if (backup_file)
  810         device_free(cd, device);
  811 
  812     return r;
  813 }