2 * cryptsetup LUKS2 fuzz target
4 * Copyright (C) 2022-2023 Daniel Zatovic <daniel.zatovic@gmail.com>
5 * Copyright (C) 2022-2023 Red Hat, Inc. All rights reserved.
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #define FILESIZE (16777216)
24 #include "src/cryptsetup.h"
26 #include "luks2/luks2.h"
27 #include "crypto_backend/crypto_backend.h"
28 #include "FuzzerInterface.h"
30 static int calculate_checksum(const uint8_t* data, size_t size) {
31 struct crypt_hash *hd = NULL;
32 struct luks2_hdr_disk *hdr = NULL;
34 uint64_t hdr_size1, hdr_size2;
38 if (sizeof(struct luks2_hdr_disk) > size)
40 hdr = CONST_CAST(struct luks2_hdr_disk *) data;
42 hdr_size1 = be64_to_cpu(hdr->hdr_size);
45 memset(&hdr->csum, 0, LUKS2_CHECKSUM_L);
46 if ((r = crypt_hash_init(&hd, "sha256")))
48 if ((r = crypt_hash_write(hd, CONST_CAST(char*) data, hdr_size1)))
50 hash_size = crypt_hash_size("sha256");
55 if ((r = crypt_hash_final(hd, (char*)&hdr->csum, (size_t)hash_size)))
57 crypt_hash_destroy(hd);
59 /* secondary header */
60 if (hdr_size1 < sizeof(struct luks2_hdr_disk))
61 hdr_size1 = sizeof(struct luks2_hdr_disk);
63 if (hdr_size1 + sizeof(struct luks2_hdr_disk) > size)
65 hdr = CONST_CAST(struct luks2_hdr_disk *) (data + hdr_size1);
67 hdr_size2 = be64_to_cpu(hdr->hdr_size);
68 if (hdr_size2 > size || (hdr_size1 + hdr_size2) > size)
71 memset(&hdr->csum, 0, LUKS2_CHECKSUM_L);
72 if ((r = crypt_hash_init(&hd, "sha256")))
74 if ((r = crypt_hash_write(hd, (char*) hdr, hdr_size2)))
76 if ((r = crypt_hash_final(hd, (char*)&hdr->csum, (size_t)hash_size)))
81 crypt_hash_destroy(hd);
85 int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
87 struct crypt_device *cd = NULL;
88 char name[] = "/tmp/test-script-fuzz.XXXXXX";
90 if (calculate_checksum(data, size))
93 fd = mkostemp(name, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC);
95 err(EXIT_FAILURE, "mkostemp() failed");
98 if (ftruncate(fd, FILESIZE) == -1)
101 if (write_buffer(fd, data, size) != (ssize_t)size)
104 if (crypt_init(&cd, name) == 0)
105 (void)crypt_load(cd, CRYPT_LUKS2, NULL);