1 /* $OpenBSD: auth.c,v 1.153 2021/07/05 00:50:25 dtucker Exp $ */
2 /*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26 #include "includes.h"
27 __RCSID("$FreeBSD$");
28
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/socket.h>
32 #include <sys/wait.h>
33
34 #include <netinet/in.h>
35
36 #include <stdlib.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #ifdef HAVE_PATHS_H
40 # include <paths.h>
41 #endif
42 #include <pwd.h>
43 #ifdef HAVE_LOGIN_H
44 #include <login.h>
45 #endif
46 #ifdef USE_SHADOW
47 #include <shadow.h>
48 #endif
49 #include <stdarg.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <limits.h>
54 #include <netdb.h>
55 #include <time.h>
56
57 #include "xmalloc.h"
58 #include "match.h"
59 #include "groupaccess.h"
60 #include "log.h"
61 #include "sshbuf.h"
62 #include "misc.h"
63 #include "servconf.h"
64 #include "sshkey.h"
65 #include "hostfile.h"
66 #include "auth.h"
67 #include "auth-options.h"
68 #include "canohost.h"
69 #include "uidswap.h"
70 #include "packet.h"
71 #include "loginrec.h"
72 #ifdef GSSAPI
73 #include "ssh-gss.h"
74 #endif
75 #include "authfile.h"
76 #include "monitor_wrap.h"
77 #include "ssherr.h"
78 #include "compat.h"
79 #include "channels.h"
80 #include "blacklist_client.h"
81
82 /* import */
83 extern ServerOptions options;
84 extern struct include_list includes;
85 extern int use_privsep;
86 extern struct sshbuf *loginmsg;
87 extern struct passwd *privsep_pw;
88 extern struct sshauthopt *auth_opts;
89
90 /* Debugging messages */
91 static struct sshbuf *auth_debug;
92
93 /*
94 * Check if the user is allowed to log in via ssh. If user is listed
95 * in DenyUsers or one of user's groups is listed in DenyGroups, false
96 * will be returned. If AllowUsers isn't empty and user isn't listed
97 * there, or if AllowGroups isn't empty and one of user's groups isn't
98 * listed there, false will be returned.
99 * If the user's shell is not executable, false will be returned.
100 * Otherwise true is returned.
101 */
102 int
allowed_user(struct ssh * ssh,struct passwd * pw)103 allowed_user(struct ssh *ssh, struct passwd * pw)
104 {
105 struct stat st;
106 const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
107 u_int i;
108 int r;
109 #ifdef USE_SHADOW
110 struct spwd *spw = NULL;
111 #endif
112
113 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
114 if (!pw || !pw->pw_name)
115 return 0;
116
117 #ifdef USE_SHADOW
118 if (!options.use_pam)
119 spw = getspnam(pw->pw_name);
120 #ifdef HAS_SHADOW_EXPIRE
121 if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
122 return 0;
123 #endif /* HAS_SHADOW_EXPIRE */
124 #endif /* USE_SHADOW */
125
126 /* grab passwd field for locked account check */
127 passwd = pw->pw_passwd;
128 #ifdef USE_SHADOW
129 if (spw != NULL)
130 #ifdef USE_LIBIAF
131 passwd = get_iaf_password(pw);
132 #else
133 passwd = spw->sp_pwdp;
134 #endif /* USE_LIBIAF */
135 #endif
136
137 /* check for locked account */
138 if (!options.use_pam && passwd && *passwd) {
139 int locked = 0;
140
141 #ifdef LOCKED_PASSWD_STRING
142 if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
143 locked = 1;
144 #endif
145 #ifdef LOCKED_PASSWD_PREFIX
146 if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
147 strlen(LOCKED_PASSWD_PREFIX)) == 0)
148 locked = 1;
149 #endif
150 #ifdef LOCKED_PASSWD_SUBSTR
151 if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
152 locked = 1;
153 #endif
154 #ifdef USE_LIBIAF
155 free((void *) passwd);
156 #endif /* USE_LIBIAF */
157 if (locked) {
158 logit("User %.100s not allowed because account is locked",
159 pw->pw_name);
160 return 0;
161 }
162 }
163
164 /*
165 * Deny if shell does not exist or is not executable unless we
166 * are chrooting.
167 */
168 if (options.chroot_directory == NULL ||
169 strcasecmp(options.chroot_directory, "none") == 0) {
170 char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
171 _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
172
173 if (stat(shell, &st) == -1) {
174 logit("User %.100s not allowed because shell %.100s "
175 "does not exist", pw->pw_name, shell);
176 free(shell);
177 return 0;
178 }
179 if (S_ISREG(st.st_mode) == 0 ||
180 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
181 logit("User %.100s not allowed because shell %.100s "
182 "is not executable", pw->pw_name, shell);
183 free(shell);
184 return 0;
185 }
186 free(shell);
187 }
188
189 if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
190 options.num_deny_groups > 0 || options.num_allow_groups > 0) {
191 hostname = auth_get_canonical_hostname(ssh, options.use_dns);
192 ipaddr = ssh_remote_ipaddr(ssh);
193 }
194
195 /* Return false if user is listed in DenyUsers */
196 if (options.num_deny_users > 0) {
197 for (i = 0; i < options.num_deny_users; i++) {
198 r = match_user(pw->pw_name, hostname, ipaddr,
199 options.deny_users[i]);
200 if (r < 0) {
201 fatal("Invalid DenyUsers pattern \"%.100s\"",
202 options.deny_users[i]);
203 } else if (r != 0) {
204 logit("User %.100s from %.100s not allowed "
205 "because listed in DenyUsers",
206 pw->pw_name, hostname);
207 return 0;
208 }
209 }
210 }
211 /* Return false if AllowUsers isn't empty and user isn't listed there */
212 if (options.num_allow_users > 0) {
213 for (i = 0; i < options.num_allow_users; i++) {
214 r = match_user(pw->pw_name, hostname, ipaddr,
215 options.allow_users[i]);
216 if (r < 0) {
217 fatal("Invalid AllowUsers pattern \"%.100s\"",
218 options.allow_users[i]);
219 } else if (r == 1)
220 break;
221 }
222 /* i < options.num_allow_users iff we break for loop */
223 if (i >= options.num_allow_users) {
224 logit("User %.100s from %.100s not allowed because "
225 "not listed in AllowUsers", pw->pw_name, hostname);
226 return 0;
227 }
228 }
229 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
230 /* Get the user's group access list (primary and supplementary) */
231 if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
232 logit("User %.100s from %.100s not allowed because "
233 "not in any group", pw->pw_name, hostname);
234 return 0;
235 }
236
237 /* Return false if one of user's groups is listed in DenyGroups */
238 if (options.num_deny_groups > 0)
239 if (ga_match(options.deny_groups,
240 options.num_deny_groups)) {
241 ga_free();
242 logit("User %.100s from %.100s not allowed "
243 "because a group is listed in DenyGroups",
244 pw->pw_name, hostname);
245 return 0;
246 }
247 /*
248 * Return false if AllowGroups isn't empty and one of user's groups
249 * isn't listed there
250 */
251 if (options.num_allow_groups > 0)
252 if (!ga_match(options.allow_groups,
253 options.num_allow_groups)) {
254 ga_free();
255 logit("User %.100s from %.100s not allowed "
256 "because none of user's groups are listed "
257 "in AllowGroups", pw->pw_name, hostname);
258 return 0;
259 }
260 ga_free();
261 }
262
263 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
264 if (!sys_auth_allowed_user(pw, loginmsg))
265 return 0;
266 #endif
267
268 /* We found no reason not to let this user try to log on... */
269 return 1;
270 }
271
272 /*
273 * Formats any key left in authctxt->auth_method_key for inclusion in
274 * auth_log()'s message. Also includes authxtct->auth_method_info if present.
275 */
276 static char *
format_method_key(Authctxt * authctxt)277 format_method_key(Authctxt *authctxt)
278 {
279 const struct sshkey *key = authctxt->auth_method_key;
280 const char *methinfo = authctxt->auth_method_info;
281 char *fp, *cafp, *ret = NULL;
282
283 if (key == NULL)
284 return NULL;
285
286 if (sshkey_is_cert(key)) {
287 fp = sshkey_fingerprint(key,
288 options.fingerprint_hash, SSH_FP_DEFAULT);
289 cafp = sshkey_fingerprint(key->cert->signature_key,
290 options.fingerprint_hash, SSH_FP_DEFAULT);
291 xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s",
292 sshkey_type(key), fp == NULL ? "(null)" : fp,
293 key->cert->key_id,
294 (unsigned long long)key->cert->serial,
295 sshkey_type(key->cert->signature_key),
296 cafp == NULL ? "(null)" : cafp,
297 methinfo == NULL ? "" : ", ",
298 methinfo == NULL ? "" : methinfo);
299 free(fp);
300 free(cafp);
301 } else {
302 fp = sshkey_fingerprint(key, options.fingerprint_hash,
303 SSH_FP_DEFAULT);
304 xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
305 fp == NULL ? "(null)" : fp,
306 methinfo == NULL ? "" : ", ",
307 methinfo == NULL ? "" : methinfo);
308 free(fp);
309 }
310 return ret;
311 }
312
313 void
auth_log(struct ssh * ssh,int authenticated,int partial,const char * method,const char * submethod)314 auth_log(struct ssh *ssh, int authenticated, int partial,
315 const char *method, const char *submethod)
316 {
317 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
318 int level = SYSLOG_LEVEL_VERBOSE;
319 const char *authmsg;
320 char *extra = NULL;
321
322 if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
323 return;
324
325 /* Raise logging level */
326 if (authenticated == 1 ||
327 !authctxt->valid ||
328 authctxt->failures >= options.max_authtries / 2 ||
329 strcmp(method, "password") == 0)
330 level = SYSLOG_LEVEL_INFO;
331
332 if (authctxt->postponed)
333 authmsg = "Postponed";
334 else if (partial)
335 authmsg = "Partial";
336 else {
337 authmsg = authenticated ? "Accepted" : "Failed";
338 if (authenticated)
339 BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_OK, "ssh");
340 }
341
342 if ((extra = format_method_key(authctxt)) == NULL) {
343 if (authctxt->auth_method_info != NULL)
344 extra = xstrdup(authctxt->auth_method_info);
345 }
346
347 do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
348 authmsg,
349 method,
350 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
351 authctxt->valid ? "" : "invalid user ",
352 authctxt->user,
353 ssh_remote_ipaddr(ssh),
354 ssh_remote_port(ssh),
355 extra != NULL ? ": " : "",
356 extra != NULL ? extra : "");
357
358 free(extra);
359
360 #if defined(CUSTOM_FAILED_LOGIN) || defined(SSH_AUDIT_EVENTS)
361 if (authenticated == 0 && !(authctxt->postponed || partial)) {
362 /* Log failed login attempt */
363 # ifdef CUSTOM_FAILED_LOGIN
364 if (strcmp(method, "password") == 0 ||
365 strncmp(method, "keyboard-interactive", 20) == 0 ||
366 strcmp(method, "challenge-response") == 0)
367 record_failed_login(ssh, authctxt->user,
368 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
369 # endif
370 # ifdef SSH_AUDIT_EVENTS
371 audit_event(ssh, audit_classify_auth(method));
372 # endif
373 }
374 #endif
375 #if defined(CUSTOM_FAILED_LOGIN) && defined(WITH_AIXAUTHENTICATE)
376 if (authenticated)
377 sys_auth_record_login(authctxt->user,
378 auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
379 loginmsg);
380 #endif
381 }
382
383 void
auth_maxtries_exceeded(struct ssh * ssh)384 auth_maxtries_exceeded(struct ssh *ssh)
385 {
386 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
387
388 error("maximum authentication attempts exceeded for "
389 "%s%.100s from %.200s port %d ssh2",
390 authctxt->valid ? "" : "invalid user ",
391 authctxt->user,
392 ssh_remote_ipaddr(ssh),
393 ssh_remote_port(ssh));
394 ssh_packet_disconnect(ssh, "Too many authentication failures");
395 /* NOTREACHED */
396 }
397
398 /*
399 * Check whether root logins are disallowed.
400 */
401 int
auth_root_allowed(struct ssh * ssh,const char * method)402 auth_root_allowed(struct ssh *ssh, const char *method)
403 {
404 switch (options.permit_root_login) {
405 case PERMIT_YES:
406 return 1;
407 case PERMIT_NO_PASSWD:
408 if (strcmp(method, "publickey") == 0 ||
409 strcmp(method, "hostbased") == 0 ||
410 strcmp(method, "gssapi-with-mic") == 0)
411 return 1;
412 break;
413 case PERMIT_FORCED_ONLY:
414 if (auth_opts->force_command != NULL) {
415 logit("Root login accepted for forced command.");
416 return 1;
417 }
418 break;
419 }
420 logit("ROOT LOGIN REFUSED FROM %.200s port %d",
421 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
422 return 0;
423 }
424
425
426 /*
427 * Given a template and a passwd structure, build a filename
428 * by substituting % tokenised options. Currently, %% becomes '%',
429 * %h becomes the home directory and %u the username.
430 *
431 * This returns a buffer allocated by xmalloc.
432 */
433 char *
expand_authorized_keys(const char * filename,struct passwd * pw)434 expand_authorized_keys(const char *filename, struct passwd *pw)
435 {
436 char *file, uidstr[32], ret[PATH_MAX];
437 int i;
438
439 snprintf(uidstr, sizeof(uidstr), "%llu",
440 (unsigned long long)pw->pw_uid);
441 file = percent_expand(filename, "h", pw->pw_dir,
442 "u", pw->pw_name, "U", uidstr, (char *)NULL);
443
444 /*
445 * Ensure that filename starts anchored. If not, be backward
446 * compatible and prepend the '%h/'
447 */
448 if (path_absolute(file))
449 return (file);
450
451 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
452 if (i < 0 || (size_t)i >= sizeof(ret))
453 fatal("expand_authorized_keys: path too long");
454 free(file);
455 return (xstrdup(ret));
456 }
457
458 char *
authorized_principals_file(struct passwd * pw)459 authorized_principals_file(struct passwd *pw)
460 {
461 if (options.authorized_principals_file == NULL)
462 return NULL;
463 return expand_authorized_keys(options.authorized_principals_file, pw);
464 }
465
466 /* return ok if key exists in sysfile or userfile */
467 HostStatus
check_key_in_hostfiles(struct passwd * pw,struct sshkey * key,const char * host,const char * sysfile,const char * userfile)468 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
469 const char *sysfile, const char *userfile)
470 {
471 char *user_hostfile;
472 struct stat st;
473 HostStatus host_status;
474 struct hostkeys *hostkeys;
475 const struct hostkey_entry *found;
476
477 hostkeys = init_hostkeys();
478 load_hostkeys(hostkeys, host, sysfile, 0);
479 if (userfile != NULL) {
480 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
481 if (options.strict_modes &&
482 (stat(user_hostfile, &st) == 0) &&
483 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
484 (st.st_mode & 022) != 0)) {
485 logit("Authentication refused for %.100s: "
486 "bad owner or modes for %.200s",
487 pw->pw_name, user_hostfile);
488 auth_debug_add("Ignored %.200s: bad ownership or modes",
489 user_hostfile);
490 } else {
491 temporarily_use_uid(pw);
492 load_hostkeys(hostkeys, host, user_hostfile, 0);
493 restore_uid();
494 }
495 free(user_hostfile);
496 }
497 host_status = check_key_in_hostkeys(hostkeys, key, &found);
498 if (host_status == HOST_REVOKED)
499 error("WARNING: revoked key for %s attempted authentication",
500 host);
501 else if (host_status == HOST_OK)
502 debug_f("key for %s found at %s:%ld",
503 found->host, found->file, found->line);
504 else
505 debug_f("key for host %s not found", host);
506
507 free_hostkeys(hostkeys);
508
509 return host_status;
510 }
511
512 static FILE *
auth_openfile(const char * file,struct passwd * pw,int strict_modes,int log_missing,char * file_type)513 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
514 int log_missing, char *file_type)
515 {
516 char line[1024];
517 struct stat st;
518 int fd;
519 FILE *f;
520
521 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
522 if (log_missing || errno != ENOENT)
523 debug("Could not open %s '%s': %s", file_type, file,
524 strerror(errno));
525 return NULL;
526 }
527
528 if (fstat(fd, &st) == -1) {
529 close(fd);
530 return NULL;
531 }
532 if (!S_ISREG(st.st_mode)) {
533 logit("User %s %s %s is not a regular file",
534 pw->pw_name, file_type, file);
535 close(fd);
536 return NULL;
537 }
538 unset_nonblock(fd);
539 if ((f = fdopen(fd, "r")) == NULL) {
540 close(fd);
541 return NULL;
542 }
543 if (strict_modes &&
544 safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
545 fclose(f);
546 logit("Authentication refused: %s", line);
547 auth_debug_add("Ignored %s: %s", file_type, line);
548 return NULL;
549 }
550
551 return f;
552 }
553
554
555 FILE *
auth_openkeyfile(const char * file,struct passwd * pw,int strict_modes)556 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
557 {
558 return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
559 }
560
561 FILE *
auth_openprincipals(const char * file,struct passwd * pw,int strict_modes)562 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
563 {
564 return auth_openfile(file, pw, strict_modes, 0,
565 "authorized principals");
566 }
567
568 struct passwd *
getpwnamallow(struct ssh * ssh,const char * user)569 getpwnamallow(struct ssh *ssh, const char *user)
570 {
571 #ifdef HAVE_LOGIN_CAP
572 extern login_cap_t *lc;
573 #ifdef HAVE_AUTH_HOSTOK
574 const char *from_host, *from_ip;
575 #endif
576 #ifdef BSD_AUTH
577 auth_session_t *as;
578 #endif
579 #endif
580 struct passwd *pw;
581 struct connection_info *ci;
582 u_int i;
583
584 ci = get_connection_info(ssh, 1, options.use_dns);
585 ci->user = user;
586 parse_server_match_config(&options, &includes, ci);
587 log_change_level(options.log_level);
588 log_verbose_reset();
589 for (i = 0; i < options.num_log_verbose; i++)
590 log_verbose_add(options.log_verbose[i]);
591 process_permitopen(ssh, &options);
592
593 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
594 aix_setauthdb(user);
595 #endif
596
597 pw = getpwnam(user);
598
599 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
600 aix_restoreauthdb();
601 #endif
602 if (pw == NULL) {
603 BLACKLIST_NOTIFY(ssh, BLACKLIST_BAD_USER, user);
604 logit("Invalid user %.100s from %.100s port %d",
605 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
606 #ifdef CUSTOM_FAILED_LOGIN
607 record_failed_login(ssh, user,
608 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
609 #endif
610 #ifdef SSH_AUDIT_EVENTS
611 audit_event(ssh, SSH_INVALID_USER);
612 #endif /* SSH_AUDIT_EVENTS */
613 return (NULL);
614 }
615 if (!allowed_user(ssh, pw))
616 return (NULL);
617 #ifdef HAVE_LOGIN_CAP
618 if ((lc = login_getpwclass(pw)) == NULL) {
619 debug("unable to get login class: %s", user);
620 return (NULL);
621 }
622 #ifdef HAVE_AUTH_HOSTOK
623 from_host = auth_get_canonical_hostname(ssh, options.use_dns);
624 from_ip = ssh_remote_ipaddr(ssh);
625 if (!auth_hostok(lc, from_host, from_ip)) {
626 debug("Denied connection for %.200s from %.200s [%.200s].",
627 pw->pw_name, from_host, from_ip);
628 return (NULL);
629 }
630 #endif /* HAVE_AUTH_HOSTOK */
631 #ifdef HAVE_AUTH_TIMEOK
632 if (!auth_timeok(lc, time(NULL))) {
633 debug("LOGIN %.200s REFUSED (TIME)", pw->pw_name);
634 return (NULL);
635 }
636 #endif /* HAVE_AUTH_TIMEOK */
637 #ifdef BSD_AUTH
638 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
639 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
640 debug("Approval failure for %s", user);
641 pw = NULL;
642 }
643 if (as != NULL)
644 auth_close(as);
645 #endif
646 #endif
647 if (pw != NULL)
648 return (pwcopy(pw));
649 return (NULL);
650 }
651
652 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
653 int
auth_key_is_revoked(struct sshkey * key)654 auth_key_is_revoked(struct sshkey *key)
655 {
656 char *fp = NULL;
657 int r;
658
659 if (options.revoked_keys_file == NULL)
660 return 0;
661 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
662 SSH_FP_DEFAULT)) == NULL) {
663 r = SSH_ERR_ALLOC_FAIL;
664 error_fr(r, "fingerprint key");
665 goto out;
666 }
667
668 r = sshkey_check_revoked(key, options.revoked_keys_file);
669 switch (r) {
670 case 0:
671 break; /* not revoked */
672 case SSH_ERR_KEY_REVOKED:
673 error("Authentication key %s %s revoked by file %s",
674 sshkey_type(key), fp, options.revoked_keys_file);
675 goto out;
676 default:
677 error_r(r, "Error checking authentication key %s %s in "
678 "revoked keys file %s", sshkey_type(key), fp,
679 options.revoked_keys_file);
680 goto out;
681 }
682
683 /* Success */
684 r = 0;
685
686 out:
687 free(fp);
688 return r == 0 ? 0 : 1;
689 }
690
691 void
auth_debug_add(const char * fmt,...)692 auth_debug_add(const char *fmt,...)
693 {
694 char buf[1024];
695 va_list args;
696 int r;
697
698 if (auth_debug == NULL)
699 return;
700
701 va_start(args, fmt);
702 vsnprintf(buf, sizeof(buf), fmt, args);
703 va_end(args);
704 if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
705 fatal_fr(r, "sshbuf_put_cstring");
706 }
707
708 void
auth_debug_send(struct ssh * ssh)709 auth_debug_send(struct ssh *ssh)
710 {
711 char *msg;
712 int r;
713
714 if (auth_debug == NULL)
715 return;
716 while (sshbuf_len(auth_debug) != 0) {
717 if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
718 fatal_fr(r, "sshbuf_get_cstring");
719 ssh_packet_send_debug(ssh, "%s", msg);
720 free(msg);
721 }
722 }
723
724 void
auth_debug_reset(void)725 auth_debug_reset(void)
726 {
727 if (auth_debug != NULL)
728 sshbuf_reset(auth_debug);
729 else if ((auth_debug = sshbuf_new()) == NULL)
730 fatal_f("sshbuf_new failed");
731 }
732
733 struct passwd *
fakepw(void)734 fakepw(void)
735 {
736 static struct passwd fake;
737
738 memset(&fake, 0, sizeof(fake));
739 fake.pw_name = "NOUSER";
740 fake.pw_passwd =
741 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
742 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
743 fake.pw_gecos = "NOUSER";
744 #endif
745 fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
746 fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
747 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
748 fake.pw_class = "";
749 #endif
750 fake.pw_dir = "/nonexist";
751 fake.pw_shell = "/nonexist";
752
753 return (&fake);
754 }
755
756 /*
757 * Returns the remote DNS hostname as a string. The returned string must not
758 * be freed. NB. this will usually trigger a DNS query the first time it is
759 * called.
760 * This function does additional checks on the hostname to mitigate some
761 * attacks on based on conflation of hostnames and IP addresses.
762 */
763
764 static char *
remote_hostname(struct ssh * ssh)765 remote_hostname(struct ssh *ssh)
766 {
767 struct sockaddr_storage from;
768 socklen_t fromlen;
769 struct addrinfo hints, *ai, *aitop;
770 char name[NI_MAXHOST], ntop2[NI_MAXHOST];
771 const char *ntop = ssh_remote_ipaddr(ssh);
772
773 /* Get IP address of client. */
774 fromlen = sizeof(from);
775 memset(&from, 0, sizeof(from));
776 if (getpeername(ssh_packet_get_connection_in(ssh),
777 (struct sockaddr *)&from, &fromlen) == -1) {
778 debug("getpeername failed: %.100s", strerror(errno));
779 return xstrdup(ntop);
780 }
781
782 ipv64_normalise_mapped(&from, &fromlen);
783 if (from.ss_family == AF_INET6)
784 fromlen = sizeof(struct sockaddr_in6);
785
786 debug3("Trying to reverse map address %.100s.", ntop);
787 /* Map the IP address to a host name. */
788 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
789 NULL, 0, NI_NAMEREQD) != 0) {
790 /* Host name not found. Use ip address. */
791 return xstrdup(ntop);
792 }
793
794 /*
795 * if reverse lookup result looks like a numeric hostname,
796 * someone is trying to trick us by PTR record like following:
797 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5
798 */
799 memset(&hints, 0, sizeof(hints));
800 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
801 hints.ai_flags = AI_NUMERICHOST;
802 if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
803 logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
804 name, ntop);
805 freeaddrinfo(ai);
806 return xstrdup(ntop);
807 }
808
809 /* Names are stored in lowercase. */
810 lowercase(name);
811
812 /*
813 * Map it back to an IP address and check that the given
814 * address actually is an address of this host. This is
815 * necessary because anyone with access to a name server can
816 * define arbitrary names for an IP address. Mapping from
817 * name to IP address can be trusted better (but can still be
818 * fooled if the intruder has access to the name server of
819 * the domain).
820 */
821 memset(&hints, 0, sizeof(hints));
822 hints.ai_family = from.ss_family;
823 hints.ai_socktype = SOCK_STREAM;
824 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
825 logit("reverse mapping checking getaddrinfo for %.700s "
826 "[%s] failed.", name, ntop);
827 return xstrdup(ntop);
828 }
829 /* Look for the address from the list of addresses. */
830 for (ai = aitop; ai; ai = ai->ai_next) {
831 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
832 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
833 (strcmp(ntop, ntop2) == 0))
834 break;
835 }
836 freeaddrinfo(aitop);
837 /* If we reached the end of the list, the address was not there. */
838 if (ai == NULL) {
839 /* Address not found for the host name. */
840 logit("Address %.100s maps to %.600s, but this does not "
841 "map back to the address.", ntop, name);
842 return xstrdup(ntop);
843 }
844 return xstrdup(name);
845 }
846
847 /*
848 * Return the canonical name of the host in the other side of the current
849 * connection. The host name is cached, so it is efficient to call this
850 * several times.
851 */
852
853 const char *
auth_get_canonical_hostname(struct ssh * ssh,int use_dns)854 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
855 {
856 static char *dnsname;
857
858 if (!use_dns)
859 return ssh_remote_ipaddr(ssh);
860 else if (dnsname != NULL)
861 return dnsname;
862 else {
863 dnsname = remote_hostname(ssh);
864 return dnsname;
865 }
866 }
867
868 /* These functions link key/cert options to the auth framework */
869
870 /* Log sshauthopt options locally and (optionally) for remote transmission */
871 void
auth_log_authopts(const char * loc,const struct sshauthopt * opts,int do_remote)872 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
873 {
874 int do_env = options.permit_user_env && opts->nenv > 0;
875 int do_permitopen = opts->npermitopen > 0 &&
876 (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
877 int do_permitlisten = opts->npermitlisten > 0 &&
878 (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
879 size_t i;
880 char msg[1024], buf[64];
881
882 snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
883 /* Try to keep this alphabetically sorted */
884 snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
885 opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
886 opts->force_command == NULL ? "" : " command",
887 do_env ? " environment" : "",
888 opts->valid_before == 0 ? "" : "expires",
889 opts->no_require_user_presence ? " no-touch-required" : "",
890 do_permitopen ? " permitopen" : "",
891 do_permitlisten ? " permitlisten" : "",
892 opts->permit_port_forwarding_flag ? " port-forwarding" : "",
893 opts->cert_principals == NULL ? "" : " principals",
894 opts->permit_pty_flag ? " pty" : "",
895 opts->require_verify ? " uv" : "",
896 opts->force_tun_device == -1 ? "" : " tun=",
897 opts->force_tun_device == -1 ? "" : buf,
898 opts->permit_user_rc ? " user-rc" : "",
899 opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
900
901 debug("%s: %s", loc, msg);
902 if (do_remote)
903 auth_debug_add("%s: %s", loc, msg);
904
905 if (options.permit_user_env) {
906 for (i = 0; i < opts->nenv; i++) {
907 debug("%s: environment: %s", loc, opts->env[i]);
908 if (do_remote) {
909 auth_debug_add("%s: environment: %s",
910 loc, opts->env[i]);
911 }
912 }
913 }
914
915 /* Go into a little more details for the local logs. */
916 if (opts->valid_before != 0) {
917 format_absolute_time(opts->valid_before, buf, sizeof(buf));
918 debug("%s: expires at %s", loc, buf);
919 }
920 if (opts->cert_principals != NULL) {
921 debug("%s: authorized principals: \"%s\"",
922 loc, opts->cert_principals);
923 }
924 if (opts->force_command != NULL)
925 debug("%s: forced command: \"%s\"", loc, opts->force_command);
926 if (do_permitopen) {
927 for (i = 0; i < opts->npermitopen; i++) {
928 debug("%s: permitted open: %s",
929 loc, opts->permitopen[i]);
930 }
931 }
932 if (do_permitlisten) {
933 for (i = 0; i < opts->npermitlisten; i++) {
934 debug("%s: permitted listen: %s",
935 loc, opts->permitlisten[i]);
936 }
937 }
938 }
939
940 /* Activate a new set of key/cert options; merging with what is there. */
941 int
auth_activate_options(struct ssh * ssh,struct sshauthopt * opts)942 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
943 {
944 struct sshauthopt *old = auth_opts;
945 const char *emsg = NULL;
946
947 debug_f("setting new authentication options");
948 if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
949 error("Inconsistent authentication options: %s", emsg);
950 return -1;
951 }
952 return 0;
953 }
954
955 /* Disable forwarding, etc for the session */
956 void
auth_restrict_session(struct ssh * ssh)957 auth_restrict_session(struct ssh *ssh)
958 {
959 struct sshauthopt *restricted;
960
961 debug_f("restricting session");
962
963 /* A blank sshauthopt defaults to permitting nothing */
964 restricted = sshauthopt_new();
965 restricted->permit_pty_flag = 1;
966 restricted->restricted = 1;
967
968 if (auth_activate_options(ssh, restricted) != 0)
969 fatal_f("failed to restrict session");
970 sshauthopt_free(restricted);
971 }
972
973 int
auth_authorise_keyopts(struct ssh * ssh,struct passwd * pw,struct sshauthopt * opts,int allow_cert_authority,const char * loc)974 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
975 struct sshauthopt *opts, int allow_cert_authority, const char *loc)
976 {
977 const char *remote_ip = ssh_remote_ipaddr(ssh);
978 const char *remote_host = auth_get_canonical_hostname(ssh,
979 options.use_dns);
980 time_t now = time(NULL);
981 char buf[64];
982
983 /*
984 * Check keys/principals file expiry time.
985 * NB. validity interval in certificate is handled elsewhere.
986 */
987 if (opts->valid_before && now > 0 &&
988 opts->valid_before < (uint64_t)now) {
989 format_absolute_time(opts->valid_before, buf, sizeof(buf));
990 debug("%s: entry expired at %s", loc, buf);
991 auth_debug_add("%s: entry expired at %s", loc, buf);
992 return -1;
993 }
994 /* Consistency checks */
995 if (opts->cert_principals != NULL && !opts->cert_authority) {
996 debug("%s: principals on non-CA key", loc);
997 auth_debug_add("%s: principals on non-CA key", loc);
998 /* deny access */
999 return -1;
1000 }
1001 /* cert-authority flag isn't valid in authorized_principals files */
1002 if (!allow_cert_authority && opts->cert_authority) {
1003 debug("%s: cert-authority flag invalid here", loc);
1004 auth_debug_add("%s: cert-authority flag invalid here", loc);
1005 /* deny access */
1006 return -1;
1007 }
1008
1009 /* Perform from= checks */
1010 if (opts->required_from_host_keys != NULL) {
1011 switch (match_host_and_ip(remote_host, remote_ip,
1012 opts->required_from_host_keys )) {
1013 case 1:
1014 /* Host name matches. */
1015 break;
1016 case -1:
1017 default:
1018 debug("%s: invalid from criteria", loc);
1019 auth_debug_add("%s: invalid from criteria", loc);
1020 /* FALLTHROUGH */
1021 case 0:
1022 logit("%s: Authentication tried for %.100s with "
1023 "correct key but not from a permitted "
1024 "host (host=%.200s, ip=%.200s, required=%.200s).",
1025 loc, pw->pw_name, remote_host, remote_ip,
1026 opts->required_from_host_keys);
1027 auth_debug_add("%s: Your host '%.200s' is not "
1028 "permitted to use this key for login.",
1029 loc, remote_host);
1030 /* deny access */
1031 return -1;
1032 }
1033 }
1034 /* Check source-address restriction from certificate */
1035 if (opts->required_from_host_cert != NULL) {
1036 switch (addr_match_cidr_list(remote_ip,
1037 opts->required_from_host_cert)) {
1038 case 1:
1039 /* accepted */
1040 break;
1041 case -1:
1042 default:
1043 /* invalid */
1044 error("%s: Certificate source-address invalid", loc);
1045 /* FALLTHROUGH */
1046 case 0:
1047 logit("%s: Authentication tried for %.100s with valid "
1048 "certificate but not from a permitted source "
1049 "address (%.200s).", loc, pw->pw_name, remote_ip);
1050 auth_debug_add("%s: Your address '%.200s' is not "
1051 "permitted to use this certificate for login.",
1052 loc, remote_ip);
1053 return -1;
1054 }
1055 }
1056 /*
1057 *
1058 * XXX this is spammy. We should report remotely only for keys
1059 * that are successful in actual auth attempts, and not PK_OK
1060 * tests.
1061 */
1062 auth_log_authopts(loc, opts, 1);
1063
1064 return 0;
1065 }
1066