| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include "alloc-util.h" |
| 4 |
#include "cryptsetup-keyfile.h" |
| 5 |
#include "fileio.h" |
| 6 |
#include "iovec-util.h" |
| 7 |
#include "log.h" |
| 8 |
#include "path-util.h" |
| 9 |
#include "strv.h" |
| 10 |
|
| 11 |
int find_key_file(const char *key_file, char **search_path, const char *bindname, struct iovec *ret_key) { |
| 12 |
|
| 13 |
int r; |
| 14 |
|
| 15 |
assert(key_file); |
| 16 |
assert(ret_key); |
| 17 |
|
| 18 |
if (strv_isempty(search_path) || path_is_absolute(key_file)) { |
| 19 |
|
| 20 |
r = read_full_file_full( |
| 21 |
AT_FDCWD, key_file, UINT64_MAX, SIZE_MAX, |
| 22 |
READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET, |
| 23 |
bindname, |
| 24 |
(char**) &ret_key->iov_base, &ret_key->iov_len); |
| 25 |
if (r == -E2BIG) |
| 26 |
return log_error_errno(r, "Key file '%s' too large.", key_file); |
| 27 |
if (r < 0) |
| 28 |
return log_error_errno(r, "Failed to load key file '%s': %m", key_file); |
| 29 |
|
| 30 |
return 1; |
| 31 |
} |
| 32 |
|
| 33 |
STRV_FOREACH(i, search_path) { |
| 34 |
_cleanup_free_ char *joined = NULL; |
| 35 |
|
| 36 |
joined = path_join(*i, key_file); |
| 37 |
if (!joined) |
| 38 |
return log_oom(); |
| 39 |
|
| 40 |
r = read_full_file_full( |
| 41 |
AT_FDCWD, joined, UINT64_MAX, SIZE_MAX, |
| 42 |
READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET, |
| 43 |
bindname, |
| 44 |
(char**) &ret_key->iov_base, &ret_key->iov_len); |
| 45 |
if (r >= 0) |
| 46 |
return 1; |
| 47 |
if (r == -E2BIG) { |
| 48 |
log_warning_errno(r, "Key file '%s' too large, ignoring.", key_file); |
| 49 |
continue; |
| 50 |
} |
| 51 |
if (r != -ENOENT) |
| 52 |
return log_error_errno(r, "Failed to load key file '%s': %m", key_file); |
| 53 |
} |
| 54 |
|
| 55 |
/* Search path supplied, but file not found, report by returning NULL, but not failing */ |
| 56 |
*ret_key = IOVEC_MAKE(NULL, 0); |
| 57 |
return 0; |
| 58 |
} |