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