1 /* $OpenBSD: ssh.c,v 1.630 2026/04/02 07:50:55 djm Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
9 *
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 *
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
18 *
19 * Modified to work with SSLeay by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 *
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 */
42
43 #include "includes.h"
44
45 #include <sys/types.h>
46 #include <sys/socket.h>
47 #include <sys/stat.h>
48 #include <sys/wait.h>
49 #include <sys/utsname.h>
50
51 #include <ctype.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <netdb.h>
55 #include <paths.h>
56 #include <pwd.h>
57 #include <signal.h>
58 #include <stdarg.h>
59 #include <stddef.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 #include <limits.h>
65 #include <locale.h>
66
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69
70 #ifdef WITH_OPENSSL
71 #include <openssl/evp.h>
72 #include <openssl/err.h>
73 #endif
74 #include "openbsd-compat/openssl-compat.h"
75
76 #include "xmalloc.h"
77 #include "ssh.h"
78 #include "ssh2.h"
79 #include "compat.h"
80 #include "cipher.h"
81 #include "packet.h"
82 #include "sshbuf.h"
83 #include "channels.h"
84 #include "sshkey.h"
85 #include "authfd.h"
86 #include "authfile.h"
87 #include "pathnames.h"
88 #include "clientloop.h"
89 #include "log.h"
90 #include "misc.h"
91 #include "readconf.h"
92 #include "sshconnect.h"
93 #include "kex.h"
94 #include "mac.h"
95 #include "match.h"
96 #include "version.h"
97 #include "ssherr.h"
98 #include "utf8.h"
99
100 #ifdef ENABLE_PKCS11
101 #include "ssh-pkcs11.h"
102 #endif
103
104 extern char *__progname;
105
106 /* Saves a copy of argv for setproctitle emulation */
107 #ifndef HAVE_SETPROCTITLE
108 static char **saved_av;
109 #endif
110
111 /* Flag indicating whether debug mode is on. May be set on the command line. */
112 int debug_flag = 0;
113
114 /* Flag indicating whether a tty should be requested */
115 int tty_flag = 0;
116
117 /*
118 * Flag indicating that the current process should be backgrounded and
119 * a new mux-client launched in the foreground for ControlPersist.
120 */
121 static int need_controlpersist_detach = 0;
122
123 /* Copies of flags for ControlPersist foreground mux-client */
124 static int ostdin_null_flag, osession_type, otty_flag, orequest_tty;
125 static int ofork_after_authentication;
126
127 /*
128 * General data structure for command line options and options configurable
129 * in configuration files. See readconf.h.
130 */
131 Options options;
132
133 /* optional user configfile */
134 char *config = NULL;
135
136 /*
137 * Name of the host we are connecting to. This is the name given on the
138 * command line, or the Hostname specified for the user-supplied name in a
139 * configuration file.
140 */
141 char *host;
142
143 /*
144 * A config can specify a path to forward, overriding SSH_AUTH_SOCK. If this is
145 * not NULL, forward the socket at this path instead.
146 */
147 char *forward_agent_sock_path = NULL;
148
149 /* socket address the host resolves to */
150 struct sockaddr_storage hostaddr;
151
152 /* Private host keys. */
153 Sensitive sensitive_data;
154
155 /* command to be executed */
156 struct sshbuf *command;
157
158 /* # of replies received for global requests */
159 static int forward_confirms_pending = -1;
160
161 /* mux.c */
162 extern int muxserver_sock;
163 extern u_int muxclient_command;
164
165 /* Prints a help message to the user. This function never returns. */
166
167 static void
usage(void)168 usage(void)
169 {
170 fprintf(stderr,
171 "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address]\n"
172 " [-c cipher_spec] [-D [bind_address:]port] [-E log_file]\n"
173 " [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file]\n"
174 " [-J destination] [-L address] [-l login_name] [-m mac_spec]\n"
175 " [-O ctl_cmd] [-o option] [-P tag] [-p port] [-R address]\n"
176 " [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
177 " destination [command [argument ...]]\n"
178 " ssh [-Q query_option]\n"
179 );
180 exit(255);
181 }
182
183 static int ssh_session2(struct ssh *, const struct ssh_conn_info *);
184 static void load_public_identity_files(const struct ssh_conn_info *);
185 static void main_sigchld_handler(int);
186
187 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
188 static void
tilde_expand_paths(char ** paths,u_int num_paths)189 tilde_expand_paths(char **paths, u_int num_paths)
190 {
191 u_int i;
192 char *cp;
193
194 for (i = 0; i < num_paths; i++) {
195 cp = tilde_expand_filename(paths[i], getuid());
196 free(paths[i]);
197 paths[i] = cp;
198 }
199 }
200
201 /*
202 * Expands the set of percent_expand options used by the majority of keywords
203 * in the client that support percent expansion.
204 * Caller must free returned string.
205 */
206 static char *
default_client_percent_expand(const char * str,const struct ssh_conn_info * cinfo)207 default_client_percent_expand(const char *str,
208 const struct ssh_conn_info *cinfo)
209 {
210 return percent_expand(str,
211 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
212 (char *)NULL);
213 }
214
215 /*
216 * Expands the set of percent_expand options used by the majority of keywords
217 * AND perform environment variable substitution.
218 * Caller must free returned string.
219 */
220 static char *
default_client_percent_dollar_expand(const char * str,const struct ssh_conn_info * cinfo)221 default_client_percent_dollar_expand(const char *str,
222 const struct ssh_conn_info *cinfo)
223 {
224 char *ret;
225
226 ret = percent_dollar_expand(str,
227 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
228 (char *)NULL);
229 if (ret == NULL)
230 fatal("invalid environment variable expansion");
231 return ret;
232 }
233
234 /*
235 * Attempt to resolve a host name / port to a set of addresses and
236 * optionally return any CNAMEs encountered along the way.
237 * Returns NULL on failure.
238 * NB. this function must operate with a options having undefined members.
239 */
240 static struct addrinfo *
resolve_host(const char * name,int port,int logerr,char * cname,size_t clen)241 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
242 {
243 char strport[NI_MAXSERV];
244 const char *errstr = NULL;
245 struct addrinfo hints, *res;
246 int gaierr;
247 LogLevel loglevel = SYSLOG_LEVEL_DEBUG1;
248
249 if (port <= 0)
250 port = default_ssh_port();
251 if (cname != NULL)
252 *cname = '\0';
253 debug3_f("lookup %s:%d", name, port);
254
255 snprintf(strport, sizeof strport, "%d", port);
256 memset(&hints, 0, sizeof(hints));
257 hints.ai_family = options.address_family == -1 ?
258 AF_UNSPEC : options.address_family;
259 hints.ai_socktype = SOCK_STREAM;
260 if (cname != NULL)
261 hints.ai_flags = AI_CANONNAME;
262 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
263 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
264 loglevel = SYSLOG_LEVEL_ERROR;
265 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
266 __progname, name, ssh_gai_strerror(gaierr));
267 return NULL;
268 }
269 if (cname != NULL && res->ai_canonname != NULL) {
270 if (!valid_domain(res->ai_canonname, 0, &errstr)) {
271 error("ignoring bad CNAME \"%s\" for host \"%s\": %s",
272 res->ai_canonname, name, errstr);
273 } else if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
274 error_f("host \"%s\" cname \"%s\" too long (max %lu)",
275 name, res->ai_canonname, (u_long)clen);
276 if (clen > 0)
277 *cname = '\0';
278 }
279 }
280 return res;
281 }
282
283 /* Returns non-zero if name can only be an address and not a hostname */
284 static int
is_addr_fast(const char * name)285 is_addr_fast(const char *name)
286 {
287 return (strchr(name, '%') != NULL || strchr(name, ':') != NULL ||
288 strspn(name, "0123456789.") == strlen(name));
289 }
290
291 /* Returns non-zero if name represents a valid, single address */
292 static int
is_addr(const char * name)293 is_addr(const char *name)
294 {
295 char strport[NI_MAXSERV];
296 struct addrinfo hints, *res;
297
298 if (is_addr_fast(name))
299 return 1;
300
301 snprintf(strport, sizeof strport, "%u", default_ssh_port());
302 memset(&hints, 0, sizeof(hints));
303 hints.ai_family = options.address_family == -1 ?
304 AF_UNSPEC : options.address_family;
305 hints.ai_socktype = SOCK_STREAM;
306 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
307 if (getaddrinfo(name, strport, &hints, &res) != 0)
308 return 0;
309 if (res == NULL || res->ai_next != NULL) {
310 freeaddrinfo(res);
311 return 0;
312 }
313 freeaddrinfo(res);
314 return 1;
315 }
316
317 /*
318 * Attempt to resolve a numeric host address / port to a single address.
319 * Returns a canonical address string.
320 * Returns NULL on failure.
321 * NB. this function must operate with a options having undefined members.
322 */
323 static struct addrinfo *
resolve_addr(const char * name,int port,char * caddr,size_t clen)324 resolve_addr(const char *name, int port, char *caddr, size_t clen)
325 {
326 char addr[NI_MAXHOST], strport[NI_MAXSERV];
327 struct addrinfo hints, *res;
328 int gaierr;
329
330 if (port <= 0)
331 port = default_ssh_port();
332 snprintf(strport, sizeof strport, "%u", port);
333 memset(&hints, 0, sizeof(hints));
334 hints.ai_family = options.address_family == -1 ?
335 AF_UNSPEC : options.address_family;
336 hints.ai_socktype = SOCK_STREAM;
337 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
338 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
339 debug2_f("could not resolve name %.100s as address: %s",
340 name, ssh_gai_strerror(gaierr));
341 return NULL;
342 }
343 if (res == NULL) {
344 debug_f("getaddrinfo %.100s returned no addresses", name);
345 return NULL;
346 }
347 if (res->ai_next != NULL) {
348 debug_f("getaddrinfo %.100s returned multiple addresses", name);
349 goto fail;
350 }
351 if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
352 addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
353 debug_f("Could not format address for name %.100s: %s",
354 name, ssh_gai_strerror(gaierr));
355 goto fail;
356 }
357 if (strlcpy(caddr, addr, clen) >= clen) {
358 error_f("host \"%s\" addr \"%s\" too long (max %lu)",
359 name, addr, (u_long)clen);
360 if (clen > 0)
361 *caddr = '\0';
362 fail:
363 freeaddrinfo(res);
364 return NULL;
365 }
366 return res;
367 }
368
369 /*
370 * Check whether the cname is a permitted replacement for the hostname
371 * and perform the replacement if it is.
372 * NB. this function must operate with a options having undefined members.
373 */
374 static int
check_follow_cname(int direct,char ** namep,const char * cname)375 check_follow_cname(int direct, char **namep, const char *cname)
376 {
377 int i;
378 struct allowed_cname *rule;
379
380 if (*cname == '\0' || !config_has_permitted_cnames(&options) ||
381 strcmp(*namep, cname) == 0)
382 return 0;
383 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
384 return 0;
385 /*
386 * Don't attempt to canonicalize names that will be interpreted by
387 * a proxy or jump host unless the user specifically requests so.
388 */
389 if (!direct &&
390 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
391 return 0;
392 debug3_f("check \"%s\" CNAME \"%s\"", *namep, cname);
393 for (i = 0; i < options.num_permitted_cnames; i++) {
394 rule = options.permitted_cnames + i;
395 if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
396 match_pattern_list(cname, rule->target_list, 1) != 1)
397 continue;
398 verbose("Canonicalized DNS aliased hostname "
399 "\"%s\" => \"%s\"", *namep, cname);
400 free(*namep);
401 *namep = xstrdup(cname);
402 return 1;
403 }
404 return 0;
405 }
406
407 /*
408 * Attempt to resolve the supplied hostname after applying the user's
409 * canonicalization rules. Returns the address list for the host or NULL
410 * if no name was found after canonicalization.
411 * NB. this function must operate with a options having undefined members.
412 */
413 static struct addrinfo *
resolve_canonicalize(char ** hostp,int port)414 resolve_canonicalize(char **hostp, int port)
415 {
416 int i, direct, ndots;
417 char *cp, *fullhost, newname[NI_MAXHOST];
418 struct addrinfo *addrs;
419
420 /*
421 * Attempt to canonicalise addresses, regardless of
422 * whether hostname canonicalisation was requested
423 */
424 if ((addrs = resolve_addr(*hostp, port,
425 newname, sizeof(newname))) != NULL) {
426 debug2_f("hostname %.100s is address", *hostp);
427 if (strcasecmp(*hostp, newname) != 0) {
428 debug2_f("canonicalised address \"%s\" => \"%s\"",
429 *hostp, newname);
430 free(*hostp);
431 *hostp = xstrdup(newname);
432 }
433 return addrs;
434 }
435
436 /*
437 * If this looks like an address but didn't parse as one, it might
438 * be an address with an invalid interface scope. Skip further
439 * attempts at canonicalisation.
440 */
441 if (is_addr_fast(*hostp)) {
442 debug_f("hostname %.100s is an unrecognised address", *hostp);
443 return NULL;
444 }
445
446 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
447 return NULL;
448
449 /*
450 * Don't attempt to canonicalize names that will be interpreted by
451 * a proxy unless the user specifically requests so.
452 */
453 direct = option_clear_or_none(options.proxy_command) &&
454 option_clear_or_none(options.jump_host);
455 if (!direct &&
456 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
457 return NULL;
458
459 /* If domain name is anchored, then resolve it now */
460 if ((*hostp)[strlen(*hostp) - 1] == '.') {
461 debug3_f("name is fully qualified");
462 fullhost = xstrdup(*hostp);
463 if ((addrs = resolve_host(fullhost, port, 0,
464 newname, sizeof(newname))) != NULL)
465 goto found;
466 free(fullhost);
467 goto notfound;
468 }
469
470 /* Don't apply canonicalization to sufficiently-qualified hostnames */
471 ndots = 0;
472 for (cp = *hostp; *cp != '\0'; cp++) {
473 if (*cp == '.')
474 ndots++;
475 }
476 if (ndots > options.canonicalize_max_dots) {
477 debug3_f("not canonicalizing hostname \"%s\" (max dots %d)",
478 *hostp, options.canonicalize_max_dots);
479 return NULL;
480 }
481 /* Attempt each supplied suffix */
482 for (i = 0; i < options.num_canonical_domains; i++) {
483 if (strcasecmp(options.canonical_domains[i], "none") == 0)
484 break;
485 xasprintf(&fullhost, "%s.%s.", *hostp,
486 options.canonical_domains[i]);
487 debug3_f("attempting \"%s\" => \"%s\"", *hostp, fullhost);
488 if ((addrs = resolve_host(fullhost, port, 0,
489 newname, sizeof(newname))) == NULL) {
490 free(fullhost);
491 continue;
492 }
493 found:
494 /* Remove trailing '.' */
495 fullhost[strlen(fullhost) - 1] = '\0';
496 /* Follow CNAME if requested */
497 if (!check_follow_cname(direct, &fullhost, newname)) {
498 debug("Canonicalized hostname \"%s\" => \"%s\"",
499 *hostp, fullhost);
500 }
501 free(*hostp);
502 *hostp = fullhost;
503 return addrs;
504 }
505 notfound:
506 if (!options.canonicalize_fallback_local)
507 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
508 debug2_f("host %s not found in any suffix", *hostp);
509 return NULL;
510 }
511
512 /*
513 * Check the result of hostkey loading, ignoring some errors and either
514 * discarding the key or fatal()ing for others.
515 */
516 static void
check_load(int r,struct sshkey ** k,const char * path,const char * message)517 check_load(int r, struct sshkey **k, const char *path, const char *message)
518 {
519 char *fp;
520
521 switch (r) {
522 case 0:
523 if (k == NULL || *k == NULL)
524 return;
525 /* Check RSA keys size and discard if undersized */
526 if ((r = sshkey_check_rsa_length(*k,
527 options.required_rsa_size)) != 0) {
528 error_r(r, "load %s \"%s\"", message, path);
529 free(*k);
530 *k = NULL;
531 break;
532 }
533 if ((fp = sshkey_fingerprint(*k,
534 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
535 fatal_f("failed to fingerprint %s %s key from %s",
536 sshkey_type(*k), message, path);
537 }
538 debug("loaded %s from %s: %s %s", message, path,
539 sshkey_type(*k), fp);
540 free(fp);
541 break;
542 case SSH_ERR_INTERNAL_ERROR:
543 case SSH_ERR_ALLOC_FAIL:
544 fatal_r(r, "load %s \"%s\"", message, path);
545 case SSH_ERR_SYSTEM_ERROR:
546 /* Ignore missing files */
547 if (errno == ENOENT)
548 break;
549 /* FALLTHROUGH */
550 default:
551 error_r(r, "load %s \"%s\"", message, path);
552 break;
553 }
554 if (k != NULL && *k == NULL)
555 debug("no %s loaded from %s", message, path);
556 }
557
558 /*
559 * Read per-user configuration file. Ignore the system wide config
560 * file if the user specifies a config file on the command line.
561 */
562 static void
process_config_files(const char * host_name,struct passwd * pw,int final_pass,int * want_final_pass)563 process_config_files(const char *host_name, struct passwd *pw,
564 int final_pass, int *want_final_pass)
565 {
566 char *cmd, buf[PATH_MAX];
567 int r;
568
569 if ((cmd = sshbuf_dup_string(command)) == NULL)
570 fatal_f("sshbuf_dup_string failed");
571 if (config != NULL) {
572 if (strcasecmp(config, "none") != 0 &&
573 !read_config_file(config, pw, host, host_name, cmd,
574 &options,
575 SSHCONF_USERCONF | (final_pass ? SSHCONF_FINAL : 0),
576 want_final_pass))
577 fatal("Can't open user config file %.100s: "
578 "%.100s", config, strerror(errno));
579 } else {
580 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
581 _PATH_SSH_USER_CONFFILE);
582 if (r > 0 && (size_t)r < sizeof(buf))
583 (void)read_config_file(buf, pw, host, host_name, cmd,
584 &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
585 (final_pass ? SSHCONF_FINAL : 0), want_final_pass);
586
587 /* Read systemwide configuration file after user config. */
588 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
589 host, host_name, cmd, &options,
590 final_pass ? SSHCONF_FINAL : 0, want_final_pass);
591 }
592 free(cmd);
593 }
594
595 /* Rewrite the port number in an addrinfo list of addresses */
596 static void
set_addrinfo_port(struct addrinfo * addrs,int port)597 set_addrinfo_port(struct addrinfo *addrs, int port)
598 {
599 struct addrinfo *addr;
600
601 for (addr = addrs; addr != NULL; addr = addr->ai_next) {
602 switch (addr->ai_family) {
603 case AF_INET:
604 ((struct sockaddr_in *)addr->ai_addr)->
605 sin_port = htons(port);
606 break;
607 case AF_INET6:
608 ((struct sockaddr_in6 *)addr->ai_addr)->
609 sin6_port = htons(port);
610 break;
611 }
612 }
613 }
614
615 static void
ssh_conn_info_free(struct ssh_conn_info * cinfo)616 ssh_conn_info_free(struct ssh_conn_info *cinfo)
617 {
618 if (cinfo == NULL)
619 return;
620 free(cinfo->conn_hash_hex);
621 free(cinfo->shorthost);
622 free(cinfo->uidstr);
623 free(cinfo->keyalias);
624 free(cinfo->thishost);
625 free(cinfo->host_arg);
626 free(cinfo->portstr);
627 free(cinfo->remhost);
628 free(cinfo->remuser);
629 free(cinfo->homedir);
630 free(cinfo->locuser);
631 free(cinfo->jmphost);
632 free(cinfo);
633 }
634
635 /*
636 * Main program for the ssh client.
637 */
638 int
main(int ac,char ** av)639 main(int ac, char **av)
640 {
641 struct ssh *ssh = NULL;
642 int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
643 int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0;
644 int user_on_commandline = 0, user_was_default = 0, user_expanded = 0;
645 char *p, *cp, *line, *argv0, *logfile, *args;
646 char cname[NI_MAXHOST], thishost[NI_MAXHOST];
647 struct stat st;
648 struct passwd *pw;
649 extern int optind, optreset;
650 extern char *optarg;
651 struct Forward fwd;
652 struct addrinfo *addrs = NULL;
653 size_t n, len;
654 u_int j;
655 struct utsname utsname;
656 struct ssh_conn_info *cinfo = NULL;
657
658 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
659 sanitise_stdfd();
660
661 /*
662 * Discard other fds that are hanging around. These can cause problem
663 * with backgrounded ssh processes started by ControlPersist.
664 */
665 closefrom(STDERR_FILENO + 1);
666
667 __progname = ssh_get_progname(av[0]);
668
669 #ifndef HAVE_SETPROCTITLE
670 /* Prepare for later setproctitle emulation */
671 /* Save argv so it isn't clobbered by setproctitle() emulation */
672 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
673 for (i = 0; i < ac; i++)
674 saved_av[i] = xstrdup(av[i]);
675 saved_av[i] = NULL;
676 compat_init_setproctitle(ac, av);
677 av = saved_av;
678 #endif
679
680 seed_rng();
681
682 /* Get user data. */
683 pw = getpwuid(getuid());
684 if (!pw) {
685 logit("No user exists for uid %lu", (u_long)getuid());
686 exit(255);
687 }
688 /* Take a copy of the returned structure. */
689 pw = pwcopy(pw);
690
691 /*
692 * Set our umask to something reasonable, as some files are created
693 * with the default umask. This will make them world-readable but
694 * writable only by the owner, which is ok for all files for which we
695 * don't set the modes explicitly.
696 */
697 umask(022 | umask(077));
698
699 msetlocale();
700
701 /*
702 * Initialize option structure to indicate that no values have been
703 * set.
704 */
705 initialize_options(&options);
706
707 /*
708 * Prepare main ssh transport/connection structures
709 */
710 if ((ssh = ssh_alloc_session_state()) == NULL)
711 fatal("Couldn't allocate session state");
712 channel_init_channels(ssh);
713
714 /* Parse command-line arguments. */
715 args = argv_assemble(ac, av); /* logged later */
716 host = NULL;
717 use_syslog = 0;
718 logfile = NULL;
719 argv0 = av[0];
720
721 again:
722 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
723 "AB:CD:E:F:GI:J:KL:MNO:P:Q:R:S:TVw:W:XYy")) != -1) { /* HUZdhjruz */
724 switch (opt) {
725 case '1':
726 fatal("SSH protocol v.1 is no longer supported");
727 break;
728 case '2':
729 /* Ignored */
730 break;
731 case '4':
732 options.address_family = AF_INET;
733 break;
734 case '6':
735 options.address_family = AF_INET6;
736 break;
737 case 'n':
738 options.stdin_null = 1;
739 break;
740 case 'f':
741 options.fork_after_authentication = 1;
742 options.stdin_null = 1;
743 break;
744 case 'x':
745 options.forward_x11 = 0;
746 break;
747 case 'X':
748 options.forward_x11 = 1;
749 break;
750 case 'y':
751 use_syslog = 1;
752 break;
753 case 'E':
754 logfile = optarg;
755 break;
756 case 'G':
757 config_test = 1;
758 break;
759 case 'Y':
760 options.forward_x11 = 1;
761 options.forward_x11_trusted = 1;
762 break;
763 case 'g':
764 options.fwd_opts.gateway_ports = 1;
765 break;
766 case 'O':
767 if (options.stdio_forward_host != NULL)
768 fatal("Cannot specify multiplexing "
769 "command with -W");
770 else if (muxclient_command != 0)
771 fatal("Multiplexing command already specified");
772 if (strcmp(optarg, "check") == 0)
773 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
774 else if (strcmp(optarg, "conninfo") == 0)
775 muxclient_command = SSHMUX_COMMAND_CONNINFO;
776 else if (strcmp(optarg, "channels") == 0)
777 muxclient_command = SSHMUX_COMMAND_CHANINFO;
778 else if (strcmp(optarg, "forward") == 0)
779 muxclient_command = SSHMUX_COMMAND_FORWARD;
780 else if (strcmp(optarg, "exit") == 0)
781 muxclient_command = SSHMUX_COMMAND_TERMINATE;
782 else if (strcmp(optarg, "stop") == 0)
783 muxclient_command = SSHMUX_COMMAND_STOP;
784 else if (strcmp(optarg, "cancel") == 0)
785 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
786 else if (strcmp(optarg, "proxy") == 0)
787 muxclient_command = SSHMUX_COMMAND_PROXY;
788 else
789 fatal("Invalid multiplex command.");
790 break;
791 case 'P':
792 if (options.tag == NULL)
793 options.tag = xstrdup(optarg);
794 break;
795 case 'Q':
796 cp = NULL;
797 if (strcmp(optarg, "cipher") == 0 ||
798 strcasecmp(optarg, "Ciphers") == 0)
799 cp = cipher_alg_list('\n', 0);
800 else if (strcmp(optarg, "cipher-auth") == 0)
801 cp = cipher_alg_list('\n', 1);
802 else if (strcmp(optarg, "mac") == 0 ||
803 strcasecmp(optarg, "MACs") == 0)
804 cp = mac_alg_list('\n');
805 else if (strcmp(optarg, "kex") == 0 ||
806 strcasecmp(optarg, "KexAlgorithms") == 0)
807 cp = kex_alg_list('\n');
808 else if (strcmp(optarg, "key") == 0)
809 cp = sshkey_alg_list(0, 0, 0, '\n');
810 else if (strcmp(optarg, "key-cert") == 0)
811 cp = sshkey_alg_list(1, 0, 0, '\n');
812 else if (strcmp(optarg, "key-plain") == 0)
813 cp = sshkey_alg_list(0, 1, 0, '\n');
814 else if (strcmp(optarg, "key-ca-sign") == 0 ||
815 strcasecmp(optarg, "CASignatureAlgorithms") == 0)
816 cp = sshkey_alg_list(0, 1, 1, '\n');
817 else if (strcmp(optarg, "key-sig") == 0 ||
818 strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
819 strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
820 strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
821 strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
822 strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
823 strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
824 cp = sshkey_alg_list(0, 0, 1, '\n');
825 else if (strcmp(optarg, "sig") == 0)
826 cp = sshkey_alg_list(0, 1, 1, '\n');
827 else if (strcmp(optarg, "protocol-version") == 0)
828 cp = xstrdup("2");
829 else if (strcmp(optarg, "compression") == 0) {
830 cp = xstrdup(compression_alg_list(0));
831 len = strlen(cp);
832 for (n = 0; n < len; n++)
833 if (cp[n] == ',')
834 cp[n] = '\n';
835 } else if (strcmp(optarg, "help") == 0) {
836 cp = xstrdup(
837 "cipher\ncipher-auth\ncompression\nkex\n"
838 "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
839 "protocol-version\nsig");
840 }
841 if (cp == NULL)
842 fatal("Unsupported query \"%s\"", optarg);
843 printf("%s\n", cp);
844 free(cp);
845 exit(0);
846 break;
847 case 'a':
848 options.forward_agent = 0;
849 break;
850 case 'A':
851 options.forward_agent = 1;
852 break;
853 case 'k':
854 options.gss_deleg_creds = 0;
855 break;
856 case 'K':
857 options.gss_authentication = 1;
858 options.gss_deleg_creds = 1;
859 break;
860 case 'i':
861 p = tilde_expand_filename(optarg, getuid());
862 if (stat(p, &st) == -1)
863 fprintf(stderr, "Warning: Identity file %s "
864 "not accessible: %s.\n", p,
865 strerror(errno));
866 else
867 add_identity_file(&options, NULL, p, 1);
868 free(p);
869 break;
870 case 'I':
871 #ifdef ENABLE_PKCS11
872 free(options.pkcs11_provider);
873 options.pkcs11_provider = xstrdup(optarg);
874 #else
875 fprintf(stderr, "no support for PKCS#11.\n");
876 #endif
877 break;
878 case 'J':
879 if (options.jump_host != NULL) {
880 fatal("Only a single -J option is permitted "
881 "(use commas to separate multiple "
882 "jump hops)");
883 }
884 if (options.proxy_command != NULL)
885 fatal("Cannot specify -J with ProxyCommand");
886 if (parse_jump(optarg, &options, 1, 1) == -1)
887
888 fatal("Invalid -J argument");
889 break;
890 case 't':
891 if (options.request_tty == REQUEST_TTY_YES)
892 options.request_tty = REQUEST_TTY_FORCE;
893 else
894 options.request_tty = REQUEST_TTY_YES;
895 break;
896 case 'v':
897 if (debug_flag == 0) {
898 debug_flag = 1;
899 options.log_level = SYSLOG_LEVEL_DEBUG1;
900 } else {
901 if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
902 debug_flag++;
903 options.log_level++;
904 }
905 }
906 break;
907 case 'V':
908 fprintf(stderr, "%s, %s\n",
909 SSH_RELEASE, SSH_OPENSSL_VERSION);
910 exit(0);
911 break;
912 case 'w':
913 if (options.tun_open == -1)
914 options.tun_open = SSH_TUNMODE_DEFAULT;
915 options.tun_local = a2tun(optarg, &options.tun_remote);
916 if (options.tun_local == SSH_TUNID_ERR) {
917 fprintf(stderr,
918 "Bad tun device '%s'\n", optarg);
919 exit(255);
920 }
921 break;
922 case 'W':
923 if (options.stdio_forward_host != NULL)
924 fatal("stdio forward already specified");
925 if (muxclient_command != 0)
926 fatal("Cannot specify stdio forward with -O");
927 if (parse_forward(&fwd, optarg, 1, 0)) {
928 options.stdio_forward_host =
929 fwd.listen_port == PORT_STREAMLOCAL ?
930 fwd.listen_path : fwd.listen_host;
931 options.stdio_forward_port = fwd.listen_port;
932 free(fwd.connect_host);
933 } else {
934 fprintf(stderr,
935 "Bad stdio forwarding specification '%s'\n",
936 optarg);
937 exit(255);
938 }
939 options.request_tty = REQUEST_TTY_NO;
940 options.session_type = SESSION_TYPE_NONE;
941 break;
942 case 'q':
943 options.log_level = SYSLOG_LEVEL_QUIET;
944 break;
945 case 'e':
946 if (strlen(optarg) == 2 && optarg[0] == '^' &&
947 (u_char) optarg[1] >= 64 &&
948 (u_char) optarg[1] < 128)
949 options.escape_char = (u_char) optarg[1] & 31;
950 else if (strlen(optarg) == 1)
951 options.escape_char = (u_char) optarg[0];
952 else if (strcmp(optarg, "none") == 0)
953 options.escape_char = SSH_ESCAPECHAR_NONE;
954 else {
955 fprintf(stderr, "Bad escape character '%s'.\n",
956 optarg);
957 exit(255);
958 }
959 break;
960 case 'c':
961 if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
962 optarg + 1 : optarg)) {
963 fprintf(stderr, "Unknown cipher type '%s'\n",
964 optarg);
965 exit(255);
966 }
967 free(options.ciphers);
968 options.ciphers = xstrdup(optarg);
969 break;
970 case 'm':
971 if (mac_valid(optarg)) {
972 free(options.macs);
973 options.macs = xstrdup(optarg);
974 } else {
975 fprintf(stderr, "Unknown mac type '%s'\n",
976 optarg);
977 exit(255);
978 }
979 break;
980 case 'M':
981 if (options.control_master == SSHCTL_MASTER_YES)
982 options.control_master = SSHCTL_MASTER_ASK;
983 else
984 options.control_master = SSHCTL_MASTER_YES;
985 break;
986 case 'p':
987 if (options.port == -1) {
988 options.port = a2port(optarg);
989 if (options.port <= 0) {
990 fprintf(stderr, "Bad port '%s'\n",
991 optarg);
992 exit(255);
993 }
994 }
995 break;
996 case 'l':
997 if (options.user == NULL) {
998 options.user = xstrdup(optarg);
999 user_on_commandline = 1;
1000 }
1001 break;
1002
1003 case 'L':
1004 if (parse_forward(&fwd, optarg, 0, 0))
1005 add_local_forward(&options, &fwd);
1006 else {
1007 fprintf(stderr,
1008 "Bad local forwarding specification '%s'\n",
1009 optarg);
1010 exit(255);
1011 }
1012 break;
1013
1014 case 'R':
1015 if (parse_forward(&fwd, optarg, 0, 1) ||
1016 parse_forward(&fwd, optarg, 1, 1)) {
1017 add_remote_forward(&options, &fwd);
1018 } else {
1019 fprintf(stderr,
1020 "Bad remote forwarding specification "
1021 "'%s'\n", optarg);
1022 exit(255);
1023 }
1024 break;
1025
1026 case 'D':
1027 if (parse_forward(&fwd, optarg, 1, 0)) {
1028 add_local_forward(&options, &fwd);
1029 } else {
1030 fprintf(stderr,
1031 "Bad dynamic forwarding specification "
1032 "'%s'\n", optarg);
1033 exit(255);
1034 }
1035 break;
1036
1037 case 'C':
1038 #ifdef WITH_ZLIB
1039 options.compression = 1;
1040 #else
1041 error("Compression not supported, disabling.");
1042 #endif
1043 break;
1044 case 'N':
1045 if (options.session_type != -1 &&
1046 options.session_type != SESSION_TYPE_NONE)
1047 fatal("Cannot specify -N with -s/SessionType");
1048 options.session_type = SESSION_TYPE_NONE;
1049 options.request_tty = REQUEST_TTY_NO;
1050 break;
1051 case 'T':
1052 options.request_tty = REQUEST_TTY_NO;
1053 break;
1054 case 'o':
1055 line = xstrdup(optarg);
1056 if (process_config_line(&options, pw,
1057 host ? host : "", host ? host : "", "", line,
1058 "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1059 exit(255);
1060 free(line);
1061 break;
1062 case 's':
1063 if (options.session_type != -1 &&
1064 options.session_type != SESSION_TYPE_SUBSYSTEM)
1065 fatal("Cannot specify -s with -N/SessionType");
1066 options.session_type = SESSION_TYPE_SUBSYSTEM;
1067 break;
1068 case 'S':
1069 free(options.control_path);
1070 options.control_path = xstrdup(optarg);
1071 break;
1072 case 'b':
1073 options.bind_address = optarg;
1074 break;
1075 case 'B':
1076 options.bind_interface = optarg;
1077 break;
1078 case 'F':
1079 config = optarg;
1080 break;
1081 default:
1082 usage();
1083 }
1084 }
1085
1086 if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1087 opt_terminated = 1;
1088
1089 ac -= optind;
1090 av += optind;
1091
1092 if (ac > 0 && !host) {
1093 int tport;
1094 char *tuser;
1095 switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1096 case -1:
1097 usage();
1098 break;
1099 case 0:
1100 if (options.user == NULL) {
1101 options.user = tuser;
1102 tuser = NULL;
1103 user_on_commandline = 1;
1104 }
1105 free(tuser);
1106 if (options.port == -1 && tport != -1)
1107 options.port = tport;
1108 break;
1109 default:
1110 p = xstrdup(*av);
1111 cp = strrchr(p, '@');
1112 if (cp != NULL) {
1113 if (cp == p)
1114 usage();
1115 if (options.user == NULL) {
1116 options.user = p;
1117 p = NULL;
1118 user_on_commandline = 1;
1119 }
1120 *cp++ = '\0';
1121 host = xstrdup(cp);
1122 free(p);
1123 } else
1124 host = p;
1125 break;
1126 }
1127 if (ac > 1 && !opt_terminated) {
1128 optind = optreset = 1;
1129 goto again;
1130 }
1131 ac--, av++;
1132 }
1133
1134 /* Check that we got a host name. */
1135 if (!host)
1136 usage();
1137
1138 /*
1139 * Validate commandline-specified values that end up in %tokens
1140 * before they are used in config parsing.
1141 */
1142 if (options.user != NULL && !ssh_valid_ruser(options.user))
1143 fatal("remote username contains invalid characters");
1144 if (!ssh_valid_hostname(host))
1145 fatal("hostname contains invalid characters");
1146
1147 options.host_arg = xstrdup(host);
1148
1149 /* Initialize the command to execute on remote host. */
1150 if ((command = sshbuf_new()) == NULL)
1151 fatal("sshbuf_new failed");
1152
1153 /*
1154 * Save the command to execute on the remote host in a buffer. There
1155 * is no limit on the length of the command, except by the maximum
1156 * packet size. Also sets the tty flag if there is no command.
1157 */
1158 if (!ac) {
1159 /* No command specified - execute shell on a tty. */
1160 if (options.session_type == SESSION_TYPE_SUBSYSTEM) {
1161 fprintf(stderr,
1162 "You must specify a subsystem to invoke.\n");
1163 usage();
1164 }
1165 } else {
1166 /* A command has been specified. Store it into the buffer. */
1167 for (i = 0; i < ac; i++) {
1168 if ((r = sshbuf_putf(command, "%s%s",
1169 i ? " " : "", av[i])) != 0)
1170 fatal_fr(r, "buffer error");
1171 }
1172 }
1173
1174 ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1175
1176 /*
1177 * Initialize "log" output. Since we are the client all output
1178 * goes to stderr unless otherwise specified by -y or -E.
1179 */
1180 if (use_syslog && logfile != NULL)
1181 fatal("Can't specify both -y and -E");
1182 if (logfile != NULL)
1183 log_redirect_stderr_to(logfile);
1184 log_init(argv0,
1185 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1186 SYSLOG_LEVEL_INFO : options.log_level,
1187 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1188 SYSLOG_FACILITY_USER : options.log_facility,
1189 !use_syslog);
1190
1191 debug("%s, %s", SSH_RELEASE, SSH_OPENSSL_VERSION);
1192 if (uname(&utsname) != 0) {
1193 memset(&utsname, 0, sizeof(utsname));
1194 strlcpy(utsname.sysname, "UNKNOWN", sizeof(utsname.sysname));
1195 }
1196 debug3("Running on %s %s %s %s", utsname.sysname, utsname.release,
1197 utsname.version, utsname.machine);
1198 debug3("Started with: %s", args);
1199 free(args);
1200
1201 /* Parse the configuration files */
1202 process_config_files(options.host_arg, pw, 0, &want_final_pass);
1203 if (want_final_pass)
1204 debug("configuration requests final Match pass");
1205
1206 /* Hostname canonicalisation needs a few options filled. */
1207 fill_default_options_for_canonicalization(&options);
1208
1209 /* If the user has replaced the hostname then take it into use now */
1210 if (options.hostname != NULL) {
1211 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1212 cp = percent_expand(options.hostname,
1213 "h", host, (char *)NULL);
1214 free(host);
1215 host = cp;
1216 free(options.hostname);
1217 options.hostname = xstrdup(host);
1218 }
1219
1220 /* Don't lowercase addresses, they will be explicitly canonicalised */
1221 if ((was_addr = is_addr(host)) == 0)
1222 lowercase(host);
1223
1224 /*
1225 * Try to canonicalize if requested by configuration or the
1226 * hostname is an address.
1227 */
1228 if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1229 addrs = resolve_canonicalize(&host, options.port);
1230
1231 /*
1232 * If CanonicalizePermittedCNAMEs have been specified but
1233 * other canonicalization did not happen (by not being requested
1234 * or by failing with fallback) then the hostname may still be changed
1235 * as a result of CNAME following.
1236 *
1237 * Try to resolve the bare hostname name using the system resolver's
1238 * usual search rules and then apply the CNAME follow rules.
1239 *
1240 * Skip the lookup if a ProxyCommand is being used unless the user
1241 * has specifically requested canonicalisation for this case via
1242 * CanonicalizeHostname=always
1243 */
1244 direct = option_clear_or_none(options.proxy_command) &&
1245 option_clear_or_none(options.jump_host);
1246 if (addrs == NULL && config_has_permitted_cnames(&options) && (direct ||
1247 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1248 if ((addrs = resolve_host(host, options.port,
1249 direct, cname, sizeof(cname))) == NULL) {
1250 /* Don't fatal proxied host names not in the DNS */
1251 if (direct)
1252 cleanup_exit(255); /* logged in resolve_host */
1253 } else
1254 check_follow_cname(direct, &host, cname);
1255 }
1256
1257 /*
1258 * If canonicalisation is enabled then re-parse the configuration
1259 * files as new stanzas may match.
1260 */
1261 if (options.canonicalize_hostname != 0 && !want_final_pass) {
1262 debug("hostname canonicalisation enabled, "
1263 "will re-parse configuration");
1264 want_final_pass = 1;
1265 }
1266
1267 if (want_final_pass) {
1268 debug("re-parsing configuration");
1269 free(options.hostname);
1270 options.hostname = xstrdup(host);
1271 process_config_files(options.host_arg, pw, 1, NULL);
1272 /*
1273 * Address resolution happens early with canonicalisation
1274 * enabled and the port number may have changed since, so
1275 * reset it in address list
1276 */
1277 if (addrs != NULL && options.port > 0)
1278 set_addrinfo_port(addrs, options.port);
1279 }
1280
1281 /* Fill configuration defaults. */
1282 if (fill_default_options(&options) != 0)
1283 cleanup_exit(255);
1284
1285 if (options.user == NULL) {
1286 user_was_default = 1;
1287 options.user = xstrdup(pw->pw_name);
1288 }
1289
1290 /*
1291 * If ProxyJump option specified, then construct a ProxyCommand now.
1292 */
1293 if (options.jump_host != NULL) {
1294 char port_s[8];
1295 const char *jumpuser = options.jump_user, *sshbin = argv0;
1296 int port = options.port, jumpport = options.jump_port;
1297
1298 if (port <= 0)
1299 port = default_ssh_port();
1300 if (jumpport <= 0)
1301 jumpport = default_ssh_port();
1302 if (jumpuser == NULL)
1303 jumpuser = options.user;
1304 if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1305 strcmp(options.user, jumpuser) == 0)
1306 fatal("jumphost loop via %s", options.jump_host);
1307
1308 /*
1309 * Try to use SSH indicated by argv[0], but fall back to
1310 * "ssh" if it appears unavailable.
1311 */
1312 if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1313 sshbin = "ssh";
1314
1315 /* Consistency check */
1316 if (options.proxy_command != NULL &&
1317 strcasecmp(options.proxy_command, "none") != 0)
1318 fatal("inconsistent options: ProxyCommand+ProxyJump");
1319 /* Never use FD passing for ProxyJump */
1320 options.proxy_use_fdpass = 0;
1321 snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1322 xasprintf(&options.proxy_command,
1323 "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1324 sshbin,
1325 /* Optional "-l user" argument if jump_user set */
1326 options.jump_user == NULL ? "" : " -l ",
1327 options.jump_user == NULL ? "" : options.jump_user,
1328 /* Optional "-p port" argument if jump_port set */
1329 options.jump_port <= 0 ? "" : " -p ",
1330 options.jump_port <= 0 ? "" : port_s,
1331 /* Optional additional jump hosts ",..." */
1332 options.jump_extra == NULL ? "" : " -J ",
1333 options.jump_extra == NULL ? "" : options.jump_extra,
1334 /* Optional "-F" argument if -F specified */
1335 config == NULL ? "" : " -F ",
1336 config == NULL ? "" : config,
1337 /* Optional "-v" arguments if -v set */
1338 debug_flag ? " -" : "",
1339 debug_flag, "vvv",
1340 /* Mandatory hostname */
1341 options.jump_host);
1342 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1343 options.proxy_command);
1344 }
1345
1346 if (options.port == 0)
1347 options.port = default_ssh_port();
1348 channel_set_af(ssh, options.address_family);
1349 ssh_packet_set_qos(ssh, options.ip_qos_interactive,
1350 options.ip_qos_bulk);
1351
1352 /* Tidy and check options */
1353 if (options.host_key_alias != NULL)
1354 lowercase(options.host_key_alias);
1355 if (options.proxy_command != NULL &&
1356 strcmp(options.proxy_command, "-") == 0 &&
1357 options.proxy_use_fdpass)
1358 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1359 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1360 if (options.control_persist && options.control_path != NULL) {
1361 debug("UpdateHostKeys=ask is incompatible with "
1362 "ControlPersist; disabling");
1363 options.update_hostkeys = 0;
1364 } else if (sshbuf_len(command) != 0 ||
1365 options.remote_command != NULL ||
1366 options.request_tty == REQUEST_TTY_NO) {
1367 debug("UpdateHostKeys=ask is incompatible with "
1368 "remote command execution; disabling");
1369 options.update_hostkeys = 0;
1370 } else if (options.log_level < SYSLOG_LEVEL_INFO) {
1371 /* no point logging anything; user won't see it */
1372 options.update_hostkeys = 0;
1373 }
1374 }
1375 if (options.connection_attempts <= 0)
1376 fatal("Invalid number of ConnectionAttempts");
1377
1378 if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1379 fatal("Cannot execute command-line and remote command.");
1380
1381 /* Cannot fork to background if no command. */
1382 if (options.fork_after_authentication && sshbuf_len(command) == 0 &&
1383 options.remote_command == NULL &&
1384 options.session_type != SESSION_TYPE_NONE)
1385 fatal("Cannot fork into background without a command "
1386 "to execute.");
1387
1388 /* reinit */
1389 log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1390 for (j = 0; j < options.num_log_verbose; j++) {
1391 if (strcasecmp(options.log_verbose[j], "none") == 0)
1392 break;
1393 log_verbose_add(options.log_verbose[j]);
1394 }
1395
1396 if (options.request_tty == REQUEST_TTY_YES ||
1397 options.request_tty == REQUEST_TTY_FORCE)
1398 tty_flag = 1;
1399
1400 /* Allocate a tty by default if no command specified. */
1401 if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1402 tty_flag = options.request_tty != REQUEST_TTY_NO;
1403
1404 /* Force no tty */
1405 if (options.request_tty == REQUEST_TTY_NO ||
1406 (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY) ||
1407 options.session_type == SESSION_TYPE_NONE)
1408 tty_flag = 0;
1409 /* Do not allocate a tty if stdin is not a tty. */
1410 if ((!isatty(fileno(stdin)) || options.stdin_null) &&
1411 options.request_tty != REQUEST_TTY_FORCE) {
1412 if (tty_flag)
1413 logit("Pseudo-terminal will not be allocated because "
1414 "stdin is not a terminal.");
1415 tty_flag = 0;
1416 }
1417
1418 /* Set up strings used to percent_expand() arguments */
1419 cinfo = xcalloc(1, sizeof(*cinfo));
1420 if (gethostname(thishost, sizeof(thishost)) == -1)
1421 fatal("gethostname: %s", strerror(errno));
1422 cinfo->thishost = xstrdup(thishost);
1423 thishost[strcspn(thishost, ".")] = '\0';
1424 cinfo->shorthost = xstrdup(thishost);
1425 xasprintf(&cinfo->portstr, "%d", options.port);
1426 xasprintf(&cinfo->uidstr, "%llu",
1427 (unsigned long long)pw->pw_uid);
1428 cinfo->keyalias = xstrdup(options.host_key_alias ?
1429 options.host_key_alias : options.host_arg);
1430 cinfo->host_arg = xstrdup(options.host_arg);
1431 cinfo->remhost = xstrdup(host);
1432 cinfo->homedir = xstrdup(pw->pw_dir);
1433 cinfo->locuser = xstrdup(pw->pw_name);
1434 cinfo->jmphost = xstrdup(options.jump_host == NULL ?
1435 "" : options.jump_host);
1436
1437 /*
1438 * If the user was specified via a configuration directive then attempt
1439 * to expand it. It cannot contain %r (itself) or %C since User is
1440 * a component of the hash.
1441 */
1442 if (!user_on_commandline && !user_was_default) {
1443 if ((p = percent_dollar_expand(options.user,
1444 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS_NOUSER(cinfo),
1445 (char *)NULL)) == NULL)
1446 fatal("invalid environment variable expansion");
1447 user_expanded = strcmp(p, options.user) != 0;
1448 free(options.user);
1449 options.user = p;
1450 }
1451
1452 /*
1453 * Usernames specified on the commandline or expanded from the
1454 * configuration file must be validated.
1455 * Conversely, usernames from getpwnam(3) or specified as literals
1456 * via configuration (i.e. not expanded) are not subject to validation.
1457 */
1458 if ((user_on_commandline || user_expanded) &&
1459 !ssh_valid_ruser(options.user))
1460 fatal("remote username contains invalid characters");
1461
1462 /* Now User is expanded, store it and calculate hash. */
1463 cinfo->remuser = xstrdup(options.user);
1464 cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost,
1465 cinfo->remhost, cinfo->portstr, cinfo->remuser, cinfo->jmphost);
1466
1467 /* Find canonic host name. */
1468 if (strchr(host, '.') == NULL) {
1469 struct addrinfo hints;
1470 struct addrinfo *ai = NULL;
1471 int errgai;
1472
1473 memset(&hints, 0, sizeof(hints));
1474 hints.ai_family = options.address_family;
1475 hints.ai_flags = AI_CANONNAME;
1476 hints.ai_socktype = SOCK_STREAM;
1477 errgai = getaddrinfo(host, NULL, &hints, &ai);
1478 if (errgai == 0) {
1479 if (ai->ai_canonname != NULL) {
1480 free(host);
1481 host = xstrdup(ai->ai_canonname);
1482 }
1483 freeaddrinfo(ai);
1484 }
1485 }
1486
1487 /*
1488 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1489 * after port-forwarding is set up, so it may pick up any local
1490 * tunnel interface name allocated.
1491 */
1492 if (options.remote_command != NULL) {
1493 debug3("expanding RemoteCommand: %s", options.remote_command);
1494 cp = options.remote_command;
1495 options.remote_command = default_client_percent_expand(cp,
1496 cinfo);
1497 debug3("expanded RemoteCommand: %s", options.remote_command);
1498 free(cp);
1499 if ((r = sshbuf_put(command, options.remote_command,
1500 strlen(options.remote_command))) != 0)
1501 fatal_fr(r, "buffer error");
1502 }
1503
1504 if (options.control_path != NULL) {
1505 cp = tilde_expand_filename(options.control_path, getuid());
1506 free(options.control_path);
1507 options.control_path = default_client_percent_dollar_expand(cp,
1508 cinfo);
1509 free(cp);
1510 }
1511
1512 if (options.identity_agent != NULL) {
1513 p = tilde_expand_filename(options.identity_agent, getuid());
1514 cp = default_client_percent_dollar_expand(p, cinfo);
1515 free(p);
1516 free(options.identity_agent);
1517 options.identity_agent = cp;
1518 }
1519
1520 for (j = 0; j < options.num_revoked_host_keys; j++) {
1521 p = tilde_expand_filename(options.revoked_host_keys[j],
1522 getuid());
1523 cp = default_client_percent_dollar_expand(p, cinfo);
1524 free(p);
1525 free(options.revoked_host_keys[j]);
1526 options.revoked_host_keys[j] = cp;
1527 }
1528
1529 if (options.forward_agent_sock_path != NULL) {
1530 p = tilde_expand_filename(options.forward_agent_sock_path,
1531 getuid());
1532 cp = default_client_percent_dollar_expand(p, cinfo);
1533 free(p);
1534 free(options.forward_agent_sock_path);
1535 options.forward_agent_sock_path = cp;
1536 if (stat(options.forward_agent_sock_path, &st) != 0) {
1537 error("Cannot forward agent socket path \"%s\": %s",
1538 options.forward_agent_sock_path, strerror(errno));
1539 if (options.exit_on_forward_failure)
1540 cleanup_exit(255);
1541 }
1542 }
1543
1544 if (options.version_addendum != NULL) {
1545 cp = default_client_percent_dollar_expand(
1546 options.version_addendum, cinfo);
1547 free(options.version_addendum);
1548 options.version_addendum = cp;
1549 }
1550
1551 if (options.num_system_hostfiles > 0 &&
1552 strcasecmp(options.system_hostfiles[0], "none") == 0) {
1553 if (options.num_system_hostfiles > 1)
1554 fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1555 "appears with other entries");
1556 free(options.system_hostfiles[0]);
1557 options.system_hostfiles[0] = NULL;
1558 options.num_system_hostfiles = 0;
1559 }
1560
1561 if (options.num_user_hostfiles > 0 &&
1562 strcasecmp(options.user_hostfiles[0], "none") == 0) {
1563 if (options.num_user_hostfiles > 1)
1564 fatal("Invalid UserKnownHostsFiles: \"none\" "
1565 "appears with other entries");
1566 free(options.user_hostfiles[0]);
1567 options.user_hostfiles[0] = NULL;
1568 options.num_user_hostfiles = 0;
1569 }
1570 for (j = 0; j < options.num_user_hostfiles; j++) {
1571 if (options.user_hostfiles[j] == NULL)
1572 continue;
1573 cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1574 p = default_client_percent_dollar_expand(cp, cinfo);
1575 if (strcmp(options.user_hostfiles[j], p) != 0)
1576 debug3("expanded UserKnownHostsFile '%s' -> "
1577 "'%s'", options.user_hostfiles[j], p);
1578 free(options.user_hostfiles[j]);
1579 free(cp);
1580 options.user_hostfiles[j] = p;
1581 }
1582
1583 for (j = 0; j < options.num_setenv; j++) {
1584 char *name = options.setenv[j], *value;
1585
1586 if (name == NULL)
1587 continue;
1588 /* Expand only the value portion, not the variable name. */
1589 if ((value = strchr(name, '=')) == NULL) {
1590 /* shouldn't happen; vars are checked in readconf.c */
1591 fatal("Invalid config SetEnv: %s", name);
1592 }
1593 *value++ = '\0';
1594 cp = default_client_percent_dollar_expand(value, cinfo);
1595 xasprintf(&p, "%s=%s", name, cp);
1596 if (strcmp(value, p) != 0) {
1597 debug3("expanded SetEnv '%s' '%s' -> '%s'",
1598 name, value, cp);
1599 }
1600 free(options.setenv[j]);
1601 free(cp);
1602 options.setenv[j] = p;
1603 }
1604
1605 for (i = 0; i < options.num_local_forwards; i++) {
1606 if (options.local_forwards[i].listen_path != NULL) {
1607 cp = options.local_forwards[i].listen_path;
1608 p = options.local_forwards[i].listen_path =
1609 default_client_percent_expand(cp, cinfo);
1610 if (strcmp(cp, p) != 0)
1611 debug3("expanded LocalForward listen path "
1612 "'%s' -> '%s'", cp, p);
1613 free(cp);
1614 }
1615 if (options.local_forwards[i].connect_path != NULL) {
1616 cp = options.local_forwards[i].connect_path;
1617 p = options.local_forwards[i].connect_path =
1618 default_client_percent_expand(cp, cinfo);
1619 if (strcmp(cp, p) != 0)
1620 debug3("expanded LocalForward connect path "
1621 "'%s' -> '%s'", cp, p);
1622 free(cp);
1623 }
1624 }
1625
1626 for (i = 0; i < options.num_remote_forwards; i++) {
1627 if (options.remote_forwards[i].listen_path != NULL) {
1628 cp = options.remote_forwards[i].listen_path;
1629 p = options.remote_forwards[i].listen_path =
1630 default_client_percent_expand(cp, cinfo);
1631 if (strcmp(cp, p) != 0)
1632 debug3("expanded RemoteForward listen path "
1633 "'%s' -> '%s'", cp, p);
1634 free(cp);
1635 }
1636 if (options.remote_forwards[i].connect_path != NULL) {
1637 cp = options.remote_forwards[i].connect_path;
1638 p = options.remote_forwards[i].connect_path =
1639 default_client_percent_expand(cp, cinfo);
1640 if (strcmp(cp, p) != 0)
1641 debug3("expanded RemoteForward connect path "
1642 "'%s' -> '%s'", cp, p);
1643 free(cp);
1644 }
1645 }
1646
1647 if (config_test) {
1648 dump_client_config(&options, host);
1649 exit(0);
1650 }
1651
1652 /* Expand SecurityKeyProvider if it refers to an environment variable */
1653 if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1654 strlen(options.sk_provider) > 1) {
1655 if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1656 debug("Authenticator provider %s did not resolve; "
1657 "disabling", options.sk_provider);
1658 free(options.sk_provider);
1659 options.sk_provider = NULL;
1660 } else {
1661 debug2("resolved SecurityKeyProvider %s => %s",
1662 options.sk_provider, cp);
1663 free(options.sk_provider);
1664 options.sk_provider = xstrdup(cp);
1665 }
1666 }
1667
1668 if (muxclient_command != 0 && options.control_path == NULL)
1669 fatal("No ControlPath specified for \"-O\" command");
1670 if (options.control_path != NULL) {
1671 int sock;
1672 if ((sock = muxclient(options.control_path)) >= 0) {
1673 ssh_packet_set_connection(ssh, sock, sock);
1674 ssh_packet_set_mux(ssh);
1675 goto skip_connect;
1676 }
1677 }
1678
1679 /*
1680 * If hostname canonicalisation was not enabled, then we may not
1681 * have yet resolved the hostname. Do so now.
1682 */
1683 if (addrs == NULL && options.proxy_command == NULL) {
1684 debug2("resolving \"%s\" port %d", host, options.port);
1685 if ((addrs = resolve_host(host, options.port, 1,
1686 cname, sizeof(cname))) == NULL)
1687 cleanup_exit(255); /* resolve_host logs the error */
1688 }
1689
1690 if (options.connection_timeout >= INT_MAX/1000)
1691 timeout_ms = INT_MAX;
1692 else
1693 timeout_ms = options.connection_timeout * 1000;
1694
1695 /* Apply channels timeouts, if set */
1696 channel_clear_timeouts(ssh);
1697 for (j = 0; j < options.num_channel_timeouts; j++) {
1698 debug3("applying channel timeout %s",
1699 options.channel_timeouts[j]);
1700 if (parse_pattern_interval(options.channel_timeouts[j],
1701 &cp, &i) != 0) {
1702 fatal_f("internal error: bad timeout %s",
1703 options.channel_timeouts[j]);
1704 }
1705 channel_add_timeout(ssh, cp, i);
1706 free(cp);
1707 }
1708
1709 /* Open a connection to the remote host. */
1710 if (ssh_connect(ssh, host, options.host_arg, addrs, &hostaddr,
1711 options.port, options.connection_attempts,
1712 &timeout_ms, options.tcp_keep_alive) != 0)
1713 exit(255);
1714
1715
1716 ssh_packet_set_timeout(ssh, options.server_alive_interval,
1717 options.server_alive_count_max);
1718
1719 if (timeout_ms > 0)
1720 debug3("timeout: %d ms remain after connect", timeout_ms);
1721
1722 /*
1723 * If we successfully made the connection and we have hostbased auth
1724 * enabled, load the public keys so we can later use the ssh-keysign
1725 * helper to sign challenges.
1726 */
1727 sensitive_data.nkeys = 0;
1728 sensitive_data.keys = NULL;
1729 if (options.hostbased_authentication) {
1730 int loaded = 0;
1731
1732 sensitive_data.nkeys = 10;
1733 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1734 sizeof(*sensitive_data.keys));
1735
1736 /* XXX check errors? */
1737 #define L_PUBKEY(p,o) do { \
1738 if ((o) >= sensitive_data.nkeys) \
1739 fatal_f("pubkey out of array bounds"); \
1740 check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1741 &(sensitive_data.keys[o]), p, "hostbased pubkey"); \
1742 if (sensitive_data.keys[o] != NULL) { \
1743 debug2("hostbased pubkey \"%s\" in slot %d", p, o); \
1744 loaded++; \
1745 } \
1746 } while (0)
1747 #define L_CERT(p,o) do { \
1748 if ((o) >= sensitive_data.nkeys) \
1749 fatal_f("cert out of array bounds"); \
1750 check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), \
1751 &(sensitive_data.keys[o]), p, "hostbased cert"); \
1752 if (sensitive_data.keys[o] != NULL) { \
1753 debug2("hostbased cert \"%s\" in slot %d", p, o); \
1754 loaded++; \
1755 } \
1756 } while (0)
1757
1758 if (options.hostbased_authentication == 1) {
1759 L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1760 L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1761 L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1762 L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1763 L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1764 L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1765 if (loaded == 0)
1766 debug("HostbasedAuthentication enabled but no "
1767 "local public host keys could be loaded.");
1768 }
1769 }
1770
1771 /* load options.identity_files */
1772 load_public_identity_files(cinfo);
1773
1774 /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1775 if (options.identity_agent &&
1776 strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1777 if (strcmp(options.identity_agent, "none") == 0) {
1778 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1779 } else {
1780 cp = options.identity_agent;
1781 /* legacy (limited) format */
1782 if (cp[0] == '$' && cp[1] != '{') {
1783 if (!valid_env_name(cp + 1)) {
1784 fatal("Invalid IdentityAgent "
1785 "environment variable name %s", cp);
1786 }
1787 if ((p = getenv(cp + 1)) == NULL)
1788 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1789 else
1790 setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1791 } else {
1792 /* identity_agent specifies a path directly */
1793 setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1794 }
1795 }
1796 }
1797
1798 if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1799 cp = options.forward_agent_sock_path;
1800 if (cp[0] == '$') {
1801 if (!valid_env_name(cp + 1)) {
1802 fatal("Invalid ForwardAgent environment variable name %s", cp);
1803 }
1804 if ((p = getenv(cp + 1)) != NULL)
1805 forward_agent_sock_path = xstrdup(p);
1806 else
1807 options.forward_agent = 0;
1808 free(cp);
1809 } else {
1810 forward_agent_sock_path = cp;
1811 }
1812 }
1813
1814 /* Expand ~ in known host file names. */
1815 tilde_expand_paths(options.system_hostfiles,
1816 options.num_system_hostfiles);
1817 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1818
1819 ssh_signal(SIGCHLD, main_sigchld_handler);
1820
1821 /* Log into the remote system. Never returns if the login fails. */
1822 ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1823 options.port, pw, timeout_ms, cinfo);
1824
1825 /* We no longer need the private host keys. Clear them now. */
1826 if (sensitive_data.nkeys != 0) {
1827 for (i = 0; i < sensitive_data.nkeys; i++) {
1828 if (sensitive_data.keys[i] != NULL) {
1829 /* Destroys contents safely */
1830 debug3("clear hostkey %d", i);
1831 sshkey_free(sensitive_data.keys[i]);
1832 sensitive_data.keys[i] = NULL;
1833 }
1834 }
1835 free(sensitive_data.keys);
1836 }
1837 for (i = 0; i < options.num_identity_files; i++) {
1838 free(options.identity_files[i]);
1839 options.identity_files[i] = NULL;
1840 if (options.identity_keys[i]) {
1841 sshkey_free(options.identity_keys[i]);
1842 options.identity_keys[i] = NULL;
1843 }
1844 }
1845 for (i = 0; i < options.num_certificate_files; i++) {
1846 free(options.certificate_files[i]);
1847 options.certificate_files[i] = NULL;
1848 }
1849
1850 #ifdef ENABLE_PKCS11
1851 (void)pkcs11_del_provider(options.pkcs11_provider);
1852 #endif
1853
1854 skip_connect:
1855 if (addrs != NULL)
1856 freeaddrinfo(addrs);
1857 exit_status = ssh_session2(ssh, cinfo);
1858 ssh_conn_info_free(cinfo);
1859 channel_free_channels(ssh);
1860 ssh_packet_free(ssh);
1861 pwfree(pw);
1862
1863 if (options.control_path != NULL && muxserver_sock != -1)
1864 unlink(options.control_path);
1865
1866 /* Kill ProxyCommand if it is running. */
1867 ssh_kill_proxy_command();
1868
1869 return exit_status;
1870 }
1871
1872 static void
control_persist_detach(void)1873 control_persist_detach(void)
1874 {
1875 pid_t pid;
1876
1877 debug_f("backgrounding master process");
1878
1879 /*
1880 * master (current process) into the background, and make the
1881 * foreground process a client of the backgrounded master.
1882 */
1883 switch ((pid = fork())) {
1884 case -1:
1885 fatal_f("fork: %s", strerror(errno));
1886 case 0:
1887 /* Child: master process continues mainloop */
1888 break;
1889 default:
1890 /*
1891 * Parent: set up mux client to connect to backgrounded
1892 * master.
1893 */
1894 debug2_f("background process is %ld", (long)pid);
1895 options.stdin_null = ostdin_null_flag;
1896 options.request_tty = orequest_tty;
1897 tty_flag = otty_flag;
1898 options.fork_after_authentication = ofork_after_authentication;
1899 options.session_type = osession_type;
1900 close(muxserver_sock);
1901 muxserver_sock = -1;
1902 options.control_master = SSHCTL_MASTER_NO;
1903 (void)muxclient(options.control_path);
1904 /* muxclient() doesn't return on success. */
1905 fatal("Failed to connect to new control master");
1906 }
1907 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1908 error_f("stdfd_devnull failed");
1909 daemon(1, 1);
1910 setproctitle("%s [mux]", options.control_path);
1911 }
1912
1913 /* Do fork() after authentication. Used by "ssh -f" */
1914 static void
fork_postauth(void)1915 fork_postauth(void)
1916 {
1917 if (need_controlpersist_detach)
1918 control_persist_detach();
1919 debug("forking to background");
1920 options.fork_after_authentication = 0;
1921 if (daemon(1, 1) == -1)
1922 fatal("daemon() failed: %.200s", strerror(errno));
1923 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1924 error_f("stdfd_devnull failed");
1925 }
1926
1927 static void
forwarding_success(void)1928 forwarding_success(void)
1929 {
1930 if (forward_confirms_pending == -1)
1931 return;
1932 if (--forward_confirms_pending == 0) {
1933 debug_f("all expected forwarding replies received");
1934 if (options.fork_after_authentication)
1935 fork_postauth();
1936 } else {
1937 debug2_f("%d expected forwarding replies remaining",
1938 forward_confirms_pending);
1939 }
1940 }
1941
1942 /* Callback for remote forward global requests */
1943 static void
ssh_confirm_remote_forward(struct ssh * ssh,int type,uint32_t seq,void * ctxt)1944 ssh_confirm_remote_forward(struct ssh *ssh, int type, uint32_t seq, void *ctxt)
1945 {
1946 struct Forward *rfwd = (struct Forward *)ctxt;
1947 u_int port;
1948 int r;
1949
1950 /* XXX verbose() on failure? */
1951 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1952 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1953 rfwd->listen_path ? rfwd->listen_path :
1954 rfwd->listen_host ? rfwd->listen_host : "",
1955 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1956 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1957 rfwd->connect_host, rfwd->connect_port);
1958 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1959 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1960 if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1961 fatal_fr(r, "parse packet");
1962 if (port > 65535) {
1963 error("Invalid allocated port %u for remote "
1964 "forward to %s:%d", port,
1965 rfwd->connect_host, rfwd->connect_port);
1966 /* Ensure failure processing runs below */
1967 type = SSH2_MSG_REQUEST_FAILURE;
1968 channel_update_permission(ssh,
1969 rfwd->handle, -1);
1970 } else {
1971 rfwd->allocated_port = (int)port;
1972 logit("Allocated port %u for remote "
1973 "forward to %s:%d",
1974 rfwd->allocated_port, rfwd->connect_path ?
1975 rfwd->connect_path : rfwd->connect_host,
1976 rfwd->connect_port);
1977 channel_update_permission(ssh,
1978 rfwd->handle, rfwd->allocated_port);
1979 }
1980 } else {
1981 channel_update_permission(ssh, rfwd->handle, -1);
1982 }
1983 }
1984
1985 if (type == SSH2_MSG_REQUEST_FAILURE) {
1986 if (options.exit_on_forward_failure) {
1987 if (rfwd->listen_path != NULL)
1988 fatal("Error: remote port forwarding failed "
1989 "for listen path %s", rfwd->listen_path);
1990 else
1991 fatal("Error: remote port forwarding failed "
1992 "for listen port %d", rfwd->listen_port);
1993 } else {
1994 if (rfwd->listen_path != NULL)
1995 logit("Warning: remote port forwarding failed "
1996 "for listen path %s", rfwd->listen_path);
1997 else
1998 logit("Warning: remote port forwarding failed "
1999 "for listen port %d", rfwd->listen_port);
2000 }
2001 }
2002 forwarding_success();
2003 }
2004
2005 static void
client_cleanup_stdio_fwd(struct ssh * ssh,int id,int force,void * arg)2006 client_cleanup_stdio_fwd(struct ssh *ssh, int id, int force, void *arg)
2007 {
2008 debug("stdio forwarding: done");
2009 cleanup_exit(0);
2010 }
2011
2012 static void
ssh_stdio_confirm(struct ssh * ssh,int id,int success,void * arg)2013 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
2014 {
2015 if (!success)
2016 fatal("stdio forwarding failed");
2017 }
2018
2019 static void
ssh_tun_confirm(struct ssh * ssh,int id,int success,void * arg)2020 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
2021 {
2022 if (!success) {
2023 error("Tunnel forwarding failed");
2024 if (options.exit_on_forward_failure)
2025 cleanup_exit(255);
2026 }
2027
2028 debug_f("tunnel forward established, id=%d", id);
2029 forwarding_success();
2030 }
2031
2032 static void
ssh_init_stdio_forwarding(struct ssh * ssh)2033 ssh_init_stdio_forwarding(struct ssh *ssh)
2034 {
2035 Channel *c;
2036 int in, out;
2037
2038 if (options.stdio_forward_host == NULL)
2039 return;
2040
2041 debug3_f("%s:%d", options.stdio_forward_host,
2042 options.stdio_forward_port);
2043
2044 if ((in = dup(STDIN_FILENO)) == -1 ||
2045 (out = dup(STDOUT_FILENO)) == -1)
2046 fatal_f("dup() in/out failed");
2047 if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
2048 options.stdio_forward_port, in, out,
2049 CHANNEL_NONBLOCK_STDIO)) == NULL)
2050 fatal_f("channel_connect_stdio_fwd failed");
2051 channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
2052 channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
2053 }
2054
2055 static void
ssh_init_forward_permissions(struct ssh * ssh,const char * what,char ** opens,u_int num_opens)2056 ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
2057 u_int num_opens)
2058 {
2059 u_int i;
2060 int port;
2061 char *addr, *arg, *oarg;
2062 int where = FORWARD_LOCAL;
2063
2064 channel_clear_permission(ssh, FORWARD_ADM, where);
2065 if (num_opens == 0)
2066 return; /* permit any */
2067
2068 /* handle keywords: "any" / "none" */
2069 if (num_opens == 1 && strcmp(opens[0], "any") == 0)
2070 return;
2071 if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
2072 channel_disable_admin(ssh, where);
2073 return;
2074 }
2075 /* Otherwise treat it as a list of permitted host:port */
2076 for (i = 0; i < num_opens; i++) {
2077 oarg = arg = xstrdup(opens[i]);
2078 addr = hpdelim(&arg);
2079 if (addr == NULL)
2080 fatal_f("missing host in %s", what);
2081 addr = cleanhostname(addr);
2082 if (arg == NULL || ((port = permitopen_port(arg)) < 0))
2083 fatal_f("bad port number in %s", what);
2084 /* Send it to channels layer */
2085 channel_add_permission(ssh, FORWARD_ADM,
2086 where, addr, port);
2087 free(oarg);
2088 }
2089 }
2090
2091 static void
ssh_init_forwarding(struct ssh * ssh,char ** ifname)2092 ssh_init_forwarding(struct ssh *ssh, char **ifname)
2093 {
2094 int success = 0;
2095 int i;
2096
2097 ssh_init_forward_permissions(ssh, "permitremoteopen",
2098 options.permitted_remote_opens,
2099 options.num_permitted_remote_opens);
2100
2101 if (options.exit_on_forward_failure)
2102 forward_confirms_pending = 0; /* track pending requests */
2103 /* Initiate local TCP/IP port forwardings. */
2104 for (i = 0; i < options.num_local_forwards; i++) {
2105 debug("Local connections to %.200s:%d forwarded to remote "
2106 "address %.200s:%d",
2107 (options.local_forwards[i].listen_path != NULL) ?
2108 options.local_forwards[i].listen_path :
2109 (options.local_forwards[i].listen_host == NULL) ?
2110 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
2111 options.local_forwards[i].listen_host,
2112 options.local_forwards[i].listen_port,
2113 (options.local_forwards[i].connect_path != NULL) ?
2114 options.local_forwards[i].connect_path :
2115 options.local_forwards[i].connect_host,
2116 options.local_forwards[i].connect_port);
2117 success += channel_setup_local_fwd_listener(ssh,
2118 &options.local_forwards[i], &options.fwd_opts);
2119 }
2120 if (i > 0 && success != i && options.exit_on_forward_failure)
2121 fatal("Could not request local forwarding.");
2122 if (i > 0 && success == 0)
2123 error("Could not request local forwarding.");
2124
2125 /* Initiate remote TCP/IP port forwardings. */
2126 for (i = 0; i < options.num_remote_forwards; i++) {
2127 debug("Remote connections from %.200s:%d forwarded to "
2128 "local address %.200s:%d",
2129 (options.remote_forwards[i].listen_path != NULL) ?
2130 options.remote_forwards[i].listen_path :
2131 (options.remote_forwards[i].listen_host == NULL) ?
2132 "LOCALHOST" : options.remote_forwards[i].listen_host,
2133 options.remote_forwards[i].listen_port,
2134 (options.remote_forwards[i].connect_path != NULL) ?
2135 options.remote_forwards[i].connect_path :
2136 options.remote_forwards[i].connect_host,
2137 options.remote_forwards[i].connect_port);
2138 if ((options.remote_forwards[i].handle =
2139 channel_request_remote_forwarding(ssh,
2140 &options.remote_forwards[i])) >= 0) {
2141 client_register_global_confirm(
2142 ssh_confirm_remote_forward,
2143 &options.remote_forwards[i]);
2144 forward_confirms_pending++;
2145 } else if (options.exit_on_forward_failure)
2146 fatal("Could not request remote forwarding.");
2147 else
2148 logit("Warning: Could not request remote forwarding.");
2149 }
2150
2151 /* Initiate tunnel forwarding. */
2152 if (options.tun_open != SSH_TUNMODE_NO) {
2153 if ((*ifname = client_request_tun_fwd(ssh,
2154 options.tun_open, options.tun_local,
2155 options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
2156 forward_confirms_pending++;
2157 else if (options.exit_on_forward_failure)
2158 fatal("Could not request tunnel forwarding.");
2159 else
2160 error("Could not request tunnel forwarding.");
2161 }
2162 if (forward_confirms_pending > 0) {
2163 debug_f("expecting replies for %d forwards",
2164 forward_confirms_pending);
2165 }
2166 }
2167
2168 static void
check_agent_present(void)2169 check_agent_present(void)
2170 {
2171 int r;
2172
2173 if (options.forward_agent) {
2174 /* Clear agent forwarding if we don't have an agent. */
2175 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
2176 options.forward_agent = 0;
2177 if (r != SSH_ERR_AGENT_NOT_PRESENT)
2178 debug_r(r, "ssh_get_authentication_socket");
2179 }
2180 }
2181 }
2182
2183 static void
ssh_session2_setup(struct ssh * ssh,int id,int success,void * arg)2184 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
2185 {
2186 extern char **environ;
2187 const char *display, *term;
2188 char *proto = NULL, *data = NULL;
2189
2190 if (!success)
2191 return; /* No need for error message, channels code sends one */
2192
2193 display = getenv("DISPLAY");
2194 if (display == NULL && options.forward_x11)
2195 debug("X11 forwarding requested but DISPLAY not set");
2196 if (options.forward_x11 && client_x11_get_proto(ssh, display,
2197 options.xauth_location, options.forward_x11_trusted,
2198 options.forward_x11_timeout, &proto, &data) == 0) {
2199 /* Request forwarding with authentication spoofing. */
2200 debug("Requesting X11 forwarding with authentication "
2201 "spoofing.");
2202 x11_request_forwarding_with_spoofing(ssh, id, display, proto,
2203 data, 1);
2204 client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
2205 /* XXX exit_on_forward_failure */
2206 }
2207
2208 check_agent_present();
2209 if (options.forward_agent)
2210 client_channel_reqest_agent_forwarding(ssh, id);
2211
2212 if ((term = lookup_env_in_list("TERM", options.setenv,
2213 options.num_setenv)) == NULL || *term == '\0')
2214 term = getenv("TERM");
2215 client_session2_setup(ssh, id, tty_flag,
2216 options.session_type == SESSION_TYPE_SUBSYSTEM, term,
2217 NULL, fileno(stdin), command, environ);
2218 }
2219
2220 /* open new channel for a session */
2221 static int
ssh_session2_open(struct ssh * ssh)2222 ssh_session2_open(struct ssh *ssh)
2223 {
2224 Channel *c;
2225 int window, packetmax, in, out, err;
2226
2227 if (options.stdin_null) {
2228 in = open(_PATH_DEVNULL, O_RDONLY);
2229 } else {
2230 in = dup(STDIN_FILENO);
2231 }
2232 out = dup(STDOUT_FILENO);
2233 err = dup(STDERR_FILENO);
2234
2235 if (in == -1 || out == -1 || err == -1)
2236 fatal("dup() in/out/err failed");
2237
2238 window = CHAN_SES_WINDOW_DEFAULT;
2239 packetmax = CHAN_SES_PACKET_DEFAULT;
2240 if (tty_flag) {
2241 window >>= 1;
2242 packetmax >>= 1;
2243 }
2244 c = channel_new(ssh,
2245 "session", SSH_CHANNEL_OPENING, in, out, err,
2246 window, packetmax, CHAN_EXTENDED_WRITE,
2247 "client-session", CHANNEL_NONBLOCK_STDIO);
2248 if (tty_flag)
2249 channel_set_tty(ssh, c);
2250 debug3_f("channel_new: %d%s", c->self, tty_flag ? " (tty)" : "");
2251
2252 channel_send_open(ssh, c->self);
2253 if (options.session_type != SESSION_TYPE_NONE)
2254 channel_register_open_confirm(ssh, c->self,
2255 ssh_session2_setup, NULL);
2256
2257 return c->self;
2258 }
2259
2260 static int
ssh_session2(struct ssh * ssh,const struct ssh_conn_info * cinfo)2261 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2262 {
2263 int r, id = -1;
2264 char *cp, *tun_fwd_ifname = NULL;
2265
2266 /* XXX should be pre-session */
2267 if (!options.control_persist)
2268 ssh_init_stdio_forwarding(ssh);
2269
2270 ssh_init_forwarding(ssh, &tun_fwd_ifname);
2271
2272 if (options.local_command != NULL) {
2273 debug3("expanding LocalCommand: %s", options.local_command);
2274 cp = options.local_command;
2275 options.local_command = percent_expand(cp,
2276 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2277 "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2278 (char *)NULL);
2279 debug3("expanded LocalCommand: %s", options.local_command);
2280 free(cp);
2281 }
2282
2283 /* Start listening for multiplex clients */
2284 if (!ssh_packet_get_mux(ssh))
2285 muxserver_listen(ssh);
2286
2287 /*
2288 * If we are in control persist mode and have a working mux listen
2289 * socket, then prepare to background ourselves and have a foreground
2290 * client attach as a control client.
2291 * NB. we must save copies of the flags that we override for
2292 * the backgrounding, since we defer attachment of the client until
2293 * after the connection is fully established (in particular,
2294 * async rfwd replies have been received for ExitOnForwardFailure).
2295 */
2296 if (options.control_persist && muxserver_sock != -1) {
2297 ostdin_null_flag = options.stdin_null;
2298 osession_type = options.session_type;
2299 orequest_tty = options.request_tty;
2300 otty_flag = tty_flag;
2301 ofork_after_authentication = options.fork_after_authentication;
2302 options.stdin_null = 1;
2303 options.session_type = SESSION_TYPE_NONE;
2304 tty_flag = 0;
2305 if ((osession_type != SESSION_TYPE_NONE ||
2306 options.stdio_forward_host != NULL))
2307 need_controlpersist_detach = 1;
2308 options.fork_after_authentication = 1;
2309 }
2310 /*
2311 * ControlPersist mux listen socket setup failed, attempt the
2312 * stdio forward setup that we skipped earlier.
2313 */
2314 if (options.control_persist && muxserver_sock == -1)
2315 ssh_init_stdio_forwarding(ssh);
2316
2317 if (options.session_type != SESSION_TYPE_NONE)
2318 id = ssh_session2_open(ssh);
2319
2320 /* If we don't expect to open a new session, then disallow it */
2321 if (options.control_master == SSHCTL_MASTER_NO &&
2322 (ssh->compat & SSH_NEW_OPENSSH)) {
2323 debug("Requesting no-more-sessions@openssh.com");
2324 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2325 (r = sshpkt_put_cstring(ssh,
2326 "no-more-sessions@openssh.com")) != 0 ||
2327 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2328 (r = sshpkt_send(ssh)) != 0)
2329 fatal_fr(r, "send packet");
2330 }
2331
2332 /* Execute a local command */
2333 if (options.local_command != NULL &&
2334 options.permit_local_command)
2335 ssh_local_cmd(options.local_command);
2336
2337 /*
2338 * stdout is now owned by the session channel; clobber it here
2339 * so future channel closes are propagated to the local fd.
2340 * NB. this can only happen after LocalCommand has completed,
2341 * as it may want to write to stdout.
2342 */
2343 if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2344 error_f("stdfd_devnull failed");
2345
2346 /*
2347 * If requested and we are not interested in replies to remote
2348 * forwarding requests, then let ssh continue in the background.
2349 */
2350 if (options.fork_after_authentication) {
2351 if (options.exit_on_forward_failure &&
2352 options.num_remote_forwards > 0) {
2353 debug("deferring postauth fork until remote forward "
2354 "confirmation received");
2355 } else
2356 fork_postauth();
2357 }
2358
2359 return client_loop(ssh, tty_flag, tty_flag ?
2360 options.escape_char : SSH_ESCAPECHAR_NONE, id);
2361 }
2362
2363 /* Loads all IdentityFile and CertificateFile keys */
2364 static void
load_public_identity_files(const struct ssh_conn_info * cinfo)2365 load_public_identity_files(const struct ssh_conn_info *cinfo)
2366 {
2367 char *filename, *cp;
2368 struct sshkey *public;
2369 int i;
2370 u_int n_ids, n_certs;
2371 char *identity_files[SSH_MAX_IDENTITY_FILES];
2372 struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2373 int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2374 char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2375 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2376 int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2377 #ifdef ENABLE_PKCS11
2378 struct sshkey **keys = NULL;
2379 char **comments = NULL;
2380 int nkeys;
2381 #endif /* PKCS11 */
2382
2383 n_ids = n_certs = 0;
2384 memset(identity_files, 0, sizeof(identity_files));
2385 memset(identity_keys, 0, sizeof(identity_keys));
2386 memset(identity_file_userprovided, 0,
2387 sizeof(identity_file_userprovided));
2388 memset(certificate_files, 0, sizeof(certificate_files));
2389 memset(certificates, 0, sizeof(certificates));
2390 memset(certificate_file_userprovided, 0,
2391 sizeof(certificate_file_userprovided));
2392
2393 #ifdef ENABLE_PKCS11
2394 if (options.pkcs11_provider != NULL &&
2395 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2396 (pkcs11_init(!options.batch_mode) == 0) &&
2397 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2398 &keys, &comments)) > 0) {
2399 for (i = 0; i < nkeys; i++) {
2400 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2401 sshkey_free(keys[i]);
2402 free(comments[i]);
2403 continue;
2404 }
2405 identity_keys[n_ids] = keys[i];
2406 identity_files[n_ids] = comments[i]; /* transferred */
2407 n_ids++;
2408 }
2409 free(keys);
2410 free(comments);
2411 }
2412 #endif /* ENABLE_PKCS11 */
2413 for (i = 0; i < options.num_identity_files; i++) {
2414 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2415 strcasecmp(options.identity_files[i], "none") == 0) {
2416 free(options.identity_files[i]);
2417 options.identity_files[i] = NULL;
2418 continue;
2419 }
2420 cp = tilde_expand_filename(options.identity_files[i], getuid());
2421 filename = default_client_percent_dollar_expand(cp, cinfo);
2422 free(cp);
2423 check_load(sshkey_load_public(filename, &public, NULL),
2424 &public, filename, "pubkey");
2425 debug("identity file %s type %d", filename,
2426 public ? public->type : -1);
2427 free(options.identity_files[i]);
2428 identity_files[n_ids] = filename;
2429 identity_keys[n_ids] = public;
2430 identity_file_userprovided[n_ids] =
2431 options.identity_file_userprovided[i];
2432 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2433 continue;
2434
2435 /*
2436 * If no certificates have been explicitly listed then try
2437 * to add the default certificate variant too.
2438 */
2439 if (options.num_certificate_files != 0)
2440 continue;
2441 xasprintf(&cp, "%s-cert", filename);
2442 check_load(sshkey_load_public(cp, &public, NULL),
2443 &public, filename, "identity pubkey");
2444 if (public == NULL) {
2445 free(cp);
2446 continue;
2447 }
2448 if (!sshkey_is_cert(public)) {
2449 debug_f("key %s type %s is not a certificate",
2450 cp, sshkey_type(public));
2451 sshkey_free(public);
2452 free(cp);
2453 continue;
2454 }
2455 free(cp);
2456 /* NB. leave filename pointing to private key */
2457 identity_files[n_ids] = xstrdup(filename);
2458 identity_keys[n_ids] = public;
2459 identity_file_userprovided[n_ids] =
2460 options.identity_file_userprovided[i];
2461 n_ids++;
2462 }
2463
2464 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2465 fatal_f("too many certificates");
2466 for (i = 0; i < options.num_certificate_files; i++) {
2467 cp = tilde_expand_filename(options.certificate_files[i],
2468 getuid());
2469 filename = default_client_percent_dollar_expand(cp, cinfo);
2470 free(cp);
2471
2472 check_load(sshkey_load_public(filename, &public, NULL),
2473 &public, filename, "identity cert");
2474 free(options.certificate_files[i]);
2475 options.certificate_files[i] = NULL;
2476 if (public == NULL) {
2477 free(filename);
2478 continue;
2479 }
2480 if (!sshkey_is_cert(public)) {
2481 debug_f("key %s type %s is not a certificate",
2482 filename, sshkey_type(public));
2483 sshkey_free(public);
2484 free(filename);
2485 continue;
2486 }
2487 certificate_files[n_certs] = filename;
2488 certificates[n_certs] = public;
2489 certificate_file_userprovided[n_certs] =
2490 options.certificate_file_userprovided[i];
2491 ++n_certs;
2492 }
2493
2494 options.num_identity_files = n_ids;
2495 memcpy(options.identity_files, identity_files, sizeof(identity_files));
2496 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2497 memcpy(options.identity_file_userprovided,
2498 identity_file_userprovided, sizeof(identity_file_userprovided));
2499
2500 options.num_certificate_files = n_certs;
2501 memcpy(options.certificate_files,
2502 certificate_files, sizeof(certificate_files));
2503 memcpy(options.certificates, certificates, sizeof(certificates));
2504 memcpy(options.certificate_file_userprovided,
2505 certificate_file_userprovided,
2506 sizeof(certificate_file_userprovided));
2507 }
2508
2509 static void
main_sigchld_handler(int sig)2510 main_sigchld_handler(int sig)
2511 {
2512 int save_errno = errno;
2513 pid_t pid;
2514 int status;
2515
2516 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2517 (pid == -1 && errno == EINTR))
2518 ;
2519 errno = save_errno;
2520 }
2521