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