1 /* $OpenBSD: auth.c,v 1.133 2018/09/12 01:19:12 djm Exp $ */
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
29 #include <sys/types.h>
31 #include <sys/socket.h>
34 #include <netinet/in.h>
57 #include "groupaccess.h"
65 #include "auth-options.h"
74 #include "monitor_wrap.h"
79 #include "blacklist_client.h"
82 extern ServerOptions options;
83 extern int use_privsep;
84 extern struct sshbuf *loginmsg;
85 extern struct passwd *privsep_pw;
86 extern struct sshauthopt *auth_opts;
88 /* Debugging messages */
89 static struct sshbuf *auth_debug;
92 * Check if the user is allowed to log in via ssh. If user is listed
93 * in DenyUsers or one of user's groups is listed in DenyGroups, false
94 * will be returned. If AllowUsers isn't empty and user isn't listed
95 * there, or if AllowGroups isn't empty and one of user's groups isn't
96 * listed there, false will be returned.
97 * If the user's shell is not executable, false will be returned.
98 * Otherwise true is returned.
101 allowed_user(struct passwd * pw)
103 struct ssh *ssh = active_state; /* XXX */
105 const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
109 struct spwd *spw = NULL;
112 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
113 if (!pw || !pw->pw_name)
117 if (!options.use_pam)
118 spw = getspnam(pw->pw_name);
119 #ifdef HAS_SHADOW_EXPIRE
120 if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
122 #endif /* HAS_SHADOW_EXPIRE */
123 #endif /* USE_SHADOW */
125 /* grab passwd field for locked account check */
126 passwd = pw->pw_passwd;
130 passwd = get_iaf_password(pw);
132 passwd = spw->sp_pwdp;
133 #endif /* USE_LIBIAF */
136 /* check for locked account */
137 if (!options.use_pam && passwd && *passwd) {
140 #ifdef LOCKED_PASSWD_STRING
141 if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
144 #ifdef LOCKED_PASSWD_PREFIX
145 if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
146 strlen(LOCKED_PASSWD_PREFIX)) == 0)
149 #ifdef LOCKED_PASSWD_SUBSTR
150 if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
154 free((void *) passwd);
155 #endif /* USE_LIBIAF */
157 logit("User %.100s not allowed because account is locked",
164 * Deny if shell does not exist or is not executable unless we
167 if (options.chroot_directory == NULL ||
168 strcasecmp(options.chroot_directory, "none") == 0) {
169 char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
170 _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
172 if (stat(shell, &st) != 0) {
173 logit("User %.100s not allowed because shell %.100s "
174 "does not exist", pw->pw_name, shell);
178 if (S_ISREG(st.st_mode) == 0 ||
179 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
180 logit("User %.100s not allowed because shell %.100s "
181 "is not executable", pw->pw_name, shell);
188 if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
189 options.num_deny_groups > 0 || options.num_allow_groups > 0) {
190 hostname = auth_get_canonical_hostname(ssh, options.use_dns);
191 ipaddr = ssh_remote_ipaddr(ssh);
194 /* Return false if user is listed in DenyUsers */
195 if (options.num_deny_users > 0) {
196 for (i = 0; i < options.num_deny_users; i++) {
197 r = match_user(pw->pw_name, hostname, ipaddr,
198 options.deny_users[i]);
200 fatal("Invalid DenyUsers pattern \"%.100s\"",
201 options.deny_users[i]);
203 logit("User %.100s from %.100s not allowed "
204 "because listed in DenyUsers",
205 pw->pw_name, hostname);
210 /* Return false if AllowUsers isn't empty and user isn't listed there */
211 if (options.num_allow_users > 0) {
212 for (i = 0; i < options.num_allow_users; i++) {
213 r = match_user(pw->pw_name, hostname, ipaddr,
214 options.allow_users[i]);
216 fatal("Invalid AllowUsers pattern \"%.100s\"",
217 options.allow_users[i]);
221 /* i < options.num_allow_users iff we break for loop */
222 if (i >= options.num_allow_users) {
223 logit("User %.100s from %.100s not allowed because "
224 "not listed in AllowUsers", pw->pw_name, hostname);
228 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
229 /* Get the user's group access list (primary and supplementary) */
230 if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
231 logit("User %.100s from %.100s not allowed because "
232 "not in any group", pw->pw_name, hostname);
236 /* Return false if one of user's groups is listed in DenyGroups */
237 if (options.num_deny_groups > 0)
238 if (ga_match(options.deny_groups,
239 options.num_deny_groups)) {
241 logit("User %.100s from %.100s not allowed "
242 "because a group is listed in DenyGroups",
243 pw->pw_name, hostname);
247 * Return false if AllowGroups isn't empty and one of user's groups
250 if (options.num_allow_groups > 0)
251 if (!ga_match(options.allow_groups,
252 options.num_allow_groups)) {
254 logit("User %.100s from %.100s not allowed "
255 "because none of user's groups are listed "
256 "in AllowGroups", pw->pw_name, hostname);
262 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
263 if (!sys_auth_allowed_user(pw, &loginmsg))
267 /* We found no reason not to let this user try to log on... */
272 * Formats any key left in authctxt->auth_method_key for inclusion in
273 * auth_log()'s message. Also includes authxtct->auth_method_info if present.
276 format_method_key(Authctxt *authctxt)
278 const struct sshkey *key = authctxt->auth_method_key;
279 const char *methinfo = authctxt->auth_method_info;
280 char *fp, *cafp, *ret = NULL;
285 if (sshkey_is_cert(key)) {
286 fp = sshkey_fingerprint(key,
287 options.fingerprint_hash, SSH_FP_DEFAULT);
288 cafp = sshkey_fingerprint(key->cert->signature_key,
289 options.fingerprint_hash, SSH_FP_DEFAULT);
290 xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s",
291 sshkey_type(key), fp == NULL ? "(null)" : fp,
293 (unsigned long long)key->cert->serial,
294 sshkey_type(key->cert->signature_key),
295 cafp == NULL ? "(null)" : cafp,
296 methinfo == NULL ? "" : ", ",
297 methinfo == NULL ? "" : methinfo);
301 fp = sshkey_fingerprint(key, options.fingerprint_hash,
303 xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
304 fp == NULL ? "(null)" : fp,
305 methinfo == NULL ? "" : ", ",
306 methinfo == NULL ? "" : methinfo);
313 auth_log(Authctxt *authctxt, int authenticated, int partial,
314 const char *method, const char *submethod)
316 struct ssh *ssh = active_state; /* XXX */
317 int level = SYSLOG_LEVEL_VERBOSE;
321 if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
324 /* Raise logging level */
325 if (authenticated == 1 ||
327 authctxt->failures >= options.max_authtries / 2 ||
328 strcmp(method, "password") == 0)
329 level = SYSLOG_LEVEL_INFO;
331 if (authctxt->postponed)
332 authmsg = "Postponed";
336 authmsg = authenticated ? "Accepted" : "Failed";
338 BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, "ssh");
341 if ((extra = format_method_key(authctxt)) == NULL) {
342 if (authctxt->auth_method_info != NULL)
343 extra = xstrdup(authctxt->auth_method_info);
346 do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
349 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
350 authctxt->valid ? "" : "invalid user ",
352 ssh_remote_ipaddr(ssh),
353 ssh_remote_port(ssh),
354 extra != NULL ? ": " : "",
355 extra != NULL ? extra : "");
359 #ifdef CUSTOM_FAILED_LOGIN
360 if (authenticated == 0 && !authctxt->postponed &&
361 (strcmp(method, "password") == 0 ||
362 strncmp(method, "keyboard-interactive", 20) == 0 ||
363 strcmp(method, "challenge-response") == 0))
364 record_failed_login(authctxt->user,
365 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
366 # ifdef WITH_AIXAUTHENTICATE
368 sys_auth_record_login(authctxt->user,
369 auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
373 #ifdef SSH_AUDIT_EVENTS
374 if (authenticated == 0 && !authctxt->postponed)
375 audit_event(audit_classify_auth(method));
381 auth_maxtries_exceeded(Authctxt *authctxt)
383 struct ssh *ssh = active_state; /* XXX */
385 error("maximum authentication attempts exceeded for "
386 "%s%.100s from %.200s port %d ssh2",
387 authctxt->valid ? "" : "invalid user ",
389 ssh_remote_ipaddr(ssh),
390 ssh_remote_port(ssh));
391 packet_disconnect("Too many authentication failures");
396 * Check whether root logins are disallowed.
399 auth_root_allowed(struct ssh *ssh, const char *method)
401 switch (options.permit_root_login) {
404 case PERMIT_NO_PASSWD:
405 if (strcmp(method, "publickey") == 0 ||
406 strcmp(method, "hostbased") == 0 ||
407 strcmp(method, "gssapi-with-mic") == 0)
410 case PERMIT_FORCED_ONLY:
411 if (auth_opts->force_command != NULL) {
412 logit("Root login accepted for forced command.");
417 logit("ROOT LOGIN REFUSED FROM %.200s port %d",
418 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
424 * Given a template and a passwd structure, build a filename
425 * by substituting % tokenised options. Currently, %% becomes '%',
426 * %h becomes the home directory and %u the username.
428 * This returns a buffer allocated by xmalloc.
431 expand_authorized_keys(const char *filename, struct passwd *pw)
433 char *file, uidstr[32], ret[PATH_MAX];
436 snprintf(uidstr, sizeof(uidstr), "%llu",
437 (unsigned long long)pw->pw_uid);
438 file = percent_expand(filename, "h", pw->pw_dir,
439 "u", pw->pw_name, "U", uidstr, (char *)NULL);
442 * Ensure that filename starts anchored. If not, be backward
443 * compatible and prepend the '%h/'
448 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
449 if (i < 0 || (size_t)i >= sizeof(ret))
450 fatal("expand_authorized_keys: path too long");
452 return (xstrdup(ret));
456 authorized_principals_file(struct passwd *pw)
458 if (options.authorized_principals_file == NULL)
460 return expand_authorized_keys(options.authorized_principals_file, pw);
463 /* return ok if key exists in sysfile or userfile */
465 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
466 const char *sysfile, const char *userfile)
470 HostStatus host_status;
471 struct hostkeys *hostkeys;
472 const struct hostkey_entry *found;
474 hostkeys = init_hostkeys();
475 load_hostkeys(hostkeys, host, sysfile);
476 if (userfile != NULL) {
477 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
478 if (options.strict_modes &&
479 (stat(user_hostfile, &st) == 0) &&
480 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
481 (st.st_mode & 022) != 0)) {
482 logit("Authentication refused for %.100s: "
483 "bad owner or modes for %.200s",
484 pw->pw_name, user_hostfile);
485 auth_debug_add("Ignored %.200s: bad ownership or modes",
488 temporarily_use_uid(pw);
489 load_hostkeys(hostkeys, host, user_hostfile);
494 host_status = check_key_in_hostkeys(hostkeys, key, &found);
495 if (host_status == HOST_REVOKED)
496 error("WARNING: revoked key for %s attempted authentication",
498 else if (host_status == HOST_OK)
499 debug("%s: key for %s found at %s:%ld", __func__,
500 found->host, found->file, found->line);
502 debug("%s: key for host %s not found", __func__, host);
504 free_hostkeys(hostkeys);
510 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
511 int log_missing, char *file_type)
518 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
519 if (log_missing || errno != ENOENT)
520 debug("Could not open %s '%s': %s", file_type, file,
525 if (fstat(fd, &st) < 0) {
529 if (!S_ISREG(st.st_mode)) {
530 logit("User %s %s %s is not a regular file",
531 pw->pw_name, file_type, file);
536 if ((f = fdopen(fd, "r")) == NULL) {
541 safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
543 logit("Authentication refused: %s", line);
544 auth_debug_add("Ignored %s: %s", file_type, line);
553 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
555 return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
559 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
561 return auth_openfile(file, pw, strict_modes, 0,
562 "authorized principals");
566 getpwnamallow(const char *user)
568 struct ssh *ssh = active_state; /* XXX */
569 #ifdef HAVE_LOGIN_CAP
570 extern login_cap_t *lc;
576 struct connection_info *ci = get_connection_info(1, options.use_dns);
579 parse_server_match_config(&options, ci);
580 log_change_level(options.log_level);
581 process_permitopen(ssh, &options);
583 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
589 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
594 * Windows usernames are case-insensitive. To avoid later problems
595 * when trying to match the username, the user is only allowed to
596 * login if the username is given in the same case as stored in the
599 if (pw != NULL && strcmp(user, pw->pw_name) != 0) {
600 logit("Login name %.100s does not match stored username %.100s",
606 BLACKLIST_NOTIFY(BLACKLIST_BAD_USER, user);
607 logit("Invalid user %.100s from %.100s port %d",
608 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
609 #ifdef CUSTOM_FAILED_LOGIN
610 record_failed_login(user,
611 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
613 #ifdef SSH_AUDIT_EVENTS
614 audit_event(SSH_INVALID_USER);
615 #endif /* SSH_AUDIT_EVENTS */
618 if (!allowed_user(pw))
620 #ifdef HAVE_LOGIN_CAP
621 if ((lc = login_getpwclass(pw)) == NULL) {
622 debug("unable to get login class: %s", user);
626 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
627 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
628 debug("Approval failure for %s", user);
640 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
642 auth_key_is_revoked(struct sshkey *key)
647 if (options.revoked_keys_file == NULL)
649 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
650 SSH_FP_DEFAULT)) == NULL) {
651 r = SSH_ERR_ALLOC_FAIL;
652 error("%s: fingerprint key: %s", __func__, ssh_err(r));
656 r = sshkey_check_revoked(key, options.revoked_keys_file);
659 break; /* not revoked */
660 case SSH_ERR_KEY_REVOKED:
661 error("Authentication key %s %s revoked by file %s",
662 sshkey_type(key), fp, options.revoked_keys_file);
665 error("Error checking authentication key %s %s in "
666 "revoked keys file %s: %s", sshkey_type(key), fp,
667 options.revoked_keys_file, ssh_err(r));
676 return r == 0 ? 0 : 1;
680 auth_debug_add(const char *fmt,...)
686 if (auth_debug == NULL)
690 vsnprintf(buf, sizeof(buf), fmt, args);
692 if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
693 fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r));
697 auth_debug_send(void)
699 struct ssh *ssh = active_state; /* XXX */
703 if (auth_debug == NULL)
705 while (sshbuf_len(auth_debug) != 0) {
706 if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
707 fatal("%s: sshbuf_get_cstring: %s",
708 __func__, ssh_err(r));
709 ssh_packet_send_debug(ssh, "%s", msg);
715 auth_debug_reset(void)
717 if (auth_debug != NULL)
718 sshbuf_reset(auth_debug);
719 else if ((auth_debug = sshbuf_new()) == NULL)
720 fatal("%s: sshbuf_new failed", __func__);
726 static struct passwd fake;
728 memset(&fake, 0, sizeof(fake));
729 fake.pw_name = "NOUSER";
731 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
732 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
733 fake.pw_gecos = "NOUSER";
735 fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
736 fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
737 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
740 fake.pw_dir = "/nonexist";
741 fake.pw_shell = "/nonexist";
747 * Returns the remote DNS hostname as a string. The returned string must not
748 * be freed. NB. this will usually trigger a DNS query the first time it is
750 * This function does additional checks on the hostname to mitigate some
751 * attacks on legacy rhosts-style authentication.
752 * XXX is RhostsRSAAuthentication vulnerable to these?
753 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
757 remote_hostname(struct ssh *ssh)
759 struct sockaddr_storage from;
761 struct addrinfo hints, *ai, *aitop;
762 char name[NI_MAXHOST], ntop2[NI_MAXHOST];
763 const char *ntop = ssh_remote_ipaddr(ssh);
765 /* Get IP address of client. */
766 fromlen = sizeof(from);
767 memset(&from, 0, sizeof(from));
768 if (getpeername(ssh_packet_get_connection_in(ssh),
769 (struct sockaddr *)&from, &fromlen) < 0) {
770 debug("getpeername failed: %.100s", strerror(errno));
774 ipv64_normalise_mapped(&from, &fromlen);
775 if (from.ss_family == AF_INET6)
776 fromlen = sizeof(struct sockaddr_in6);
778 debug3("Trying to reverse map address %.100s.", ntop);
779 /* Map the IP address to a host name. */
780 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
781 NULL, 0, NI_NAMEREQD) != 0) {
782 /* Host name not found. Use ip address. */
787 * if reverse lookup result looks like a numeric hostname,
788 * someone is trying to trick us by PTR record like following:
789 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5
791 memset(&hints, 0, sizeof(hints));
792 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
793 hints.ai_flags = AI_NUMERICHOST;
794 if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
795 logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
801 /* Names are stored in lowercase. */
805 * Map it back to an IP address and check that the given
806 * address actually is an address of this host. This is
807 * necessary because anyone with access to a name server can
808 * define arbitrary names for an IP address. Mapping from
809 * name to IP address can be trusted better (but can still be
810 * fooled if the intruder has access to the name server of
813 memset(&hints, 0, sizeof(hints));
814 hints.ai_family = from.ss_family;
815 hints.ai_socktype = SOCK_STREAM;
816 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
817 logit("reverse mapping checking getaddrinfo for %.700s "
818 "[%s] failed.", name, ntop);
821 /* Look for the address from the list of addresses. */
822 for (ai = aitop; ai; ai = ai->ai_next) {
823 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
824 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
825 (strcmp(ntop, ntop2) == 0))
829 /* If we reached the end of the list, the address was not there. */
831 /* Address not found for the host name. */
832 logit("Address %.100s maps to %.600s, but this does not "
833 "map back to the address.", ntop, name);
840 * Return the canonical name of the host in the other side of the current
841 * connection. The host name is cached, so it is efficient to call this
846 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
848 static char *dnsname;
851 return ssh_remote_ipaddr(ssh);
852 else if (dnsname != NULL)
855 dnsname = remote_hostname(ssh);
861 * Runs command in a subprocess with a minimal environment.
862 * Returns pid on success, 0 on failure.
863 * The child stdout and stderr maybe captured, left attached or sent to
864 * /dev/null depending on the contents of flags.
865 * "tag" is prepended to log messages.
866 * NB. "command" is only used for logging; the actual command executed is
870 subprocess(const char *tag, struct passwd *pw, const char *command,
871 int ac, char **av, FILE **child, u_int flags)
875 int fd, devnull, p[2], i;
877 char *cp, errmsg[512];
884 debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
885 tag, command, pw->pw_name, flags);
887 /* Check consistency */
888 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
889 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
890 error("%s: inconsistent flags", __func__);
893 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
894 error("%s: inconsistent flags/output", __func__);
899 * If executing an explicit binary, then verify the it exists
900 * and appears safe-ish to execute
903 error("%s path is not absolute", tag);
906 temporarily_use_uid(pw);
907 if (stat(av[0], &st) < 0) {
908 error("Could not stat %s \"%s\": %s", tag,
909 av[0], strerror(errno));
913 if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
914 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
918 /* Prepare to keep the child's stdout if requested */
920 error("%s: pipe: %s", tag, strerror(errno));
926 switch ((pid = fork())) {
928 error("%s: fork: %s", tag, strerror(errno));
933 /* Prepare a minimal environment for the child. */
935 child_env = xcalloc(sizeof(*child_env), envsize);
936 child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
937 child_set_env(&child_env, &envsize, "USER", pw->pw_name);
938 child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
939 child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
940 if ((cp = getenv("LANG")) != NULL)
941 child_set_env(&child_env, &envsize, "LANG", cp);
943 for (i = 0; i < NSIG; i++)
946 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
947 error("%s: open %s: %s", tag, _PATH_DEVNULL,
951 if (dup2(devnull, STDIN_FILENO) == -1) {
952 error("%s: dup2: %s", tag, strerror(errno));
956 /* Set up stdout as requested; leave stderr in place for now. */
958 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
960 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
962 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
963 error("%s: dup2: %s", tag, strerror(errno));
966 closefrom(STDERR_FILENO + 1);
968 /* Don't use permanently_set_uid() here to avoid fatal() */
969 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
970 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
974 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
975 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
979 /* stdin is pointed to /dev/null at this point */
980 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
981 dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
982 error("%s: dup2: %s", tag, strerror(errno));
986 execve(av[0], av, child_env);
987 error("%s exec \"%s\": %s", tag, command, strerror(errno));
989 default: /* parent */
994 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
996 else if ((f = fdopen(p[0], "r")) == NULL) {
997 error("%s: fdopen: %s", tag, strerror(errno));
999 /* Don't leave zombie child */
1001 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
1006 debug3("%s: %s pid %ld", __func__, tag, (long)pid);
1012 /* These functions link key/cert options to the auth framework */
1014 /* Log sshauthopt options locally and (optionally) for remote transmission */
1016 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
1018 int do_env = options.permit_user_env && opts->nenv > 0;
1019 int do_permitopen = opts->npermitopen > 0 &&
1020 (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
1021 int do_permitlisten = opts->npermitlisten > 0 &&
1022 (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
1024 char msg[1024], buf[64];
1026 snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
1027 /* Try to keep this alphabetically sorted */
1028 snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s",
1029 opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
1030 opts->force_command == NULL ? "" : " command",
1031 do_env ? " environment" : "",
1032 opts->valid_before == 0 ? "" : "expires",
1033 do_permitopen ? " permitopen" : "",
1034 do_permitlisten ? " permitlisten" : "",
1035 opts->permit_port_forwarding_flag ? " port-forwarding" : "",
1036 opts->cert_principals == NULL ? "" : " principals",
1037 opts->permit_pty_flag ? " pty" : "",
1038 opts->force_tun_device == -1 ? "" : " tun=",
1039 opts->force_tun_device == -1 ? "" : buf,
1040 opts->permit_user_rc ? " user-rc" : "",
1041 opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
1043 debug("%s: %s", loc, msg);
1045 auth_debug_add("%s: %s", loc, msg);
1047 if (options.permit_user_env) {
1048 for (i = 0; i < opts->nenv; i++) {
1049 debug("%s: environment: %s", loc, opts->env[i]);
1051 auth_debug_add("%s: environment: %s",
1057 /* Go into a little more details for the local logs. */
1058 if (opts->valid_before != 0) {
1059 format_absolute_time(opts->valid_before, buf, sizeof(buf));
1060 debug("%s: expires at %s", loc, buf);
1062 if (opts->cert_principals != NULL) {
1063 debug("%s: authorized principals: \"%s\"",
1064 loc, opts->cert_principals);
1066 if (opts->force_command != NULL)
1067 debug("%s: forced command: \"%s\"", loc, opts->force_command);
1068 if (do_permitopen) {
1069 for (i = 0; i < opts->npermitopen; i++) {
1070 debug("%s: permitted open: %s",
1071 loc, opts->permitopen[i]);
1074 if (do_permitlisten) {
1075 for (i = 0; i < opts->npermitlisten; i++) {
1076 debug("%s: permitted listen: %s",
1077 loc, opts->permitlisten[i]);
1082 /* Activate a new set of key/cert options; merging with what is there. */
1084 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
1086 struct sshauthopt *old = auth_opts;
1087 const char *emsg = NULL;
1089 debug("%s: setting new authentication options", __func__);
1090 if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
1091 error("Inconsistent authentication options: %s", emsg);
1097 /* Disable forwarding, etc for the session */
1099 auth_restrict_session(struct ssh *ssh)
1101 struct sshauthopt *restricted;
1103 debug("%s: restricting session", __func__);
1105 /* A blank sshauthopt defaults to permitting nothing */
1106 restricted = sshauthopt_new();
1107 restricted->permit_pty_flag = 1;
1108 restricted->restricted = 1;
1110 if (auth_activate_options(ssh, restricted) != 0)
1111 fatal("%s: failed to restrict session", __func__);
1112 sshauthopt_free(restricted);
1116 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
1117 struct sshauthopt *opts, int allow_cert_authority, const char *loc)
1119 const char *remote_ip = ssh_remote_ipaddr(ssh);
1120 const char *remote_host = auth_get_canonical_hostname(ssh,
1122 time_t now = time(NULL);
1126 * Check keys/principals file expiry time.
1127 * NB. validity interval in certificate is handled elsewhere.
1129 if (opts->valid_before && now > 0 &&
1130 opts->valid_before < (uint64_t)now) {
1131 format_absolute_time(opts->valid_before, buf, sizeof(buf));
1132 debug("%s: entry expired at %s", loc, buf);
1133 auth_debug_add("%s: entry expired at %s", loc, buf);
1136 /* Consistency checks */
1137 if (opts->cert_principals != NULL && !opts->cert_authority) {
1138 debug("%s: principals on non-CA key", loc);
1139 auth_debug_add("%s: principals on non-CA key", loc);
1143 /* cert-authority flag isn't valid in authorized_principals files */
1144 if (!allow_cert_authority && opts->cert_authority) {
1145 debug("%s: cert-authority flag invalid here", loc);
1146 auth_debug_add("%s: cert-authority flag invalid here", loc);
1151 /* Perform from= checks */
1152 if (opts->required_from_host_keys != NULL) {
1153 switch (match_host_and_ip(remote_host, remote_ip,
1154 opts->required_from_host_keys )) {
1156 /* Host name matches. */
1160 debug("%s: invalid from criteria", loc);
1161 auth_debug_add("%s: invalid from criteria", loc);
1164 logit("%s: Authentication tried for %.100s with "
1165 "correct key but not from a permitted "
1166 "host (host=%.200s, ip=%.200s, required=%.200s).",
1167 loc, pw->pw_name, remote_host, remote_ip,
1168 opts->required_from_host_keys);
1169 auth_debug_add("%s: Your host '%.200s' is not "
1170 "permitted to use this key for login.",
1176 /* Check source-address restriction from certificate */
1177 if (opts->required_from_host_cert != NULL) {
1178 switch (addr_match_cidr_list(remote_ip,
1179 opts->required_from_host_cert)) {
1186 error("%s: Certificate source-address invalid",
1190 logit("%s: Authentication tried for %.100s with valid "
1191 "certificate but not from a permitted source "
1192 "address (%.200s).", loc, pw->pw_name, remote_ip);
1193 auth_debug_add("%s: Your address '%.200s' is not "
1194 "permitted to use this certificate for login.",
1201 * XXX this is spammy. We should report remotely only for keys
1202 * that are successful in actual auth attempts, and not PK_OK
1205 auth_log_authopts(loc, opts, 1);