2 * Helper utilities for LUKS2 features
4 * Copyright (C) 2018-2020 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2018-2020 Milan Broz
6 * Copyright (C) 2018-2020 Ondrej Kozina
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.
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.
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.
23 #include "cryptsetup.h"
26 * FIXME: 4MiBs is max LUKS2 mda length (including binary header).
27 * In future, read max allowed JSON size from config section.
29 #define LUKS2_MAX_MDA_SIZE 0x400000
30 int tools_read_json_file(struct crypt_device *cd, const char *file, char **json, size_t *json_size)
36 block = tools_signals_blocked();
40 if (tools_is_stdin(file)) {
42 log_dbg("STDIN descriptor JSON read requested.");
44 log_dbg("File descriptor JSON read requested.");
45 fd = open(file, O_RDONLY);
47 log_err(_("Failed to open file %s in read-only mode."), file);
53 buf = malloc(LUKS2_MAX_MDA_SIZE);
59 if (isatty(fd) && !opt_batch_mode)
60 log_std(_("Provide valid LUKS2 token JSON:\n"));
62 /* we expect JSON (string) */
64 ret = read_buffer_intr(fd, buf, LUKS2_MAX_MDA_SIZE - 1, &quit);
67 log_err(_("Failed to read JSON file."));
72 log_err(_("\nRead interrupted."));
76 *json_size = (size_t)ret;
78 *(*json + ret) = '\0';
82 if (fd >= 0 && fd != STDIN_FILENO)
85 memset(buf, 0, LUKS2_MAX_MDA_SIZE);
91 int tools_write_json_file(struct crypt_device *cd, const char *file, const char *json)
97 if (!json || !(json_len = strlen(json)) || json_len >= LUKS2_MAX_MDA_SIZE)
100 block = tools_signals_blocked();
104 if (tools_is_stdin(file)) {
106 log_dbg("STDOUT descriptor JSON write requested.");
108 log_dbg("File descriptor JSON write requested.");
109 fd = open(file, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
113 log_err(_("Failed to open file %s in write mode."), file ?: "");
119 ret = write_buffer_intr(fd, json, json_len, &quit);
122 log_err(_("\nWrite interrupted."));
125 if (ret < 0 || (size_t)ret != json_len) {
126 log_err(_("Failed to write JSON file."));
132 (void) write_buffer_intr(fd, "\n", 1, &quit);
136 if (fd >=0 && fd != STDOUT_FILENO)