Debian Codegraph @

src/libc/musl/crypt.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <assert.h>
4 #include <crypt.h>
5 #include <errno.h>
6 #include <stdbool.h>
7 #include <stdint.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/random.h>
11
12 const char* missing_crypt_preferred_method(void) {
13 return "$6$";
14 }
15
16 char* missing_crypt_gensalt_ra(const char *prefix, unsigned long count, const char *rbytes, int nrbytes) {
17 static const char table[] =
18 "abcdefghijklmnopqrstuvwxyz"
19 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20 "0123456789"
21 "./";
22
23 static_assert(sizeof(table) == 64U + 1U);
24
25 /* This doesn't do anything but SHA512, and silently ignore all arguments, to make it legacy-free and
26 * minimize the implementation. */
27
28 /* Insist on the best randomness by getrandom(), this is about keeping passwords secret after all. */
29 uint8_t raw[16];
30 for (size_t i = 0; i < sizeof(raw);) {
31 size_t n = sizeof(raw) - i;
32 ssize_t l = getrandom(raw + i, n, 0);
33 if (l < 0)
34 return NULL;
35 if (l == 0) {
36 /* Weird, should never happen. */
37 errno = EIO;
38 return NULL;
39 }
40
41 if ((size_t) l == n)
42 break; /* Done reading, success. */
43
44 i += l;
45 /* Interrupted by a signal; keep going. */
46 }
47
48 /* "$6$" + salt + "$" + NUL */
49 char *salt = malloc(3 + sizeof(raw) + 1 + 1);
50 if (!salt) {
51 errno = ENOMEM;
52 return NULL;
53 }
54
55 /* We only bother with SHA512 hashed passwords, the rest is legacy, and we don't do legacy. */
56 char *p = stpcpy(salt, "$6$");
57 for (size_t i = 0; i < sizeof(raw); i++)
58 *p++ = table[raw[i] & 63];
59 *p++ = '$';
60 *p = '\0';
61
62 return salt;
63 }
64
65 char* missing_crypt_ra(const char *phrase, const char *setting, void **data, int *size) {
66 struct crypt_data *buf = NULL;
67 bool allocated = false;
68
69 if (!phrase || !setting || !data || !size) {
70 errno = EINVAL;
71 return NULL;
72 }
73
74 if (*data) {
75 if (*size != sizeof(struct crypt_data)) {
76 errno = EINVAL;
77 return NULL;
78 }
79
80 buf = *data;
81 } else {
82 if (*size != 0) {
83 errno = EINVAL;
84 return NULL;
85 }
86
87 buf = calloc(1, sizeof(struct crypt_data));
88 if (!buf) {
89 errno = ENOMEM;
90 return NULL;
91 }
92
93 allocated = true;
94 }
95
96 /* crypt_r may return a pointer to an invalid hashed password on error. Our callers expect NULL on
97 * error, so let's just return that. */
98
99 char *t = crypt_r(phrase, setting, buf);
100 if (!t || t[0] == '*') {
101 if (allocated)
102 free(buf);
103 return NULL;
104 }
105
106 if (allocated) {
107 *data = buf;
108 *size = sizeof(struct crypt_data);
109 }
110 return t;
111 }