Fixed the build error for riscv64 arch using gcc 13
[platform/upstream/cryptsetup.git] / lib / luks2 / luks2_json_metadata.c
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  * Copyright (C) 2015-2021 Ondrej Kozina
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include "luks2_internal.h"
24 #include "../integrity/integrity.h"
25 #include <assert.h>
26 #include <ctype.h>
27 #include <uuid/uuid.h>
28
29 #define LUKS_STRIPES 4000
30
31 struct interval {
32         uint64_t offset;
33         uint64_t length;
34 };
35
36 void hexprint_base64(struct crypt_device *cd, json_object *jobj,
37                      const char *sep, const char *line_sep)
38 {
39         char *buf = NULL;
40         size_t buf_len;
41         unsigned int i;
42
43         if (!base64_decode_alloc(json_object_get_string(jobj),
44                                  json_object_get_string_len(jobj),
45                                  &buf, &buf_len))
46                 return;
47
48         for (i = 0; i < buf_len; i++) {
49                 if (i && !(i % 16))
50                         log_std(cd, "\n\t%s", line_sep);
51                 log_std(cd, "%02hhx%s", buf[i], sep);
52         }
53         log_std(cd, "\n");
54         free(buf);
55 }
56
57 void JSON_DBG(struct crypt_device *cd, json_object *jobj, const char *desc)
58 {
59         if (desc)
60                 crypt_log(cd, CRYPT_LOG_DEBUG_JSON, desc);
61         crypt_log(cd, CRYPT_LOG_DEBUG_JSON, json_object_to_json_string_ext(jobj,
62                 JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_NOSLASHESCAPE));
63 }
64
65 /*
66  * JSON array helpers
67  */
68 struct json_object *LUKS2_array_jobj(struct json_object *array, const char *num)
69 {
70         struct json_object *jobj1;
71         int i;
72
73         for (i = 0; i < (int) json_object_array_length(array); i++) {
74                 jobj1 = json_object_array_get_idx(array, i);
75                 if (!strcmp(num, json_object_get_string(jobj1)))
76                         return jobj1;
77         }
78
79         return NULL;
80 }
81
82 struct json_object *LUKS2_array_remove(struct json_object *array, const char *num)
83 {
84         struct json_object *jobj1, *jobj_removing = NULL, *array_new;
85         int i;
86
87         jobj_removing = LUKS2_array_jobj(array, num);
88         if (!jobj_removing)
89                 return NULL;
90
91         /* Create new array without jobj_removing. */
92         array_new = json_object_new_array();
93         for (i = 0; i < (int) json_object_array_length(array); i++) {
94                 jobj1 = json_object_array_get_idx(array, i);
95                 if (jobj1 != jobj_removing)
96                         json_object_array_add(array_new, json_object_get(jobj1));
97         }
98
99         return array_new;
100 }
101
102 /*
103  * JSON struct access helpers
104  */
105 json_object *LUKS2_get_keyslot_jobj(struct luks2_hdr *hdr, int keyslot)
106 {
107         json_object *jobj1, *jobj2;
108         char keyslot_name[16];
109
110         if (!hdr || keyslot < 0)
111                 return NULL;
112
113         if (snprintf(keyslot_name, sizeof(keyslot_name), "%u", keyslot) < 1)
114                 return NULL;
115
116         if (!json_object_object_get_ex(hdr->jobj, "keyslots", &jobj1))
117                 return NULL;
118
119         if (!json_object_object_get_ex(jobj1, keyslot_name, &jobj2))
120                 return NULL;
121
122         return jobj2;
123 }
124
125 json_object *LUKS2_get_tokens_jobj(struct luks2_hdr *hdr)
126 {
127         json_object *jobj_tokens;
128
129         if (!hdr || !json_object_object_get_ex(hdr->jobj, "tokens", &jobj_tokens))
130                 return NULL;
131
132         return jobj_tokens;
133 }
134
135 json_object *LUKS2_get_token_jobj(struct luks2_hdr *hdr, int token)
136 {
137         json_object *jobj1, *jobj2;
138         char token_name[16];
139
140         if (!hdr || token < 0)
141                 return NULL;
142
143         jobj1 = LUKS2_get_tokens_jobj(hdr);
144         if (!jobj1)
145                 return NULL;
146
147         if (snprintf(token_name, sizeof(token_name), "%u", token) < 1)
148                 return NULL;
149
150         json_object_object_get_ex(jobj1, token_name, &jobj2);
151         return jobj2;
152 }
153
154 json_object *LUKS2_get_digest_jobj(struct luks2_hdr *hdr, int digest)
155 {
156         json_object *jobj1, *jobj2;
157         char digest_name[16];
158
159         if (!hdr || digest < 0)
160                 return NULL;
161
162         if (snprintf(digest_name, sizeof(digest_name), "%u", digest) < 1)
163                 return NULL;
164
165         if (!json_object_object_get_ex(hdr->jobj, "digests", &jobj1))
166                 return NULL;
167
168         json_object_object_get_ex(jobj1, digest_name, &jobj2);
169         return jobj2;
170 }
171
172 static json_object *json_get_segments_jobj(json_object *hdr_jobj)
173 {
174         json_object *jobj_segments;
175
176         if (!hdr_jobj || !json_object_object_get_ex(hdr_jobj, "segments", &jobj_segments))
177                 return NULL;
178
179         return jobj_segments;
180 }
181
182 json_object *LUKS2_get_segment_jobj(struct luks2_hdr *hdr, int segment)
183 {
184         if (!hdr)
185                 return NULL;
186
187         if (segment == CRYPT_DEFAULT_SEGMENT)
188                 segment = LUKS2_get_default_segment(hdr);
189
190         return json_segments_get_segment(json_get_segments_jobj(hdr->jobj), segment);
191 }
192
193 json_object *LUKS2_get_segments_jobj(struct luks2_hdr *hdr)
194 {
195         return hdr ? json_get_segments_jobj(hdr->jobj) : NULL;
196 }
197
198 int LUKS2_segments_count(struct luks2_hdr *hdr)
199 {
200         if (!hdr)
201                 return -EINVAL;
202
203         return json_segments_count(LUKS2_get_segments_jobj(hdr));
204 }
205
206 int LUKS2_get_default_segment(struct luks2_hdr *hdr)
207 {
208         int s = LUKS2_get_segment_id_by_flag(hdr, "backup-final");
209         if (s >= 0)
210                 return s;
211
212         if (LUKS2_segments_count(hdr) == 1)
213                 return 0;
214
215         return -EINVAL;
216 }
217
218 /*
219  * json_type_int needs to be validated first.
220  * See validate_json_uint32()
221  */
222 uint32_t crypt_jobj_get_uint32(json_object *jobj)
223 {
224         return json_object_get_int64(jobj);
225 }
226
227 /* jobj has to be json_type_string and numbered */
228 static json_bool json_str_to_uint64(json_object *jobj, uint64_t *value)
229 {
230         char *endptr;
231         unsigned long long tmp;
232
233         errno = 0;
234         tmp = strtoull(json_object_get_string(jobj), &endptr, 10);
235         if (*endptr || errno) {
236                 *value = 0;
237                 return 0;
238         }
239
240         *value = tmp;
241         return 1;
242 }
243
244 uint64_t crypt_jobj_get_uint64(json_object *jobj)
245 {
246         uint64_t r;
247         json_str_to_uint64(jobj, &r);
248         return r;
249 }
250
251 json_object *crypt_jobj_new_uint64(uint64_t value)
252 {
253         /* 18446744073709551615 */
254         char num[21];
255         int r;
256         json_object *jobj;
257
258         r = snprintf(num, sizeof(num), "%" PRIu64, value);
259         if (r < 0 || (size_t)r >= sizeof(num))
260                 return NULL;
261
262         jobj = json_object_new_string(num);
263         return jobj;
264 }
265
266 /*
267  * Validate helpers
268  */
269 static json_bool numbered(struct crypt_device *cd, const char *name, const char *key)
270 {
271         int i;
272
273         for (i = 0; key[i]; i++)
274                 if (!isdigit(key[i])) {
275                         log_dbg(cd, "%s \"%s\" is not in numbered form.", name, key);
276                         return 0;
277                 }
278         return 1;
279 }
280
281 json_object *json_contains(struct crypt_device *cd, json_object *jobj, const char *name,
282                            const char *section, const char *key, json_type type)
283 {
284         json_object *sobj;
285
286         if (!json_object_object_get_ex(jobj, key, &sobj) ||
287             !json_object_is_type(sobj, type)) {
288                 log_dbg(cd, "%s \"%s\" is missing \"%s\" (%s) specification.",
289                         section, name, key, json_type_to_name(type));
290                 return NULL;
291         }
292
293         return sobj;
294 }
295
296 json_bool validate_json_uint32(json_object *jobj)
297 {
298         int64_t tmp;
299
300         errno = 0;
301         tmp = json_object_get_int64(jobj);
302
303         return (errno || tmp < 0 || tmp > UINT32_MAX) ? 0 : 1;
304 }
305
306 static json_bool validate_keyslots_array(struct crypt_device *cd,
307                                          json_object *jarr, json_object *jobj_keys)
308 {
309         json_object *jobj;
310         int i = 0, length = (int) json_object_array_length(jarr);
311
312         while (i < length) {
313                 jobj = json_object_array_get_idx(jarr, i);
314                 if (!json_object_is_type(jobj, json_type_string)) {
315                         log_dbg(cd, "Illegal value type in keyslots array at index %d.", i);
316                         return 0;
317                 }
318
319                 if (!json_contains(cd, jobj_keys, "", "Keyslots section",
320                                    json_object_get_string(jobj), json_type_object))
321                         return 0;
322
323                 i++;
324         }
325
326         return 1;
327 }
328
329 static json_bool validate_segments_array(struct crypt_device *cd,
330                                          json_object *jarr, json_object *jobj_segments)
331 {
332         json_object *jobj;
333         int i = 0, length = (int) json_object_array_length(jarr);
334
335         while (i < length) {
336                 jobj = json_object_array_get_idx(jarr, i);
337                 if (!json_object_is_type(jobj, json_type_string)) {
338                         log_dbg(cd, "Illegal value type in segments array at index %d.", i);
339                         return 0;
340                 }
341
342                 if (!json_contains(cd, jobj_segments, "", "Segments section",
343                                    json_object_get_string(jobj), json_type_object))
344                         return 0;
345
346                 i++;
347         }
348
349         return 1;
350 }
351
352 static json_bool segment_has_digest(const char *segment_name, json_object *jobj_digests)
353 {
354         json_object *jobj_segments;
355
356         json_object_object_foreach(jobj_digests, key, val) {
357                 UNUSED(key);
358                 json_object_object_get_ex(val, "segments", &jobj_segments);
359                 if (LUKS2_array_jobj(jobj_segments, segment_name))
360                         return 1;
361         }
362
363         return 0;
364 }
365
366 static json_bool validate_intervals(struct crypt_device *cd,
367                                     int length, const struct interval *ix,
368                                     uint64_t metadata_size, uint64_t keyslots_area_end)
369 {
370         int j, i = 0;
371
372         while (i < length) {
373                 if (ix[i].offset < 2 * metadata_size) {
374                         log_dbg(cd, "Illegal area offset: %" PRIu64 ".", ix[i].offset);
375                         return 0;
376                 }
377
378                 if (!ix[i].length) {
379                         log_dbg(cd, "Area length must be greater than zero.");
380                         return 0;
381                 }
382
383                 if ((ix[i].offset + ix[i].length) > keyslots_area_end) {
384                         log_dbg(cd, "Area [%" PRIu64 ", %" PRIu64 "] overflows binary keyslots area (ends at offset: %" PRIu64 ").",
385                                 ix[i].offset, ix[i].offset + ix[i].length, keyslots_area_end);
386                         return 0;
387                 }
388
389                 for (j = 0; j < length; j++) {
390                         if (i == j)
391                                 continue;
392                         if ((ix[i].offset >= ix[j].offset) && (ix[i].offset < (ix[j].offset + ix[j].length))) {
393                                 log_dbg(cd, "Overlapping areas [%" PRIu64 ",%" PRIu64 "] and [%" PRIu64 ",%" PRIu64 "].",
394                                         ix[i].offset, ix[i].offset + ix[i].length,
395                                         ix[j].offset, ix[j].offset + ix[j].length);
396                                 return 0;
397                         }
398                 }
399
400                 i++;
401         }
402
403         return 1;
404 }
405
406 static int LUKS2_keyslot_validate(struct crypt_device *cd, json_object *hdr_jobj, json_object *hdr_keyslot, const char *key)
407 {
408         json_object *jobj_key_size;
409
410         if (!json_contains(cd, hdr_keyslot, key, "Keyslot", "type", json_type_string))
411                 return 1;
412         if (!(jobj_key_size = json_contains(cd, hdr_keyslot, key, "Keyslot", "key_size", json_type_int)))
413                 return 1;
414
415         /* enforce uint32_t type */
416         if (!validate_json_uint32(jobj_key_size)) {
417                 log_dbg(cd, "Illegal field \"key_size\":%s.",
418                         json_object_get_string(jobj_key_size));
419                 return 1;
420         }
421
422         return 0;
423 }
424
425 int LUKS2_token_validate(struct crypt_device *cd,
426                          json_object *hdr_jobj, json_object *jobj_token, const char *key)
427 {
428         json_object *jarr, *jobj_keyslots;
429
430         /* keyslots are not yet validated, but we need to know token doesn't reference missing keyslot */
431         if (!json_object_object_get_ex(hdr_jobj, "keyslots", &jobj_keyslots))
432                 return 1;
433
434         if (!json_contains(cd, jobj_token, key, "Token", "type", json_type_string))
435                 return 1;
436
437         jarr = json_contains(cd, jobj_token, key, "Token", "keyslots", json_type_array);
438         if (!jarr)
439                 return 1;
440
441         if (!validate_keyslots_array(cd, jarr, jobj_keyslots))
442                 return 1;
443
444         return 0;
445 }
446
447 static int hdr_validate_json_size(struct crypt_device *cd, json_object *hdr_jobj, uint64_t hdr_json_size)
448 {
449         json_object *jobj, *jobj1;
450         const char *json;
451         uint64_t json_area_size, json_size;
452
453         json_object_object_get_ex(hdr_jobj, "config", &jobj);
454         json_object_object_get_ex(jobj, "json_size", &jobj1);
455
456         json = json_object_to_json_string_ext(hdr_jobj,
457                 JSON_C_TO_STRING_PLAIN | JSON_C_TO_STRING_NOSLASHESCAPE);
458         json_area_size = crypt_jobj_get_uint64(jobj1);
459         json_size = (uint64_t)strlen(json);
460
461         if (hdr_json_size != json_area_size) {
462                 log_dbg(cd, "JSON area size does not match value in binary header.");
463                 return 1;
464         }
465
466         if (json_size > json_area_size) {
467                 log_dbg(cd, "JSON does not fit in the designated area.");
468                 return 1;
469         }
470
471         return 0;
472 }
473
474 int LUKS2_check_json_size(struct crypt_device *cd, const struct luks2_hdr *hdr)
475 {
476         return hdr_validate_json_size(cd, hdr->jobj, hdr->hdr_size - LUKS2_HDR_BIN_LEN);
477 }
478
479 static int hdr_validate_keyslots(struct crypt_device *cd, json_object *hdr_jobj)
480 {
481         json_object *jobj;
482
483         if (!json_object_object_get_ex(hdr_jobj, "keyslots", &jobj)) {
484                 log_dbg(cd, "Missing keyslots section.");
485                 return 1;
486         }
487
488         json_object_object_foreach(jobj, key, val) {
489                 if (!numbered(cd, "Keyslot", key))
490                         return 1;
491                 if (LUKS2_keyslot_validate(cd, hdr_jobj, val, key))
492                         return 1;
493         }
494
495         return 0;
496 }
497
498 static int hdr_validate_tokens(struct crypt_device *cd, json_object *hdr_jobj)
499 {
500         json_object *jobj;
501
502         if (!json_object_object_get_ex(hdr_jobj, "tokens", &jobj)) {
503                 log_dbg(cd, "Missing tokens section.");
504                 return 1;
505         }
506
507         json_object_object_foreach(jobj, key, val) {
508                 if (!numbered(cd, "Token", key))
509                         return 1;
510                 if (LUKS2_token_validate(cd, hdr_jobj, val, key))
511                         return 1;
512         }
513
514         return 0;
515 }
516
517 static int hdr_validate_crypt_segment(struct crypt_device *cd,
518                                       json_object *jobj, const char *key, json_object *jobj_digests,
519         uint64_t offset, uint64_t size)
520 {
521         json_object *jobj_ivoffset, *jobj_sector_size, *jobj_integrity;
522         uint32_t sector_size;
523         uint64_t ivoffset;
524
525         if (!(jobj_ivoffset = json_contains(cd, jobj, key, "Segment", "iv_tweak", json_type_string)) ||
526             !json_contains(cd, jobj, key, "Segment", "encryption", json_type_string) ||
527             !(jobj_sector_size = json_contains(cd, jobj, key, "Segment", "sector_size", json_type_int)))
528                 return 1;
529
530         /* integrity */
531         if (json_object_object_get_ex(jobj, "integrity", &jobj_integrity)) {
532                 if (!json_contains(cd, jobj, key, "Segment", "integrity", json_type_object) ||
533                     !json_contains(cd, jobj_integrity, key, "Segment integrity", "type", json_type_string) ||
534                     !json_contains(cd, jobj_integrity, key, "Segment integrity", "journal_encryption", json_type_string) ||
535                     !json_contains(cd, jobj_integrity, key, "Segment integrity", "journal_integrity", json_type_string))
536                         return 1;
537         }
538
539         /* enforce uint32_t type */
540         if (!validate_json_uint32(jobj_sector_size)) {
541                 log_dbg(cd, "Illegal field \"sector_size\":%s.",
542                         json_object_get_string(jobj_sector_size));
543                 return 1;
544         }
545
546         sector_size = crypt_jobj_get_uint32(jobj_sector_size);
547         if (!sector_size || MISALIGNED_512(sector_size)) {
548                 log_dbg(cd, "Illegal sector size: %" PRIu32, sector_size);
549                 return 1;
550         }
551
552         if (!numbered(cd, "iv_tweak", json_object_get_string(jobj_ivoffset)) ||
553             !json_str_to_uint64(jobj_ivoffset, &ivoffset)) {
554                 log_dbg(cd, "Illegal iv_tweak value.");
555                 return 1;
556         }
557
558         if (size % sector_size) {
559                 log_dbg(cd, "Size field has to be aligned to sector size: %" PRIu32, sector_size);
560                 return 1;
561         }
562
563         return !segment_has_digest(key, jobj_digests);
564 }
565
566 static bool validate_segment_intervals(struct crypt_device *cd,
567                                     int length, const struct interval *ix)
568 {
569         int j, i = 0;
570
571         while (i < length) {
572                 if (ix[i].length == UINT64_MAX && (i != (length - 1))) {
573                         log_dbg(cd, "Only last regular segment is allowed to have 'dynamic' size.");
574                         return false;
575                 }
576
577                 for (j = 0; j < length; j++) {
578                         if (i == j)
579                                 continue;
580                         if ((ix[i].offset >= ix[j].offset) && (ix[j].length == UINT64_MAX || (ix[i].offset < (ix[j].offset + ix[j].length)))) {
581                                 log_dbg(cd, "Overlapping segments [%" PRIu64 ",%" PRIu64 "]%s and [%" PRIu64 ",%" PRIu64 "]%s.",
582                                         ix[i].offset, ix[i].offset + ix[i].length, ix[i].length == UINT64_MAX ? "(dynamic)" : "",
583                                         ix[j].offset, ix[j].offset + ix[j].length, ix[j].length == UINT64_MAX ? "(dynamic)" : "");
584                                 return false;
585                         }
586                 }
587
588                 i++;
589         }
590
591         return true;
592 }
593
594 static int reqs_unknown(uint32_t reqs)
595 {
596         return reqs & CRYPT_REQUIREMENT_UNKNOWN;
597 }
598
599 static int reqs_reencrypt(uint32_t reqs)
600 {
601         return reqs & CRYPT_REQUIREMENT_OFFLINE_REENCRYPT;
602 }
603
604 static int reqs_reencrypt_online(uint32_t reqs)
605 {
606         return reqs & CRYPT_REQUIREMENT_ONLINE_REENCRYPT;
607 }
608
609 /*
610  * Config section requirements object must be valid.
611  * Also general segments section must be validated first.
612  */
613 static int validate_reencrypt_segments(struct crypt_device *cd, json_object *hdr_jobj, json_object *jobj_segments, int first_backup, int segments_count)
614 {
615         json_object *jobj, *jobj_backup_previous = NULL, *jobj_backup_final = NULL;
616         uint32_t reqs;
617         int i, r;
618         struct luks2_hdr dummy = {
619                 .jobj = hdr_jobj
620         };
621
622         r = LUKS2_config_get_requirements(cd, &dummy, &reqs);
623         if (r)
624                 return 1;
625
626         if (reqs_reencrypt_online(reqs)) {
627                 for (i = first_backup; i < segments_count; i++) {
628                         jobj = json_segments_get_segment(jobj_segments, i);
629                         if (!jobj)
630                                 return 1;
631                         if (json_segment_contains_flag(jobj, "backup-final", 0))
632                                 jobj_backup_final = jobj;
633                         else if (json_segment_contains_flag(jobj, "backup-previous", 0))
634                                 jobj_backup_previous = jobj;
635                 }
636
637                 if (!jobj_backup_final || !jobj_backup_previous) {
638                         log_dbg(cd, "Backup segment is missing.");
639                         return 1;
640                 }
641
642                 for (i = 0; i < first_backup; i++) {
643                         jobj = json_segments_get_segment(jobj_segments, i);
644                         if (!jobj)
645                                 return 1;
646
647                         if (json_segment_contains_flag(jobj, "in-reencryption", 0)) {
648                                 if (!json_segment_cmp(jobj, jobj_backup_final)) {
649                                         log_dbg(cd, "Segment in reencryption does not match backup final segment.");
650                                         return 1;
651                                 }
652                                 continue;
653                         }
654
655                         if (!json_segment_cmp(jobj, jobj_backup_final) &&
656                             !json_segment_cmp(jobj, jobj_backup_previous)) {
657                                 log_dbg(cd, "Segment does not match neither backup final or backup previous segment.");
658                                 return 1;
659                         }
660                 }
661         }
662
663         return 0;
664 }
665
666 static int hdr_validate_segments(struct crypt_device *cd, json_object *hdr_jobj)
667 {
668         json_object *jobj_segments, *jobj_digests, *jobj_offset, *jobj_size, *jobj_type, *jobj_flags, *jobj;
669         uint64_t offset, size;
670         int i, r, count, first_backup = -1;
671         struct interval *intervals = NULL;
672
673         if (!json_object_object_get_ex(hdr_jobj, "segments", &jobj_segments)) {
674                 log_dbg(cd, "Missing segments section.");
675                 return 1;
676         }
677
678         count = json_object_object_length(jobj_segments);
679         if (count < 1) {
680                 log_dbg(cd, "Empty segments section.");
681                 return 1;
682         }
683
684         /* digests should already be validated */
685         if (!json_object_object_get_ex(hdr_jobj, "digests", &jobj_digests))
686                 return 1;
687
688         json_object_object_foreach(jobj_segments, key, val) {
689                 if (!numbered(cd, "Segment", key))
690                         return 1;
691
692                 /* those fields are mandatory for all segment types */
693                 if (!(jobj_type =   json_contains(cd, val, key, "Segment", "type",   json_type_string)) ||
694                     !(jobj_offset = json_contains(cd, val, key, "Segment", "offset", json_type_string)) ||
695                     !(jobj_size =   json_contains(cd, val, key, "Segment", "size",   json_type_string)))
696                         return 1;
697
698                 if (!numbered(cd, "offset", json_object_get_string(jobj_offset)) ||
699                     !json_str_to_uint64(jobj_offset, &offset))
700                         return 1;
701
702                 /* size "dynamic" means whole device starting at 'offset' */
703                 if (strcmp(json_object_get_string(jobj_size), "dynamic")) {
704                         if (!numbered(cd, "size", json_object_get_string(jobj_size)) ||
705                             !json_str_to_uint64(jobj_size, &size) || !size)
706                                 return 1;
707                 } else
708                         size = 0;
709
710                 /* all device-mapper devices are aligned to 512 sector size */
711                 if (MISALIGNED_512(offset)) {
712                         log_dbg(cd, "Offset field has to be aligned to sector size: %" PRIu32, SECTOR_SIZE);
713                         return 1;
714                 }
715                 if (MISALIGNED_512(size)) {
716                         log_dbg(cd, "Size field has to be aligned to sector size: %" PRIu32, SECTOR_SIZE);
717                         return 1;
718                 }
719
720                 /* flags array is optional and must contain strings */
721                 if (json_object_object_get_ex(val, "flags", NULL)) {
722                         if (!(jobj_flags = json_contains(cd, val, key, "Segment", "flags", json_type_array)))
723                                 return 1;
724                         for (i = 0; i < (int) json_object_array_length(jobj_flags); i++)
725                                 if (!json_object_is_type(json_object_array_get_idx(jobj_flags, i), json_type_string))
726                                         return 1;
727                 }
728
729                 i = atoi(key);
730                 if (json_segment_is_backup(val)) {
731                         if (first_backup < 0 || i < first_backup)
732                                 first_backup = i;
733                 } else {
734                         if ((first_backup >= 0) && i >= first_backup) {
735                                 log_dbg(cd, "Regular segment at %d is behind backup segment at %d", i, first_backup);
736                                 return 1;
737                         }
738                 }
739
740                 /* crypt */
741                 if (!strcmp(json_object_get_string(jobj_type), "crypt") &&
742                     hdr_validate_crypt_segment(cd, val, key, jobj_digests, offset, size))
743                         return 1;
744         }
745
746         if (first_backup == 0) {
747                 log_dbg(cd, "No regular segment.");
748                 return 1;
749         }
750
751         /* avoid needlessly large allocation when first backup segment is invalid */
752         if (first_backup >= count) {
753                 log_dbg(cd, "Gap between last regular segment and backup segment at key %d.", first_backup);
754                 return 1;
755         }
756
757         if (first_backup < 0)
758                 first_backup = count;
759
760         if ((size_t)first_backup < SIZE_MAX / sizeof(*intervals))
761                 intervals = malloc(first_backup * sizeof(*intervals));
762
763         if (!intervals) {
764                 log_dbg(cd, "Not enough memory.");
765                 return 1;
766         }
767
768         for (i = 0; i < first_backup; i++) {
769                 jobj = json_segments_get_segment(jobj_segments, i);
770                 if (!jobj) {
771                         log_dbg(cd, "Gap at key %d in segments object.", i);
772                         free(intervals);
773                         return 1;
774                 }
775                 intervals[i].offset = json_segment_get_offset(jobj, 0);
776                 intervals[i].length = json_segment_get_size(jobj, 0) ?: UINT64_MAX;
777         }
778
779         r = !validate_segment_intervals(cd, first_backup, intervals);
780         free(intervals);
781
782         if (r)
783                 return 1;
784
785         for (; i < count; i++) {
786                 if (!json_segments_get_segment(jobj_segments, i)) {
787                         log_dbg(cd, "Gap at key %d in segments object.", i);
788                         return 1;
789                 }
790         }
791
792         return validate_reencrypt_segments(cd, hdr_jobj, jobj_segments, first_backup, count);
793 }
794
795 static uint64_t LUKS2_metadata_size_jobj(json_object *jobj)
796 {
797         json_object *jobj1, *jobj2;
798         uint64_t json_size;
799
800         json_object_object_get_ex(jobj, "config", &jobj1);
801         json_object_object_get_ex(jobj1, "json_size", &jobj2);
802         json_str_to_uint64(jobj2, &json_size);
803
804         return json_size + LUKS2_HDR_BIN_LEN;
805 }
806
807 uint64_t LUKS2_metadata_size(struct luks2_hdr *hdr)
808 {
809         return LUKS2_metadata_size_jobj(hdr->jobj);
810 }
811
812 static int hdr_validate_areas(struct crypt_device *cd, json_object *hdr_jobj)
813 {
814         struct interval *intervals;
815         json_object *jobj_keyslots, *jobj_offset, *jobj_length, *jobj_segments, *jobj_area;
816         int length, ret, i = 0;
817         uint64_t metadata_size;
818
819         if (!json_object_object_get_ex(hdr_jobj, "keyslots", &jobj_keyslots))
820                 return 1;
821
822         /* segments are already validated */
823         if (!json_object_object_get_ex(hdr_jobj, "segments", &jobj_segments))
824                 return 1;
825
826         /* config is already validated */
827         metadata_size = LUKS2_metadata_size_jobj(hdr_jobj);
828
829         length = json_object_object_length(jobj_keyslots);
830
831         /* Empty section */
832         if (length == 0)
833                 return 0;
834
835         if (length < 0) {
836                 log_dbg(cd, "Invalid keyslot areas specification.");
837                 return 1;
838         }
839
840         intervals = malloc(length * sizeof(*intervals));
841         if (!intervals) {
842                 log_dbg(cd, "Not enough memory.");
843                 return -ENOMEM;
844         }
845
846         json_object_object_foreach(jobj_keyslots, key, val) {
847
848                 if (!(jobj_area = json_contains(cd, val, key, "Keyslot", "area", json_type_object)) ||
849                     !json_contains(cd, jobj_area, key, "Keyslot area", "type", json_type_string) ||
850                     !(jobj_offset = json_contains(cd, jobj_area, key, "Keyslot", "offset", json_type_string)) ||
851                     !(jobj_length = json_contains(cd, jobj_area, key, "Keyslot", "size", json_type_string)) ||
852                     !numbered(cd, "offset", json_object_get_string(jobj_offset)) ||
853                     !numbered(cd, "size", json_object_get_string(jobj_length))) {
854                         free(intervals);
855                         return 1;
856                 }
857
858                 /* rule out values > UINT64_MAX */
859                 if (!json_str_to_uint64(jobj_offset, &intervals[i].offset) ||
860                     !json_str_to_uint64(jobj_length, &intervals[i].length)) {
861                         free(intervals);
862                         return 1;
863                 }
864
865                 i++;
866         }
867
868         if (length != i) {
869                 free(intervals);
870                 return 1;
871         }
872
873         ret = validate_intervals(cd, length, intervals, metadata_size, LUKS2_hdr_and_areas_size_jobj(hdr_jobj)) ? 0 : 1;
874
875         free(intervals);
876
877         return ret;
878 }
879
880 static int hdr_validate_digests(struct crypt_device *cd, json_object *hdr_jobj)
881 {
882         json_object *jarr_keys, *jarr_segs, *jobj, *jobj_keyslots, *jobj_segments;
883
884         if (!json_object_object_get_ex(hdr_jobj, "digests", &jobj)) {
885                 log_dbg(cd, "Missing digests section.");
886                 return 1;
887         }
888
889         /* keyslots are not yet validated, but we need to know digest doesn't reference missing keyslot */
890         if (!json_object_object_get_ex(hdr_jobj, "keyslots", &jobj_keyslots))
891                 return 1;
892
893         /* segments are not yet validated, but we need to know digest doesn't reference missing segment */
894         if (!json_object_object_get_ex(hdr_jobj, "segments", &jobj_segments))
895                 return 1;
896
897         json_object_object_foreach(jobj, key, val) {
898                 if (!numbered(cd, "Digest", key))
899                         return 1;
900
901                 if (!json_contains(cd, val, key, "Digest", "type", json_type_string) ||
902                     !(jarr_keys = json_contains(cd, val, key, "Digest", "keyslots", json_type_array)) ||
903                     !(jarr_segs = json_contains(cd, val, key, "Digest", "segments", json_type_array)))
904                         return 1;
905
906                 if (!validate_keyslots_array(cd, jarr_keys, jobj_keyslots))
907                         return 1;
908                 if (!validate_segments_array(cd, jarr_segs, jobj_segments))
909                         return 1;
910         }
911
912         return 0;
913 }
914
915 /* requirements being validated in stand-alone routine */
916 static int hdr_validate_config(struct crypt_device *cd, json_object *hdr_jobj)
917 {
918         json_object *jobj_config, *jobj;
919         int i;
920         uint64_t keyslots_size, metadata_size, segment_offset;
921
922         if (!json_object_object_get_ex(hdr_jobj, "config", &jobj_config)) {
923                 log_dbg(cd, "Missing config section.");
924                 return 1;
925         }
926
927         if (!(jobj = json_contains(cd, jobj_config, "section", "Config", "json_size", json_type_string)) ||
928             !json_str_to_uint64(jobj, &metadata_size))
929                 return 1;
930
931         /* single metadata instance is assembled from json area size plus
932          * binary header size */
933         metadata_size += LUKS2_HDR_BIN_LEN;
934
935         if (!(jobj = json_contains(cd, jobj_config, "section", "Config", "keyslots_size", json_type_string)) ||
936             !json_str_to_uint64(jobj, &keyslots_size))
937                 return 1;
938
939         if (LUKS2_check_metadata_area_size(metadata_size)) {
940                 log_dbg(cd, "Unsupported LUKS2 header size (%" PRIu64 ").", metadata_size);
941                 return 1;
942         }
943
944         if (LUKS2_check_keyslots_area_size(keyslots_size)) {
945                 log_dbg(cd, "Unsupported LUKS2 keyslots size (%" PRIu64 ").", keyslots_size);
946                 return 1;
947         }
948
949         /*
950          * validate keyslots_size fits in between (2 * metadata_size) and first
951          * segment_offset (except detached header)
952          */
953         segment_offset = json_segments_get_minimal_offset(json_get_segments_jobj(hdr_jobj), 0);
954         if (segment_offset &&
955             (segment_offset < keyslots_size ||
956              (segment_offset - keyslots_size) < (2 * metadata_size))) {
957                 log_dbg(cd, "keyslots_size is too large %" PRIu64 " (bytes). Data offset: %" PRIu64
958                         ", keyslots offset: %" PRIu64, keyslots_size, segment_offset, 2 * metadata_size);
959                 return 1;
960         }
961
962         /* Flags array is optional */
963         if (json_object_object_get_ex(jobj_config, "flags", &jobj)) {
964                 if (!json_contains(cd, jobj_config, "section", "Config", "flags", json_type_array))
965                         return 1;
966
967                 /* All array members must be strings */
968                 for (i = 0; i < (int) json_object_array_length(jobj); i++)
969                         if (!json_object_is_type(json_object_array_get_idx(jobj, i), json_type_string))
970                                 return 1;
971         }
972
973         return 0;
974 }
975
976 static int hdr_validate_requirements(struct crypt_device *cd, json_object *hdr_jobj)
977 {
978         int i;
979         json_object *jobj_config, *jobj, *jobj1;
980
981         if (!json_object_object_get_ex(hdr_jobj, "config", &jobj_config)) {
982                 log_dbg(cd, "Missing config section.");
983                 return 1;
984         }
985
986         /* Requirements object is optional */
987         if (json_object_object_get_ex(jobj_config, "requirements", &jobj)) {
988                 if (!json_contains(cd, jobj_config, "section", "Config", "requirements", json_type_object))
989                         return 1;
990
991                 /* Mandatory array is optional */
992                 if (json_object_object_get_ex(jobj, "mandatory", &jobj1)) {
993                         if (!json_contains(cd, jobj, "section", "Requirements", "mandatory", json_type_array))
994                                 return 1;
995
996                         /* All array members must be strings */
997                         for (i = 0; i < (int) json_object_array_length(jobj1); i++)
998                                 if (!json_object_is_type(json_object_array_get_idx(jobj1, i), json_type_string))
999                                         return 1;
1000                 }
1001         }
1002
1003         return 0;
1004 }
1005
1006 int LUKS2_hdr_validate(struct crypt_device *cd, json_object *hdr_jobj, uint64_t json_size)
1007 {
1008         struct {
1009                 int (*validate)(struct crypt_device *, json_object *);
1010         } checks[] = {
1011                 { hdr_validate_requirements },
1012                 { hdr_validate_tokens   },
1013                 { hdr_validate_digests  },
1014                 { hdr_validate_segments },
1015                 { hdr_validate_keyslots },
1016                 { hdr_validate_config   },
1017                 { hdr_validate_areas    },
1018                 { NULL }
1019         };
1020         int i;
1021
1022         if (!hdr_jobj)
1023                 return 1;
1024
1025         for (i = 0; checks[i].validate; i++)
1026                 if (checks[i].validate && checks[i].validate(cd, hdr_jobj))
1027                         return 1;
1028
1029         if (hdr_validate_json_size(cd, hdr_jobj, json_size))
1030                 return 1;
1031
1032         /* validate keyslot implementations */
1033         if (LUKS2_keyslots_validate(cd, hdr_jobj))
1034                 return 1;
1035
1036         return 0;
1037 }
1038
1039 /* FIXME: should we expose do_recovery parameter explicitly? */
1040 int LUKS2_hdr_read(struct crypt_device *cd, struct luks2_hdr *hdr, int repair)
1041 {
1042         int r;
1043
1044         r = device_read_lock(cd, crypt_metadata_device(cd));
1045         if (r) {
1046                 log_err(cd, _("Failed to acquire read lock on device %s."),
1047                         device_path(crypt_metadata_device(cd)));
1048                 return r;
1049         }
1050
1051         r = LUKS2_disk_hdr_read(cd, hdr, crypt_metadata_device(cd), 1, !repair);
1052         if (r == -EAGAIN) {
1053                 /* unlikely: auto-recovery is required and failed due to read lock being held */
1054                 device_read_unlock(cd, crypt_metadata_device(cd));
1055
1056                 /* Do not use LUKS2_device_write lock. Recovery. */
1057                 r = device_write_lock(cd, crypt_metadata_device(cd));
1058                 if (r < 0) {
1059                         log_err(cd, _("Failed to acquire write lock on device %s."),
1060                                 device_path(crypt_metadata_device(cd)));
1061                         return r;
1062                 }
1063
1064                 r = LUKS2_disk_hdr_read(cd, hdr, crypt_metadata_device(cd), 1, !repair);
1065
1066                 device_write_unlock(cd, crypt_metadata_device(cd));
1067         } else
1068                 device_read_unlock(cd, crypt_metadata_device(cd));
1069
1070         return r;
1071 }
1072
1073 static int hdr_cleanup_and_validate(struct crypt_device *cd, struct luks2_hdr *hdr)
1074 {
1075         LUKS2_digests_erase_unused(cd, hdr);
1076
1077         return LUKS2_hdr_validate(cd, hdr->jobj, hdr->hdr_size - LUKS2_HDR_BIN_LEN);
1078 }
1079
1080 int LUKS2_hdr_write_force(struct crypt_device *cd, struct luks2_hdr *hdr)
1081 {
1082         if (hdr_cleanup_and_validate(cd, hdr))
1083                 return -EINVAL;
1084
1085         return LUKS2_disk_hdr_write(cd, hdr, crypt_metadata_device(cd), false);
1086 }
1087
1088 int LUKS2_hdr_write(struct crypt_device *cd, struct luks2_hdr *hdr)
1089 {
1090         if (hdr_cleanup_and_validate(cd, hdr))
1091                 return -EINVAL;
1092
1093         return LUKS2_disk_hdr_write(cd, hdr, crypt_metadata_device(cd), true);
1094 }
1095
1096 int LUKS2_hdr_uuid(struct crypt_device *cd, struct luks2_hdr *hdr, const char *uuid)
1097 {
1098         uuid_t partitionUuid;
1099
1100         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
1101                 log_err(cd, _("Wrong LUKS UUID format provided."));
1102                 return -EINVAL;
1103         }
1104         if (!uuid)
1105                 uuid_generate(partitionUuid);
1106
1107         uuid_unparse(partitionUuid, hdr->uuid);
1108
1109         return LUKS2_hdr_write(cd, hdr);
1110 }
1111
1112 int LUKS2_hdr_labels(struct crypt_device *cd, struct luks2_hdr *hdr,
1113                      const char *label, const char *subsystem, int commit)
1114 {
1115         //FIXME: check if the labels are the same and skip this.
1116
1117         memset(hdr->label, 0, LUKS2_LABEL_L);
1118         if (label)
1119                 strncpy(hdr->label, label, LUKS2_LABEL_L-1);
1120
1121         memset(hdr->subsystem, 0, LUKS2_LABEL_L);
1122         if (subsystem)
1123                 strncpy(hdr->subsystem, subsystem, LUKS2_LABEL_L-1);
1124
1125         return commit ? LUKS2_hdr_write(cd, hdr) : 0;
1126 }
1127
1128 void LUKS2_hdr_free(struct crypt_device *cd, struct luks2_hdr *hdr)
1129 {
1130         if (json_object_put(hdr->jobj))
1131                 hdr->jobj = NULL;
1132         else if (hdr->jobj)
1133                 log_dbg(cd, "LUKS2 header still in use");
1134 }
1135
1136 static uint64_t LUKS2_keyslots_size_jobj(json_object *jobj)
1137 {
1138         json_object *jobj1, *jobj2;
1139         uint64_t keyslots_size;
1140
1141         json_object_object_get_ex(jobj, "config", &jobj1);
1142         json_object_object_get_ex(jobj1, "keyslots_size", &jobj2);
1143         json_str_to_uint64(jobj2, &keyslots_size);
1144
1145         return keyslots_size;
1146 }
1147
1148 uint64_t LUKS2_keyslots_size(struct luks2_hdr *hdr)
1149 {
1150         return LUKS2_keyslots_size_jobj(hdr->jobj);
1151 }
1152
1153 uint64_t LUKS2_hdr_and_areas_size_jobj(json_object *jobj)
1154 {
1155         return 2 * LUKS2_metadata_size_jobj(jobj) + LUKS2_keyslots_size_jobj(jobj);
1156 }
1157
1158 uint64_t LUKS2_hdr_and_areas_size(struct luks2_hdr *hdr)
1159 {
1160         return LUKS2_hdr_and_areas_size_jobj(hdr->jobj);
1161 }
1162
1163 int LUKS2_hdr_backup(struct crypt_device *cd, struct luks2_hdr *hdr,
1164                      const char *backup_file)
1165 {
1166         struct device *device = crypt_metadata_device(cd);
1167         int fd, devfd, r = 0;
1168         ssize_t hdr_size;
1169         ssize_t ret, buffer_size;
1170         char *buffer = NULL;
1171
1172         hdr_size = LUKS2_hdr_and_areas_size(hdr);
1173         buffer_size = size_round_up(hdr_size, crypt_getpagesize());
1174
1175         buffer = crypt_safe_alloc(buffer_size);
1176         if (!buffer)
1177                 return -ENOMEM;
1178
1179         log_dbg(cd, "Storing backup of header (%zu bytes).", hdr_size);
1180         log_dbg(cd, "Output backup file size: %zu bytes.", buffer_size);
1181
1182         r = device_read_lock(cd, device);
1183         if (r) {
1184                 log_err(cd, _("Failed to acquire read lock on device %s."),
1185                         device_path(crypt_metadata_device(cd)));
1186                 crypt_safe_free(buffer);
1187                 return r;
1188         }
1189
1190         devfd = device_open_locked(cd, device, O_RDONLY);
1191         if (devfd < 0) {
1192                 device_read_unlock(cd, device);
1193                 log_err(cd, _("Device %s is not a valid LUKS device."), device_path(device));
1194                 crypt_safe_free(buffer);
1195                 return devfd == -1 ? -EINVAL : devfd;
1196         }
1197
1198         if (read_lseek_blockwise(devfd, device_block_size(cd, device),
1199                            device_alignment(device), buffer, hdr_size, 0) < hdr_size) {
1200                 device_read_unlock(cd, device);
1201                 crypt_safe_free(buffer);
1202                 return -EIO;
1203         }
1204
1205         device_read_unlock(cd, device);
1206
1207         fd = open(backup_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR);
1208         if (fd == -1) {
1209                 if (errno == EEXIST)
1210                         log_err(cd, _("Requested header backup file %s already exists."), backup_file);
1211                 else
1212                         log_err(cd, _("Cannot create header backup file %s."), backup_file);
1213                 crypt_safe_free(buffer);
1214                 return -EINVAL;
1215         }
1216         ret = write_buffer(fd, buffer, buffer_size);
1217         close(fd);
1218         if (ret < buffer_size) {
1219                 log_err(cd, _("Cannot write header backup file %s."), backup_file);
1220                 r = -EIO;
1221         } else
1222                 r = 0;
1223
1224         crypt_safe_free(buffer);
1225         return r;
1226 }
1227
1228 int LUKS2_hdr_restore(struct crypt_device *cd, struct luks2_hdr *hdr,
1229                      const char *backup_file)
1230 {
1231         struct device *backup_device, *device = crypt_metadata_device(cd);
1232         int r, fd, devfd = -1, diff_uuid = 0;
1233         ssize_t ret, buffer_size = 0;
1234         char *buffer = NULL, msg[1024];
1235         struct luks2_hdr hdr_file;
1236         struct luks2_hdr tmp_hdr = {};
1237         uint32_t reqs = 0;
1238
1239         r = device_alloc(cd, &backup_device, backup_file);
1240         if (r < 0)
1241                 return r;
1242
1243         r = device_read_lock(cd, backup_device);
1244         if (r) {
1245                 log_err(cd, _("Failed to acquire read lock on device %s."),
1246                         device_path(backup_device));
1247                 device_free(cd, backup_device);
1248                 return r;
1249         }
1250
1251         r = LUKS2_disk_hdr_read(cd, &hdr_file, backup_device, 0, 0);
1252         device_read_unlock(cd, backup_device);
1253         device_free(cd, backup_device);
1254
1255         if (r < 0) {
1256                 log_err(cd, _("Backup file does not contain valid LUKS header."));
1257                 goto out;
1258         }
1259
1260         /* do not allow header restore from backup with unmet requirements */
1261         if (LUKS2_unmet_requirements(cd, &hdr_file, CRYPT_REQUIREMENT_ONLINE_REENCRYPT, 1)) {
1262                 log_err(cd, _("Forbidden LUKS2 requirements detected in backup %s."),
1263                         backup_file);
1264                 r = -ETXTBSY;
1265                 goto out;
1266         }
1267
1268         buffer_size = LUKS2_hdr_and_areas_size(&hdr_file);
1269         buffer = crypt_safe_alloc(buffer_size);
1270         if (!buffer) {
1271                 r = -ENOMEM;
1272                 goto out;
1273         }
1274
1275         fd = open(backup_file, O_RDONLY);
1276         if (fd == -1) {
1277                 log_err(cd, _("Cannot open header backup file %s."), backup_file);
1278                 r = -EINVAL;
1279                 goto out;
1280         }
1281
1282         ret = read_buffer(fd, buffer, buffer_size);
1283         close(fd);
1284         if (ret < buffer_size) {
1285                 log_err(cd, _("Cannot read header backup file %s."), backup_file);
1286                 r = -EIO;
1287                 goto out;
1288         }
1289
1290         r = LUKS2_hdr_read(cd, &tmp_hdr, 0);
1291         if (r == 0) {
1292                 log_dbg(cd, "Device %s already contains LUKS2 header, checking UUID and requirements.", device_path(device));
1293                 r = LUKS2_config_get_requirements(cd, &tmp_hdr, &reqs);
1294                 if (r)
1295                         goto out;
1296
1297                 if (memcmp(tmp_hdr.uuid, hdr_file.uuid, LUKS2_UUID_L))
1298                         diff_uuid = 1;
1299
1300                 if (!reqs_reencrypt(reqs)) {
1301                         log_dbg(cd, "Checking LUKS2 header size and offsets.");
1302                         if (LUKS2_get_data_offset(&tmp_hdr) != LUKS2_get_data_offset(&hdr_file)) {
1303                                 log_err(cd, _("Data offset differ on device and backup, restore failed."));
1304                                 r = -EINVAL;
1305                                 goto out;
1306                         }
1307                         /* FIXME: what could go wrong? Erase if we're fine with consequences */
1308                         if (buffer_size != (ssize_t) LUKS2_hdr_and_areas_size(&tmp_hdr)) {
1309                                 log_err(cd, _("Binary header with keyslot areas size differ on device and backup, restore failed."));
1310                                 r = -EINVAL;
1311                                 goto out;
1312                         }
1313                 }
1314         }
1315
1316         r = snprintf(msg, sizeof(msg), _("Device %s %s%s%s%s"), device_path(device),
1317                      r ? _("does not contain LUKS2 header. Replacing header can destroy data on that device.") :
1318                          _("already contains LUKS2 header. Replacing header will destroy existing keyslots."),
1319                      diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "",
1320                      reqs_unknown(reqs) ? _("\nWARNING: unknown LUKS2 requirements detected in real device header!"
1321                                             "\nReplacing header with backup may corrupt the data on that device!") : "",
1322                      reqs_reencrypt(reqs) ? _("\nWARNING: Unfinished offline reencryption detected on the device!"
1323                                               "\nReplacing header with backup may corrupt data.") : "");
1324         if (r < 0 || (size_t) r >= sizeof(msg)) {
1325                 r = -ENOMEM;
1326                 goto out;
1327         }
1328
1329         if (!crypt_confirm(cd, msg)) {
1330                 r = -EINVAL;
1331                 goto out;
1332         }
1333
1334         log_dbg(cd, "Storing backup of header (%zu bytes) to device %s.", buffer_size, device_path(device));
1335
1336         /* Do not use LUKS2_device_write lock for checking sequence id on restore */
1337         r = device_write_lock(cd, device);
1338         if (r < 0) {
1339                 log_err(cd, _("Failed to acquire write lock on device %s."),
1340                         device_path(device));
1341                 goto out;
1342         }
1343
1344         devfd = device_open_locked(cd, device, O_RDWR);
1345         if (devfd < 0) {
1346                 if (errno == EACCES)
1347                         log_err(cd, _("Cannot write to device %s, permission denied."),
1348                                 device_path(device));
1349                 else
1350                         log_err(cd, _("Cannot open device %s."), device_path(device));
1351                 device_write_unlock(cd, device);
1352                 r = -EINVAL;
1353                 goto out;
1354         }
1355
1356         if (write_lseek_blockwise(devfd, device_block_size(cd, device),
1357                             device_alignment(device), buffer, buffer_size, 0) < buffer_size)
1358                 r = -EIO;
1359         else
1360                 r = 0;
1361
1362         device_write_unlock(cd, device);
1363 out:
1364         LUKS2_hdr_free(cd, hdr);
1365         LUKS2_hdr_free(cd, &hdr_file);
1366         LUKS2_hdr_free(cd, &tmp_hdr);
1367         crypt_safe_memzero(&hdr_file, sizeof(hdr_file));
1368         crypt_safe_memzero(&tmp_hdr, sizeof(tmp_hdr));
1369         crypt_safe_free(buffer);
1370
1371         device_sync(cd, device);
1372
1373         return r;
1374 }
1375
1376 /*
1377  * Persistent config flags
1378  */
1379 static const struct  {
1380         uint32_t flag;
1381         const char *description;
1382 } persistent_flags[] = {
1383         { CRYPT_ACTIVATE_ALLOW_DISCARDS,         "allow-discards" },
1384         { CRYPT_ACTIVATE_SAME_CPU_CRYPT,         "same-cpu-crypt" },
1385         { CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS, "submit-from-crypt-cpus" },
1386         { CRYPT_ACTIVATE_NO_JOURNAL,             "no-journal" },
1387         { CRYPT_ACTIVATE_NO_READ_WORKQUEUE,      "no-read-workqueue" },
1388         { CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE,     "no-write-workqueue" },
1389         { 0, NULL }
1390 };
1391
1392 int LUKS2_config_get_flags(struct crypt_device *cd, struct luks2_hdr *hdr, uint32_t *flags)
1393 {
1394         json_object *jobj1, *jobj_config, *jobj_flags;
1395         int i, j, found;
1396
1397         if (!hdr || !flags)
1398                 return -EINVAL;
1399
1400         *flags = 0;
1401
1402         if (!json_object_object_get_ex(hdr->jobj, "config", &jobj_config))
1403                 return 0;
1404
1405         if (!json_object_object_get_ex(jobj_config, "flags", &jobj_flags))
1406                 return 0;
1407
1408         for (i = 0; i < (int) json_object_array_length(jobj_flags); i++) {
1409                 jobj1 = json_object_array_get_idx(jobj_flags, i);
1410                 found = 0;
1411                 for (j = 0; persistent_flags[j].description && !found; j++)
1412                         if (!strcmp(persistent_flags[j].description,
1413                                     json_object_get_string(jobj1))) {
1414                                 *flags |= persistent_flags[j].flag;
1415                                 log_dbg(cd, "Using persistent flag %s.",
1416                                         json_object_get_string(jobj1));
1417                                 found = 1;
1418                         }
1419                 if (!found)
1420                         log_verbose(cd, _("Ignored unknown flag %s."),
1421                                     json_object_get_string(jobj1));
1422         }
1423
1424         return 0;
1425 }
1426
1427 int LUKS2_config_set_flags(struct crypt_device *cd, struct luks2_hdr *hdr, uint32_t flags)
1428 {
1429         json_object *jobj_config, *jobj_flags;
1430         int i;
1431
1432         if (!json_object_object_get_ex(hdr->jobj, "config", &jobj_config))
1433                 return 0;
1434
1435         jobj_flags = json_object_new_array();
1436
1437         for (i = 0; persistent_flags[i].description; i++) {
1438                 if (flags & persistent_flags[i].flag) {
1439                         log_dbg(cd, "Setting persistent flag: %s.", persistent_flags[i].description);
1440                         json_object_array_add(jobj_flags,
1441                                 json_object_new_string(persistent_flags[i].description));
1442                 }
1443         }
1444
1445         /* Replace or add new flags array */
1446         json_object_object_add(jobj_config, "flags", jobj_flags);
1447
1448         return LUKS2_hdr_write(cd, hdr);
1449 }
1450
1451 /*
1452  * json format example (mandatory array must not be ignored,
1453  * all other future fields may be added later)
1454  *
1455  * "requirements": {
1456  *       mandatory : [],
1457  *       optional0 : [],
1458  *       optional1 : "lala"
1459  * }
1460  */
1461
1462 /* LUKS2 library requirements */
1463 struct requirement_flag {
1464         uint32_t flag;
1465         uint32_t version;
1466         const char *description;
1467 };
1468
1469 static const struct requirement_flag unknown_requirement_flag = { CRYPT_REQUIREMENT_UNKNOWN, 0, NULL };
1470
1471 static const struct requirement_flag requirements_flags[] = {
1472         { CRYPT_REQUIREMENT_OFFLINE_REENCRYPT,1, "offline-reencrypt" },
1473         { CRYPT_REQUIREMENT_ONLINE_REENCRYPT, 2, "online-reencrypt-v2" },
1474         { CRYPT_REQUIREMENT_ONLINE_REENCRYPT, 1, "online-reencrypt" },
1475         { 0, 0, NULL }
1476 };
1477
1478 static const struct requirement_flag *get_requirement_by_name(const char *requirement)
1479 {
1480         int i;
1481
1482         for (i = 0; requirements_flags[i].description; i++)
1483                 if (!strcmp(requirement, requirements_flags[i].description))
1484                         return requirements_flags + i;
1485
1486         return &unknown_requirement_flag;
1487 }
1488
1489 int LUKS2_config_get_reencrypt_version(struct luks2_hdr *hdr, uint32_t *version)
1490 {
1491         json_object *jobj_config, *jobj_requirements, *jobj_mandatory, *jobj;
1492         int i, len;
1493         const struct requirement_flag *req;
1494
1495         assert(hdr && version);
1496         if (!hdr || !version)
1497                 return -EINVAL;
1498
1499         if (!json_object_object_get_ex(hdr->jobj, "config", &jobj_config))
1500                 return -EINVAL;
1501
1502         if (!json_object_object_get_ex(jobj_config, "requirements", &jobj_requirements))
1503                 return -ENOENT;
1504
1505         if (!json_object_object_get_ex(jobj_requirements, "mandatory", &jobj_mandatory))
1506                 return -ENOENT;
1507
1508         len = (int) json_object_array_length(jobj_mandatory);
1509         if (len <= 0)
1510                 return -ENOENT;
1511
1512         for (i = 0; i < len; i++) {
1513                 jobj = json_object_array_get_idx(jobj_mandatory, i);
1514
1515                 /* search for requirements prefixed with "online-reencrypt" */
1516                 if (strncmp(json_object_get_string(jobj), "online-reencrypt", 16))
1517                         continue;
1518
1519                 /* check current library is aware of the requirement */
1520                 req = get_requirement_by_name(json_object_get_string(jobj));
1521                 if (req->flag == (uint32_t)CRYPT_REQUIREMENT_UNKNOWN)
1522                         continue;
1523
1524                 *version = req->version;
1525
1526                 return 0;
1527         }
1528
1529         return -ENOENT;
1530 }
1531
1532 static const struct requirement_flag *stored_requirement_name_by_id(struct crypt_device *cd, struct luks2_hdr *hdr, uint32_t req_id)
1533 {
1534         json_object *jobj_config, *jobj_requirements, *jobj_mandatory, *jobj;
1535         int i, len;
1536         const struct requirement_flag *req;
1537
1538         assert(hdr);
1539         if (!hdr)
1540                 return NULL;
1541
1542         if (!json_object_object_get_ex(hdr->jobj, "config", &jobj_config))
1543                 return NULL;
1544
1545         if (!json_object_object_get_ex(jobj_config, "requirements", &jobj_requirements))
1546                 return NULL;
1547
1548         if (!json_object_object_get_ex(jobj_requirements, "mandatory", &jobj_mandatory))
1549                 return NULL;
1550
1551         len = (int) json_object_array_length(jobj_mandatory);
1552         if (len <= 0)
1553                 return 0;
1554
1555         for (i = 0; i < len; i++) {
1556                 jobj = json_object_array_get_idx(jobj_mandatory, i);
1557                 req = get_requirement_by_name(json_object_get_string(jobj));
1558                 if (req->flag == req_id)
1559                         return req;
1560         }
1561
1562         return NULL;
1563 }
1564
1565 /*
1566  * returns count of requirements (past cryptsetup 2.0 release)
1567  */
1568 int LUKS2_config_get_requirements(struct crypt_device *cd, struct luks2_hdr *hdr, uint32_t *reqs)
1569 {
1570         json_object *jobj_config, *jobj_requirements, *jobj_mandatory, *jobj;
1571         int i, len;
1572         const struct requirement_flag *req;
1573
1574         assert(hdr);
1575         if (!hdr || !reqs)
1576                 return -EINVAL;
1577
1578         *reqs = 0;
1579
1580         if (!json_object_object_get_ex(hdr->jobj, "config", &jobj_config))
1581                 return 0;
1582
1583         if (!json_object_object_get_ex(jobj_config, "requirements", &jobj_requirements))
1584                 return 0;
1585
1586         if (!json_object_object_get_ex(jobj_requirements, "mandatory", &jobj_mandatory))
1587                 return 0;
1588
1589         len = (int) json_object_array_length(jobj_mandatory);
1590         if (len <= 0)
1591                 return 0;
1592
1593         log_dbg(cd, "LUKS2 requirements detected:");
1594
1595         for (i = 0; i < len; i++) {
1596                 jobj = json_object_array_get_idx(jobj_mandatory, i);
1597                 req = get_requirement_by_name(json_object_get_string(jobj));
1598                 log_dbg(cd, "%s - %sknown", json_object_get_string(jobj),
1599                                         reqs_unknown(req->flag) ? "un" : "");
1600                 *reqs |= req->flag;
1601         }
1602
1603         return 0;
1604 }
1605
1606 int LUKS2_config_set_requirements(struct crypt_device *cd, struct luks2_hdr *hdr, uint32_t reqs, bool commit)
1607 {
1608         json_object *jobj_config, *jobj_requirements, *jobj_mandatory, *jobj;
1609         int i, r = -EINVAL;
1610         const struct requirement_flag *req;
1611         uint32_t req_id;
1612
1613         if (!hdr)
1614                 return -EINVAL;
1615
1616         jobj_mandatory = json_object_new_array();
1617         if (!jobj_mandatory)
1618                 return -ENOMEM;
1619
1620         for (i = 0; requirements_flags[i].description; i++) {
1621                 req_id = reqs & requirements_flags[i].flag;
1622                 if (req_id) {
1623                         /* retain already stored version of requirement flag */
1624                         req = stored_requirement_name_by_id(cd, hdr, req_id);
1625                         if (req)
1626                                 jobj = json_object_new_string(req->description);
1627                         else
1628                                 jobj = json_object_new_string(requirements_flags[i].description);
1629                         if (!jobj) {
1630                                 r = -ENOMEM;
1631                                 goto err;
1632                         }
1633                         json_object_array_add(jobj_mandatory, jobj);
1634                         /* erase processed flag from input set */
1635                         reqs &= ~(requirements_flags[i].flag);
1636                 }
1637         }
1638
1639         /* any remaining bit in requirements is unknown therefore illegal */
1640         if (reqs) {
1641                 log_dbg(cd, "Illegal requirement flag(s) requested");
1642                 goto err;
1643         }
1644
1645         if (!json_object_object_get_ex(hdr->jobj, "config", &jobj_config))
1646                 goto err;
1647
1648         if (!json_object_object_get_ex(jobj_config, "requirements", &jobj_requirements)) {
1649                 jobj_requirements = json_object_new_object();
1650                 if (!jobj_requirements) {
1651                         r = -ENOMEM;
1652                         goto err;
1653                 }
1654                 json_object_object_add(jobj_config, "requirements", jobj_requirements);
1655         }
1656
1657         if (json_object_array_length(jobj_mandatory) > 0) {
1658                 /* replace mandatory field with new values */
1659                 json_object_object_add(jobj_requirements, "mandatory", jobj_mandatory);
1660         } else {
1661                 /* new mandatory field was empty, delete old one */
1662                 json_object_object_del(jobj_requirements, "mandatory");
1663                 json_object_put(jobj_mandatory);
1664         }
1665
1666         /* remove empty requirements object */
1667         if (!json_object_object_length(jobj_requirements))
1668                 json_object_object_del(jobj_config, "requirements");
1669
1670         return commit ? LUKS2_hdr_write(cd, hdr) : 0;
1671 err:
1672         json_object_put(jobj_mandatory);
1673         return r;
1674 }
1675
1676 /*
1677  * Header dump
1678  */
1679 static void hdr_dump_config(struct crypt_device *cd, json_object *hdr_jobj)
1680 {
1681
1682         json_object *jobj1, *jobj_config, *jobj_flags, *jobj_requirements, *jobj_mandatory;
1683         int i = 0, flags = 0, reqs = 0;
1684
1685         log_std(cd, "Flags:       \t");
1686
1687         if (json_object_object_get_ex(hdr_jobj, "config", &jobj_config)) {
1688                 if (json_object_object_get_ex(jobj_config, "flags", &jobj_flags))
1689                         flags = (int) json_object_array_length(jobj_flags);
1690                 if (json_object_object_get_ex(jobj_config, "requirements", &jobj_requirements) &&
1691                     json_object_object_get_ex(jobj_requirements, "mandatory", &jobj_mandatory))
1692                         reqs = (int) json_object_array_length(jobj_mandatory);
1693         }
1694
1695         for (i = 0; i < flags; i++) {
1696                 jobj1 = json_object_array_get_idx(jobj_flags, i);
1697                 log_std(cd, "%s ", json_object_get_string(jobj1));
1698         }
1699
1700         log_std(cd, "%s\n%s", flags > 0 ? "" : "(no flags)", reqs > 0 ? "" : "\n");
1701
1702         if (reqs > 0) {
1703                 log_std(cd, "Requirements:\t");
1704                 for (i = 0; i < reqs; i++) {
1705                         jobj1 = json_object_array_get_idx(jobj_mandatory, i);
1706                         log_std(cd, "%s ", json_object_get_string(jobj1));
1707                 }
1708                 log_std(cd, "\n\n");
1709         }
1710 }
1711
1712 static const char *get_priority_desc(json_object *jobj)
1713 {
1714         crypt_keyslot_priority priority;
1715         json_object *jobj_priority;
1716         const char *text;
1717
1718         if (json_object_object_get_ex(jobj, "priority", &jobj_priority))
1719                 priority = (crypt_keyslot_priority)(int)json_object_get_int(jobj_priority);
1720         else
1721                 priority = CRYPT_SLOT_PRIORITY_NORMAL;
1722
1723         switch (priority) {
1724                 case CRYPT_SLOT_PRIORITY_IGNORE: text = "ignored"; break;
1725                 case CRYPT_SLOT_PRIORITY_PREFER: text = "preferred"; break;
1726                 case CRYPT_SLOT_PRIORITY_NORMAL: text = "normal"; break;
1727                 default: text = "invalid";
1728         }
1729
1730         return text;
1731 }
1732
1733 static void hdr_dump_keyslots(struct crypt_device *cd, json_object *hdr_jobj)
1734 {
1735         char slot[16];
1736         json_object *keyslots_jobj, *digests_jobj, *jobj2, *jobj3, *val;
1737         const char *tmps;
1738         int i, j, r;
1739
1740         log_std(cd, "Keyslots:\n");
1741         json_object_object_get_ex(hdr_jobj, "keyslots", &keyslots_jobj);
1742
1743         for (j = 0; j < LUKS2_KEYSLOTS_MAX; j++) {
1744                 (void) snprintf(slot, sizeof(slot), "%i", j);
1745                 json_object_object_get_ex(keyslots_jobj, slot, &val);
1746                 if (!val)
1747                         continue;
1748
1749                 json_object_object_get_ex(val, "type", &jobj2);
1750                 tmps = json_object_get_string(jobj2);
1751
1752                 r = LUKS2_keyslot_for_segment(crypt_get_hdr(cd, CRYPT_LUKS2), j, CRYPT_ONE_SEGMENT);
1753                 log_std(cd, "  %s: %s%s\n", slot, tmps, r == -ENOENT ? " (unbound)" : "");
1754
1755                 if (json_object_object_get_ex(val, "key_size", &jobj2))
1756                         log_std(cd, "\tKey:        %u bits\n", crypt_jobj_get_uint32(jobj2) * 8);
1757
1758                 log_std(cd, "\tPriority:   %s\n", get_priority_desc(val));
1759
1760                 LUKS2_keyslot_dump(cd, j);
1761
1762                 json_object_object_get_ex(hdr_jobj, "digests", &digests_jobj);
1763                 json_object_object_foreach(digests_jobj, key2, val2) {
1764                         json_object_object_get_ex(val2, "keyslots", &jobj2);
1765                         for (i = 0; i < (int) json_object_array_length(jobj2); i++) {
1766                                 jobj3 = json_object_array_get_idx(jobj2, i);
1767                                 if (!strcmp(slot, json_object_get_string(jobj3))) {
1768                                         log_std(cd, "\tDigest ID:  %s\n", key2);
1769                                 }
1770                         }
1771                 }
1772         }
1773 }
1774
1775 static void hdr_dump_tokens(struct crypt_device *cd, json_object *hdr_jobj)
1776 {
1777         char token[16];
1778         json_object *tokens_jobj, *jobj2, *jobj3, *val;
1779         const char *tmps;
1780         int i, j;
1781
1782         log_std(cd, "Tokens:\n");
1783         json_object_object_get_ex(hdr_jobj, "tokens", &tokens_jobj);
1784
1785         for (j = 0; j < LUKS2_TOKENS_MAX; j++) {
1786                 (void) snprintf(token, sizeof(token), "%i", j);
1787                 json_object_object_get_ex(tokens_jobj, token, &val);
1788                 if (!val)
1789                         continue;
1790
1791                 json_object_object_get_ex(val, "type", &jobj2);
1792                 tmps = json_object_get_string(jobj2);
1793                 log_std(cd, "  %s: %s\n", token, tmps);
1794
1795                 LUKS2_token_dump(cd, j);
1796
1797                 json_object_object_get_ex(val, "keyslots", &jobj2);
1798                 for (i = 0; i < (int) json_object_array_length(jobj2); i++) {
1799                         jobj3 = json_object_array_get_idx(jobj2, i);
1800                         log_std(cd, "\tKeyslot:  %s\n", json_object_get_string(jobj3));
1801                 }
1802         }
1803 }
1804
1805 static void hdr_dump_segments(struct crypt_device *cd, json_object *hdr_jobj)
1806 {
1807         char segment[16];
1808         json_object *jobj_segments, *jobj_segment, *jobj1, *jobj2;
1809         int i, j, flags;
1810         uint64_t value;
1811
1812         log_std(cd, "Data segments:\n");
1813         json_object_object_get_ex(hdr_jobj, "segments", &jobj_segments);
1814
1815         for (i = 0; i < LUKS2_SEGMENT_MAX; i++) {
1816                 (void) snprintf(segment, sizeof(segment), "%i", i);
1817                 if (!json_object_object_get_ex(jobj_segments, segment, &jobj_segment))
1818                         continue;
1819
1820                 json_object_object_get_ex(jobj_segment, "type", &jobj1);
1821                 log_std(cd, "  %s: %s\n", segment, json_object_get_string(jobj1));
1822
1823                 json_object_object_get_ex(jobj_segment, "offset", &jobj1);
1824                 json_str_to_uint64(jobj1, &value);
1825                 log_std(cd, "\toffset: %" PRIu64 " [bytes]\n", value);
1826
1827                 json_object_object_get_ex(jobj_segment, "size", &jobj1);
1828                 if (!(strcmp(json_object_get_string(jobj1), "dynamic")))
1829                         log_std(cd, "\tlength: (whole device)\n");
1830                 else {
1831                         json_str_to_uint64(jobj1, &value);
1832                         log_std(cd, "\tlength: %" PRIu64 " [bytes]\n", value);
1833                 }
1834
1835                 if (json_object_object_get_ex(jobj_segment, "encryption", &jobj1))
1836                         log_std(cd, "\tcipher: %s\n", json_object_get_string(jobj1));
1837
1838                 if (json_object_object_get_ex(jobj_segment, "sector_size", &jobj1))
1839                         log_std(cd, "\tsector: %" PRIu32 " [bytes]\n", crypt_jobj_get_uint32(jobj1));
1840
1841                 if (json_object_object_get_ex(jobj_segment, "integrity", &jobj1) &&
1842                     json_object_object_get_ex(jobj1, "type", &jobj2))
1843                         log_std(cd, "\tintegrity: %s\n", json_object_get_string(jobj2));
1844
1845                 if (json_object_object_get_ex(jobj_segment, "flags", &jobj1) &&
1846                     (flags = (int)json_object_array_length(jobj1)) > 0) {
1847                         jobj2 = json_object_array_get_idx(jobj1, 0);
1848                         log_std(cd, "\tflags : %s", json_object_get_string(jobj2));
1849                         for (j = 1; j < flags; j++) {
1850                                 jobj2 = json_object_array_get_idx(jobj1, j);
1851                                 log_std(cd, ", %s", json_object_get_string(jobj2));
1852                         }
1853                         log_std(cd, "\n");
1854                 }
1855
1856                 log_std(cd, "\n");
1857         }
1858 }
1859
1860 static void hdr_dump_digests(struct crypt_device *cd, json_object *hdr_jobj)
1861 {
1862         char key[16];
1863         json_object *jobj1, *jobj2, *val;
1864         const char *tmps;
1865         int i;
1866
1867         log_std(cd, "Digests:\n");
1868         json_object_object_get_ex(hdr_jobj, "digests", &jobj1);
1869
1870         for (i = 0; i < LUKS2_DIGEST_MAX; i++) {
1871                 (void) snprintf(key, sizeof(key), "%i", i);
1872                 json_object_object_get_ex(jobj1, key, &val);
1873                 if (!val)
1874                         continue;
1875
1876                 json_object_object_get_ex(val, "type", &jobj2);
1877                 tmps = json_object_get_string(jobj2);
1878                 log_std(cd, "  %s: %s\n", key, tmps);
1879
1880                 LUKS2_digest_dump(cd, i);
1881         }
1882 }
1883
1884 int LUKS2_hdr_dump(struct crypt_device *cd, struct luks2_hdr *hdr)
1885 {
1886         if (!hdr->jobj)
1887                 return -EINVAL;
1888
1889         JSON_DBG(cd, hdr->jobj, NULL);
1890
1891         log_std(cd, "LUKS header information\n");
1892         log_std(cd, "Version:       \t%u\n", hdr->version);
1893         log_std(cd, "Epoch:         \t%" PRIu64 "\n", hdr->seqid);
1894         log_std(cd, "Metadata area: \t%" PRIu64 " [bytes]\n", LUKS2_metadata_size(hdr));
1895         log_std(cd, "Keyslots area: \t%" PRIu64 " [bytes]\n", LUKS2_keyslots_size(hdr));
1896         log_std(cd, "UUID:          \t%s\n", *hdr->uuid ? hdr->uuid : "(no UUID)");
1897         log_std(cd, "Label:         \t%s\n", *hdr->label ? hdr->label : "(no label)");
1898         log_std(cd, "Subsystem:     \t%s\n", *hdr->subsystem ? hdr->subsystem : "(no subsystem)");
1899
1900         hdr_dump_config(cd, hdr->jobj);
1901         hdr_dump_segments(cd, hdr->jobj);
1902         hdr_dump_keyslots(cd, hdr->jobj);
1903         hdr_dump_tokens(cd, hdr->jobj);
1904         hdr_dump_digests(cd, hdr->jobj);
1905
1906         return 0;
1907 }
1908
1909 int LUKS2_get_data_size(struct luks2_hdr *hdr, uint64_t *size, bool *dynamic)
1910 {
1911         int sector_size;
1912         json_object *jobj_segments, *jobj_size;
1913         uint64_t tmp = 0;
1914
1915         if (!size || !json_object_object_get_ex(hdr->jobj, "segments", &jobj_segments))
1916                 return -EINVAL;
1917
1918         json_object_object_foreach(jobj_segments, key, val) {
1919                 UNUSED(key);
1920                 if (json_segment_is_backup(val))
1921                         continue;
1922
1923                 json_object_object_get_ex(val, "size", &jobj_size);
1924                 if (!strcmp(json_object_get_string(jobj_size), "dynamic")) {
1925                         sector_size = json_segment_get_sector_size(val);
1926                         /* last dynamic segment must have at least one sector in size */
1927                         if (tmp)
1928                                 *size = tmp + (sector_size > 0 ? sector_size : SECTOR_SIZE);
1929                         else
1930                                 *size = 0;
1931                         if (dynamic)
1932                                 *dynamic = true;
1933                         return 0;
1934                 }
1935
1936                 tmp += crypt_jobj_get_uint64(jobj_size);
1937         }
1938
1939         /* impossible, real device size must not be zero */
1940         if (!tmp)
1941                 return -EINVAL;
1942
1943         *size = tmp;
1944         if (dynamic)
1945                 *dynamic = false;
1946         return 0;
1947 }
1948
1949 uint64_t LUKS2_get_data_offset(struct luks2_hdr *hdr)
1950 {
1951         crypt_reencrypt_info ri;
1952         json_object *jobj;
1953
1954         ri = LUKS2_reencrypt_status(hdr);
1955         if (ri == CRYPT_REENCRYPT_CLEAN || ri == CRYPT_REENCRYPT_CRASH) {
1956                 jobj = LUKS2_get_segment_by_flag(hdr, "backup-final");
1957                 if (jobj)
1958                         return json_segment_get_offset(jobj, 1);
1959         }
1960
1961         return json_segments_get_minimal_offset(LUKS2_get_segments_jobj(hdr), 1);
1962 }
1963
1964 const char *LUKS2_get_cipher(struct luks2_hdr *hdr, int segment)
1965 {
1966         json_object *jobj_segment;
1967
1968         if (!hdr)
1969                 return NULL;
1970
1971         if (segment == CRYPT_DEFAULT_SEGMENT)
1972                 segment = LUKS2_get_default_segment(hdr);
1973
1974         jobj_segment = json_segments_get_segment(json_get_segments_jobj(hdr->jobj), segment);
1975         if (!jobj_segment)
1976                 return NULL;
1977
1978         /* FIXME: default encryption (for other segment types) must be string here. */
1979         return json_segment_get_cipher(jobj_segment) ?: "null";
1980 }
1981
1982 crypt_reencrypt_info LUKS2_reencrypt_status(struct luks2_hdr *hdr)
1983 {
1984         uint32_t reqs;
1985
1986         /*
1987          * Any unknown requirement or offline reencryption should abort
1988          * anything related to online-reencryption handling
1989          */
1990         if (LUKS2_config_get_requirements(NULL, hdr, &reqs))
1991                 return CRYPT_REENCRYPT_INVALID;
1992
1993         if (!reqs_reencrypt_online(reqs))
1994                 return CRYPT_REENCRYPT_NONE;
1995
1996         if (json_segments_segment_in_reencrypt(LUKS2_get_segments_jobj(hdr)) < 0)
1997                 return CRYPT_REENCRYPT_CLEAN;
1998
1999         return CRYPT_REENCRYPT_CRASH;
2000 }
2001
2002 const char *LUKS2_get_keyslot_cipher(struct luks2_hdr *hdr, int keyslot, size_t *key_size)
2003 {
2004         json_object *jobj_keyslot, *jobj_area, *jobj1;
2005
2006         jobj_keyslot = LUKS2_get_keyslot_jobj(hdr, keyslot);
2007         if (!jobj_keyslot)
2008                 return NULL;
2009
2010         if (!json_object_object_get_ex(jobj_keyslot, "area", &jobj_area))
2011                 return NULL;
2012
2013         /* currently we only support raw length preserving area encryption */
2014         json_object_object_get_ex(jobj_area, "type", &jobj1);
2015         if (strcmp(json_object_get_string(jobj1), "raw"))
2016                 return NULL;
2017
2018         if (!json_object_object_get_ex(jobj_area, "key_size", &jobj1))
2019                 return NULL;
2020         *key_size = json_object_get_int(jobj1);
2021
2022         if (!json_object_object_get_ex(jobj_area, "encryption", &jobj1))
2023                 return NULL;
2024
2025         return json_object_get_string(jobj1);
2026 }
2027
2028 const char *LUKS2_get_integrity(struct luks2_hdr *hdr, int segment)
2029 {
2030         json_object *jobj1, *jobj2, *jobj3;
2031
2032         jobj1 = LUKS2_get_segment_jobj(hdr, segment);
2033         if (!jobj1)
2034                 return NULL;
2035
2036         if (!json_object_object_get_ex(jobj1, "integrity", &jobj2))
2037                 return NULL;
2038
2039         if (!json_object_object_get_ex(jobj2, "type", &jobj3))
2040                 return NULL;
2041
2042         return json_object_get_string(jobj3);
2043 }
2044
2045 /* FIXME: this only ensures that once we have journal encryption, it is not ignored. */
2046 /* implement segment count and type restrictions (crypt and only single crypt) */
2047 static int LUKS2_integrity_compatible(struct luks2_hdr *hdr)
2048 {
2049         json_object *jobj1, *jobj2, *jobj3, *jobj4;
2050         const char *str;
2051
2052         if (!json_object_object_get_ex(hdr->jobj, "segments", &jobj1))
2053                 return 0;
2054
2055         if (!(jobj2 = LUKS2_get_segment_jobj(hdr, CRYPT_DEFAULT_SEGMENT)))
2056                 return 0;
2057
2058         if (!json_object_object_get_ex(jobj2, "integrity", &jobj3))
2059                 return 0;
2060
2061         if (!json_object_object_get_ex(jobj3, "journal_encryption", &jobj4) ||
2062             !(str = json_object_get_string(jobj4)) ||
2063             strcmp(str, "none"))
2064                 return 0;
2065
2066         if (!json_object_object_get_ex(jobj3, "journal_integrity", &jobj4) ||
2067             !(str = json_object_get_string(jobj4)) ||
2068             strcmp(str, "none"))
2069                 return 0;
2070
2071         return 1;
2072 }
2073
2074 static int LUKS2_keyslot_get_volume_key_size(struct luks2_hdr *hdr, const char *keyslot)
2075 {
2076         json_object *jobj1, *jobj2, *jobj3;
2077
2078         if (!json_object_object_get_ex(hdr->jobj, "keyslots", &jobj1))
2079                 return -1;
2080
2081         if (!json_object_object_get_ex(jobj1, keyslot, &jobj2))
2082                 return -1;
2083
2084         if (!json_object_object_get_ex(jobj2, "key_size", &jobj3))
2085                 return -1;
2086
2087         return json_object_get_int(jobj3);
2088 }
2089
2090 /* Key size used for encryption of keyslot */
2091 int LUKS2_get_keyslot_stored_key_size(struct luks2_hdr *hdr, int keyslot)
2092 {
2093         char keyslot_name[16];
2094
2095         if (snprintf(keyslot_name, sizeof(keyslot_name), "%u", keyslot) < 1)
2096                 return -1;
2097
2098         return LUKS2_keyslot_get_volume_key_size(hdr, keyslot_name);
2099 }
2100
2101 int LUKS2_get_volume_key_size(struct luks2_hdr *hdr, int segment)
2102 {
2103         json_object *jobj_digests, *jobj_digest_segments, *jobj_digest_keyslots, *jobj1;
2104         char buf[16];
2105
2106         if (segment == CRYPT_DEFAULT_SEGMENT)
2107                 segment = LUKS2_get_default_segment(hdr);
2108
2109         if (snprintf(buf, sizeof(buf), "%u", segment) < 1)
2110                 return -1;
2111
2112         json_object_object_get_ex(hdr->jobj, "digests", &jobj_digests);
2113
2114         json_object_object_foreach(jobj_digests, key, val) {
2115                 UNUSED(key);
2116                 json_object_object_get_ex(val, "segments", &jobj_digest_segments);
2117                 json_object_object_get_ex(val, "keyslots", &jobj_digest_keyslots);
2118
2119                 if (!LUKS2_array_jobj(jobj_digest_segments, buf))
2120                         continue;
2121                 if (json_object_array_length(jobj_digest_keyslots) <= 0)
2122                         continue;
2123
2124                 jobj1 = json_object_array_get_idx(jobj_digest_keyslots, 0);
2125
2126                 return LUKS2_keyslot_get_volume_key_size(hdr, json_object_get_string(jobj1));
2127         }
2128
2129         return -1;
2130 }
2131
2132 int LUKS2_get_sector_size(struct luks2_hdr *hdr)
2133 {
2134         json_object *jobj_segment;
2135
2136         jobj_segment = LUKS2_get_segment_jobj(hdr, CRYPT_DEFAULT_SEGMENT);
2137         if (!jobj_segment)
2138                 return SECTOR_SIZE;
2139
2140         return json_segment_get_sector_size(jobj_segment) ?: SECTOR_SIZE;
2141 }
2142
2143 int LUKS2_assembly_multisegment_dmd(struct crypt_device *cd,
2144         struct luks2_hdr *hdr,
2145         struct volume_key *vks,
2146         json_object *jobj_segments,
2147         struct crypt_dm_active_device *dmd)
2148 {
2149         struct volume_key *vk;
2150         json_object *jobj;
2151         enum devcheck device_check;
2152         int r;
2153         unsigned s = 0;
2154         uint64_t data_offset, segment_size, segment_offset, segment_start = 0;
2155         struct dm_target *t = &dmd->segment;
2156
2157         if (dmd->flags & CRYPT_ACTIVATE_SHARED)
2158                 device_check = DEV_OK;
2159         else
2160                 device_check = DEV_EXCL;
2161
2162         data_offset = LUKS2_reencrypt_data_offset(hdr, true);
2163
2164         r = device_block_adjust(cd, crypt_data_device(cd), device_check,
2165                                                         data_offset, &dmd->size, &dmd->flags);
2166         if (r)
2167                 return r;
2168
2169         r = dm_targets_allocate(&dmd->segment, json_segments_count(jobj_segments));
2170         if (r)
2171                 goto err;
2172
2173         r = -EINVAL;
2174
2175         while (t) {
2176                 jobj = json_segments_get_segment(jobj_segments, s);
2177                 if (!jobj) {
2178                         log_dbg(cd, "Internal error. Segment %u is null.", s);
2179                         r = -EINVAL;
2180                         goto err;
2181                 }
2182
2183                 segment_offset = json_segment_get_offset(jobj, 1);
2184                 segment_size = json_segment_get_size(jobj, 1);
2185                 /* 'dynamic' length allowed in last segment only */
2186                 if (!segment_size && !t->next)
2187                         segment_size = dmd->size - segment_start;
2188                 if (!segment_size) {
2189                         log_dbg(cd, "Internal error. Wrong segment size %u", s);
2190                         r = -EINVAL;
2191                         goto err;
2192                 }
2193
2194                 if (!strcmp(json_segment_type(jobj), "crypt")) {
2195                         vk = crypt_volume_key_by_id(vks, LUKS2_digest_by_segment(hdr, s));
2196                         if (!vk) {
2197                                 log_err(cd, _("Missing key for dm-crypt segment %u"), s);
2198                                 r = -EINVAL;
2199                                 goto err;
2200                         }
2201
2202                         r = dm_crypt_target_set(t, segment_start, segment_size,
2203                                         crypt_data_device(cd), vk,
2204                                         json_segment_get_cipher(jobj),
2205                                         json_segment_get_iv_offset(jobj),
2206                                         segment_offset, "none", 0,
2207                                         json_segment_get_sector_size(jobj));
2208                         if (r) {
2209                                 log_err(cd, _("Failed to set dm-crypt segment."));
2210                                 goto err;
2211                         }
2212                 } else if (!strcmp(json_segment_type(jobj), "linear")) {
2213                         r = dm_linear_target_set(t, segment_start, segment_size, crypt_data_device(cd), segment_offset);
2214                         if (r) {
2215                                 log_err(cd, _("Failed to set dm-linear segment."));
2216                                 goto err;
2217                         }
2218                 } else {
2219                         r = -EINVAL;
2220                         goto err;
2221                 }
2222
2223                 segment_start += segment_size;
2224                 t = t->next;
2225                 s++;
2226         }
2227
2228         return r;
2229 err:
2230         dm_targets_free(cd, dmd);
2231         return r;
2232 }
2233
2234 /* FIXME: This shares almost all code with activate_multi_custom */
2235 static int _reload_custom_multi(struct crypt_device *cd,
2236         const char *name,
2237         struct volume_key *vks,
2238         json_object *jobj_segments,
2239         uint64_t device_size,
2240         uint32_t flags)
2241 {
2242         int r;
2243         struct luks2_hdr *hdr = crypt_get_hdr(cd, CRYPT_LUKS2);
2244         struct crypt_dm_active_device dmd =  {
2245                 .uuid   = crypt_get_uuid(cd),
2246                 .size = device_size >> SECTOR_SHIFT
2247         };
2248
2249         /* do not allow activation when particular requirements detected */
2250         if ((r = LUKS2_unmet_requirements(cd, hdr, CRYPT_REQUIREMENT_ONLINE_REENCRYPT, 0)))
2251                 return r;
2252
2253         /* Add persistent activation flags */
2254         if (!(flags & CRYPT_ACTIVATE_IGNORE_PERSISTENT))
2255                 LUKS2_config_get_flags(cd, hdr, &dmd.flags);
2256
2257         dmd.flags |= (flags | CRYPT_ACTIVATE_SHARED);
2258
2259         r = LUKS2_assembly_multisegment_dmd(cd, hdr, vks, jobj_segments, &dmd);
2260         if (!r)
2261                 r = dm_reload_device(cd, name, &dmd, 0, 0);
2262
2263         dm_targets_free(cd, &dmd);
2264         return r;
2265 }
2266
2267 int LUKS2_reload(struct crypt_device *cd,
2268         const char *name,
2269         struct volume_key *vks,
2270         uint64_t device_size,
2271         uint32_t flags)
2272 {
2273         if (crypt_get_integrity_tag_size(cd))
2274                 return -ENOTSUP;
2275
2276         return _reload_custom_multi(cd, name, vks,
2277                         LUKS2_get_segments_jobj(crypt_get_hdr(cd, CRYPT_LUKS2)), device_size, flags);
2278 }
2279
2280 int LUKS2_activate_multi(struct crypt_device *cd,
2281         const char *name,
2282         struct volume_key *vks,
2283         uint64_t device_size,
2284         uint32_t flags)
2285 {
2286         struct luks2_hdr *hdr = crypt_get_hdr(cd, CRYPT_LUKS2);
2287         json_object *jobj_segments = LUKS2_get_segments_jobj(hdr);
2288         int r;
2289         struct crypt_dm_active_device dmd = {
2290                 .size   = device_size,
2291                 .uuid   = crypt_get_uuid(cd)
2292         };
2293
2294         /* do not allow activation when particular requirements detected */
2295         if ((r = LUKS2_unmet_requirements(cd, hdr, CRYPT_REQUIREMENT_ONLINE_REENCRYPT, 0)))
2296                 return r;
2297
2298         /* Add persistent activation flags */
2299         if (!(flags & CRYPT_ACTIVATE_IGNORE_PERSISTENT))
2300                 LUKS2_config_get_flags(cd, hdr, &dmd.flags);
2301
2302         dmd.flags |= flags;
2303
2304         r = LUKS2_assembly_multisegment_dmd(cd, hdr, vks, jobj_segments, &dmd);
2305         if (!r)
2306                 r = dm_create_device(cd, name, CRYPT_LUKS2, &dmd);
2307
2308         dm_targets_free(cd, &dmd);
2309         return r;
2310 }
2311
2312 int LUKS2_activate(struct crypt_device *cd,
2313         const char *name,
2314         struct volume_key *vk,
2315         uint32_t flags)
2316 {
2317         int r;
2318         struct luks2_hdr *hdr = crypt_get_hdr(cd, CRYPT_LUKS2);
2319         struct crypt_dm_active_device dmdi = {}, dmd = {
2320                 .uuid   = crypt_get_uuid(cd)
2321         };
2322
2323         /* do not allow activation when particular requirements detected */
2324         if ((r = LUKS2_unmet_requirements(cd, hdr, 0, 0)))
2325                 return r;
2326
2327         r = dm_crypt_target_set(&dmd.segment, 0, dmd.size, crypt_data_device(cd),
2328                         vk, crypt_get_cipher_spec(cd), crypt_get_iv_offset(cd),
2329                         crypt_get_data_offset(cd), crypt_get_integrity(cd) ?: "none",
2330                         crypt_get_integrity_tag_size(cd), crypt_get_sector_size(cd));
2331         if (r < 0)
2332                 return r;
2333
2334         /* Add persistent activation flags */
2335         if (!(flags & CRYPT_ACTIVATE_IGNORE_PERSISTENT))
2336                 LUKS2_config_get_flags(cd, hdr, &dmd.flags);
2337
2338         dmd.flags |= flags;
2339
2340         if (crypt_get_integrity_tag_size(cd)) {
2341                 if (!LUKS2_integrity_compatible(hdr)) {
2342                         log_err(cd, _("Unsupported device integrity configuration."));
2343                         return -EINVAL;
2344                 }
2345
2346                 if (dmd.flags & CRYPT_ACTIVATE_ALLOW_DISCARDS) {
2347                         log_err(cd, _("Discard/TRIM is not supported."));
2348                         return -EINVAL;
2349                 }
2350
2351                 r = INTEGRITY_create_dmd_device(cd, NULL, NULL, NULL, NULL, &dmdi, dmd.flags, 0);
2352                 if (r)
2353                         return r;
2354
2355                 dmdi.flags |= CRYPT_ACTIVATE_PRIVATE;
2356                 dmdi.uuid = dmd.uuid;
2357                 dmd.segment.u.crypt.offset = 0;
2358                 dmd.segment.size = dmdi.segment.size;
2359
2360                 r = create_or_reload_device_with_integrity(cd, name, CRYPT_LUKS2, &dmd, &dmdi);
2361         } else
2362                 r = create_or_reload_device(cd, name, CRYPT_LUKS2, &dmd);
2363
2364         dm_targets_free(cd, &dmd);
2365         dm_targets_free(cd, &dmdi);
2366
2367         return r;
2368 }
2369
2370 static bool is_reencryption_helper(const char *name)
2371 {
2372         size_t len;
2373
2374         if (!name)
2375                 return false;
2376
2377         len = strlen(name);
2378         return (len >= 9 && (!strncmp(name + len - 8, "-hotzone-", 9) ||
2379                              !strcmp(name + len - 8, "-overlay")));
2380
2381 }
2382
2383 static bool contains_reencryption_helper(char **names)
2384 {
2385         while (*names) {
2386                 if (is_reencryption_helper(*names++))
2387                         return true;
2388         }
2389
2390         return false;
2391 }
2392
2393 int LUKS2_deactivate(struct crypt_device *cd, const char *name, struct luks2_hdr *hdr, struct crypt_dm_active_device *dmd, uint32_t flags)
2394 {
2395         int r, ret;
2396         struct dm_target *tgt;
2397         crypt_status_info ci;
2398         struct crypt_dm_active_device dmdc;
2399         char **dep, deps_uuid_prefix[40], *deps[MAX_DM_DEPS+1] = { 0 };
2400         const char *namei = NULL;
2401         struct crypt_lock_handle *reencrypt_lock = NULL;
2402
2403         if (!dmd || !dmd->uuid || strncmp(CRYPT_LUKS2, dmd->uuid, sizeof(CRYPT_LUKS2)-1))
2404                 return -EINVAL;
2405
2406         /* uuid mismatch with metadata (if available) */
2407         if (hdr && crypt_uuid_cmp(dmd->uuid, hdr->uuid))
2408                 return -EINVAL;
2409
2410         r = snprintf(deps_uuid_prefix, sizeof(deps_uuid_prefix), CRYPT_SUBDEV "-%.32s", dmd->uuid + 6);
2411         if (r < 0 || (size_t)r != (sizeof(deps_uuid_prefix) - 1))
2412                 return -EINVAL;
2413
2414         tgt = &dmd->segment;
2415
2416         /* TODO: We have LUKS2 dependencies now */
2417         if (hdr && single_segment(dmd) && tgt->type == DM_CRYPT && crypt_get_integrity_tag_size(cd))
2418                 namei = device_dm_name(tgt->data_device);
2419
2420         r = dm_device_deps(cd, name, deps_uuid_prefix, deps, ARRAY_SIZE(deps));
2421         if (r < 0)
2422                 goto out;
2423
2424         if (contains_reencryption_helper(deps)) {
2425                 r = LUKS2_reencrypt_lock_by_dm_uuid(cd, dmd->uuid, &reencrypt_lock);
2426                 if (r) {
2427                         if (r == -EBUSY)
2428                                 log_err(cd, _("Reencryption in-progress. Cannot deactivate device."));
2429                         else
2430                                 log_err(cd, _("Failed to get reencryption lock."));
2431                         goto out;
2432                 }
2433         }
2434
2435         dep = deps;
2436         while (*dep) {
2437                 if (is_reencryption_helper(*dep) && (dm_status_suspended(cd, *dep) > 0)) {
2438                         if (dm_error_device(cd, *dep))
2439                                 log_err(cd, _("Failed to replace suspended device %s with dm-error target."), *dep);
2440                 }
2441                 dep++;
2442         }
2443
2444         r = dm_query_device(cd, name, DM_ACTIVE_CRYPT_KEY | DM_ACTIVE_CRYPT_KEYSIZE, &dmdc);
2445         if (r < 0) {
2446                 memset(&dmdc, 0, sizeof(dmdc));
2447                 dmdc.segment.type = DM_UNKNOWN;
2448         }
2449
2450         /* Remove top level device first */
2451         r = dm_remove_device(cd, name, flags);
2452         if (!r) {
2453                 tgt = &dmdc.segment;
2454                 while (tgt) {
2455                         if (tgt->type == DM_CRYPT)
2456                                 crypt_drop_keyring_key_by_description(cd, tgt->u.crypt.vk->key_description, LOGON_KEY);
2457                         tgt = tgt->next;
2458                 }
2459         }
2460         dm_targets_free(cd, &dmdc);
2461
2462         /* TODO: We have LUKS2 dependencies now */
2463         if (r >= 0 && namei) {
2464                 log_dbg(cd, "Deactivating integrity device %s.", namei);
2465                 r = dm_remove_device(cd, namei, 0);
2466         }
2467
2468         if (!r) {
2469                 ret = 0;
2470                 dep = deps;
2471                 while (*dep) {
2472                         log_dbg(cd, "Deactivating LUKS2 dependent device %s.", *dep);
2473                         r = dm_query_device(cd, *dep, DM_ACTIVE_CRYPT_KEY | DM_ACTIVE_CRYPT_KEYSIZE, &dmdc);
2474                         if (r < 0) {
2475                                 memset(&dmdc, 0, sizeof(dmdc));
2476                                 dmdc.segment.type = DM_UNKNOWN;
2477                         }
2478
2479                         r = dm_remove_device(cd, *dep, flags);
2480                         if (r < 0) {
2481                                 ci = crypt_status(cd, *dep);
2482                                 if (ci == CRYPT_BUSY)
2483                                         log_err(cd, _("Device %s is still in use."), *dep);
2484                                 if (ci == CRYPT_INACTIVE)
2485                                         r = 0;
2486                         }
2487                         if (!r) {
2488                                 tgt = &dmdc.segment;
2489                                 while (tgt) {
2490                                         if (tgt->type == DM_CRYPT)
2491                                                 crypt_drop_keyring_key_by_description(cd, tgt->u.crypt.vk->key_description, LOGON_KEY);
2492                                         tgt = tgt->next;
2493                                 }
2494                         }
2495                         dm_targets_free(cd, &dmdc);
2496                         if (r && !ret)
2497                                 ret = r;
2498                         dep++;
2499                 }
2500                 r = ret;
2501         }
2502
2503 out:
2504         LUKS2_reencrypt_unlock(cd, reencrypt_lock);
2505         dep = deps;
2506         while (*dep)
2507                 free(*dep++);
2508
2509         return r;
2510 }
2511
2512 int LUKS2_unmet_requirements(struct crypt_device *cd, struct luks2_hdr *hdr, uint32_t reqs_mask, int quiet)
2513 {
2514         uint32_t reqs;
2515         int r = LUKS2_config_get_requirements(cd, hdr, &reqs);
2516
2517         if (r) {
2518                 if (!quiet)
2519                         log_err(cd, _("Failed to read LUKS2 requirements."));
2520                 return r;
2521         }
2522
2523         /* do not mask unknown requirements check */
2524         if (reqs_unknown(reqs)) {
2525                 if (!quiet)
2526                         log_err(cd, _("Unmet LUKS2 requirements detected."));
2527                 return -ETXTBSY;
2528         }
2529
2530         /* mask out permitted requirements */
2531         reqs &= ~reqs_mask;
2532
2533         if (reqs_reencrypt(reqs) && !quiet)
2534                 log_err(cd, _("Operation incompatible with device marked for legacy reencryption. Aborting."));
2535         if (reqs_reencrypt_online(reqs) && !quiet)
2536                 log_err(cd, _("Operation incompatible with device marked for LUKS2 reencryption. Aborting."));
2537
2538         /* any remaining unmasked requirement fails the check */
2539         return reqs ? -EINVAL : 0;
2540 }
2541
2542 /*
2543  * NOTE: this routine is called on json object that failed validation.
2544  *       Proceed with caution :)
2545  *
2546  * known glitches so far:
2547  *
2548  * any version < 2.0.3:
2549  *  - luks2 keyslot pbkdf params change via crypt_keyslot_change_by_passphrase()
2550  *    could leave previous type parameters behind. Correct this by purging
2551  *    all params not needed by current type.
2552  */
2553 void LUKS2_hdr_repair(struct crypt_device *cd, json_object *hdr_jobj)
2554 {
2555         json_object *jobj_keyslots;
2556
2557         if (!json_object_object_get_ex(hdr_jobj, "keyslots", &jobj_keyslots))
2558                 return;
2559         if (!json_object_is_type(jobj_keyslots, json_type_object))
2560                 return;
2561
2562         LUKS2_keyslots_repair(cd, jobj_keyslots);
2563 }
2564
2565 void json_object_object_del_by_uint(json_object *jobj, unsigned key)
2566 {
2567         char key_name[16];
2568
2569         if (snprintf(key_name, sizeof(key_name), "%u", key) < 1)
2570                 return;
2571         json_object_object_del(jobj, key_name);
2572 }
2573
2574 int json_object_object_add_by_uint(json_object *jobj, unsigned key, json_object *jobj_val)
2575 {
2576         char key_name[16];
2577
2578         if (snprintf(key_name, sizeof(key_name), "%u", key) < 1)
2579                 return -EINVAL;
2580
2581 #if HAVE_DECL_JSON_OBJECT_OBJECT_ADD_EX
2582         return json_object_object_add_ex(jobj, key_name, jobj_val, 0) ? -ENOMEM : 0;
2583 #else
2584         json_object_object_add(jobj, key_name, jobj_val);
2585         return 0;
2586 #endif
2587 }
2588
2589 /* jobj_dst must contain pointer initialized to NULL (see json-c json_object_deep_copy API) */
2590 int json_object_copy(json_object *jobj_src, json_object **jobj_dst)
2591 {
2592         if (!jobj_src || !jobj_dst || *jobj_dst)
2593                 return -1;
2594
2595 #if HAVE_DECL_JSON_OBJECT_DEEP_COPY
2596         return json_object_deep_copy(jobj_src, jobj_dst, NULL);
2597 #else
2598         *jobj_dst = json_tokener_parse(json_object_get_string(jobj_src));
2599         return *jobj_dst ? 0 : -1;
2600 #endif
2601 }