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