| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include "alloc-util.h" |
| 4 |
#include "keyring-util.h" |
| 5 |
#include "log.h" |
| 6 |
|
| 7 |
int keyring_read(key_serial_t serial, void **ret, size_t *ret_size) { |
| 8 |
size_t bufsize = 100; |
| 9 |
|
| 10 |
for (;;) { |
| 11 |
_cleanup_(erase_and_freep) uint8_t *buf = NULL; |
| 12 |
long n; |
| 13 |
|
| 14 |
buf = new(uint8_t, bufsize + 1); |
| 15 |
if (!buf) |
| 16 |
return -ENOMEM; |
| 17 |
|
| 18 |
n = keyctl(KEYCTL_READ, (unsigned long) serial, (unsigned long) buf, (unsigned long) bufsize, 0); |
| 19 |
if (n < 0) |
| 20 |
return -errno; |
| 21 |
|
| 22 |
if ((size_t) n <= bufsize) { |
| 23 |
buf[n] = 0; /* NUL terminate, just in case */ |
| 24 |
|
| 25 |
if (ret) |
| 26 |
*ret = TAKE_PTR(buf); |
| 27 |
if (ret_size) |
| 28 |
*ret_size = n; |
| 29 |
|
| 30 |
return 0; |
| 31 |
} |
| 32 |
|
| 33 |
bufsize = (size_t) n; |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
int keyring_describe(key_serial_t serial, char **ret) { |
| 38 |
_cleanup_free_ char *tuple = NULL; |
| 39 |
size_t sz = 64; |
| 40 |
int c = -1; /* Workaround for maybe-uninitialized false positive due to missing_syscall indirection */ |
| 41 |
|
| 42 |
assert(ret); |
| 43 |
|
| 44 |
for (;;) { |
| 45 |
tuple = new(char, sz); |
| 46 |
if (!tuple) |
| 47 |
return log_oom_debug(); |
| 48 |
|
| 49 |
c = keyctl(KEYCTL_DESCRIBE, serial, (unsigned long) tuple, c, 0); |
| 50 |
if (c < 0) |
| 51 |
return log_debug_errno(errno, "Failed to describe key id %d: %m", serial); |
| 52 |
|
| 53 |
if ((size_t) c <= sz) |
| 54 |
break; |
| 55 |
|
| 56 |
sz = c; |
| 57 |
free(tuple); |
| 58 |
} |
| 59 |
|
| 60 |
/* The kernel returns a final NUL in the string, verify that. */ |
| 61 |
assert(tuple[c-1] == 0); |
| 62 |
|
| 63 |
*ret = TAKE_PTR(tuple); |
| 64 |
|
| 65 |
return 0; |
| 66 |
} |