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