6d3fa1e1812db963dfde31bd94d1d00ef46d076e
[platform/upstream/cryptsetup.git] / lib / luks2 / luks2_luks1_convert.c
1 /*
2  * LUKS - Linux Unified Key Setup v2, LUKS1 conversion code
3  *
4  * Copyright (C) 2015-2023 Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2015-2023 Ondrej Kozina
6  * Copyright (C) 2015-2023 Milan Broz
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include "luks2_internal.h"
24 #include "../luks1/luks.h"
25 #include "../luks1/af.h"
26
27 /* This differs from LUKS_check_cipher() that it does not check dm-crypt fallback. */
28 int LUKS2_check_cipher(struct crypt_device *cd,
29                       size_t keylength,
30                       const char *cipher,
31                       const char *cipher_mode)
32 {
33         int r;
34         struct crypt_storage *s;
35         char buf[SECTOR_SIZE], *empty_key;
36
37         log_dbg(cd, "Checking if cipher %s-%s is usable (storage wrapper).", cipher, cipher_mode);
38
39         empty_key = crypt_safe_alloc(keylength);
40         if (!empty_key)
41                 return -ENOMEM;
42
43         /* No need to get KEY quality random but it must avoid known weak keys. */
44         r = crypt_random_get(cd, empty_key, keylength, CRYPT_RND_NORMAL);
45         if (r < 0)
46                 goto out;
47
48         r = crypt_storage_init(&s, SECTOR_SIZE, cipher, cipher_mode, empty_key, keylength, false);
49         if (r < 0)
50                 goto out;
51
52         memset(buf, 0, sizeof(buf));
53         r = crypt_storage_decrypt(s, 0, sizeof(buf), buf);
54         crypt_storage_destroy(s);
55 out:
56         crypt_safe_free(empty_key);
57         crypt_safe_memzero(buf, sizeof(buf));
58         return r;
59 }
60
61 static int json_luks1_keyslot(const struct luks_phdr *hdr_v1, int keyslot, struct json_object **keyslot_object)
62 {
63         char *base64_str, cipher[LUKS_CIPHERNAME_L+LUKS_CIPHERMODE_L];
64         size_t base64_len;
65         struct json_object *keyslot_obj, *field, *jobj_kdf, *jobj_af, *jobj_area;
66         uint64_t offset, area_size, length;
67         int r;
68
69         keyslot_obj = json_object_new_object();
70         json_object_object_add(keyslot_obj, "type", json_object_new_string("luks2"));
71         json_object_object_add(keyslot_obj, "key_size", json_object_new_int64(hdr_v1->keyBytes));
72
73         /* KDF */
74         jobj_kdf = json_object_new_object();
75         json_object_object_add(jobj_kdf, "type", json_object_new_string(CRYPT_KDF_PBKDF2));
76         json_object_object_add(jobj_kdf, "hash", json_object_new_string(hdr_v1->hashSpec));
77         json_object_object_add(jobj_kdf, "iterations", json_object_new_int64(hdr_v1->keyblock[keyslot].passwordIterations));
78         /* salt field */
79         r = crypt_base64_encode(&base64_str, &base64_len, hdr_v1->keyblock[keyslot].passwordSalt, LUKS_SALTSIZE);
80         if (r < 0) {
81                 json_object_put(keyslot_obj);
82                 json_object_put(jobj_kdf);
83                 return r;
84         }
85         field = json_object_new_string_len(base64_str, base64_len);
86         free(base64_str);
87         json_object_object_add(jobj_kdf, "salt", field);
88         json_object_object_add(keyslot_obj, "kdf", jobj_kdf);
89
90         /* AF */
91         jobj_af = json_object_new_object();
92         json_object_object_add(jobj_af, "type", json_object_new_string("luks1"));
93         json_object_object_add(jobj_af, "hash", json_object_new_string(hdr_v1->hashSpec));
94         /* stripes field ignored, fixed to LUKS_STRIPES (4000) */
95         json_object_object_add(jobj_af, "stripes", json_object_new_int(LUKS_STRIPES));
96         json_object_object_add(keyslot_obj, "af", jobj_af);
97
98         /* Area */
99         jobj_area = json_object_new_object();
100         json_object_object_add(jobj_area, "type", json_object_new_string("raw"));
101
102         /* encryption algorithm field */
103         if (*hdr_v1->cipherMode != '\0') {
104                 if (snprintf(cipher, sizeof(cipher), "%s-%s", hdr_v1->cipherName, hdr_v1->cipherMode) < 0) {
105                         json_object_put(keyslot_obj);
106                         json_object_put(jobj_area);
107                         return -EINVAL;
108                 }
109                 json_object_object_add(jobj_area, "encryption", json_object_new_string(cipher));
110         } else
111                 json_object_object_add(jobj_area, "encryption", json_object_new_string(hdr_v1->cipherName));
112
113         /* area */
114         if (LUKS_keyslot_area(hdr_v1, keyslot, &offset, &length)) {
115                 json_object_put(keyslot_obj);
116                 json_object_put(jobj_area);
117                 return -EINVAL;
118         }
119         area_size = size_round_up(length, 4096);
120         json_object_object_add(jobj_area, "key_size", json_object_new_int(hdr_v1->keyBytes));
121         json_object_object_add(jobj_area, "offset", crypt_jobj_new_uint64(offset));
122         json_object_object_add(jobj_area, "size", crypt_jobj_new_uint64(area_size));
123         json_object_object_add(keyslot_obj, "area", jobj_area);
124
125         *keyslot_object = keyslot_obj;
126         return 0;
127 }
128
129 static int json_luks1_keyslots(const struct luks_phdr *hdr_v1, struct json_object **keyslots_object)
130 {
131         int keyslot, r;
132         struct json_object *keyslot_obj, *field;
133
134         keyslot_obj = json_object_new_object();
135         if (!keyslot_obj)
136                 return -ENOMEM;
137
138         for (keyslot = 0; keyslot < LUKS_NUMKEYS; keyslot++) {
139                 if (hdr_v1->keyblock[keyslot].active != LUKS_KEY_ENABLED)
140                         continue;
141                 r = json_luks1_keyslot(hdr_v1, keyslot, &field);
142                 if (r) {
143                         json_object_put(keyslot_obj);
144                         return r;
145                 }
146                 json_object_object_add_by_uint(keyslot_obj, keyslot, field);
147         }
148
149         *keyslots_object = keyslot_obj;
150         return 0;
151 }
152
153 static int json_luks1_segment(const struct luks_phdr *hdr_v1, struct json_object **segment_object)
154 {
155         const char *c;
156         char cipher[LUKS_CIPHERNAME_L+LUKS_CIPHERMODE_L];
157         struct json_object *segment_obj, *field;
158         uint64_t number;
159
160         segment_obj = json_object_new_object();
161         if (!segment_obj)
162                 return -ENOMEM;
163
164         /* type field */
165         field = json_object_new_string("crypt");
166         if (!field) {
167                 json_object_put(segment_obj);
168                 return -ENOMEM;
169         }
170         json_object_object_add(segment_obj, "type", field);
171
172         /* offset field */
173         number = (uint64_t)hdr_v1->payloadOffset * SECTOR_SIZE;
174
175         field = crypt_jobj_new_uint64(number);
176         if (!field) {
177                 json_object_put(segment_obj);
178                 return -ENOMEM;
179         }
180         json_object_object_add(segment_obj, "offset", field);
181
182         /* iv_tweak field */
183         field = json_object_new_string("0");
184         if (!field) {
185                 json_object_put(segment_obj);
186                 return -ENOMEM;
187         }
188         json_object_object_add(segment_obj, "iv_tweak", field);
189
190         /* length field */
191         field = json_object_new_string("dynamic");
192         if (!field) {
193                 json_object_put(segment_obj);
194                 return -ENOMEM;
195         }
196         json_object_object_add(segment_obj, "size", field);
197
198         /* cipher field */
199         if (*hdr_v1->cipherMode != '\0') {
200                 if (snprintf(cipher, sizeof(cipher), "%s-%s", hdr_v1->cipherName, hdr_v1->cipherMode) < 0) {
201                         json_object_put(segment_obj);
202                         return -EINVAL;
203                 }
204                 c = cipher;
205         } else
206                 c = hdr_v1->cipherName;
207
208         field = json_object_new_string(c);
209         if (!field) {
210                 json_object_put(segment_obj);
211                 return -ENOMEM;
212         }
213         json_object_object_add(segment_obj, "encryption", field);
214
215         /* block field */
216         field = json_object_new_int(SECTOR_SIZE);
217         if (!field) {
218                 json_object_put(segment_obj);
219                 return -ENOMEM;
220         }
221         json_object_object_add(segment_obj, "sector_size", field);
222
223         *segment_object = segment_obj;
224         return 0;
225 }
226
227 static int json_luks1_segments(const struct luks_phdr *hdr_v1, struct json_object **segments_object)
228 {
229         int r;
230         struct json_object *segments_obj, *field;
231
232         segments_obj = json_object_new_object();
233         if (!segments_obj)
234                 return -ENOMEM;
235
236         r = json_luks1_segment(hdr_v1, &field);
237         if (r) {
238                 json_object_put(segments_obj);
239                 return r;
240         }
241         json_object_object_add_by_uint(segments_obj, 0, field);
242
243         *segments_object = segments_obj;
244         return 0;
245 }
246
247 static int json_luks1_digest(const struct luks_phdr *hdr_v1, struct json_object **digest_object)
248 {
249         char keyslot_str[16], *base64_str;
250         int r, ks;
251         size_t base64_len;
252         struct json_object *digest_obj, *array, *field;
253
254         digest_obj = json_object_new_object();
255         if (!digest_obj)
256                 return -ENOMEM;
257
258         /* type field */
259         field = json_object_new_string("pbkdf2");
260         if (!field) {
261                 json_object_put(digest_obj);
262                 return -ENOMEM;
263         }
264         json_object_object_add(digest_obj, "type", field);
265
266         /* keyslots array */
267         array = json_object_new_array();
268         if (!array) {
269                 json_object_put(digest_obj);
270                 return -ENOMEM;
271         }
272         json_object_object_add(digest_obj, "keyslots", json_object_get(array));
273
274         for (ks = 0; ks < LUKS_NUMKEYS; ks++) {
275                 if (hdr_v1->keyblock[ks].active != LUKS_KEY_ENABLED)
276                         continue;
277                 if (snprintf(keyslot_str, sizeof(keyslot_str), "%d", ks) < 0) {
278                         json_object_put(field);
279                         json_object_put(array);
280                         json_object_put(digest_obj);
281                         return -EINVAL;
282                 }
283
284                 field = json_object_new_string(keyslot_str);
285                 if (!field || json_object_array_add(array, field) < 0) {
286                         json_object_put(field);
287                         json_object_put(array);
288                         json_object_put(digest_obj);
289                         return -ENOMEM;
290                 }
291         }
292
293         json_object_put(array);
294
295         /* segments array */
296         array = json_object_new_array();
297         if (!array) {
298                 json_object_put(digest_obj);
299                 return -ENOMEM;
300         }
301         json_object_object_add(digest_obj, "segments", json_object_get(array));
302
303         field = json_object_new_string("0");
304         if (!field || json_object_array_add(array, field) < 0) {
305                 json_object_put(field);
306                 json_object_put(array);
307                 json_object_put(digest_obj);
308                 return -ENOMEM;
309         }
310
311         json_object_put(array);
312
313         /* hash field */
314         field = json_object_new_string(hdr_v1->hashSpec);
315         if (!field) {
316                 json_object_put(digest_obj);
317                 return -ENOMEM;
318         }
319         json_object_object_add(digest_obj, "hash", field);
320
321         /* salt field */
322         r = crypt_base64_encode(&base64_str, &base64_len, hdr_v1->mkDigestSalt, LUKS_SALTSIZE);
323         if (r < 0) {
324                 json_object_put(digest_obj);
325                 return r;
326         }
327
328         field = json_object_new_string_len(base64_str, base64_len);
329         free(base64_str);
330         if (!field) {
331                 json_object_put(digest_obj);
332                 return -ENOMEM;
333         }
334         json_object_object_add(digest_obj, "salt", field);
335
336         /* digest field */
337         r = crypt_base64_encode(&base64_str, &base64_len, hdr_v1->mkDigest, LUKS_DIGESTSIZE);
338         if (r < 0) {
339                 json_object_put(digest_obj);
340                 return r;
341         }
342
343         field = json_object_new_string_len(base64_str, base64_len);
344         free(base64_str);
345         if (!field) {
346                 json_object_put(digest_obj);
347                 return -ENOMEM;
348         }
349         json_object_object_add(digest_obj, "digest", field);
350
351         /* iterations field */
352         field = json_object_new_int64(hdr_v1->mkDigestIterations);
353         if (!field) {
354                 json_object_put(digest_obj);
355                 return -ENOMEM;
356         }
357         json_object_object_add(digest_obj, "iterations", field);
358
359         *digest_object = digest_obj;
360         return 0;
361 }
362
363 static int json_luks1_digests(const struct luks_phdr *hdr_v1, struct json_object **digests_object)
364 {
365         int r;
366         struct json_object *digests_obj, *field;
367
368         digests_obj = json_object_new_object();
369         if (!digests_obj)
370                 return -ENOMEM;
371
372         r = json_luks1_digest(hdr_v1, &field);
373         if (r) {
374                 json_object_put(digests_obj);
375                 return r;
376         }
377         json_object_object_add(digests_obj, "0", field);
378
379         *digests_object = digests_obj;
380         return 0;
381 }
382
383 static int json_luks1_object(struct luks_phdr *hdr_v1, struct json_object **luks1_object, uint64_t keyslots_size)
384 {
385         int r;
386         struct json_object *luks1_obj, *field;
387         uint64_t json_size;
388
389         luks1_obj = json_object_new_object();
390         if (!luks1_obj)
391                 return -ENOMEM;
392
393         /* keyslots field */
394         r = json_luks1_keyslots(hdr_v1, &field);
395         if (r) {
396                 json_object_put(luks1_obj);
397                 return r;
398         }
399         json_object_object_add(luks1_obj, "keyslots", field);
400
401         /* tokens field */
402         field = json_object_new_object();
403         if (!field) {
404                 json_object_put(luks1_obj);
405                 return -ENOMEM;
406         }
407         json_object_object_add(luks1_obj, "tokens", field);
408
409         /* segments field */
410         r = json_luks1_segments(hdr_v1, &field);
411         if (r) {
412                 json_object_put(luks1_obj);
413                 return r;
414         }
415         json_object_object_add(luks1_obj, "segments", field);
416
417         /* digests field */
418         r = json_luks1_digests(hdr_v1, &field);
419         if (r) {
420                 json_object_put(luks1_obj);
421                 return r;
422         }
423         json_object_object_add(luks1_obj, "digests", field);
424
425         /* config field */
426         /* anything else? */
427         field = json_object_new_object();
428         if (!field) {
429                 json_object_put(luks1_obj);
430                 return -ENOMEM;
431         }
432         json_object_object_add(luks1_obj, "config", field);
433
434         json_size = LUKS2_HDR_16K_LEN - LUKS2_HDR_BIN_LEN;
435         json_object_object_add(field, "json_size", crypt_jobj_new_uint64(json_size));
436         keyslots_size -= (keyslots_size % 4096);
437         json_object_object_add(field, "keyslots_size", crypt_jobj_new_uint64(keyslots_size));
438
439         *luks1_object = luks1_obj;
440         return 0;
441 }
442
443 static void move_keyslot_offset(json_object *jobj, int offset_add)
444 {
445         json_object *jobj1, *jobj2, *jobj_area;
446         uint64_t offset = 0;
447
448         json_object_object_get_ex(jobj, "keyslots", &jobj1);
449         json_object_object_foreach(jobj1, key, val) {
450                 UNUSED(key);
451                 json_object_object_get_ex(val, "area", &jobj_area);
452                 json_object_object_get_ex(jobj_area, "offset", &jobj2);
453                 offset = crypt_jobj_get_uint64(jobj2) + offset_add;
454                 json_object_object_add(jobj_area, "offset", crypt_jobj_new_uint64(offset));
455         }
456 }
457
458 static int move_keyslot_areas(struct crypt_device *cd, off_t offset_from,
459                               off_t offset_to, size_t buf_size)
460 {
461         int devfd, r = -EIO;
462         struct device *device = crypt_metadata_device(cd);
463         void *buf = NULL;
464
465         log_dbg(cd, "Moving keyslot areas of size %zu from %jd to %jd.",
466                 buf_size, (intmax_t)offset_from, (intmax_t)offset_to);
467
468         if (posix_memalign(&buf, crypt_getpagesize(), buf_size))
469                 return -ENOMEM;
470
471         devfd = device_open(cd, device, O_RDWR);
472         if (devfd < 0) {
473                 free(buf);
474                 return -EIO;
475         }
476
477         /* This can safely fail (for block devices). It only allocates space if it is possible. */
478         if (posix_fallocate(devfd, offset_to, buf_size))
479                 log_dbg(cd, "Preallocation (fallocate) of new keyslot area not available.");
480
481         /* Try to read *new* area to check that area is there (trimmed backup). */
482         if (read_lseek_blockwise(devfd, device_block_size(cd, device),
483                                  device_alignment(device), buf, buf_size,
484                                  offset_to)!= (ssize_t)buf_size)
485                 goto out;
486
487         if (read_lseek_blockwise(devfd, device_block_size(cd, device),
488                                  device_alignment(device), buf, buf_size,
489                                  offset_from)!= (ssize_t)buf_size)
490                 goto out;
491
492         if (write_lseek_blockwise(devfd, device_block_size(cd, device),
493                                   device_alignment(device), buf, buf_size,
494                                   offset_to) != (ssize_t)buf_size)
495                 goto out;
496
497         r = 0;
498 out:
499         device_sync(cd, device);
500         crypt_safe_memzero(buf, buf_size);
501         free(buf);
502
503         return r;
504 }
505
506 static int luks_header_in_use(struct crypt_device *cd)
507 {
508         int r;
509
510         r = lookup_dm_dev_by_uuid(cd, crypt_get_uuid(cd), crypt_get_type(cd));
511         if (r < 0)
512                 log_err(cd, _("Cannot check status of device with uuid: %s."), crypt_get_uuid(cd));
513
514         return r;
515 }
516
517 /* Check if there is a luksmeta area (foreign metadata created by the luksmeta package) */
518 static int luksmeta_header_present(struct crypt_device *cd, off_t luks1_size)
519 {
520         int devfd, r = 0;
521         static const uint8_t LM_MAGIC[] = { 'L', 'U', 'K', 'S', 'M', 'E', 'T', 'A' };
522         struct device *device = crypt_metadata_device(cd);
523         void *buf = NULL;
524
525         if (posix_memalign(&buf, crypt_getpagesize(), sizeof(LM_MAGIC)))
526                 return -ENOMEM;
527
528         devfd = device_open(cd, device, O_RDONLY);
529         if (devfd < 0) {
530                 free(buf);
531                 return -EIO;
532         }
533
534         /* Note: we must not detect failure as problem here, header can be trimmed. */
535         if (read_lseek_blockwise(devfd, device_block_size(cd, device), device_alignment(device),
536                 buf, sizeof(LM_MAGIC), luks1_size) == (ssize_t)sizeof(LM_MAGIC) &&
537                 !memcmp(LM_MAGIC, buf, sizeof(LM_MAGIC))) {
538                         log_err(cd, _("Unable to convert header with LUKSMETA additional metadata."));
539                         r = -EBUSY;
540         }
541
542         free(buf);
543         return r;
544 }
545
546 /* Convert LUKS1 -> LUKS2 */
547 int LUKS2_luks1_to_luks2(struct crypt_device *cd, struct luks_phdr *hdr1, struct luks2_hdr *hdr2)
548 {
549         int r;
550         json_object *jobj = NULL;
551         size_t buf_size, buf_offset, luks1_size, luks1_shift = 2 * LUKS2_HDR_16K_LEN - LUKS_ALIGN_KEYSLOTS;
552         uint64_t required_size, max_size = crypt_get_data_offset(cd) * SECTOR_SIZE;
553
554         /* for detached headers max size == device size */
555         if (!max_size && (r = device_size(crypt_metadata_device(cd), &max_size)))
556                 return r;
557
558         luks1_size = LUKS_device_sectors(hdr1) << SECTOR_SHIFT;
559         luks1_size = size_round_up(luks1_size, LUKS_ALIGN_KEYSLOTS);
560         if (!luks1_size)
561                 return -EINVAL;
562
563         if (LUKS_keyslots_offset(hdr1) != (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
564                 log_dbg(cd, "Unsupported keyslots material offset: %zu.", LUKS_keyslots_offset(hdr1));
565                 return -EINVAL;
566         }
567
568         if (LUKS2_check_cipher(cd, hdr1->keyBytes, hdr1->cipherName, hdr1->cipherMode)) {
569                 log_err(cd, _("Unable to use cipher specification %s-%s for LUKS2."),
570                         hdr1->cipherName, hdr1->cipherMode);
571                 return -EINVAL;
572         }
573
574         if (luksmeta_header_present(cd, luks1_size))
575                 return -EINVAL;
576
577         log_dbg(cd, "Max size: %" PRIu64 ", LUKS1 (full) header size %zu , required shift: %zu",
578                 max_size, luks1_size, luks1_shift);
579
580         required_size = luks1_size + luks1_shift;
581
582         if ((max_size < required_size) &&
583             device_fallocate(crypt_metadata_device(cd), required_size)) {
584                 log_err(cd, _("Unable to move keyslot area. Not enough space."));
585                 return -EINVAL;
586         }
587
588         if (max_size < required_size)
589                 max_size = required_size;
590
591         r = json_luks1_object(hdr1, &jobj, max_size - 2 * LUKS2_HDR_16K_LEN);
592         if (r < 0)
593                 return r;
594
595         move_keyslot_offset(jobj, luks1_shift);
596
597         /* Create and fill LUKS2 hdr */
598         memset(hdr2, 0, sizeof(*hdr2));
599         hdr2->hdr_size = LUKS2_HDR_16K_LEN;
600         hdr2->seqid = 1;
601         hdr2->version = 2;
602         strncpy(hdr2->checksum_alg, "sha256", LUKS2_CHECKSUM_ALG_L);
603         crypt_random_get(cd, (char*)hdr2->salt1, sizeof(hdr2->salt1), CRYPT_RND_SALT);
604         crypt_random_get(cd, (char*)hdr2->salt2, sizeof(hdr2->salt2), CRYPT_RND_SALT);
605         strncpy(hdr2->uuid, crypt_get_uuid(cd), LUKS2_UUID_L-1); /* UUID should be max 36 chars */
606         hdr2->jobj = jobj;
607
608         /*
609          * It duplicates check in LUKS2_hdr_write() but we don't want to move
610          * keyslot areas in case it would fail later
611          */
612         if (max_size < LUKS2_hdr_and_areas_size(hdr2)) {
613                 r = -EINVAL;
614                 goto out;
615         }
616
617         /* check future LUKS2 metadata before moving keyslots area */
618         if (LUKS2_hdr_validate(cd, hdr2->jobj, hdr2->hdr_size - LUKS2_HDR_BIN_LEN)) {
619                 log_err(cd, _("Cannot convert to LUKS2 format - invalid metadata."));
620                 r = -EINVAL;
621                 goto out;
622         }
623
624         if ((r = luks_header_in_use(cd))) {
625                 if (r > 0)
626                         r = -EBUSY;
627                 goto out;
628         }
629
630         /* move keyslots 4k -> 32k offset */
631         buf_offset = 2 * LUKS2_HDR_16K_LEN;
632         buf_size   = luks1_size - LUKS_ALIGN_KEYSLOTS;
633
634         /* check future LUKS2 keyslots area is at least as large as LUKS1 keyslots area */
635         if (buf_size > LUKS2_keyslots_size(hdr2)) {
636                 log_err(cd, _("Unable to move keyslot area. LUKS2 keyslots area too small."));
637                 r = -EINVAL;
638                 goto out;
639         }
640
641         if ((r = move_keyslot_areas(cd, 8 * SECTOR_SIZE, buf_offset, buf_size)) < 0) {
642                 log_err(cd, _("Unable to move keyslot area."));
643                 goto out;
644         }
645
646         /* Write new LUKS2 JSON */
647         r = LUKS2_hdr_write(cd, hdr2);
648 out:
649         LUKS2_hdr_free(cd, hdr2);
650
651         return r;
652 }
653
654 static int keyslot_LUKS1_compatible(struct crypt_device *cd, struct luks2_hdr *hdr,
655                                     int keyslot, uint32_t key_size, const char *hash)
656 {
657         json_object *jobj_keyslot, *jobj, *jobj_kdf, *jobj_af;
658         uint64_t l2_offset, l2_length;
659         size_t ks_key_size;
660         const char *ks_cipher, *data_cipher;
661
662         jobj_keyslot = LUKS2_get_keyslot_jobj(hdr, keyslot);
663         if (!jobj_keyslot)
664                 return 1;
665
666         if (!json_object_object_get_ex(jobj_keyslot, "type", &jobj) ||
667             strcmp(json_object_get_string(jobj), "luks2"))
668                 return 0;
669
670         /* Using PBKDF2, this implies memory and parallel is not used. */
671         jobj = NULL;
672         if (!json_object_object_get_ex(jobj_keyslot, "kdf", &jobj_kdf) ||
673             !json_object_object_get_ex(jobj_kdf, "type", &jobj) ||
674             strcmp(json_object_get_string(jobj), CRYPT_KDF_PBKDF2) ||
675             !json_object_object_get_ex(jobj_kdf, "hash", &jobj) ||
676             strcmp(json_object_get_string(jobj), hash))
677                 return 0;
678
679         jobj = NULL;
680         if (!json_object_object_get_ex(jobj_keyslot, "af", &jobj_af) ||
681             !json_object_object_get_ex(jobj_af, "stripes", &jobj) ||
682             json_object_get_int(jobj) != LUKS_STRIPES)
683                 return 0;
684
685         jobj = NULL;
686         if (!json_object_object_get_ex(jobj_af, "hash", &jobj) ||
687             (crypt_hash_size(json_object_get_string(jobj)) < 0) ||
688             strcmp(json_object_get_string(jobj), hash))
689                 return 0;
690
691         ks_cipher = LUKS2_get_keyslot_cipher(hdr, keyslot, &ks_key_size);
692         data_cipher = LUKS2_get_cipher(hdr, CRYPT_DEFAULT_SEGMENT);
693         if (!ks_cipher || !data_cipher || key_size != ks_key_size || strcmp(ks_cipher, data_cipher)) {
694                 log_dbg(cd, "Cipher in keyslot %d is different from volume key encryption.", keyslot);
695                 return 0;
696         }
697
698         if (LUKS2_keyslot_area(hdr, keyslot, &l2_offset, &l2_length))
699                 return 0;
700
701         if (l2_length != (size_round_up(AF_split_sectors(key_size, LUKS_STRIPES) * SECTOR_SIZE, 4096))) {
702                 log_dbg(cd, "Area length in LUKS2 keyslot (%d) is not compatible with LUKS1", keyslot);
703                 return 0;
704         }
705
706         return 1;
707 }
708
709 /* Convert LUKS2 -> LUKS1 */
710 int LUKS2_luks2_to_luks1(struct crypt_device *cd, struct luks2_hdr *hdr2, struct luks_phdr *hdr1)
711 {
712         size_t buf_size, buf_offset;
713         char cipher[LUKS_CIPHERNAME_L], cipher_mode[LUKS_CIPHERMODE_L];
714         char *digest, *digest_salt;
715         const char *hash;
716         size_t len;
717         json_object *jobj_keyslot, *jobj_digest, *jobj_segment, *jobj_kdf, *jobj_area, *jobj1, *jobj2;
718         uint32_t key_size;
719         int i, r, last_active = 0;
720         uint64_t offset, area_length;
721         char *buf, luksMagic[] = LUKS_MAGIC;
722
723         jobj_digest  = LUKS2_get_digest_jobj(hdr2, 0);
724         if (!jobj_digest)
725                 return -EINVAL;
726
727         jobj_segment = LUKS2_get_segment_jobj(hdr2, CRYPT_DEFAULT_SEGMENT);
728         if (!jobj_segment)
729                 return -EINVAL;
730
731         if (json_segment_get_sector_size(jobj_segment) != SECTOR_SIZE) {
732                 log_err(cd, _("Cannot convert to LUKS1 format - default segment encryption sector size is not 512 bytes."));
733                 return -EINVAL;
734         }
735
736         json_object_object_get_ex(hdr2->jobj, "digests", &jobj1);
737         if (!json_object_object_get_ex(jobj_digest, "type", &jobj2) ||
738             strcmp(json_object_get_string(jobj2), "pbkdf2") ||
739             json_object_object_length(jobj1) != 1) {
740                 log_err(cd, _("Cannot convert to LUKS1 format - key slot digests are not LUKS1 compatible."));
741                 return -EINVAL;
742         }
743         if (!json_object_object_get_ex(jobj_digest, "hash", &jobj2))
744                 return -EINVAL;
745         hash = json_object_get_string(jobj2);
746
747         r = crypt_parse_name_and_mode(LUKS2_get_cipher(hdr2, CRYPT_DEFAULT_SEGMENT), cipher, NULL, cipher_mode);
748         if (r < 0)
749                 return r;
750
751         if (crypt_cipher_wrapped_key(cipher, cipher_mode)) {
752                 log_err(cd, _("Cannot convert to LUKS1 format - device uses wrapped key cipher %s."), cipher);
753                 return -EINVAL;
754         }
755
756         if (json_segments_count(LUKS2_get_segments_jobj(hdr2)) != 1) {
757                 log_err(cd, _("Cannot convert to LUKS1 format - device uses more segments."));
758                 return -EINVAL;
759         }
760
761         r = LUKS2_tokens_count(hdr2);
762         if (r < 0)
763                 return r;
764         if (r > 0) {
765                 log_err(cd, _("Cannot convert to LUKS1 format - LUKS2 header contains %u token(s)."), r);
766                 return -EINVAL;
767         }
768
769         r = LUKS2_get_volume_key_size(hdr2, 0);
770         if (r < 0)
771                 return -EINVAL;
772         key_size = r;
773
774         for (i = 0; i < LUKS2_KEYSLOTS_MAX; i++) {
775                 if (LUKS2_keyslot_info(hdr2, i) == CRYPT_SLOT_INACTIVE)
776                         continue;
777
778                 if (LUKS2_keyslot_info(hdr2, i) == CRYPT_SLOT_INVALID) {
779                         log_err(cd, _("Cannot convert to LUKS1 format - keyslot %u is in invalid state."), i);
780                         return -EINVAL;
781                 }
782
783                 if (i >= LUKS_NUMKEYS) {
784                         log_err(cd, _("Cannot convert to LUKS1 format - slot %u (over maximum slots) is still active."), i);
785                         return -EINVAL;
786                 }
787
788                 if (!keyslot_LUKS1_compatible(cd, hdr2, i, key_size, hash)) {
789                         log_err(cd, _("Cannot convert to LUKS1 format - keyslot %u is not LUKS1 compatible."), i);
790                         return -EINVAL;
791                 }
792         }
793
794         memset(hdr1, 0, sizeof(*hdr1));
795
796         for (i = 0; i < LUKS_NUMKEYS; i++) {
797                 hdr1->keyblock[i].active = LUKS_KEY_DISABLED;
798                 hdr1->keyblock[i].stripes = LUKS_STRIPES;
799
800                 jobj_keyslot = LUKS2_get_keyslot_jobj(hdr2, i);
801
802                 if (jobj_keyslot) {
803                         if (!json_object_object_get_ex(jobj_keyslot, "area", &jobj_area))
804                                 return -EINVAL;
805                         if (!json_object_object_get_ex(jobj_area, "offset", &jobj1))
806                                 return -EINVAL;
807                         offset = crypt_jobj_get_uint64(jobj1);
808                 } else {
809                         if (LUKS2_find_area_gap(cd, hdr2, key_size, &offset, &area_length))
810                                 return -EINVAL;
811                         /*
812                          * We have to create placeholder luks2 keyslots in place of all
813                          * inactive keyslots. Otherwise we would allocate all
814                          * inactive luks1 keyslots over same binary keyslot area.
815                          */
816                         if (placeholder_keyslot_alloc(cd, i, offset, area_length))
817                                 return -EINVAL;
818                 }
819
820                 offset /= SECTOR_SIZE;
821                 if (offset > UINT32_MAX)
822                         return -EINVAL;
823
824                 hdr1->keyblock[i].keyMaterialOffset = offset;
825                 hdr1->keyblock[i].keyMaterialOffset -=
826                                 ((2 * LUKS2_HDR_16K_LEN - LUKS_ALIGN_KEYSLOTS) / SECTOR_SIZE);
827
828                 if (!jobj_keyslot)
829                         continue;
830
831                 hdr1->keyblock[i].active = LUKS_KEY_ENABLED;
832                 last_active = i;
833
834                 if (!json_object_object_get_ex(jobj_keyslot, "kdf", &jobj_kdf))
835                         continue;
836
837                 if (!json_object_object_get_ex(jobj_kdf, "iterations", &jobj1))
838                         continue;
839                 hdr1->keyblock[i].passwordIterations = crypt_jobj_get_uint32(jobj1);
840
841                 if (!json_object_object_get_ex(jobj_kdf, "salt", &jobj1))
842                         continue;
843
844                 if (crypt_base64_decode(&buf, &len, json_object_get_string(jobj1),
845                                         json_object_get_string_len(jobj1)))
846                         continue;
847                 if (len > 0 && len != LUKS_SALTSIZE) {
848                         free(buf);
849                         continue;
850                 }
851                 memcpy(hdr1->keyblock[i].passwordSalt, buf, LUKS_SALTSIZE);
852                 free(buf);
853         }
854
855         if (!jobj_keyslot) {
856                 jobj_keyslot = LUKS2_get_keyslot_jobj(hdr2, last_active);
857                 if (!jobj_keyslot)
858                         return -EINVAL;
859         }
860
861         if (!json_object_object_get_ex(jobj_keyslot, "area", &jobj_area))
862                 return -EINVAL;
863         if (!json_object_object_get_ex(jobj_area, "encryption", &jobj1))
864                 return -EINVAL;
865         r = crypt_parse_name_and_mode(json_object_get_string(jobj1), cipher, NULL, cipher_mode);
866         if (r < 0)
867                 return r;
868
869         strncpy(hdr1->cipherName, cipher, LUKS_CIPHERNAME_L - 1);
870         hdr1->cipherName[LUKS_CIPHERNAME_L-1] = '\0';
871         strncpy(hdr1->cipherMode, cipher_mode, LUKS_CIPHERMODE_L - 1);
872         hdr1->cipherMode[LUKS_CIPHERMODE_L-1] = '\0';
873
874         if (!json_object_object_get_ex(jobj_keyslot, "kdf", &jobj_kdf))
875                 return -EINVAL;
876         if (!json_object_object_get_ex(jobj_kdf, "hash", &jobj1))
877                 return -EINVAL;
878         strncpy(hdr1->hashSpec, json_object_get_string(jobj1), sizeof(hdr1->hashSpec) - 1);
879
880         hdr1->keyBytes = key_size;
881
882         if (!json_object_object_get_ex(jobj_digest, "iterations", &jobj1))
883                 return -EINVAL;
884         hdr1->mkDigestIterations = crypt_jobj_get_uint32(jobj1);
885
886         if (!json_object_object_get_ex(jobj_digest, "digest", &jobj1))
887                 return -EINVAL;
888         r = crypt_base64_decode(&digest, &len, json_object_get_string(jobj1),
889                                 json_object_get_string_len(jobj1));
890         if (r < 0)
891                 return r;
892         /* We can store full digest here, not only sha1 length */
893         if (len < LUKS_DIGESTSIZE) {
894                 free(digest);
895                 return -EINVAL;
896         }
897         memcpy(hdr1->mkDigest, digest, LUKS_DIGESTSIZE);
898         free(digest);
899
900         if (!json_object_object_get_ex(jobj_digest, "salt", &jobj1))
901                 return -EINVAL;
902         r = crypt_base64_decode(&digest_salt, &len, json_object_get_string(jobj1),
903                                 json_object_get_string_len(jobj1));
904         if (r < 0)
905                 return r;
906         if (len != LUKS_SALTSIZE) {
907                 free(digest_salt);
908                 return -EINVAL;
909         }
910         memcpy(hdr1->mkDigestSalt, digest_salt, LUKS_SALTSIZE);
911         free(digest_salt);
912
913         if (!json_object_object_get_ex(jobj_segment, "offset", &jobj1))
914                 return -EINVAL;
915         offset = crypt_jobj_get_uint64(jobj1) / SECTOR_SIZE;
916         if (offset > UINT32_MAX)
917                 return -EINVAL;
918         hdr1->payloadOffset = offset;
919
920         strncpy(hdr1->uuid, hdr2->uuid, UUID_STRING_L); /* max 36 chars */
921         hdr1->uuid[UUID_STRING_L-1] = '\0';
922
923         memcpy(hdr1->magic, luksMagic, LUKS_MAGIC_L);
924
925         hdr1->version = 1;
926
927         r = luks_header_in_use(cd);
928         if (r)
929                 return r > 0 ? -EBUSY : r;
930
931         /* move keyslots 32k -> 4k offset */
932         buf_offset = 2 * LUKS2_HDR_16K_LEN;
933         buf_size   = LUKS2_keyslots_size(hdr2);
934         r = move_keyslot_areas(cd, buf_offset, 8 * SECTOR_SIZE, buf_size);
935         if (r < 0) {
936                 log_err(cd, _("Unable to move keyslot area."));
937                 return r;
938         }
939
940         crypt_wipe_device(cd, crypt_metadata_device(cd), CRYPT_WIPE_ZERO, 0,
941                           8 * SECTOR_SIZE, 8 * SECTOR_SIZE, NULL, NULL);
942
943         /* Write new LUKS1 hdr */
944         return LUKS_write_phdr(hdr1, cd);
945 }