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