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