Debian Codegraph @

authenticate.c

raw symbols SCIP
1 /*
2 * Support rsync daemon authentication.
3 *
4 * Copyright (C) 1998-2000 Andrew Tridgell
5 * Copyright (C) 2002-2022 Wayne Davison
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
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.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, visit the http://fsf.org website.
19 */
20
21 #include "rsync.h"
22 #include "itypes.h"
23 #include "ifuncs.h"
24
25 /* O_CLOEXEC is absent on some still-supported targets. The random-source fd
26 * is read and closed synchronously, so the established zero-value fallback is
27 * sufficient without adding a configure dependency. */
28 #ifndef O_CLOEXEC
29 #define O_CLOEXEC 0
30 #endif
31
32 extern int read_only;
33 extern char *password_file;
34 extern struct name_num_obj valid_auth_checksums;
35
36 /***************************************************************************
37 encode a buffer using base64 - simple and slow algorithm. null terminates
38 the result.
39 ***************************************************************************/
40 void base64_encode(const char *buf, int len, char *out, int pad)
41 {
42 char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
43 int bit_offset, byte_offset, idx, i;
44 const uchar *d = (const uchar *)buf;
45 int bytes = (len*8 + 5)/6;
46
47 for (i = 0; i < bytes; i++) {
48 byte_offset = (i*6)/8;
49 bit_offset = (i*6)%8;
50 if (bit_offset < 3) {
51 idx = (d[byte_offset] >> (2-bit_offset)) & 0x3F;
52 } else {
53 idx = (d[byte_offset] << (bit_offset-2)) & 0x3F;
54 if (byte_offset+1 < len) {
55 idx |= (d[byte_offset+1] >> (8-(bit_offset-2)));
56 }
57 }
58 out[i] = b64[idx];
59 }
60
61 while (pad && (i % 4))
62 out[i++] = '=';
63
64 out[i] = '\0';
65 }
66
67 /* Fill buf with len bytes from the kernel CSPRNG. Returns 1 on success.
68 * We read /dev/urandom directly rather than depending on getrandom()/
69 * arc4random_buf() availability so this works on every platform rsync
70 * targets without new configure probes. */
71 static int get_random_bytes(char *buf, int len)
72 {
73 int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
74 int got = 0;
75 if (fd < 0)
76 return 0;
77 while (got < len) {
78 int n = read(fd, buf + got, len - got);
79 if (n <= 0)
80 break;
81 got += n;
82 }
83 close(fd);
84 return got == len;
85 }
86
87 /* Generate a challenge buffer and return it base64-encoded. */
88 static void gen_challenge(const char *addr, char *challenge)
89 {
90 char input[32];
91 char rnd[32];
92 char digest[MAX_DIGEST_LEN];
93 struct timeval tv;
94 int len;
95
96 memset(input, 0, sizeof input);
97
98 strlcpy(input, addr, 17);
99 sys_gettimeofday(&tv);
100 SIVAL(input, 16, tv.tv_sec);
101 SIVAL(input, 20, tv.tv_usec);
102 SIVAL(input, 24, getpid());
103
104 len = sum_init(valid_auth_checksums.negotiated_nni, 0);
105 /* The challenge must be unpredictable to a network observer; addr+time
106 * +pid alone is ~35 bits and lets an attacker enumerate the preimage
107 * offline. Hash 32 bytes from the kernel RNG first so the digest
108 * carries full entropy, keeping the legacy inputs as a mix-in so a
109 * urandom failure degrades to (never below) the old behaviour. */
110 if (get_random_bytes(rnd, sizeof rnd))
111 sum_update(rnd, sizeof rnd);
112 else
113 rprintf(FWARNING, "gen_challenge: /dev/urandom unavailable, "
114 "falling back to time-based challenge\n");
115 sum_update(input, sizeof input);
116 sum_end(digest);
117
118 base64_encode(digest, len, challenge, 0);
119 }
120
121 /* Generate an MD4 hash created from the combination of the password
122 * and the challenge string and return it base64-encoded. */
123 static void generate_hash(const char *in, const char *challenge, char *out)
124 {
125 char buf[MAX_DIGEST_LEN];
126 int len;
127
128 len = sum_init(valid_auth_checksums.negotiated_nni, 0);
129 sum_update(in, strlen(in));
130 sum_update(challenge, strlen(challenge));
131 sum_end(buf);
132
133 base64_encode(buf, len, out, 0);
134 }
135
136 /* Return the secret for a user from the secret file, null terminated.
137 * Maximum length is len (not counting the null). */
138 static const char *check_secret(int module, const char *user, const char *group,
139 const char *challenge, const char *pass)
140 {
141 char line[1024];
142 char pass2[MAX_DIGEST_LEN*2];
143 const char *fname = lp_secrets_file(module);
144 STRUCT_STAT st;
145 int ok = 1;
146 int user_len = strlen(user);
147 int group_len = group ? strlen(group) : 0;
148 char *err;
149 FILE *fh;
150
151 /* Daemon 'secrets file = PATH' open. A planted symlink would be
152 * followed and the strict-modes fstat() check below runs on the target
153 * inode, so a symlink to /etc/shadow (0640 root:shadow) would pass and
154 * the daemon would auth against shadow hashes. Refuse symlinks not
155 * owned by uid 0 or our euid. */
156 if (!fname || !*fname)
157 return "no secrets file";
158 {
159 int fd = open_no_attacker_symlinks(fname, O_RDONLY, 0);
160 if (fd < 0)
161 return "no secrets file";
162 fh = fdopen(fd, "r");
163 if (!fh) {
164 close(fd);
165 return "no secrets file";
166 }
167 }
168
169 if (do_fstat(fileno(fh), &st) == -1) {
170 rsyserr(FLOG, errno, "fstat(%s)", fname);
171 ok = 0;
172 } else if (lp_strict_modes(module)) {
173 if ((st.st_mode & 06) != 0) {
174 rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n");
175 ok = 0;
176 } else if (MY_UID() == ROOT_UID && st.st_uid != ROOT_UID) {
177 rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n");
178 ok = 0;
179 }
180 }
181 if (!ok) {
182 fclose(fh);
183 return "ignoring secrets file";
184 }
185
186 if (*user == '#') {
187 /* Reject attempt to match a comment. */
188 fclose(fh);
189 return "invalid username";
190 }
191
192 /* Try to find a line that starts with the user (or @group) name and a ':'. */
193 err = "secret not found";
194 while ((user || group) && fgets(line, sizeof line, fh) != NULL) {
195 const char **ptr, *s = strtok(line, "\n\r");
196 int len;
197 if (!s)
198 continue;
199 if (*s == '@') {
200 ptr = &group;
201 len = group_len;
202 s++;
203 } else {
204 ptr = &user;
205 len = user_len;
206 }
207 if (!*ptr || strncmp(s, *ptr, len) != 0 || s[len] != ':')
208 continue;
209 generate_hash(s+len+1, challenge, pass2);
210 if (strcmp(pass, pass2) == 0) {
211 err = NULL;
212 break;
213 }
214 err = "password mismatch";
215 *ptr = NULL; /* Don't look for name again. */
216 }
217
218 fclose(fh);
219
220 force_memzero(line, sizeof line);
221 force_memzero(pass2, sizeof pass2);
222
223 return err;
224 }
225
226 static const char *getpassf(const char *filename)
227 {
228 STRUCT_STAT st;
229 char buffer[512], *p;
230 int n;
231
232 if (!filename)
233 return NULL;
234
235 if (strcmp(filename, "-") == 0) {
236 n = fgets(buffer, sizeof buffer, stdin) == NULL ? -1 : (int)strlen(buffer);
237 } else {
238 int fd;
239
240 /* --password-file=PATH client open. Its first line is sent as the
241 * auth response, so a planted symlink leaks the target's content
242 * (e.g. shadow hashes) to a malicious daemon; the do_stat()
243 * other-access check runs on the target mode and passes 0640
244 * root:shadow. Refuse symlinks not owned by uid 0 or our euid. */
245 if ((fd = open_no_attacker_symlinks(filename, O_RDONLY, 0)) < 0) {
246 rsyserr(FERROR, errno, "could not open password file %s", filename);
247 exit_cleanup(RERR_SYNTAX);
248 }
249
250 /* fstat the opened fd, not the pathname: a same-object check
251 * (matching check_secret() above) so an attacker who swaps the
252 * path between open and check can't make the owner/mode test
253 * validate a different inode than the one we read the password
254 * from. */
255 if (do_fstat(fd, &st) == -1) {
256 rsyserr(FERROR, errno, "fstat(%s)", filename);
257 exit_cleanup(RERR_SYNTAX);
258 }
259 if ((st.st_mode & 06) != 0) {
260 rprintf(FERROR, "ERROR: password file must not be other-accessible\n");
261 exit_cleanup(RERR_SYNTAX);
262 }
263 if (MY_UID() == ROOT_UID && st.st_uid != ROOT_UID) {
264 rprintf(FERROR, "ERROR: password file must be owned by root when running as root\n");
265 exit_cleanup(RERR_SYNTAX);
266 }
267
268 n = read(fd, buffer, sizeof buffer - 1);
269 close(fd);
270 }
271
272 if (n > 0) {
273 buffer[n] = '\0';
274 if ((p = strtok(buffer, "\n\r")) != NULL)
275 return strdup(p);
276 }
277
278 rprintf(FERROR, "ERROR: failed to read a password from %s\n", filename);
279 exit_cleanup(RERR_SYNTAX);
280 }
281
282 /* Possibly negotiate authentication with the client. Use "leader" to
283 * start off the auth if necessary.
284 *
285 * Return NULL if authentication failed. Return "" if anonymous access.
286 * Otherwise return username.
287 */
288 char *auth_server(int f_in, int f_out, int module, const char *host,
289 const char *addr, const char *leader)
290 {
291 char *users = lp_auth_users(module);
292 char challenge[MAX_DIGEST_LEN*2];
293 char line[BIGPATHBUFLEN];
294 const char **auth_uid_groups = NULL;
295 int auth_uid_groups_cnt = -1;
296 const char *err = NULL;
297 int group_match = -1;
298 char *tok, *pass;
299 char opt_ch = '\0';
300
301 /* if no auth list then allow anyone in! */
302 if (!users || !*users)
303 return "";
304
305 negotiate_daemon_auth(f_out, 0);
306
307 /* Enforce a configured minimum auth digest (default: none). This refuses
308 * a peer that negotiated -- or, via an omitted digest list / old protocol,
309 * fell back to -- a digest weaker than the operator-required floor, e.g. a
310 * client downgraded to md5/md4. Lower rank == stronger (the auth list is
311 * ordered strongest-first), so a higher rank than the floor is too weak. */
312 {
313 const char *min_digest = lp_auth_digest(module);
314 if (min_digest && *min_digest) {
315 int floor_rank = auth_digest_rank(min_digest);
316 int got_rank = auth_digest_rank(valid_auth_checksums.negotiated_nni->name);
317 if (floor_rank < 0) {
318 rprintf(FLOG, "auth failed on module %s from %s (%s): the "
319 "configured 'auth digest = %s' is not a supported digest "
320 "on this build\n",
321 lp_name(module), host, addr, min_digest);
322 return NULL;
323 }
324 if (got_rank < 0 || got_rank > floor_rank) {
325 rprintf(FLOG, "auth failed on module %s from %s (%s): negotiated "
326 "auth digest %s is weaker than the required "
327 "'auth digest = %s'\n",
328 lp_name(module), host, addr,
329 valid_auth_checksums.negotiated_nni->name, min_digest);
330 return NULL;
331 }
332 }
333 }
334
335 gen_challenge(addr, challenge);
336
337 io_printf(f_out, "%s%s\n", leader, challenge);
338
339 if (!read_line_old(f_in, line, sizeof line, 0)
340 || (pass = strchr(line, ' ')) == NULL) {
341 rprintf(FLOG, "auth failed on module %s from %s (%s): "
342 "invalid challenge response\n",
343 lp_name(module), host, addr);
344 return NULL;
345 }
346 *pass++ = '\0';
347
348 users = strdup(users);
349
350 /* conf_strtok() honours the documented leading-comma form: a value that
351 * starts with a comma splits on commas ALONE, so an entry may contain
352 * spaces -- which is how a group name with a space is written. Splitting
353 * on whitespace here tore such an entry apart, so the rule the admin wrote
354 * never matched and a rule they never wrote appeared from its tail. The
355 * daemon's gid field already uses this parser (clientserver.c). */
356 for (tok = conf_strtok(users); tok; tok = conf_strtok(NULL)) {
357 char *opts;
358 /* See if the user appended :deny, :ro, or :rw. */
359 if ((opts = strchr(tok, ':')) != NULL) {
360 *opts++ = '\0';
361 opt_ch = isUpper(opts) ? toLower(opts) : *opts;
362 if (opt_ch == 'r') { /* handle ro and rw */
363 opt_ch = isUpper(opts+1) ? toLower(opts+1) : opts[1];
364 if (opt_ch == 'o')
365 opt_ch = 'r';
366 else if (opt_ch != 'w')
367 opt_ch = '\0';
368 } else if (opt_ch != 'd') /* if it's not deny, ignore it */
369 opt_ch = '\0';
370 } else
371 opt_ch = '\0';
372 if (*tok != '@') {
373 /* Match the username */
374 if (wildmatch(tok, line))
375 break;
376 } else {
377 #ifdef HAVE_GETGROUPLIST
378 int j;
379 /* See if authorizing user is a real user, and if so, see
380 * if it is in a group that matches tok+1 wildmat. */
381 if (auth_uid_groups_cnt < 0) {
382 item_list gid_list = EMPTY_ITEM_LIST;
383 uid_t auth_uid;
384 if (!user_to_uid(line, &auth_uid, False)
385 || getallgroups(auth_uid, &gid_list) != NULL)
386 auth_uid_groups_cnt = 0;
387 else {
388 gid_t *gid_array = gid_list.items;
389 auth_uid_groups_cnt = gid_list.count;
390 auth_uid_groups = new_array(const char *, auth_uid_groups_cnt);
391 for (j = 0; j < auth_uid_groups_cnt; j++)
392 auth_uid_groups[j] = gid_to_group(gid_array[j]);
393 }
394 }
395 for (j = 0; j < auth_uid_groups_cnt; j++) {
396 if (auth_uid_groups[j] && wildmatch(tok+1, auth_uid_groups[j])) {
397 group_match = j;
398 break;
399 }
400 }
401 if (group_match >= 0)
402 break;
403 #else
404 rprintf(FLOG, "your computer doesn't support getgrouplist(), so no @group authorization is possible.\n");
405 #endif
406 }
407 }
408
409 free(users);
410
411 if (!tok)
412 err = "no matching rule";
413 else if (opt_ch == 'd')
414 err = "denied by rule";
415 else {
416 const char *group = group_match >= 0 ? auth_uid_groups[group_match] : NULL;
417 err = check_secret(module, line, group, challenge, pass);
418 }
419
420 force_memzero(challenge, sizeof challenge);
421 force_memzero(pass, strlen(pass));
422
423 if (auth_uid_groups) {
424 int j;
425 for (j = 0; j < auth_uid_groups_cnt; j++) {
426 if (auth_uid_groups[j])
427 free((char*)auth_uid_groups[j]);
428 }
429 free(auth_uid_groups);
430 }
431
432 if (err) {
433 rprintf(FLOG, "auth failed on module %s from %s (%s) for %s: %s\n",
434 lp_name(module), host, addr, line, err);
435 return NULL;
436 }
437
438 if (opt_ch == 'r')
439 read_only = 1;
440 else if (opt_ch == 'w')
441 read_only = 0;
442
443 return strdup(line);
444 }
445
446 void auth_client(int fd, const char *user, const char *challenge)
447 {
448 const char *pass;
449 char pass2[MAX_DIGEST_LEN*2];
450
451 if (!user || !*user)
452 user = "nobody";
453 negotiate_daemon_auth(-1, 1);
454
455 if (!(pass = getpassf(password_file))
456 && !(pass = getenv("RSYNC_PASSWORD"))) {
457 /* XXX: cyeoh says that getpass is deprecated, because
458 * it may return a truncated password on some systems,
459 * and it is not in the LSB.
460 *
461 * Andrew Klein says that getpassphrase() is present
462 * on Solaris and reads up to 256 characters.
463 *
464 * OpenBSD has a readpassphrase() that might be more suitable.
465 */
466 pass = getpass("Password: ");
467 }
468
469 if (!pass)
470 pass = "";
471
472 generate_hash(pass, challenge, pass2);
473 io_printf(fd, "%s %s\n", user, pass2);
474 }