1 /* $OpenBSD: auth.c,v 1.138 2019/01/19 21:41:18 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.
28 #include <sys/types.h>
30 #include <sys/socket.h>
33 #include <netinet/in.h>
57 #include "groupaccess.h"
65 #include "auth-options.h"
74 #include "monitor_wrap.h"
81 extern ServerOptions options;
82 extern int use_privsep;
83 extern struct sshbuf *loginmsg;
84 extern struct passwd *privsep_pw;
85 extern struct sshauthopt *auth_opts;
87 /* Debugging messages */
88 static struct sshbuf *auth_debug;
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.
100 allowed_user(struct ssh *ssh, struct passwd * pw)
103 const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
107 struct spwd *spw = NULL;
110 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
111 if (!pw || !pw->pw_name)
115 if (!options.use_pam)
116 spw = getspnam(pw->pw_name);
117 #ifdef HAS_SHADOW_EXPIRE
118 if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
120 #endif /* HAS_SHADOW_EXPIRE */
121 #endif /* USE_SHADOW */
123 /* grab passwd field for locked account check */
124 passwd = pw->pw_passwd;
128 passwd = get_iaf_password(pw);
130 passwd = spw->sp_pwdp;
131 #endif /* USE_LIBIAF */
134 /* check for locked account */
135 if (!options.use_pam && passwd && *passwd) {
138 #ifdef LOCKED_PASSWD_STRING
139 if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
142 #ifdef LOCKED_PASSWD_PREFIX
143 if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
144 strlen(LOCKED_PASSWD_PREFIX)) == 0)
147 #ifdef LOCKED_PASSWD_SUBSTR
148 if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
152 free((void *) passwd);
153 #endif /* USE_LIBIAF */
155 logit("User %.100s not allowed because account is locked",
162 * Deny if shell does not exist or is not executable unless we
165 if (options.chroot_directory == NULL ||
166 strcasecmp(options.chroot_directory, "none") == 0) {
167 char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
168 _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
170 if (stat(shell, &st) != 0) {
171 logit("User %.100s not allowed because shell %.100s "
172 "does not exist", pw->pw_name, shell);
176 if (S_ISREG(st.st_mode) == 0 ||
177 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
178 logit("User %.100s not allowed because shell %.100s "
179 "is not executable", pw->pw_name, shell);
186 if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
187 options.num_deny_groups > 0 || options.num_allow_groups > 0) {
188 hostname = auth_get_canonical_hostname(ssh, options.use_dns);
189 ipaddr = ssh_remote_ipaddr(ssh);
192 /* Return false if user is listed in DenyUsers */
193 if (options.num_deny_users > 0) {
194 for (i = 0; i < options.num_deny_users; i++) {
195 r = match_user(pw->pw_name, hostname, ipaddr,
196 options.deny_users[i]);
198 fatal("Invalid DenyUsers pattern \"%.100s\"",
199 options.deny_users[i]);
201 logit("User %.100s from %.100s not allowed "
202 "because listed in DenyUsers",
203 pw->pw_name, hostname);
208 /* Return false if AllowUsers isn't empty and user isn't listed there */
209 if (options.num_allow_users > 0) {
210 for (i = 0; i < options.num_allow_users; i++) {
211 r = match_user(pw->pw_name, hostname, ipaddr,
212 options.allow_users[i]);
214 fatal("Invalid AllowUsers pattern \"%.100s\"",
215 options.allow_users[i]);
219 /* i < options.num_allow_users iff we break for loop */
220 if (i >= options.num_allow_users) {
221 logit("User %.100s from %.100s not allowed because "
222 "not listed in AllowUsers", pw->pw_name, hostname);
226 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
227 /* Get the user's group access list (primary and supplementary) */
228 if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
229 logit("User %.100s from %.100s not allowed because "
230 "not in any group", pw->pw_name, hostname);
234 /* Return false if one of user's groups is listed in DenyGroups */
235 if (options.num_deny_groups > 0)
236 if (ga_match(options.deny_groups,
237 options.num_deny_groups)) {
239 logit("User %.100s from %.100s not allowed "
240 "because a group is listed in DenyGroups",
241 pw->pw_name, hostname);
245 * Return false if AllowGroups isn't empty and one of user's groups
248 if (options.num_allow_groups > 0)
249 if (!ga_match(options.allow_groups,
250 options.num_allow_groups)) {
252 logit("User %.100s from %.100s not allowed "
253 "because none of user's groups are listed "
254 "in AllowGroups", pw->pw_name, hostname);
260 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
261 if (!sys_auth_allowed_user(pw, loginmsg))
265 /* We found no reason not to let this user try to log on... */
270 * Formats any key left in authctxt->auth_method_key for inclusion in
271 * auth_log()'s message. Also includes authxtct->auth_method_info if present.
274 format_method_key(Authctxt *authctxt)
276 const struct sshkey *key = authctxt->auth_method_key;
277 const char *methinfo = authctxt->auth_method_info;
278 char *fp, *cafp, *ret = NULL;
283 if (sshkey_is_cert(key)) {
284 fp = sshkey_fingerprint(key,
285 options.fingerprint_hash, SSH_FP_DEFAULT);
286 cafp = sshkey_fingerprint(key->cert->signature_key,
287 options.fingerprint_hash, SSH_FP_DEFAULT);
288 xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s",
289 sshkey_type(key), fp == NULL ? "(null)" : fp,
291 (unsigned long long)key->cert->serial,
292 sshkey_type(key->cert->signature_key),
293 cafp == NULL ? "(null)" : cafp,
294 methinfo == NULL ? "" : ", ",
295 methinfo == NULL ? "" : methinfo);
299 fp = sshkey_fingerprint(key, options.fingerprint_hash,
301 xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
302 fp == NULL ? "(null)" : fp,
303 methinfo == NULL ? "" : ", ",
304 methinfo == NULL ? "" : methinfo);
311 auth_log(struct ssh *ssh, int authenticated, int partial,
312 const char *method, const char *submethod)
314 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
315 int level = SYSLOG_LEVEL_VERBOSE;
319 if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
322 /* Raise logging level */
323 if (authenticated == 1 ||
325 authctxt->failures >= options.max_authtries / 2 ||
326 strcmp(method, "password") == 0)
327 level = SYSLOG_LEVEL_INFO;
329 if (authctxt->postponed)
330 authmsg = "Postponed";
334 authmsg = authenticated ? "Accepted" : "Failed";
336 if ((extra = format_method_key(authctxt)) == NULL) {
337 if (authctxt->auth_method_info != NULL)
338 extra = xstrdup(authctxt->auth_method_info);
341 do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
344 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
345 authctxt->valid ? "" : "invalid user ",
347 ssh_remote_ipaddr(ssh),
348 ssh_remote_port(ssh),
349 extra != NULL ? ": " : "",
350 extra != NULL ? extra : "");
354 #ifdef CUSTOM_FAILED_LOGIN
355 if (authenticated == 0 && !authctxt->postponed &&
356 (strcmp(method, "password") == 0 ||
357 strncmp(method, "keyboard-interactive", 20) == 0 ||
358 strcmp(method, "challenge-response") == 0))
359 record_failed_login(ssh, authctxt->user,
360 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
361 # ifdef WITH_AIXAUTHENTICATE
363 sys_auth_record_login(authctxt->user,
364 auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
368 #ifdef SSH_AUDIT_EVENTS
369 if (authenticated == 0 && !authctxt->postponed)
370 audit_event(ssh, audit_classify_auth(method));
376 auth_maxtries_exceeded(struct ssh *ssh)
378 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
380 error("maximum authentication attempts exceeded for "
381 "%s%.100s from %.200s port %d ssh2",
382 authctxt->valid ? "" : "invalid user ",
384 ssh_remote_ipaddr(ssh),
385 ssh_remote_port(ssh));
386 ssh_packet_disconnect(ssh, "Too many authentication failures");
391 * Check whether root logins are disallowed.
394 auth_root_allowed(struct ssh *ssh, const char *method)
396 switch (options.permit_root_login) {
399 case PERMIT_NO_PASSWD:
400 if (strcmp(method, "publickey") == 0 ||
401 strcmp(method, "hostbased") == 0 ||
402 strcmp(method, "gssapi-with-mic") == 0)
405 case PERMIT_FORCED_ONLY:
406 if (auth_opts->force_command != NULL) {
407 logit("Root login accepted for forced command.");
412 logit("ROOT LOGIN REFUSED FROM %.200s port %d",
413 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
419 * Given a template and a passwd structure, build a filename
420 * by substituting % tokenised options. Currently, %% becomes '%',
421 * %h becomes the home directory and %u the username.
423 * This returns a buffer allocated by xmalloc.
426 expand_authorized_keys(const char *filename, struct passwd *pw)
428 char *file, uidstr[32], ret[PATH_MAX];
431 snprintf(uidstr, sizeof(uidstr), "%llu",
432 (unsigned long long)pw->pw_uid);
433 file = percent_expand(filename, "h", pw->pw_dir,
434 "u", pw->pw_name, "U", uidstr, (char *)NULL);
437 * Ensure that filename starts anchored. If not, be backward
438 * compatible and prepend the '%h/'
440 if (path_absolute(file))
443 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
444 if (i < 0 || (size_t)i >= sizeof(ret))
445 fatal("expand_authorized_keys: path too long");
447 return (xstrdup(ret));
451 authorized_principals_file(struct passwd *pw)
453 if (options.authorized_principals_file == NULL)
455 return expand_authorized_keys(options.authorized_principals_file, pw);
458 /* return ok if key exists in sysfile or userfile */
460 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
461 const char *sysfile, const char *userfile)
465 HostStatus host_status;
466 struct hostkeys *hostkeys;
467 const struct hostkey_entry *found;
469 hostkeys = init_hostkeys();
470 load_hostkeys(hostkeys, host, sysfile);
471 if (userfile != NULL) {
472 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
473 if (options.strict_modes &&
474 (stat(user_hostfile, &st) == 0) &&
475 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
476 (st.st_mode & 022) != 0)) {
477 logit("Authentication refused for %.100s: "
478 "bad owner or modes for %.200s",
479 pw->pw_name, user_hostfile);
480 auth_debug_add("Ignored %.200s: bad ownership or modes",
483 temporarily_use_uid(pw);
484 load_hostkeys(hostkeys, host, user_hostfile);
489 host_status = check_key_in_hostkeys(hostkeys, key, &found);
490 if (host_status == HOST_REVOKED)
491 error("WARNING: revoked key for %s attempted authentication",
493 else if (host_status == HOST_OK)
494 debug("%s: key for %s found at %s:%ld", __func__,
495 found->host, found->file, found->line);
497 debug("%s: key for host %s not found", __func__, host);
499 free_hostkeys(hostkeys);
505 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
506 int log_missing, char *file_type)
513 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
514 if (log_missing || errno != ENOENT)
515 debug("Could not open %s '%s': %s", file_type, file,
520 if (fstat(fd, &st) < 0) {
524 if (!S_ISREG(st.st_mode)) {
525 logit("User %s %s %s is not a regular file",
526 pw->pw_name, file_type, file);
531 if ((f = fdopen(fd, "r")) == NULL) {
536 safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
538 logit("Authentication refused: %s", line);
539 auth_debug_add("Ignored %s: %s", file_type, line);
548 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
550 return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
554 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
556 return auth_openfile(file, pw, strict_modes, 0,
557 "authorized principals");
561 getpwnamallow(struct ssh *ssh, const char *user)
563 #ifdef HAVE_LOGIN_CAP
564 extern login_cap_t *lc;
570 struct connection_info *ci;
572 ci = get_connection_info(ssh, 1, options.use_dns);
574 parse_server_match_config(&options, ci);
575 log_change_level(options.log_level);
576 process_permitopen(ssh, &options);
578 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
584 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
588 logit("Invalid user %.100s from %.100s port %d",
589 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
590 #ifdef CUSTOM_FAILED_LOGIN
591 record_failed_login(ssh, user,
592 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
594 #ifdef SSH_AUDIT_EVENTS
595 audit_event(ssh, SSH_INVALID_USER);
596 #endif /* SSH_AUDIT_EVENTS */
599 if (!allowed_user(ssh, pw))
601 #ifdef HAVE_LOGIN_CAP
602 if ((lc = login_getclass(pw->pw_class)) == NULL) {
603 debug("unable to get login class: %s", user);
607 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
608 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
609 debug("Approval failure for %s", user);
621 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
623 auth_key_is_revoked(struct sshkey *key)
628 if (options.revoked_keys_file == NULL)
630 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
631 SSH_FP_DEFAULT)) == NULL) {
632 r = SSH_ERR_ALLOC_FAIL;
633 error("%s: fingerprint key: %s", __func__, ssh_err(r));
637 r = sshkey_check_revoked(key, options.revoked_keys_file);
640 break; /* not revoked */
641 case SSH_ERR_KEY_REVOKED:
642 error("Authentication key %s %s revoked by file %s",
643 sshkey_type(key), fp, options.revoked_keys_file);
646 error("Error checking authentication key %s %s in "
647 "revoked keys file %s: %s", sshkey_type(key), fp,
648 options.revoked_keys_file, ssh_err(r));
657 return r == 0 ? 0 : 1;
661 auth_debug_add(const char *fmt,...)
667 if (auth_debug == NULL)
671 vsnprintf(buf, sizeof(buf), fmt, args);
673 if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
674 fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r));
678 auth_debug_send(struct ssh *ssh)
683 if (auth_debug == NULL)
685 while (sshbuf_len(auth_debug) != 0) {
686 if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
687 fatal("%s: sshbuf_get_cstring: %s",
688 __func__, ssh_err(r));
689 ssh_packet_send_debug(ssh, "%s", msg);
695 auth_debug_reset(void)
697 if (auth_debug != NULL)
698 sshbuf_reset(auth_debug);
699 else if ((auth_debug = sshbuf_new()) == NULL)
700 fatal("%s: sshbuf_new failed", __func__);
706 static struct passwd fake;
708 memset(&fake, 0, sizeof(fake));
709 fake.pw_name = "NOUSER";
711 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
712 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
713 fake.pw_gecos = "NOUSER";
715 fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
716 fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
717 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
720 fake.pw_dir = "/nonexist";
721 fake.pw_shell = "/nonexist";
727 * Returns the remote DNS hostname as a string. The returned string must not
728 * be freed. NB. this will usually trigger a DNS query the first time it is
730 * This function does additional checks on the hostname to mitigate some
731 * attacks on legacy rhosts-style authentication.
732 * XXX is RhostsRSAAuthentication vulnerable to these?
733 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
737 remote_hostname(struct ssh *ssh)
739 struct sockaddr_storage from;
741 struct addrinfo hints, *ai, *aitop;
742 char name[NI_MAXHOST], ntop2[NI_MAXHOST];
743 const char *ntop = ssh_remote_ipaddr(ssh);
745 /* Get IP address of client. */
746 fromlen = sizeof(from);
747 memset(&from, 0, sizeof(from));
748 if (getpeername(ssh_packet_get_connection_in(ssh),
749 (struct sockaddr *)&from, &fromlen) < 0) {
750 debug("getpeername failed: %.100s", strerror(errno));
754 ipv64_normalise_mapped(&from, &fromlen);
755 if (from.ss_family == AF_INET6)
756 fromlen = sizeof(struct sockaddr_in6);
758 debug3("Trying to reverse map address %.100s.", ntop);
759 /* Map the IP address to a host name. */
760 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
761 NULL, 0, NI_NAMEREQD) != 0) {
762 /* Host name not found. Use ip address. */
767 * if reverse lookup result looks like a numeric hostname,
768 * someone is trying to trick us by PTR record like following:
769 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5
771 memset(&hints, 0, sizeof(hints));
772 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
773 hints.ai_flags = AI_NUMERICHOST;
774 if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
775 logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
781 /* Names are stored in lowercase. */
785 * Map it back to an IP address and check that the given
786 * address actually is an address of this host. This is
787 * necessary because anyone with access to a name server can
788 * define arbitrary names for an IP address. Mapping from
789 * name to IP address can be trusted better (but can still be
790 * fooled if the intruder has access to the name server of
793 memset(&hints, 0, sizeof(hints));
794 hints.ai_family = from.ss_family;
795 hints.ai_socktype = SOCK_STREAM;
796 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
797 logit("reverse mapping checking getaddrinfo for %.700s "
798 "[%s] failed.", name, ntop);
801 /* Look for the address from the list of addresses. */
802 for (ai = aitop; ai; ai = ai->ai_next) {
803 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
804 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
805 (strcmp(ntop, ntop2) == 0))
809 /* If we reached the end of the list, the address was not there. */
811 /* Address not found for the host name. */
812 logit("Address %.100s maps to %.600s, but this does not "
813 "map back to the address.", ntop, name);
820 * Return the canonical name of the host in the other side of the current
821 * connection. The host name is cached, so it is efficient to call this
826 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
828 static char *dnsname;
831 return ssh_remote_ipaddr(ssh);
832 else if (dnsname != NULL)
835 dnsname = remote_hostname(ssh);
841 * Runs command in a subprocess with a minimal environment.
842 * Returns pid on success, 0 on failure.
843 * The child stdout and stderr maybe captured, left attached or sent to
844 * /dev/null depending on the contents of flags.
845 * "tag" is prepended to log messages.
846 * NB. "command" is only used for logging; the actual command executed is
850 subprocess(const char *tag, struct passwd *pw, const char *command,
851 int ac, char **av, FILE **child, u_int flags)
855 int fd, devnull, p[2], i;
857 char *cp, errmsg[512];
864 debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
865 tag, command, pw->pw_name, flags);
867 /* Check consistency */
868 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
869 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
870 error("%s: inconsistent flags", __func__);
873 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
874 error("%s: inconsistent flags/output", __func__);
879 * If executing an explicit binary, then verify the it exists
880 * and appears safe-ish to execute
882 if (!path_absolute(av[0])) {
883 error("%s path is not absolute", tag);
886 temporarily_use_uid(pw);
887 if (stat(av[0], &st) < 0) {
888 error("Could not stat %s \"%s\": %s", tag,
889 av[0], strerror(errno));
893 if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
894 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
898 /* Prepare to keep the child's stdout if requested */
900 error("%s: pipe: %s", tag, strerror(errno));
906 switch ((pid = fork())) {
908 error("%s: fork: %s", tag, strerror(errno));
913 /* Prepare a minimal environment for the child. */
915 child_env = xcalloc(sizeof(*child_env), envsize);
916 child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
917 child_set_env(&child_env, &envsize, "USER", pw->pw_name);
918 child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
919 child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
920 if ((cp = getenv("LANG")) != NULL)
921 child_set_env(&child_env, &envsize, "LANG", cp);
923 for (i = 0; i < NSIG; i++)
926 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
927 error("%s: open %s: %s", tag, _PATH_DEVNULL,
931 if (dup2(devnull, STDIN_FILENO) == -1) {
932 error("%s: dup2: %s", tag, strerror(errno));
936 /* Set up stdout as requested; leave stderr in place for now. */
938 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
940 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
942 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
943 error("%s: dup2: %s", tag, strerror(errno));
946 closefrom(STDERR_FILENO + 1);
948 /* Don't use permanently_set_uid() here to avoid fatal() */
949 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
950 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
954 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
955 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
959 /* stdin is pointed to /dev/null at this point */
960 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
961 dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
962 error("%s: dup2: %s", tag, strerror(errno));
966 execve(av[0], av, child_env);
967 error("%s exec \"%s\": %s", tag, command, strerror(errno));
969 default: /* parent */
974 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
976 else if ((f = fdopen(p[0], "r")) == NULL) {
977 error("%s: fdopen: %s", tag, strerror(errno));
979 /* Don't leave zombie child */
981 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
986 debug3("%s: %s pid %ld", __func__, tag, (long)pid);
992 /* These functions link key/cert options to the auth framework */
994 /* Log sshauthopt options locally and (optionally) for remote transmission */
996 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
998 int do_env = options.permit_user_env && opts->nenv > 0;
999 int do_permitopen = opts->npermitopen > 0 &&
1000 (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
1001 int do_permitlisten = opts->npermitlisten > 0 &&
1002 (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
1004 char msg[1024], buf[64];
1006 snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
1007 /* Try to keep this alphabetically sorted */
1008 snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s",
1009 opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
1010 opts->force_command == NULL ? "" : " command",
1011 do_env ? " environment" : "",
1012 opts->valid_before == 0 ? "" : "expires",
1013 do_permitopen ? " permitopen" : "",
1014 do_permitlisten ? " permitlisten" : "",
1015 opts->permit_port_forwarding_flag ? " port-forwarding" : "",
1016 opts->cert_principals == NULL ? "" : " principals",
1017 opts->permit_pty_flag ? " pty" : "",
1018 opts->force_tun_device == -1 ? "" : " tun=",
1019 opts->force_tun_device == -1 ? "" : buf,
1020 opts->permit_user_rc ? " user-rc" : "",
1021 opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
1023 debug("%s: %s", loc, msg);
1025 auth_debug_add("%s: %s", loc, msg);
1027 if (options.permit_user_env) {
1028 for (i = 0; i < opts->nenv; i++) {
1029 debug("%s: environment: %s", loc, opts->env[i]);
1031 auth_debug_add("%s: environment: %s",
1037 /* Go into a little more details for the local logs. */
1038 if (opts->valid_before != 0) {
1039 format_absolute_time(opts->valid_before, buf, sizeof(buf));
1040 debug("%s: expires at %s", loc, buf);
1042 if (opts->cert_principals != NULL) {
1043 debug("%s: authorized principals: \"%s\"",
1044 loc, opts->cert_principals);
1046 if (opts->force_command != NULL)
1047 debug("%s: forced command: \"%s\"", loc, opts->force_command);
1048 if (do_permitopen) {
1049 for (i = 0; i < opts->npermitopen; i++) {
1050 debug("%s: permitted open: %s",
1051 loc, opts->permitopen[i]);
1054 if (do_permitlisten) {
1055 for (i = 0; i < opts->npermitlisten; i++) {
1056 debug("%s: permitted listen: %s",
1057 loc, opts->permitlisten[i]);
1062 /* Activate a new set of key/cert options; merging with what is there. */
1064 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
1066 struct sshauthopt *old = auth_opts;
1067 const char *emsg = NULL;
1069 debug("%s: setting new authentication options", __func__);
1070 if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
1071 error("Inconsistent authentication options: %s", emsg);
1077 /* Disable forwarding, etc for the session */
1079 auth_restrict_session(struct ssh *ssh)
1081 struct sshauthopt *restricted;
1083 debug("%s: restricting session", __func__);
1085 /* A blank sshauthopt defaults to permitting nothing */
1086 restricted = sshauthopt_new();
1087 restricted->permit_pty_flag = 1;
1088 restricted->restricted = 1;
1090 if (auth_activate_options(ssh, restricted) != 0)
1091 fatal("%s: failed to restrict session", __func__);
1092 sshauthopt_free(restricted);
1096 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
1097 struct sshauthopt *opts, int allow_cert_authority, const char *loc)
1099 const char *remote_ip = ssh_remote_ipaddr(ssh);
1100 const char *remote_host = auth_get_canonical_hostname(ssh,
1102 time_t now = time(NULL);
1106 * Check keys/principals file expiry time.
1107 * NB. validity interval in certificate is handled elsewhere.
1109 if (opts->valid_before && now > 0 &&
1110 opts->valid_before < (uint64_t)now) {
1111 format_absolute_time(opts->valid_before, buf, sizeof(buf));
1112 debug("%s: entry expired at %s", loc, buf);
1113 auth_debug_add("%s: entry expired at %s", loc, buf);
1116 /* Consistency checks */
1117 if (opts->cert_principals != NULL && !opts->cert_authority) {
1118 debug("%s: principals on non-CA key", loc);
1119 auth_debug_add("%s: principals on non-CA key", loc);
1123 /* cert-authority flag isn't valid in authorized_principals files */
1124 if (!allow_cert_authority && opts->cert_authority) {
1125 debug("%s: cert-authority flag invalid here", loc);
1126 auth_debug_add("%s: cert-authority flag invalid here", loc);
1131 /* Perform from= checks */
1132 if (opts->required_from_host_keys != NULL) {
1133 switch (match_host_and_ip(remote_host, remote_ip,
1134 opts->required_from_host_keys )) {
1136 /* Host name matches. */
1140 debug("%s: invalid from criteria", loc);
1141 auth_debug_add("%s: invalid from criteria", loc);
1144 logit("%s: Authentication tried for %.100s with "
1145 "correct key but not from a permitted "
1146 "host (host=%.200s, ip=%.200s, required=%.200s).",
1147 loc, pw->pw_name, remote_host, remote_ip,
1148 opts->required_from_host_keys);
1149 auth_debug_add("%s: Your host '%.200s' is not "
1150 "permitted to use this key for login.",
1156 /* Check source-address restriction from certificate */
1157 if (opts->required_from_host_cert != NULL) {
1158 switch (addr_match_cidr_list(remote_ip,
1159 opts->required_from_host_cert)) {
1166 error("%s: Certificate source-address invalid",
1170 logit("%s: Authentication tried for %.100s with valid "
1171 "certificate but not from a permitted source "
1172 "address (%.200s).", loc, pw->pw_name, remote_ip);
1173 auth_debug_add("%s: Your address '%.200s' is not "
1174 "permitted to use this certificate for login.",
1181 * XXX this is spammy. We should report remotely only for keys
1182 * that are successful in actual auth attempts, and not PK_OK
1185 auth_log_authopts(loc, opts, 1);