Coverage Report

Created: 2026-09-06 07:14

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