1 /* $OpenBSD: auth.c,v 1.132 2018/07/11 08:19:35 martijn 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, *ret = NULL;
285 if (sshkey_is_cert(key)) {
286 fp = sshkey_fingerprint(key->cert->signature_key,
287 options.fingerprint_hash, SSH_FP_DEFAULT);
288 xasprintf(&ret, "%s ID %s (serial %llu) CA %s %s%s%s",
289 sshkey_type(key), key->cert->key_id,
290 (unsigned long long)key->cert->serial,
291 sshkey_type(key->cert->signature_key),
292 fp == NULL ? "(null)" : fp,
293 methinfo == NULL ? "" : ", ",
294 methinfo == NULL ? "" : methinfo);
297 fp = sshkey_fingerprint(key, options.fingerprint_hash,
299 xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
300 fp == NULL ? "(null)" : fp,
301 methinfo == NULL ? "" : ", ",
302 methinfo == NULL ? "" : methinfo);
309 auth_log(Authctxt *authctxt, int authenticated, int partial,
310 const char *method, const char *submethod)
312 struct ssh *ssh = active_state; /* XXX */
313 void (*authlog) (const char *fmt,...) = verbose;
317 if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
320 /* Raise logging level */
321 if (authenticated == 1 ||
323 authctxt->failures >= options.max_authtries / 2 ||
324 strcmp(method, "password") == 0)
327 if (authctxt->postponed)
328 authmsg = "Postponed";
332 authmsg = authenticated ? "Accepted" : "Failed";
334 BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, "ssh");
337 if ((extra = format_method_key(authctxt)) == NULL) {
338 if (authctxt->auth_method_info != NULL)
339 extra = xstrdup(authctxt->auth_method_info);
342 authlog("%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
345 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
346 authctxt->valid ? "" : "invalid user ",
348 ssh_remote_ipaddr(ssh),
349 ssh_remote_port(ssh),
350 extra != NULL ? ": " : "",
351 extra != NULL ? extra : "");
355 #ifdef CUSTOM_FAILED_LOGIN
356 if (authenticated == 0 && !authctxt->postponed &&
357 (strcmp(method, "password") == 0 ||
358 strncmp(method, "keyboard-interactive", 20) == 0 ||
359 strcmp(method, "challenge-response") == 0))
360 record_failed_login(authctxt->user,
361 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
362 # ifdef WITH_AIXAUTHENTICATE
364 sys_auth_record_login(authctxt->user,
365 auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
369 #ifdef SSH_AUDIT_EVENTS
370 if (authenticated == 0 && !authctxt->postponed)
371 audit_event(audit_classify_auth(method));
377 auth_maxtries_exceeded(Authctxt *authctxt)
379 struct ssh *ssh = active_state; /* XXX */
381 error("maximum authentication attempts exceeded for "
382 "%s%.100s from %.200s port %d ssh2",
383 authctxt->valid ? "" : "invalid user ",
385 ssh_remote_ipaddr(ssh),
386 ssh_remote_port(ssh));
387 packet_disconnect("Too many authentication failures");
392 * Check whether root logins are disallowed.
395 auth_root_allowed(struct ssh *ssh, const char *method)
397 switch (options.permit_root_login) {
400 case PERMIT_NO_PASSWD:
401 if (strcmp(method, "publickey") == 0 ||
402 strcmp(method, "hostbased") == 0 ||
403 strcmp(method, "gssapi-with-mic") == 0)
406 case PERMIT_FORCED_ONLY:
407 if (auth_opts->force_command != NULL) {
408 logit("Root login accepted for forced command.");
413 logit("ROOT LOGIN REFUSED FROM %.200s port %d",
414 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
420 * Given a template and a passwd structure, build a filename
421 * by substituting % tokenised options. Currently, %% becomes '%',
422 * %h becomes the home directory and %u the username.
424 * This returns a buffer allocated by xmalloc.
427 expand_authorized_keys(const char *filename, struct passwd *pw)
429 char *file, uidstr[32], ret[PATH_MAX];
432 snprintf(uidstr, sizeof(uidstr), "%llu",
433 (unsigned long long)pw->pw_uid);
434 file = percent_expand(filename, "h", pw->pw_dir,
435 "u", pw->pw_name, "U", uidstr, (char *)NULL);
438 * Ensure that filename starts anchored. If not, be backward
439 * compatible and prepend the '%h/'
444 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
445 if (i < 0 || (size_t)i >= sizeof(ret))
446 fatal("expand_authorized_keys: path too long");
448 return (xstrdup(ret));
452 authorized_principals_file(struct passwd *pw)
454 if (options.authorized_principals_file == NULL)
456 return expand_authorized_keys(options.authorized_principals_file, pw);
459 /* return ok if key exists in sysfile or userfile */
461 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
462 const char *sysfile, const char *userfile)
466 HostStatus host_status;
467 struct hostkeys *hostkeys;
468 const struct hostkey_entry *found;
470 hostkeys = init_hostkeys();
471 load_hostkeys(hostkeys, host, sysfile);
472 if (userfile != NULL) {
473 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
474 if (options.strict_modes &&
475 (stat(user_hostfile, &st) == 0) &&
476 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
477 (st.st_mode & 022) != 0)) {
478 logit("Authentication refused for %.100s: "
479 "bad owner or modes for %.200s",
480 pw->pw_name, user_hostfile);
481 auth_debug_add("Ignored %.200s: bad ownership or modes",
484 temporarily_use_uid(pw);
485 load_hostkeys(hostkeys, host, user_hostfile);
490 host_status = check_key_in_hostkeys(hostkeys, key, &found);
491 if (host_status == HOST_REVOKED)
492 error("WARNING: revoked key for %s attempted authentication",
494 else if (host_status == HOST_OK)
495 debug("%s: key for %s found at %s:%ld", __func__,
496 found->host, found->file, found->line);
498 debug("%s: key for host %s not found", __func__, host);
500 free_hostkeys(hostkeys);
506 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
507 int log_missing, char *file_type)
514 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
515 if (log_missing || errno != ENOENT)
516 debug("Could not open %s '%s': %s", file_type, file,
521 if (fstat(fd, &st) < 0) {
525 if (!S_ISREG(st.st_mode)) {
526 logit("User %s %s %s is not a regular file",
527 pw->pw_name, file_type, file);
532 if ((f = fdopen(fd, "r")) == NULL) {
537 safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
539 logit("Authentication refused: %s", line);
540 auth_debug_add("Ignored %s: %s", file_type, line);
549 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
551 return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
555 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
557 return auth_openfile(file, pw, strict_modes, 0,
558 "authorized principals");
562 getpwnamallow(const char *user)
564 struct ssh *ssh = active_state; /* XXX */
565 #ifdef HAVE_LOGIN_CAP
566 extern login_cap_t *lc;
572 struct connection_info *ci = get_connection_info(1, options.use_dns);
575 parse_server_match_config(&options, ci);
576 log_change_level(options.log_level);
577 process_permitopen(ssh, &options);
579 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
585 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
590 * Windows usernames are case-insensitive. To avoid later problems
591 * when trying to match the username, the user is only allowed to
592 * login if the username is given in the same case as stored in the
595 if (pw != NULL && strcmp(user, pw->pw_name) != 0) {
596 logit("Login name %.100s does not match stored username %.100s",
602 BLACKLIST_NOTIFY(BLACKLIST_BAD_USER, user);
603 logit("Invalid user %.100s from %.100s port %d",
604 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
605 #ifdef CUSTOM_FAILED_LOGIN
606 record_failed_login(user,
607 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
609 #ifdef SSH_AUDIT_EVENTS
610 audit_event(SSH_INVALID_USER);
611 #endif /* SSH_AUDIT_EVENTS */
614 if (!allowed_user(pw))
616 #ifdef HAVE_LOGIN_CAP
617 if ((lc = login_getpwclass(pw)) == NULL) {
618 debug("unable to get login class: %s", user);
622 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
623 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
624 debug("Approval failure for %s", user);
636 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
638 auth_key_is_revoked(struct sshkey *key)
643 if (options.revoked_keys_file == NULL)
645 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
646 SSH_FP_DEFAULT)) == NULL) {
647 r = SSH_ERR_ALLOC_FAIL;
648 error("%s: fingerprint key: %s", __func__, ssh_err(r));
652 r = sshkey_check_revoked(key, options.revoked_keys_file);
655 break; /* not revoked */
656 case SSH_ERR_KEY_REVOKED:
657 error("Authentication key %s %s revoked by file %s",
658 sshkey_type(key), fp, options.revoked_keys_file);
661 error("Error checking authentication key %s %s in "
662 "revoked keys file %s: %s", sshkey_type(key), fp,
663 options.revoked_keys_file, ssh_err(r));
672 return r == 0 ? 0 : 1;
676 auth_debug_add(const char *fmt,...)
682 if (auth_debug == NULL)
686 vsnprintf(buf, sizeof(buf), fmt, args);
688 if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
689 fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r));
693 auth_debug_send(void)
695 struct ssh *ssh = active_state; /* XXX */
699 if (auth_debug == NULL)
701 while (sshbuf_len(auth_debug) != 0) {
702 if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
703 fatal("%s: sshbuf_get_cstring: %s",
704 __func__, ssh_err(r));
705 ssh_packet_send_debug(ssh, "%s", msg);
711 auth_debug_reset(void)
713 if (auth_debug != NULL)
714 sshbuf_reset(auth_debug);
715 else if ((auth_debug = sshbuf_new()) == NULL)
716 fatal("%s: sshbuf_new failed", __func__);
722 static struct passwd fake;
724 memset(&fake, 0, sizeof(fake));
725 fake.pw_name = "NOUSER";
727 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
728 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
729 fake.pw_gecos = "NOUSER";
731 fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
732 fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
733 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
736 fake.pw_dir = "/nonexist";
737 fake.pw_shell = "/nonexist";
743 * Returns the remote DNS hostname as a string. The returned string must not
744 * be freed. NB. this will usually trigger a DNS query the first time it is
746 * This function does additional checks on the hostname to mitigate some
747 * attacks on legacy rhosts-style authentication.
748 * XXX is RhostsRSAAuthentication vulnerable to these?
749 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
753 remote_hostname(struct ssh *ssh)
755 struct sockaddr_storage from;
757 struct addrinfo hints, *ai, *aitop;
758 char name[NI_MAXHOST], ntop2[NI_MAXHOST];
759 const char *ntop = ssh_remote_ipaddr(ssh);
761 /* Get IP address of client. */
762 fromlen = sizeof(from);
763 memset(&from, 0, sizeof(from));
764 if (getpeername(ssh_packet_get_connection_in(ssh),
765 (struct sockaddr *)&from, &fromlen) < 0) {
766 debug("getpeername failed: %.100s", strerror(errno));
770 ipv64_normalise_mapped(&from, &fromlen);
771 if (from.ss_family == AF_INET6)
772 fromlen = sizeof(struct sockaddr_in6);
774 debug3("Trying to reverse map address %.100s.", ntop);
775 /* Map the IP address to a host name. */
776 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
777 NULL, 0, NI_NAMEREQD) != 0) {
778 /* Host name not found. Use ip address. */
783 * if reverse lookup result looks like a numeric hostname,
784 * someone is trying to trick us by PTR record like following:
785 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5
787 memset(&hints, 0, sizeof(hints));
788 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
789 hints.ai_flags = AI_NUMERICHOST;
790 if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
791 logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
797 /* Names are stored in lowercase. */
801 * Map it back to an IP address and check that the given
802 * address actually is an address of this host. This is
803 * necessary because anyone with access to a name server can
804 * define arbitrary names for an IP address. Mapping from
805 * name to IP address can be trusted better (but can still be
806 * fooled if the intruder has access to the name server of
809 memset(&hints, 0, sizeof(hints));
810 hints.ai_family = from.ss_family;
811 hints.ai_socktype = SOCK_STREAM;
812 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
813 logit("reverse mapping checking getaddrinfo for %.700s "
814 "[%s] failed.", name, ntop);
817 /* Look for the address from the list of addresses. */
818 for (ai = aitop; ai; ai = ai->ai_next) {
819 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
820 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
821 (strcmp(ntop, ntop2) == 0))
825 /* If we reached the end of the list, the address was not there. */
827 /* Address not found for the host name. */
828 logit("Address %.100s maps to %.600s, but this does not "
829 "map back to the address.", ntop, name);
836 * Return the canonical name of the host in the other side of the current
837 * connection. The host name is cached, so it is efficient to call this
842 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
844 static char *dnsname;
847 return ssh_remote_ipaddr(ssh);
848 else if (dnsname != NULL)
851 dnsname = remote_hostname(ssh);
857 * Runs command in a subprocess with a minimal environment.
858 * Returns pid on success, 0 on failure.
859 * The child stdout and stderr maybe captured, left attached or sent to
860 * /dev/null depending on the contents of flags.
861 * "tag" is prepended to log messages.
862 * NB. "command" is only used for logging; the actual command executed is
866 subprocess(const char *tag, struct passwd *pw, const char *command,
867 int ac, char **av, FILE **child, u_int flags)
871 int fd, devnull, p[2], i;
873 char *cp, errmsg[512];
880 debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
881 tag, command, pw->pw_name, flags);
883 /* Check consistency */
884 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
885 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
886 error("%s: inconsistent flags", __func__);
889 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
890 error("%s: inconsistent flags/output", __func__);
895 * If executing an explicit binary, then verify the it exists
896 * and appears safe-ish to execute
899 error("%s path is not absolute", tag);
902 temporarily_use_uid(pw);
903 if (stat(av[0], &st) < 0) {
904 error("Could not stat %s \"%s\": %s", tag,
905 av[0], strerror(errno));
909 if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
910 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
914 /* Prepare to keep the child's stdout if requested */
916 error("%s: pipe: %s", tag, strerror(errno));
922 switch ((pid = fork())) {
924 error("%s: fork: %s", tag, strerror(errno));
929 /* Prepare a minimal environment for the child. */
931 child_env = xcalloc(sizeof(*child_env), envsize);
932 child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
933 child_set_env(&child_env, &envsize, "USER", pw->pw_name);
934 child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
935 child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
936 if ((cp = getenv("LANG")) != NULL)
937 child_set_env(&child_env, &envsize, "LANG", cp);
939 for (i = 0; i < NSIG; i++)
942 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
943 error("%s: open %s: %s", tag, _PATH_DEVNULL,
947 if (dup2(devnull, STDIN_FILENO) == -1) {
948 error("%s: dup2: %s", tag, strerror(errno));
952 /* Set up stdout as requested; leave stderr in place for now. */
954 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
956 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
958 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
959 error("%s: dup2: %s", tag, strerror(errno));
962 closefrom(STDERR_FILENO + 1);
964 /* Don't use permanently_set_uid() here to avoid fatal() */
965 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
966 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
970 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
971 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
975 /* stdin is pointed to /dev/null at this point */
976 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
977 dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
978 error("%s: dup2: %s", tag, strerror(errno));
982 execve(av[0], av, child_env);
983 error("%s exec \"%s\": %s", tag, command, strerror(errno));
985 default: /* parent */
990 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
992 else if ((f = fdopen(p[0], "r")) == NULL) {
993 error("%s: fdopen: %s", tag, strerror(errno));
995 /* Don't leave zombie child */
997 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
1002 debug3("%s: %s pid %ld", __func__, tag, (long)pid);
1008 /* These functions link key/cert options to the auth framework */
1010 /* Log sshauthopt options locally and (optionally) for remote transmission */
1012 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
1014 int do_env = options.permit_user_env && opts->nenv > 0;
1015 int do_permitopen = opts->npermitopen > 0 &&
1016 (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
1017 int do_permitlisten = opts->npermitlisten > 0 &&
1018 (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
1020 char msg[1024], buf[64];
1022 snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
1023 /* Try to keep this alphabetically sorted */
1024 snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s",
1025 opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
1026 opts->force_command == NULL ? "" : " command",
1027 do_env ? " environment" : "",
1028 opts->valid_before == 0 ? "" : "expires",
1029 do_permitopen ? " permitopen" : "",
1030 do_permitlisten ? " permitlisten" : "",
1031 opts->permit_port_forwarding_flag ? " port-forwarding" : "",
1032 opts->cert_principals == NULL ? "" : " principals",
1033 opts->permit_pty_flag ? " pty" : "",
1034 opts->force_tun_device == -1 ? "" : " tun=",
1035 opts->force_tun_device == -1 ? "" : buf,
1036 opts->permit_user_rc ? " user-rc" : "",
1037 opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
1039 debug("%s: %s", loc, msg);
1041 auth_debug_add("%s: %s", loc, msg);
1043 if (options.permit_user_env) {
1044 for (i = 0; i < opts->nenv; i++) {
1045 debug("%s: environment: %s", loc, opts->env[i]);
1047 auth_debug_add("%s: environment: %s",
1053 /* Go into a little more details for the local logs. */
1054 if (opts->valid_before != 0) {
1055 format_absolute_time(opts->valid_before, buf, sizeof(buf));
1056 debug("%s: expires at %s", loc, buf);
1058 if (opts->cert_principals != NULL) {
1059 debug("%s: authorized principals: \"%s\"",
1060 loc, opts->cert_principals);
1062 if (opts->force_command != NULL)
1063 debug("%s: forced command: \"%s\"", loc, opts->force_command);
1064 if (do_permitopen) {
1065 for (i = 0; i < opts->npermitopen; i++) {
1066 debug("%s: permitted open: %s",
1067 loc, opts->permitopen[i]);
1070 if (do_permitlisten) {
1071 for (i = 0; i < opts->npermitlisten; i++) {
1072 debug("%s: permitted listen: %s",
1073 loc, opts->permitlisten[i]);
1078 /* Activate a new set of key/cert options; merging with what is there. */
1080 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
1082 struct sshauthopt *old = auth_opts;
1083 const char *emsg = NULL;
1085 debug("%s: setting new authentication options", __func__);
1086 if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
1087 error("Inconsistent authentication options: %s", emsg);
1093 /* Disable forwarding, etc for the session */
1095 auth_restrict_session(struct ssh *ssh)
1097 struct sshauthopt *restricted;
1099 debug("%s: restricting session", __func__);
1101 /* A blank sshauthopt defaults to permitting nothing */
1102 restricted = sshauthopt_new();
1103 restricted->permit_pty_flag = 1;
1104 restricted->restricted = 1;
1106 if (auth_activate_options(ssh, restricted) != 0)
1107 fatal("%s: failed to restrict session", __func__);
1108 sshauthopt_free(restricted);
1112 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
1113 struct sshauthopt *opts, int allow_cert_authority, const char *loc)
1115 const char *remote_ip = ssh_remote_ipaddr(ssh);
1116 const char *remote_host = auth_get_canonical_hostname(ssh,
1118 time_t now = time(NULL);
1122 * Check keys/principals file expiry time.
1123 * NB. validity interval in certificate is handled elsewhere.
1125 if (opts->valid_before && now > 0 &&
1126 opts->valid_before < (uint64_t)now) {
1127 format_absolute_time(opts->valid_before, buf, sizeof(buf));
1128 debug("%s: entry expired at %s", loc, buf);
1129 auth_debug_add("%s: entry expired at %s", loc, buf);
1132 /* Consistency checks */
1133 if (opts->cert_principals != NULL && !opts->cert_authority) {
1134 debug("%s: principals on non-CA key", loc);
1135 auth_debug_add("%s: principals on non-CA key", loc);
1139 /* cert-authority flag isn't valid in authorized_principals files */
1140 if (!allow_cert_authority && opts->cert_authority) {
1141 debug("%s: cert-authority flag invalid here", loc);
1142 auth_debug_add("%s: cert-authority flag invalid here", loc);
1147 /* Perform from= checks */
1148 if (opts->required_from_host_keys != NULL) {
1149 switch (match_host_and_ip(remote_host, remote_ip,
1150 opts->required_from_host_keys )) {
1152 /* Host name matches. */
1156 debug("%s: invalid from criteria", loc);
1157 auth_debug_add("%s: invalid from criteria", loc);
1160 logit("%s: Authentication tried for %.100s with "
1161 "correct key but not from a permitted "
1162 "host (host=%.200s, ip=%.200s, required=%.200s).",
1163 loc, pw->pw_name, remote_host, remote_ip,
1164 opts->required_from_host_keys);
1165 auth_debug_add("%s: Your host '%.200s' is not "
1166 "permitted to use this key for login.",
1172 /* Check source-address restriction from certificate */
1173 if (opts->required_from_host_cert != NULL) {
1174 switch (addr_match_cidr_list(remote_ip,
1175 opts->required_from_host_cert)) {
1182 error("%s: Certificate source-address invalid",
1186 logit("%s: Authentication tried for %.100s with valid "
1187 "certificate but not from a permitted source "
1188 "address (%.200s).", loc, pw->pw_name, remote_ip);
1189 auth_debug_add("%s: Your address '%.200s' is not "
1190 "permitted to use this certificate for login.",
1197 * XXX this is spammy. We should report remotely only for keys
1198 * that are successful in actual auth attempts, and not PK_OK
1201 auth_log_authopts(loc, opts, 1);