jcs's openbsd hax
openbsd
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 <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
623/*
624 * Main program for the ssh client.
625 */
626int
627main(int ac, char **av)
628{
629 struct ssh *ssh = NULL;
630 int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
631 int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0;
632 int user_on_commandline = 0, user_was_default = 0, user_expanded = 0;
633 char *p, *cp, *line, *argv0, *logfile, *args;
634 char cname[NI_MAXHOST], thishost[NI_MAXHOST];
635 struct stat st;
636 struct passwd *pw;
637 extern int optind, optreset;
638 extern char *optarg;
639 struct Forward fwd;
640 struct addrinfo *addrs = NULL;
641 size_t n, len;
642 u_int j;
643 struct utsname utsname;
644 struct ssh_conn_info *cinfo = NULL;
645
646 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
647 sanitise_stdfd();
648
649 /*
650 * Discard other fds that are hanging around. These can cause problem
651 * with backgrounded ssh processes started by ControlPersist.
652 */
653 closefrom(STDERR_FILENO + 1);
654
655 if (getuid() != geteuid())
656 fatal("ssh setuid not supported.");
657 if (getgid() != getegid())
658 fatal("ssh setgid not supported.");
659
660 /* Get user data. */
661 pw = getpwuid(getuid());
662 if (!pw) {
663 logit("No user exists for uid %lu", (u_long)getuid());
664 exit(255);
665 }
666 /* Take a copy of the returned structure. */
667 pw = pwcopy(pw);
668
669 /*
670 * Set our umask to something reasonable, as some files are created
671 * with the default umask. This will make them world-readable but
672 * writable only by the owner, which is ok for all files for which we
673 * don't set the modes explicitly.
674 */
675 umask(022 | umask(077));
676
677 setlocale(LC_CTYPE, "");
678
679 /*
680 * Initialize option structure to indicate that no values have been
681 * set.
682 */
683 initialize_options(&options);
684
685 /*
686 * Prepare main ssh transport/connection structures
687 */
688 if ((ssh = ssh_alloc_session_state()) == NULL)
689 fatal("Couldn't allocate session state");
690 channel_init_channels(ssh);
691
692 /* Parse command-line arguments. */
693 args = argv_assemble(ac, av); /* logged later */
694 host = NULL;
695 use_syslog = 0;
696 logfile = NULL;
697 argv0 = av[0];
698
699 again:
700 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
701 "AB:CD:E:F:GI:J:KL:MNO:P:Q:R:S:TVw:W:XYy")) != -1) { /* HUZdhjruz */
702 switch (opt) {
703 case '1':
704 fatal("SSH protocol v.1 is no longer supported");
705 break;
706 case '2':
707 /* Ignored */
708 break;
709 case '4':
710 options.address_family = AF_INET;
711 break;
712 case '6':
713 options.address_family = AF_INET6;
714 break;
715 case 'n':
716 options.stdin_null = 1;
717 break;
718 case 'f':
719 options.fork_after_authentication = 1;
720 options.stdin_null = 1;
721 break;
722 case 'x':
723 options.forward_x11 = 0;
724 break;
725 case 'X':
726 options.forward_x11 = 1;
727 break;
728 case 'y':
729 use_syslog = 1;
730 break;
731 case 'E':
732 logfile = optarg;
733 break;
734 case 'G':
735 config_test = 1;
736 break;
737 case 'Y':
738 options.forward_x11 = 1;
739 options.forward_x11_trusted = 1;
740 break;
741 case 'g':
742 options.fwd_opts.gateway_ports = 1;
743 break;
744 case 'O':
745 if (options.stdio_forward_host != NULL)
746 fatal("Cannot specify multiplexing "
747 "command with -W");
748 else if (muxclient_command != 0)
749 fatal("Multiplexing command already specified");
750 if (strcmp(optarg, "check") == 0)
751 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
752 else if (strcmp(optarg, "conninfo") == 0)
753 muxclient_command = SSHMUX_COMMAND_CONNINFO;
754 else if (strcmp(optarg, "channels") == 0)
755 muxclient_command = SSHMUX_COMMAND_CHANINFO;
756 else if (strcmp(optarg, "forward") == 0)
757 muxclient_command = SSHMUX_COMMAND_FORWARD;
758 else if (strcmp(optarg, "exit") == 0)
759 muxclient_command = SSHMUX_COMMAND_TERMINATE;
760 else if (strcmp(optarg, "stop") == 0)
761 muxclient_command = SSHMUX_COMMAND_STOP;
762 else if (strcmp(optarg, "cancel") == 0)
763 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
764 else if (strcmp(optarg, "proxy") == 0)
765 muxclient_command = SSHMUX_COMMAND_PROXY;
766 else
767 fatal("Invalid multiplex command.");
768 break;
769 case 'P':
770 if (options.tag == NULL)
771 options.tag = xstrdup(optarg);
772 break;
773 case 'Q':
774 cp = NULL;
775 if (strcmp(optarg, "cipher") == 0 ||
776 strcasecmp(optarg, "Ciphers") == 0)
777 cp = cipher_alg_list('\n', 0);
778 else if (strcmp(optarg, "cipher-auth") == 0)
779 cp = cipher_alg_list('\n', 1);
780 else if (strcmp(optarg, "mac") == 0 ||
781 strcasecmp(optarg, "MACs") == 0)
782 cp = mac_alg_list('\n');
783 else if (strcmp(optarg, "kex") == 0 ||
784 strcasecmp(optarg, "KexAlgorithms") == 0)
785 cp = kex_alg_list('\n');
786 else if (strcmp(optarg, "key") == 0)
787 cp = sshkey_alg_list(0, 0, 0, '\n');
788 else if (strcmp(optarg, "key-cert") == 0)
789 cp = sshkey_alg_list(1, 0, 0, '\n');
790 else if (strcmp(optarg, "key-plain") == 0)
791 cp = sshkey_alg_list(0, 1, 0, '\n');
792 else if (strcmp(optarg, "key-ca-sign") == 0 ||
793 strcasecmp(optarg, "CASignatureAlgorithms") == 0)
794 cp = sshkey_alg_list(0, 1, 1, '\n');
795 else if (strcmp(optarg, "key-sig") == 0 ||
796 strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
797 strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
798 strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
799 strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
800 strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
801 strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
802 cp = sshkey_alg_list(0, 0, 1, '\n');
803 else if (strcmp(optarg, "sig") == 0)
804 cp = sshkey_alg_list(0, 1, 1, '\n');
805 else if (strcmp(optarg, "protocol-version") == 0)
806 cp = xstrdup("2");
807 else if (strcmp(optarg, "compression") == 0) {
808 cp = xstrdup(compression_alg_list(0));
809 len = strlen(cp);
810 for (n = 0; n < len; n++)
811 if (cp[n] == ',')
812 cp[n] = '\n';
813 } else if (strcmp(optarg, "help") == 0) {
814 cp = xstrdup(
815 "cipher\ncipher-auth\ncompression\nkex\n"
816 "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
817 "protocol-version\nsig");
818 }
819 if (cp == NULL)
820 fatal("Unsupported query \"%s\"", optarg);
821 printf("%s\n", cp);
822 free(cp);
823 exit(0);
824 break;
825 case 'a':
826 options.forward_agent = 0;
827 break;
828 case 'A':
829 options.forward_agent = 1;
830 break;
831 case 'k':
832 options.gss_deleg_creds = 0;
833 break;
834 case 'K':
835 options.gss_authentication = 1;
836 options.gss_deleg_creds = 1;
837 break;
838 case 'i':
839 p = tilde_expand_filename(optarg, getuid());
840 if (stat(p, &st) == -1)
841 fprintf(stderr, "Warning: Identity file %s "
842 "not accessible: %s.\n", p,
843 strerror(errno));
844 else
845 add_identity_file(&options, NULL, p, 1);
846 free(p);
847 break;
848 case 'I':
849#ifdef ENABLE_PKCS11
850 free(options.pkcs11_provider);
851 options.pkcs11_provider = xstrdup(optarg);
852#else
853 fprintf(stderr, "no support for PKCS#11.\n");
854#endif
855 break;
856 case 'J':
857 if (options.jump_host != NULL) {
858 fatal("Only a single -J option is permitted "
859 "(use commas to separate multiple "
860 "jump hops)");
861 }
862 if (options.proxy_command != NULL)
863 fatal("Cannot specify -J with ProxyCommand");
864 if (parse_jump(optarg, &options, 1, 1) == -1)
865
866 fatal("Invalid -J argument");
867 break;
868 case 't':
869 if (options.request_tty == REQUEST_TTY_YES)
870 options.request_tty = REQUEST_TTY_FORCE;
871 else
872 options.request_tty = REQUEST_TTY_YES;
873 break;
874 case 'v':
875 if (debug_flag == 0) {
876 debug_flag = 1;
877 options.log_level = SYSLOG_LEVEL_DEBUG1;
878 } else {
879 if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
880 debug_flag++;
881 options.log_level++;
882 }
883 }
884 break;
885 case 'V':
886 fprintf(stderr, "%s, %s\n",
887 SSH_VERSION, SSH_OPENSSL_VERSION);
888 exit(0);
889 break;
890 case 'w':
891 if (options.tun_open == -1)
892 options.tun_open = SSH_TUNMODE_DEFAULT;
893 options.tun_local = a2tun(optarg, &options.tun_remote);
894 if (options.tun_local == SSH_TUNID_ERR) {
895 fprintf(stderr,
896 "Bad tun device '%s'\n", optarg);
897 exit(255);
898 }
899 break;
900 case 'W':
901 if (options.stdio_forward_host != NULL)
902 fatal("stdio forward already specified");
903 if (muxclient_command != 0)
904 fatal("Cannot specify stdio forward with -O");
905 if (parse_forward(&fwd, optarg, 1, 0)) {
906 options.stdio_forward_host =
907 fwd.listen_port == PORT_STREAMLOCAL ?
908 fwd.listen_path : fwd.listen_host;
909 options.stdio_forward_port = fwd.listen_port;
910 free(fwd.connect_host);
911 } else {
912 fprintf(stderr,
913 "Bad stdio forwarding specification '%s'\n",
914 optarg);
915 exit(255);
916 }
917 options.request_tty = REQUEST_TTY_NO;
918 options.session_type = SESSION_TYPE_NONE;
919 break;
920 case 'q':
921 options.log_level = SYSLOG_LEVEL_QUIET;
922 break;
923 case 'e':
924 if (strlen(optarg) == 2 && optarg[0] == '^' &&
925 (u_char) optarg[1] >= 64 &&
926 (u_char) optarg[1] < 128)
927 options.escape_char = (u_char) optarg[1] & 31;
928 else if (strlen(optarg) == 1)
929 options.escape_char = (u_char) optarg[0];
930 else if (strcmp(optarg, "none") == 0)
931 options.escape_char = SSH_ESCAPECHAR_NONE;
932 else {
933 fprintf(stderr, "Bad escape character '%s'.\n",
934 optarg);
935 exit(255);
936 }
937 break;
938 case 'c':
939 if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
940 optarg + 1 : optarg)) {
941 fprintf(stderr, "Unknown cipher type '%s'\n",
942 optarg);
943 exit(255);
944 }
945 free(options.ciphers);
946 options.ciphers = xstrdup(optarg);
947 break;
948 case 'm':
949 if (mac_valid(optarg)) {
950 free(options.macs);
951 options.macs = xstrdup(optarg);
952 } else {
953 fprintf(stderr, "Unknown mac type '%s'\n",
954 optarg);
955 exit(255);
956 }
957 break;
958 case 'M':
959 if (options.control_master == SSHCTL_MASTER_YES)
960 options.control_master = SSHCTL_MASTER_ASK;
961 else
962 options.control_master = SSHCTL_MASTER_YES;
963 break;
964 case 'p':
965 if (options.port == -1) {
966 options.port = a2port(optarg);
967 if (options.port <= 0) {
968 fprintf(stderr, "Bad port '%s'\n",
969 optarg);
970 exit(255);
971 }
972 }
973 break;
974 case 'l':
975 if (options.user == NULL) {
976 options.user = xstrdup(optarg);
977 user_on_commandline = 1;
978 }
979 break;
980
981 case 'L':
982 if (parse_forward(&fwd, optarg, 0, 0))
983 add_local_forward(&options, &fwd);
984 else {
985 fprintf(stderr,
986 "Bad local forwarding specification '%s'\n",
987 optarg);
988 exit(255);
989 }
990 break;
991
992 case 'R':
993 if (parse_forward(&fwd, optarg, 0, 1) ||
994 parse_forward(&fwd, optarg, 1, 1)) {
995 add_remote_forward(&options, &fwd);
996 } else {
997 fprintf(stderr,
998 "Bad remote forwarding specification "
999 "'%s'\n", optarg);
1000 exit(255);
1001 }
1002 break;
1003
1004 case 'D':
1005 if (parse_forward(&fwd, optarg, 1, 0)) {
1006 add_local_forward(&options, &fwd);
1007 } else {
1008 fprintf(stderr,
1009 "Bad dynamic forwarding specification "
1010 "'%s'\n", optarg);
1011 exit(255);
1012 }
1013 break;
1014
1015 case 'C':
1016#ifdef WITH_ZLIB
1017 options.compression = 1;
1018#else
1019 error("Compression not supported, disabling.");
1020#endif
1021 break;
1022 case 'N':
1023 if (options.session_type != -1 &&
1024 options.session_type != SESSION_TYPE_NONE)
1025 fatal("Cannot specify -N with -s/SessionType");
1026 options.session_type = SESSION_TYPE_NONE;
1027 options.request_tty = REQUEST_TTY_NO;
1028 break;
1029 case 'T':
1030 options.request_tty = REQUEST_TTY_NO;
1031 break;
1032 case 'o':
1033 line = xstrdup(optarg);
1034 if (process_config_line(&options, pw,
1035 host ? host : "", host ? host : "", "", line,
1036 "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1037 exit(255);
1038 free(line);
1039 break;
1040 case 's':
1041 if (options.session_type != -1 &&
1042 options.session_type != SESSION_TYPE_SUBSYSTEM)
1043 fatal("Cannot specify -s with -N/SessionType");
1044 options.session_type = SESSION_TYPE_SUBSYSTEM;
1045 break;
1046 case 'S':
1047 free(options.control_path);
1048 options.control_path = xstrdup(optarg);
1049 break;
1050 case 'b':
1051 options.bind_address = optarg;
1052 break;
1053 case 'B':
1054 options.bind_interface = optarg;
1055 break;
1056 case 'F':
1057 config = optarg;
1058 break;
1059 default:
1060 usage();
1061 }
1062 }
1063
1064 if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1065 opt_terminated = 1;
1066
1067 ac -= optind;
1068 av += optind;
1069
1070 if (ac > 0 && !host) {
1071 int tport;
1072 char *tuser;
1073 switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1074 case -1:
1075 usage();
1076 break;
1077 case 0:
1078 if (options.user == NULL) {
1079 options.user = tuser;
1080 tuser = NULL;
1081 user_on_commandline = 1;
1082 }
1083 free(tuser);
1084 if (options.port == -1 && tport != -1)
1085 options.port = tport;
1086 break;
1087 default:
1088 p = xstrdup(*av);
1089 cp = strrchr(p, '@');
1090 if (cp != NULL) {
1091 if (cp == p)
1092 usage();
1093 if (options.user == NULL) {
1094 options.user = p;
1095 p = NULL;
1096 user_on_commandline = 1;
1097 }
1098 *cp++ = '\0';
1099 host = xstrdup(cp);
1100 free(p);
1101 } else
1102 host = p;
1103 break;
1104 }
1105 if (ac > 1 && !opt_terminated) {
1106 optind = optreset = 1;
1107 goto again;
1108 }
1109 ac--, av++;
1110 }
1111
1112 /* Check that we got a host name. */
1113 if (!host)
1114 usage();
1115
1116 /*
1117 * Validate commandline-specified values that end up in %tokens
1118 * before they are used in config parsing.
1119 */
1120 if (options.user != NULL && !ssh_valid_ruser(options.user))
1121 fatal("remote username contains invalid characters");
1122 if (!ssh_valid_hostname(host))
1123 fatal("hostname contains invalid characters");
1124
1125 options.host_arg = xstrdup(host);
1126
1127 /* Initialize the command to execute on remote host. */
1128 if ((command = sshbuf_new()) == NULL)
1129 fatal("sshbuf_new failed");
1130
1131 /*
1132 * Save the command to execute on the remote host in a buffer. There
1133 * is no limit on the length of the command, except by the maximum
1134 * packet size. Also sets the tty flag if there is no command.
1135 */
1136 if (!ac) {
1137 /* No command specified - execute shell on a tty. */
1138 if (options.session_type == SESSION_TYPE_SUBSYSTEM) {
1139 fprintf(stderr,
1140 "You must specify a subsystem to invoke.\n");
1141 usage();
1142 }
1143 } else {
1144 /* A command has been specified. Store it into the buffer. */
1145 for (i = 0; i < ac; i++) {
1146 if ((r = sshbuf_putf(command, "%s%s",
1147 i ? " " : "", av[i])) != 0)
1148 fatal_fr(r, "buffer error");
1149 }
1150 }
1151
1152 ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1153
1154 /*
1155 * Initialize "log" output. Since we are the client all output
1156 * goes to stderr unless otherwise specified by -y or -E.
1157 */
1158 if (use_syslog && logfile != NULL)
1159 fatal("Can't specify both -y and -E");
1160 if (logfile != NULL)
1161 log_redirect_stderr_to(logfile);
1162 log_init(argv0,
1163 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1164 SYSLOG_LEVEL_INFO : options.log_level,
1165 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1166 SYSLOG_FACILITY_USER : options.log_facility,
1167 !use_syslog);
1168
1169 debug("%s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1170 if (uname(&utsname) != 0) {
1171 memset(&utsname, 0, sizeof(utsname));
1172 strlcpy(utsname.sysname, "UNKNOWN", sizeof(utsname.sysname));
1173 }
1174 debug3("Running on %s %s %s %s", utsname.sysname, utsname.release,
1175 utsname.version, utsname.machine);
1176 debug3("Started with: %s", args);
1177 free(args);
1178
1179 /* Parse the configuration files */
1180 process_config_files(options.host_arg, pw, 0, &want_final_pass);
1181 if (want_final_pass)
1182 debug("configuration requests final Match pass");
1183
1184 /* Hostname canonicalisation needs a few options filled. */
1185 fill_default_options_for_canonicalization(&options);
1186
1187 /* If the user has replaced the hostname then take it into use now */
1188 if (options.hostname != NULL) {
1189 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1190 cp = percent_expand(options.hostname,
1191 "h", host, (char *)NULL);
1192 free(host);
1193 host = cp;
1194 free(options.hostname);
1195 options.hostname = xstrdup(host);
1196 }
1197
1198 /* Don't lowercase addresses, they will be explicitly canonicalised */
1199 if ((was_addr = is_addr(host)) == 0)
1200 lowercase(host);
1201
1202 /*
1203 * Try to canonicalize if requested by configuration or the
1204 * hostname is an address.
1205 */
1206 if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1207 addrs = resolve_canonicalize(&host, options.port);
1208
1209 /*
1210 * If CanonicalizePermittedCNAMEs have been specified but
1211 * other canonicalization did not happen (by not being requested
1212 * or by failing with fallback) then the hostname may still be changed
1213 * as a result of CNAME following.
1214 *
1215 * Try to resolve the bare hostname name using the system resolver's
1216 * usual search rules and then apply the CNAME follow rules.
1217 *
1218 * Skip the lookup if a ProxyCommand is being used unless the user
1219 * has specifically requested canonicalisation for this case via
1220 * CanonicalizeHostname=always
1221 */
1222 direct = option_clear_or_none(options.proxy_command) &&
1223 option_clear_or_none(options.jump_host);
1224 if (addrs == NULL && config_has_permitted_cnames(&options) && (direct ||
1225 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1226 if ((addrs = resolve_host(host, options.port,
1227 direct, cname, sizeof(cname))) == NULL) {
1228 /* Don't fatal proxied host names not in the DNS */
1229 if (direct)
1230 cleanup_exit(255); /* logged in resolve_host */
1231 } else
1232 check_follow_cname(direct, &host, cname);
1233 }
1234
1235 /*
1236 * If canonicalisation is enabled then re-parse the configuration
1237 * files as new stanzas may match.
1238 */
1239 if (options.canonicalize_hostname != 0 && !want_final_pass) {
1240 debug("hostname canonicalisation enabled, "
1241 "will re-parse configuration");
1242 want_final_pass = 1;
1243 }
1244
1245 if (want_final_pass) {
1246 debug("re-parsing configuration");
1247 free(options.hostname);
1248 options.hostname = xstrdup(host);
1249 process_config_files(options.host_arg, pw, 1, NULL);
1250 /*
1251 * Address resolution happens early with canonicalisation
1252 * enabled and the port number may have changed since, so
1253 * reset it in address list
1254 */
1255 if (addrs != NULL && options.port > 0)
1256 set_addrinfo_port(addrs, options.port);
1257 }
1258
1259 /* Fill configuration defaults. */
1260 if (fill_default_options(&options) != 0)
1261 cleanup_exit(255);
1262
1263 if (options.user == NULL) {
1264 user_was_default = 1;
1265 options.user = xstrdup(pw->pw_name);
1266 }
1267
1268 /*
1269 * If ProxyJump option specified, then construct a ProxyCommand now.
1270 */
1271 if (options.jump_host != NULL) {
1272 char port_s[8];
1273 const char *jumpuser = options.jump_user, *sshbin = argv0;
1274 int port = options.port, jumpport = options.jump_port;
1275
1276 if (port <= 0)
1277 port = default_ssh_port();
1278 if (jumpport <= 0)
1279 jumpport = default_ssh_port();
1280 if (jumpuser == NULL)
1281 jumpuser = options.user;
1282 if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1283 strcmp(options.user, jumpuser) == 0)
1284 fatal("jumphost loop via %s", options.jump_host);
1285
1286 /*
1287 * Try to use SSH indicated by argv[0], but fall back to
1288 * "ssh" if it appears unavailable.
1289 */
1290 if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1291 sshbin = "ssh";
1292
1293 /* Consistency check */
1294 if (options.proxy_command != NULL &&
1295 strcasecmp(options.proxy_command, "none") != 0)
1296 fatal("inconsistent options: ProxyCommand+ProxyJump");
1297 /* Never use FD passing for ProxyJump */
1298 options.proxy_use_fdpass = 0;
1299 snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1300 xasprintf(&options.proxy_command,
1301 "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1302 sshbin,
1303 /* Optional "-l user" argument if jump_user set */
1304 options.jump_user == NULL ? "" : " -l ",
1305 options.jump_user == NULL ? "" : options.jump_user,
1306 /* Optional "-p port" argument if jump_port set */
1307 options.jump_port <= 0 ? "" : " -p ",
1308 options.jump_port <= 0 ? "" : port_s,
1309 /* Optional additional jump hosts ",..." */
1310 options.jump_extra == NULL ? "" : " -J ",
1311 options.jump_extra == NULL ? "" : options.jump_extra,
1312 /* Optional "-F" argument if -F specified */
1313 config == NULL ? "" : " -F ",
1314 config == NULL ? "" : config,
1315 /* Optional "-v" arguments if -v set */
1316 debug_flag ? " -" : "",
1317 debug_flag, "vvv",
1318 /* Mandatory hostname */
1319 options.jump_host);
1320 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1321 options.proxy_command);
1322 }
1323
1324 if (options.port == 0)
1325 options.port = default_ssh_port();
1326 channel_set_af(ssh, options.address_family);
1327 ssh_packet_set_qos(ssh, options.ip_qos_interactive,
1328 options.ip_qos_bulk);
1329
1330 /* Tidy and check options */
1331 if (options.host_key_alias != NULL)
1332 lowercase(options.host_key_alias);
1333 if (options.proxy_command != NULL &&
1334 strcmp(options.proxy_command, "-") == 0 &&
1335 options.proxy_use_fdpass)
1336 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1337 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1338 if (options.control_persist && options.control_path != NULL) {
1339 debug("UpdateHostKeys=ask is incompatible with "
1340 "ControlPersist; disabling");
1341 options.update_hostkeys = 0;
1342 } else if (sshbuf_len(command) != 0 ||
1343 options.remote_command != NULL ||
1344 options.request_tty == REQUEST_TTY_NO) {
1345 debug("UpdateHostKeys=ask is incompatible with "
1346 "remote command execution; disabling");
1347 options.update_hostkeys = 0;
1348 } else if (options.log_level < SYSLOG_LEVEL_INFO) {
1349 /* no point logging anything; user won't see it */
1350 options.update_hostkeys = 0;
1351 }
1352 }
1353 if (options.connection_attempts <= 0)
1354 fatal("Invalid number of ConnectionAttempts");
1355
1356 if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1357 fatal("Cannot execute command-line and remote command.");
1358
1359 /* Cannot fork to background if no command. */
1360 if (options.fork_after_authentication && sshbuf_len(command) == 0 &&
1361 options.remote_command == NULL &&
1362 options.session_type != SESSION_TYPE_NONE)
1363 fatal("Cannot fork into background without a command "
1364 "to execute.");
1365
1366 /* reinit */
1367 log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1368 for (j = 0; j < options.num_log_verbose; j++) {
1369 if (strcasecmp(options.log_verbose[j], "none") == 0)
1370 break;
1371 log_verbose_add(options.log_verbose[j]);
1372 }
1373
1374 if (options.request_tty == REQUEST_TTY_YES ||
1375 options.request_tty == REQUEST_TTY_FORCE)
1376 tty_flag = 1;
1377
1378 /* Allocate a tty by default if no command specified. */
1379 if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1380 tty_flag = options.request_tty != REQUEST_TTY_NO;
1381
1382 /* Force no tty */
1383 if (options.request_tty == REQUEST_TTY_NO ||
1384 (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY) ||
1385 options.session_type == SESSION_TYPE_NONE)
1386 tty_flag = 0;
1387 /* Do not allocate a tty if stdin is not a tty. */
1388 if ((!isatty(fileno(stdin)) || options.stdin_null) &&
1389 options.request_tty != REQUEST_TTY_FORCE) {
1390 if (tty_flag)
1391 logit("Pseudo-terminal will not be allocated because "
1392 "stdin is not a terminal.");
1393 tty_flag = 0;
1394 }
1395
1396 /* Set up strings used to percent_expand() arguments */
1397 cinfo = xcalloc(1, sizeof(*cinfo));
1398 if (gethostname(thishost, sizeof(thishost)) == -1)
1399 fatal("gethostname: %s", strerror(errno));
1400 cinfo->thishost = xstrdup(thishost);
1401 thishost[strcspn(thishost, ".")] = '\0';
1402 cinfo->shorthost = xstrdup(thishost);
1403 xasprintf(&cinfo->portstr, "%d", options.port);
1404 xasprintf(&cinfo->uidstr, "%llu",
1405 (unsigned long long)pw->pw_uid);
1406 cinfo->keyalias = xstrdup(options.host_key_alias ?
1407 options.host_key_alias : options.host_arg);
1408 cinfo->host_arg = xstrdup(options.host_arg);
1409 cinfo->remhost = xstrdup(host);
1410 cinfo->homedir = xstrdup(pw->pw_dir);
1411 cinfo->locuser = xstrdup(pw->pw_name);
1412 cinfo->jmphost = xstrdup(options.jump_host == NULL ?
1413 "" : options.jump_host);
1414
1415 /*
1416 * If the user was specified via a configuration directive then attempt
1417 * to expand it. It cannot contain %r (itself) or %C since User is
1418 * a component of the hash.
1419 */
1420 if (!user_on_commandline && !user_was_default) {
1421 if ((p = percent_dollar_expand(options.user,
1422 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS_NOUSER(cinfo),
1423 (char *)NULL)) == NULL)
1424 fatal("invalid environment variable expansion");
1425 user_expanded = strcmp(p, options.user) != 0;
1426 free(options.user);
1427 options.user = p;
1428 }
1429
1430 /*
1431 * Usernames specified on the commandline or expanded from the
1432 * configuration file must be validated.
1433 * Conversely, usernames from getpwnam(3) or specified as literals
1434 * via configuration (i.e. not expanded) are not subject to validation.
1435 */
1436 if ((user_on_commandline || user_expanded) &&
1437 !ssh_valid_ruser(options.user))
1438 fatal("remote username contains invalid characters");
1439
1440 /* Now User is expanded, store it and calculate hash. */
1441 cinfo->remuser = xstrdup(options.user);
1442 cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost,
1443 cinfo->remhost, cinfo->portstr, cinfo->remuser, cinfo->jmphost);
1444
1445 /*
1446 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1447 * after port-forwarding is set up, so it may pick up any local
1448 * tunnel interface name allocated.
1449 */
1450 if (options.remote_command != NULL) {
1451 debug3("expanding RemoteCommand: %s", options.remote_command);
1452 cp = options.remote_command;
1453 options.remote_command = default_client_percent_expand(cp,
1454 cinfo);
1455 debug3("expanded RemoteCommand: %s", options.remote_command);
1456 free(cp);
1457 if ((r = sshbuf_put(command, options.remote_command,
1458 strlen(options.remote_command))) != 0)
1459 fatal_fr(r, "buffer error");
1460 }
1461
1462 if (options.control_path != NULL) {
1463 cp = tilde_expand_filename(options.control_path, getuid());
1464 free(options.control_path);
1465 options.control_path = default_client_percent_dollar_expand(cp,
1466 cinfo);
1467 free(cp);
1468 }
1469
1470 if (options.identity_agent != NULL) {
1471 p = tilde_expand_filename(options.identity_agent, getuid());
1472 cp = default_client_percent_dollar_expand(p, cinfo);
1473 free(p);
1474 free(options.identity_agent);
1475 options.identity_agent = cp;
1476 }
1477
1478 for (j = 0; j < options.num_revoked_host_keys; j++) {
1479 p = tilde_expand_filename(options.revoked_host_keys[j],
1480 getuid());
1481 cp = default_client_percent_dollar_expand(p, cinfo);
1482 free(p);
1483 free(options.revoked_host_keys[j]);
1484 options.revoked_host_keys[j] = cp;
1485 }
1486
1487 if (options.forward_agent_sock_path != NULL) {
1488 p = tilde_expand_filename(options.forward_agent_sock_path,
1489 getuid());
1490 cp = default_client_percent_dollar_expand(p, cinfo);
1491 free(p);
1492 free(options.forward_agent_sock_path);
1493 options.forward_agent_sock_path = cp;
1494 if (stat(options.forward_agent_sock_path, &st) != 0) {
1495 error("Cannot forward agent socket path \"%s\": %s",
1496 options.forward_agent_sock_path, strerror(errno));
1497 if (options.exit_on_forward_failure)
1498 cleanup_exit(255);
1499 }
1500 }
1501
1502 if (options.version_addendum != NULL) {
1503 cp = default_client_percent_dollar_expand(
1504 options.version_addendum, cinfo);
1505 free(options.version_addendum);
1506 options.version_addendum = cp;
1507 }
1508
1509 if (options.num_system_hostfiles > 0 &&
1510 strcasecmp(options.system_hostfiles[0], "none") == 0) {
1511 if (options.num_system_hostfiles > 1)
1512 fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1513 "appears with other entries");
1514 free(options.system_hostfiles[0]);
1515 options.system_hostfiles[0] = NULL;
1516 options.num_system_hostfiles = 0;
1517 }
1518
1519 if (options.num_user_hostfiles > 0 &&
1520 strcasecmp(options.user_hostfiles[0], "none") == 0) {
1521 if (options.num_user_hostfiles > 1)
1522 fatal("Invalid UserKnownHostsFiles: \"none\" "
1523 "appears with other entries");
1524 free(options.user_hostfiles[0]);
1525 options.user_hostfiles[0] = NULL;
1526 options.num_user_hostfiles = 0;
1527 }
1528 for (j = 0; j < options.num_user_hostfiles; j++) {
1529 if (options.user_hostfiles[j] == NULL)
1530 continue;
1531 cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1532 p = default_client_percent_dollar_expand(cp, cinfo);
1533 if (strcmp(options.user_hostfiles[j], p) != 0)
1534 debug3("expanded UserKnownHostsFile '%s' -> "
1535 "'%s'", options.user_hostfiles[j], p);
1536 free(options.user_hostfiles[j]);
1537 free(cp);
1538 options.user_hostfiles[j] = p;
1539 }
1540
1541 for (j = 0; j < options.num_setenv; j++) {
1542 char *name = options.setenv[j], *value;
1543
1544 if (name == NULL)
1545 continue;
1546 /* Expand only the value portion, not the variable name. */
1547 if ((value = strchr(name, '=')) == NULL) {
1548 /* shouldn't happen; vars are checked in readconf.c */
1549 fatal("Invalid config SetEnv: %s", name);
1550 }
1551 *value++ = '\0';
1552 cp = default_client_percent_dollar_expand(value, cinfo);
1553 xasprintf(&p, "%s=%s", name, cp);
1554 if (strcmp(value, p) != 0) {
1555 debug3("expanded SetEnv '%s' '%s' -> '%s'",
1556 name, value, cp);
1557 }
1558 free(options.setenv[j]);
1559 free(cp);
1560 options.setenv[j] = p;
1561 }
1562
1563 for (i = 0; i < options.num_local_forwards; i++) {
1564 if (options.local_forwards[i].listen_path != NULL) {
1565 cp = options.local_forwards[i].listen_path;
1566 p = options.local_forwards[i].listen_path =
1567 default_client_percent_expand(cp, cinfo);
1568 if (strcmp(cp, p) != 0)
1569 debug3("expanded LocalForward listen path "
1570 "'%s' -> '%s'", cp, p);
1571 free(cp);
1572 }
1573 if (options.local_forwards[i].connect_path != NULL) {
1574 cp = options.local_forwards[i].connect_path;
1575 p = options.local_forwards[i].connect_path =
1576 default_client_percent_expand(cp, cinfo);
1577 if (strcmp(cp, p) != 0)
1578 debug3("expanded LocalForward connect path "
1579 "'%s' -> '%s'", cp, p);
1580 free(cp);
1581 }
1582 }
1583
1584 for (i = 0; i < options.num_remote_forwards; i++) {
1585 if (options.remote_forwards[i].listen_path != NULL) {
1586 cp = options.remote_forwards[i].listen_path;
1587 p = options.remote_forwards[i].listen_path =
1588 default_client_percent_expand(cp, cinfo);
1589 if (strcmp(cp, p) != 0)
1590 debug3("expanded RemoteForward listen path "
1591 "'%s' -> '%s'", cp, p);
1592 free(cp);
1593 }
1594 if (options.remote_forwards[i].connect_path != NULL) {
1595 cp = options.remote_forwards[i].connect_path;
1596 p = options.remote_forwards[i].connect_path =
1597 default_client_percent_expand(cp, cinfo);
1598 if (strcmp(cp, p) != 0)
1599 debug3("expanded RemoteForward connect path "
1600 "'%s' -> '%s'", cp, p);
1601 free(cp);
1602 }
1603 }
1604
1605 if (config_test) {
1606 dump_client_config(&options, host);
1607 exit(0);
1608 }
1609
1610 /* Expand SecurityKeyProvider if it refers to an environment variable */
1611 if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1612 strlen(options.sk_provider) > 1) {
1613 if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1614 debug("Authenticator provider %s did not resolve; "
1615 "disabling", options.sk_provider);
1616 free(options.sk_provider);
1617 options.sk_provider = NULL;
1618 } else {
1619 debug2("resolved SecurityKeyProvider %s => %s",
1620 options.sk_provider, cp);
1621 free(options.sk_provider);
1622 options.sk_provider = xstrdup(cp);
1623 }
1624 }
1625
1626 if (muxclient_command != 0 && options.control_path == NULL)
1627 fatal("No ControlPath specified for \"-O\" command");
1628 if (options.control_path != NULL) {
1629 int sock;
1630 if ((sock = muxclient(options.control_path)) >= 0) {
1631 ssh_packet_set_connection(ssh, sock, sock);
1632 ssh_packet_set_mux(ssh);
1633 goto skip_connect;
1634 }
1635 }
1636
1637 /*
1638 * If hostname canonicalisation was not enabled, then we may not
1639 * have yet resolved the hostname. Do so now.
1640 */
1641 if (addrs == NULL && options.proxy_command == NULL) {
1642 debug2("resolving \"%s\" port %d", host, options.port);
1643 if ((addrs = resolve_host(host, options.port, 1,
1644 cname, sizeof(cname))) == NULL)
1645 cleanup_exit(255); /* resolve_host logs the error */
1646 }
1647
1648 if (options.connection_timeout >= INT_MAX/1000)
1649 timeout_ms = INT_MAX;
1650 else
1651 timeout_ms = options.connection_timeout * 1000;
1652
1653 /* Apply channels timeouts, if set */
1654 channel_clear_timeouts(ssh);
1655 for (j = 0; j < options.num_channel_timeouts; j++) {
1656 debug3("applying channel timeout %s",
1657 options.channel_timeouts[j]);
1658 if (parse_pattern_interval(options.channel_timeouts[j],
1659 &cp, &i) != 0) {
1660 fatal_f("internal error: bad timeout %s",
1661 options.channel_timeouts[j]);
1662 }
1663 channel_add_timeout(ssh, cp, i);
1664 free(cp);
1665 }
1666
1667 /* Open a connection to the remote host. */
1668 if (ssh_connect(ssh, host, options.host_arg, addrs, &hostaddr,
1669 options.port, options.connection_attempts,
1670 &timeout_ms, options.tcp_keep_alive) != 0)
1671 exit(255);
1672
1673
1674 ssh_packet_set_timeout(ssh, options.server_alive_interval,
1675 options.server_alive_count_max);
1676
1677 if (timeout_ms > 0)
1678 debug3("timeout: %d ms remain after connect", timeout_ms);
1679
1680 /*
1681 * If we successfully made the connection and we have hostbased auth
1682 * enabled, load the public keys so we can later use the ssh-keysign
1683 * helper to sign challenges.
1684 */
1685 sensitive_data.nkeys = 0;
1686 sensitive_data.keys = NULL;
1687 if (options.hostbased_authentication) {
1688 int loaded = 0;
1689
1690 sensitive_data.nkeys = 10;
1691 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1692 sizeof(*sensitive_data.keys));
1693
1694 /* XXX check errors? */
1695#define L_PUBKEY(p,o) do { \
1696 if ((o) >= sensitive_data.nkeys) \
1697 fatal_f("pubkey out of array bounds"); \
1698 check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1699 &(sensitive_data.keys[o]), p, "hostbased pubkey"); \
1700 if (sensitive_data.keys[o] != NULL) { \
1701 debug2("hostbased pubkey \"%s\" in slot %d", p, o); \
1702 loaded++; \
1703 } \
1704} while (0)
1705#define L_CERT(p,o) do { \
1706 if ((o) >= sensitive_data.nkeys) \
1707 fatal_f("cert out of array bounds"); \
1708 check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), \
1709 &(sensitive_data.keys[o]), p, "hostbased cert"); \
1710 if (sensitive_data.keys[o] != NULL) { \
1711 debug2("hostbased cert \"%s\" in slot %d", p, o); \
1712 loaded++; \
1713 } \
1714} while (0)
1715
1716 if (options.hostbased_authentication == 1) {
1717 L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1718 L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1719 L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1720 L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1721 L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1722 L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1723 if (loaded == 0)
1724 debug("HostbasedAuthentication enabled but no "
1725 "local public host keys could be loaded.");
1726 }
1727 }
1728
1729 /* load options.identity_files */
1730 load_public_identity_files(cinfo);
1731
1732 /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1733 if (options.identity_agent &&
1734 strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1735 if (strcmp(options.identity_agent, "none") == 0) {
1736 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1737 } else {
1738 cp = options.identity_agent;
1739 /* legacy (limited) format */
1740 if (cp[0] == '$' && cp[1] != '{') {
1741 if (!valid_env_name(cp + 1)) {
1742 fatal("Invalid IdentityAgent "
1743 "environment variable name %s", cp);
1744 }
1745 if ((p = getenv(cp + 1)) == NULL)
1746 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1747 else
1748 setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1749 } else {
1750 /* identity_agent specifies a path directly */
1751 setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1752 }
1753 }
1754 }
1755
1756 if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1757 cp = options.forward_agent_sock_path;
1758 if (cp[0] == '$') {
1759 if (!valid_env_name(cp + 1)) {
1760 fatal("Invalid ForwardAgent environment variable name %s", cp);
1761 }
1762 if ((p = getenv(cp + 1)) != NULL)
1763 forward_agent_sock_path = xstrdup(p);
1764 else
1765 options.forward_agent = 0;
1766 free(cp);
1767 } else {
1768 forward_agent_sock_path = cp;
1769 }
1770 }
1771
1772 /* Expand ~ in known host file names. */
1773 tilde_expand_paths(options.system_hostfiles,
1774 options.num_system_hostfiles);
1775 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1776
1777 ssh_signal(SIGCHLD, main_sigchld_handler);
1778
1779 /* Log into the remote system. Never returns if the login fails. */
1780 ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1781 options.port, pw, timeout_ms, cinfo);
1782
1783 /* We no longer need the private host keys. Clear them now. */
1784 if (sensitive_data.nkeys != 0) {
1785 for (i = 0; i < sensitive_data.nkeys; i++) {
1786 if (sensitive_data.keys[i] != NULL) {
1787 /* Destroys contents safely */
1788 debug3("clear hostkey %d", i);
1789 sshkey_free(sensitive_data.keys[i]);
1790 sensitive_data.keys[i] = NULL;
1791 }
1792 }
1793 free(sensitive_data.keys);
1794 }
1795 for (i = 0; i < options.num_identity_files; i++) {
1796 free(options.identity_files[i]);
1797 options.identity_files[i] = NULL;
1798 if (options.identity_keys[i]) {
1799 sshkey_free(options.identity_keys[i]);
1800 options.identity_keys[i] = NULL;
1801 }
1802 }
1803 for (i = 0; i < options.num_certificate_files; i++) {
1804 free(options.certificate_files[i]);
1805 options.certificate_files[i] = NULL;
1806 }
1807
1808#ifdef ENABLE_PKCS11
1809 (void)pkcs11_del_provider(options.pkcs11_provider);
1810#endif
1811
1812 skip_connect:
1813 if (addrs != NULL)
1814 freeaddrinfo(addrs);
1815 exit_status = ssh_session2(ssh, cinfo);
1816 ssh_conn_info_free(cinfo);
1817 channel_free_channels(ssh);
1818 ssh_packet_free(ssh);
1819 pwfree(pw);
1820
1821 if (options.control_path != NULL && muxserver_sock != -1)
1822 unlink(options.control_path);
1823
1824 /* Kill ProxyCommand if it is running. */
1825 ssh_kill_proxy_command();
1826
1827 return exit_status;
1828}
1829
1830static void
1831control_persist_detach(void)
1832{
1833 pid_t pid;
1834
1835 debug_f("backgrounding master process");
1836
1837 /*
1838 * master (current process) into the background, and make the
1839 * foreground process a client of the backgrounded master.
1840 */
1841 switch ((pid = fork())) {
1842 case -1:
1843 fatal_f("fork: %s", strerror(errno));
1844 case 0:
1845 /* Child: master process continues mainloop */
1846 break;
1847 default:
1848 /*
1849 * Parent: set up mux client to connect to backgrounded
1850 * master.
1851 */
1852 debug2_f("background process is %ld", (long)pid);
1853 options.stdin_null = ostdin_null_flag;
1854 options.request_tty = orequest_tty;
1855 tty_flag = otty_flag;
1856 options.fork_after_authentication = ofork_after_authentication;
1857 options.session_type = osession_type;
1858 close(muxserver_sock);
1859 muxserver_sock = -1;
1860 options.control_master = SSHCTL_MASTER_NO;
1861 (void)muxclient(options.control_path);
1862 /* muxclient() doesn't return on success. */
1863 fatal("Failed to connect to new control master");
1864 }
1865 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1866 error_f("stdfd_devnull failed");
1867 daemon(1, 1);
1868 setproctitle("%s [mux]", options.control_path);
1869}
1870
1871/* Do fork() after authentication. Used by "ssh -f" */
1872static void
1873fork_postauth(void)
1874{
1875 if (need_controlpersist_detach)
1876 control_persist_detach();
1877 debug("forking to background");
1878 options.fork_after_authentication = 0;
1879 if (daemon(1, 1) == -1)
1880 fatal("daemon() failed: %.200s", strerror(errno));
1881 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1882 error_f("stdfd_devnull failed");
1883}
1884
1885static void
1886forwarding_success(void)
1887{
1888 if (forward_confirms_pending == -1)
1889 return;
1890 if (--forward_confirms_pending == 0) {
1891 debug_f("all expected forwarding replies received");
1892 if (options.fork_after_authentication)
1893 fork_postauth();
1894 } else {
1895 debug2_f("%d expected forwarding replies remaining",
1896 forward_confirms_pending);
1897 }
1898}
1899
1900/* Callback for remote forward global requests */
1901static void
1902ssh_confirm_remote_forward(struct ssh *ssh, int type, uint32_t seq, void *ctxt)
1903{
1904 struct Forward *rfwd = (struct Forward *)ctxt;
1905 u_int port;
1906 int r;
1907
1908 /* XXX verbose() on failure? */
1909 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1910 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1911 rfwd->listen_path ? rfwd->listen_path :
1912 rfwd->listen_host ? rfwd->listen_host : "",
1913 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1914 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1915 rfwd->connect_host, rfwd->connect_port);
1916 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1917 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1918 if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1919 fatal_fr(r, "parse packet");
1920 if (port > 65535) {
1921 error("Invalid allocated port %u for remote "
1922 "forward to %s:%d", port,
1923 rfwd->connect_host, rfwd->connect_port);
1924 /* Ensure failure processing runs below */
1925 type = SSH2_MSG_REQUEST_FAILURE;
1926 channel_update_permission(ssh,
1927 rfwd->handle, -1);
1928 } else {
1929 rfwd->allocated_port = (int)port;
1930 logit("Allocated port %u for remote "
1931 "forward to %s:%d",
1932 rfwd->allocated_port, rfwd->connect_path ?
1933 rfwd->connect_path : rfwd->connect_host,
1934 rfwd->connect_port);
1935 channel_update_permission(ssh,
1936 rfwd->handle, rfwd->allocated_port);
1937 }
1938 } else {
1939 channel_update_permission(ssh, rfwd->handle, -1);
1940 }
1941 }
1942
1943 if (type == SSH2_MSG_REQUEST_FAILURE) {
1944 if (options.exit_on_forward_failure) {
1945 if (rfwd->listen_path != NULL)
1946 fatal("Error: remote port forwarding failed "
1947 "for listen path %s", rfwd->listen_path);
1948 else
1949 fatal("Error: remote port forwarding failed "
1950 "for listen port %d", rfwd->listen_port);
1951 } else {
1952 if (rfwd->listen_path != NULL)
1953 logit("Warning: remote port forwarding failed "
1954 "for listen path %s", rfwd->listen_path);
1955 else
1956 logit("Warning: remote port forwarding failed "
1957 "for listen port %d", rfwd->listen_port);
1958 }
1959 }
1960 forwarding_success();
1961}
1962
1963static void
1964client_cleanup_stdio_fwd(struct ssh *ssh, int id, int force, void *arg)
1965{
1966 debug("stdio forwarding: done");
1967 cleanup_exit(0);
1968}
1969
1970static void
1971ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1972{
1973 if (!success)
1974 fatal("stdio forwarding failed");
1975}
1976
1977static void
1978ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1979{
1980 if (!success) {
1981 error("Tunnel forwarding failed");
1982 if (options.exit_on_forward_failure)
1983 cleanup_exit(255);
1984 }
1985
1986 debug_f("tunnel forward established, id=%d", id);
1987 forwarding_success();
1988}
1989
1990static void
1991ssh_init_stdio_forwarding(struct ssh *ssh)
1992{
1993 Channel *c;
1994 int in, out;
1995
1996 if (options.stdio_forward_host == NULL)
1997 return;
1998
1999 debug3_f("%s:%d", options.stdio_forward_host,
2000 options.stdio_forward_port);
2001
2002 if ((in = dup(STDIN_FILENO)) == -1 ||
2003 (out = dup(STDOUT_FILENO)) == -1)
2004 fatal_f("dup() in/out failed");
2005 if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
2006 options.stdio_forward_port, in, out,
2007 CHANNEL_NONBLOCK_STDIO)) == NULL)
2008 fatal_f("channel_connect_stdio_fwd failed");
2009 channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
2010 channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
2011}
2012
2013static void
2014ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
2015 u_int num_opens)
2016{
2017 u_int i;
2018 int port;
2019 char *addr, *arg, *oarg;
2020 int where = FORWARD_LOCAL;
2021
2022 channel_clear_permission(ssh, FORWARD_ADM, where);
2023 if (num_opens == 0)
2024 return; /* permit any */
2025
2026 /* handle keywords: "any" / "none" */
2027 if (num_opens == 1 && strcmp(opens[0], "any") == 0)
2028 return;
2029 if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
2030 channel_disable_admin(ssh, where);
2031 return;
2032 }
2033 /* Otherwise treat it as a list of permitted host:port */
2034 for (i = 0; i < num_opens; i++) {
2035 oarg = arg = xstrdup(opens[i]);
2036 addr = hpdelim(&arg);
2037 if (addr == NULL)
2038 fatal_f("missing host in %s", what);
2039 addr = cleanhostname(addr);
2040 if (arg == NULL || ((port = permitopen_port(arg)) < 0))
2041 fatal_f("bad port number in %s", what);
2042 /* Send it to channels layer */
2043 channel_add_permission(ssh, FORWARD_ADM,
2044 where, addr, port);
2045 free(oarg);
2046 }
2047}
2048
2049static void
2050ssh_init_forwarding(struct ssh *ssh, char **ifname)
2051{
2052 int success = 0;
2053 int i;
2054
2055 ssh_init_forward_permissions(ssh, "permitremoteopen",
2056 options.permitted_remote_opens,
2057 options.num_permitted_remote_opens);
2058
2059 if (options.exit_on_forward_failure)
2060 forward_confirms_pending = 0; /* track pending requests */
2061 /* Initiate local TCP/IP port forwardings. */
2062 for (i = 0; i < options.num_local_forwards; i++) {
2063 debug("Local connections to %.200s:%d forwarded to remote "
2064 "address %.200s:%d",
2065 (options.local_forwards[i].listen_path != NULL) ?
2066 options.local_forwards[i].listen_path :
2067 (options.local_forwards[i].listen_host == NULL) ?
2068 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
2069 options.local_forwards[i].listen_host,
2070 options.local_forwards[i].listen_port,
2071 (options.local_forwards[i].connect_path != NULL) ?
2072 options.local_forwards[i].connect_path :
2073 options.local_forwards[i].connect_host,
2074 options.local_forwards[i].connect_port);
2075 success += channel_setup_local_fwd_listener(ssh,
2076 &options.local_forwards[i], &options.fwd_opts);
2077 }
2078 if (i > 0 && success != i && options.exit_on_forward_failure)
2079 fatal("Could not request local forwarding.");
2080 if (i > 0 && success == 0)
2081 error("Could not request local forwarding.");
2082
2083 /* Initiate remote TCP/IP port forwardings. */
2084 for (i = 0; i < options.num_remote_forwards; i++) {
2085 debug("Remote connections from %.200s:%d forwarded to "
2086 "local address %.200s:%d",
2087 (options.remote_forwards[i].listen_path != NULL) ?
2088 options.remote_forwards[i].listen_path :
2089 (options.remote_forwards[i].listen_host == NULL) ?
2090 "LOCALHOST" : options.remote_forwards[i].listen_host,
2091 options.remote_forwards[i].listen_port,
2092 (options.remote_forwards[i].connect_path != NULL) ?
2093 options.remote_forwards[i].connect_path :
2094 options.remote_forwards[i].connect_host,
2095 options.remote_forwards[i].connect_port);
2096 if ((options.remote_forwards[i].handle =
2097 channel_request_remote_forwarding(ssh,
2098 &options.remote_forwards[i])) >= 0) {
2099 client_register_global_confirm(
2100 ssh_confirm_remote_forward,
2101 &options.remote_forwards[i]);
2102 forward_confirms_pending++;
2103 } else if (options.exit_on_forward_failure)
2104 fatal("Could not request remote forwarding.");
2105 else
2106 logit("Warning: Could not request remote forwarding.");
2107 }
2108
2109 /* Initiate tunnel forwarding. */
2110 if (options.tun_open != SSH_TUNMODE_NO) {
2111 if ((*ifname = client_request_tun_fwd(ssh,
2112 options.tun_open, options.tun_local,
2113 options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
2114 forward_confirms_pending++;
2115 else if (options.exit_on_forward_failure)
2116 fatal("Could not request tunnel forwarding.");
2117 else
2118 error("Could not request tunnel forwarding.");
2119 }
2120 if (forward_confirms_pending > 0) {
2121 debug_f("expecting replies for %d forwards",
2122 forward_confirms_pending);
2123 }
2124}
2125
2126static void
2127check_agent_present(void)
2128{
2129 int r;
2130
2131 if (options.forward_agent) {
2132 /* Clear agent forwarding if we don't have an agent. */
2133 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
2134 options.forward_agent = 0;
2135 if (r != SSH_ERR_AGENT_NOT_PRESENT)
2136 debug_r(r, "ssh_get_authentication_socket");
2137 }
2138 }
2139}
2140
2141static void
2142ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
2143{
2144 extern char **environ;
2145 const char *display, *term;
2146 char *proto = NULL, *data = NULL;
2147
2148 if (!success)
2149 return; /* No need for error message, channels code sends one */
2150
2151 display = getenv("DISPLAY");
2152 if (display == NULL && options.forward_x11)
2153 debug("X11 forwarding requested but DISPLAY not set");
2154 if (options.forward_x11 && client_x11_get_proto(ssh, display,
2155 options.xauth_location, options.forward_x11_trusted,
2156 options.forward_x11_timeout, &proto, &data) == 0) {
2157 /* Request forwarding with authentication spoofing. */
2158 debug("Requesting X11 forwarding with authentication "
2159 "spoofing.");
2160 x11_request_forwarding_with_spoofing(ssh, id, display, proto,
2161 data, 1);
2162 client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
2163 /* XXX exit_on_forward_failure */
2164 }
2165
2166 check_agent_present();
2167 if (options.forward_agent)
2168 client_channel_reqest_agent_forwarding(ssh, id);
2169
2170 if ((term = lookup_env_in_list("TERM", options.setenv,
2171 options.num_setenv)) == NULL || *term == '\0')
2172 term = getenv("TERM");
2173 client_session2_setup(ssh, id, tty_flag,
2174 options.session_type == SESSION_TYPE_SUBSYSTEM, term,
2175 NULL, fileno(stdin), command, environ);
2176}
2177
2178/* open new channel for a session */
2179static int
2180ssh_session2_open(struct ssh *ssh)
2181{
2182 Channel *c;
2183 int window, packetmax, in, out, err;
2184
2185 if (options.stdin_null) {
2186 in = open(_PATH_DEVNULL, O_RDONLY);
2187 } else {
2188 in = dup(STDIN_FILENO);
2189 }
2190 out = dup(STDOUT_FILENO);
2191 err = dup(STDERR_FILENO);
2192
2193 if (in == -1 || out == -1 || err == -1)
2194 fatal("dup() in/out/err failed");
2195
2196 window = CHAN_SES_WINDOW_DEFAULT;
2197 packetmax = CHAN_SES_PACKET_DEFAULT;
2198 if (tty_flag) {
2199 window >>= 1;
2200 packetmax >>= 1;
2201 }
2202 c = channel_new(ssh,
2203 "session", SSH_CHANNEL_OPENING, in, out, err,
2204 window, packetmax, CHAN_EXTENDED_WRITE,
2205 "client-session", CHANNEL_NONBLOCK_STDIO);
2206 if (tty_flag)
2207 channel_set_tty(ssh, c);
2208 debug3_f("channel_new: %d%s", c->self, tty_flag ? " (tty)" : "");
2209
2210 channel_send_open(ssh, c->self);
2211 if (options.session_type != SESSION_TYPE_NONE)
2212 channel_register_open_confirm(ssh, c->self,
2213 ssh_session2_setup, NULL);
2214
2215 return c->self;
2216}
2217
2218static int
2219ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2220{
2221 int r, id = -1;
2222 char *cp, *tun_fwd_ifname = NULL;
2223
2224 /* XXX should be pre-session */
2225 if (!options.control_persist)
2226 ssh_init_stdio_forwarding(ssh);
2227
2228 ssh_init_forwarding(ssh, &tun_fwd_ifname);
2229
2230 if (options.local_command != NULL) {
2231 debug3("expanding LocalCommand: %s", options.local_command);
2232 cp = options.local_command;
2233 options.local_command = percent_expand(cp,
2234 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2235 "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2236 (char *)NULL);
2237 debug3("expanded LocalCommand: %s", options.local_command);
2238 free(cp);
2239 }
2240
2241 /* Start listening for multiplex clients */
2242 if (!ssh_packet_get_mux(ssh))
2243 muxserver_listen(ssh);
2244
2245 /*
2246 * If we are in control persist mode and have a working mux listen
2247 * socket, then prepare to background ourselves and have a foreground
2248 * client attach as a control client.
2249 * NB. we must save copies of the flags that we override for
2250 * the backgrounding, since we defer attachment of the client until
2251 * after the connection is fully established (in particular,
2252 * async rfwd replies have been received for ExitOnForwardFailure).
2253 */
2254 if (options.control_persist && muxserver_sock != -1) {
2255 ostdin_null_flag = options.stdin_null;
2256 osession_type = options.session_type;
2257 orequest_tty = options.request_tty;
2258 otty_flag = tty_flag;
2259 ofork_after_authentication = options.fork_after_authentication;
2260 options.stdin_null = 1;
2261 options.session_type = SESSION_TYPE_NONE;
2262 tty_flag = 0;
2263 if ((osession_type != SESSION_TYPE_NONE ||
2264 options.stdio_forward_host != NULL))
2265 need_controlpersist_detach = 1;
2266 options.fork_after_authentication = 1;
2267 }
2268 /*
2269 * ControlPersist mux listen socket setup failed, attempt the
2270 * stdio forward setup that we skipped earlier.
2271 */
2272 if (options.control_persist && muxserver_sock == -1)
2273 ssh_init_stdio_forwarding(ssh);
2274
2275 if (options.session_type != SESSION_TYPE_NONE)
2276 id = ssh_session2_open(ssh);
2277
2278 /* If we don't expect to open a new session, then disallow it */
2279 if (options.control_master == SSHCTL_MASTER_NO &&
2280 (ssh->compat & SSH_NEW_OPENSSH)) {
2281 debug("Requesting no-more-sessions@openssh.com");
2282 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2283 (r = sshpkt_put_cstring(ssh,
2284 "no-more-sessions@openssh.com")) != 0 ||
2285 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2286 (r = sshpkt_send(ssh)) != 0)
2287 fatal_fr(r, "send packet");
2288 }
2289
2290 /* Execute a local command */
2291 if (options.local_command != NULL &&
2292 options.permit_local_command)
2293 ssh_local_cmd(options.local_command);
2294
2295 /*
2296 * stdout is now owned by the session channel; clobber it here
2297 * so future channel closes are propagated to the local fd.
2298 * NB. this can only happen after LocalCommand has completed,
2299 * as it may want to write to stdout.
2300 */
2301 if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2302 error_f("stdfd_devnull failed");
2303
2304 /*
2305 * If requested and we are not interested in replies to remote
2306 * forwarding requests, then let ssh continue in the background.
2307 */
2308 if (options.fork_after_authentication) {
2309 if (options.exit_on_forward_failure &&
2310 options.num_remote_forwards > 0) {
2311 debug("deferring postauth fork until remote forward "
2312 "confirmation received");
2313 } else
2314 fork_postauth();
2315 }
2316
2317 return client_loop(ssh, tty_flag, tty_flag ?
2318 options.escape_char : SSH_ESCAPECHAR_NONE, id);
2319}
2320
2321/* Loads all IdentityFile and CertificateFile keys */
2322static void
2323load_public_identity_files(const struct ssh_conn_info *cinfo)
2324{
2325 char *filename, *cp;
2326 struct sshkey *public;
2327 int i;
2328 u_int n_ids, n_certs;
2329 char *identity_files[SSH_MAX_IDENTITY_FILES];
2330 struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2331 int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2332 char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2333 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2334 int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2335#ifdef ENABLE_PKCS11
2336 struct sshkey **keys = NULL;
2337 char **comments = NULL;
2338 int nkeys;
2339#endif /* PKCS11 */
2340
2341 n_ids = n_certs = 0;
2342 memset(identity_files, 0, sizeof(identity_files));
2343 memset(identity_keys, 0, sizeof(identity_keys));
2344 memset(identity_file_userprovided, 0,
2345 sizeof(identity_file_userprovided));
2346 memset(certificate_files, 0, sizeof(certificate_files));
2347 memset(certificates, 0, sizeof(certificates));
2348 memset(certificate_file_userprovided, 0,
2349 sizeof(certificate_file_userprovided));
2350
2351#ifdef ENABLE_PKCS11
2352 if (options.pkcs11_provider != NULL &&
2353 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2354 (pkcs11_init(!options.batch_mode) == 0) &&
2355 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2356 &keys, &comments)) > 0) {
2357 for (i = 0; i < nkeys; i++) {
2358 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2359 sshkey_free(keys[i]);
2360 free(comments[i]);
2361 continue;
2362 }
2363 identity_keys[n_ids] = keys[i];
2364 identity_files[n_ids] = comments[i]; /* transferred */
2365 n_ids++;
2366 }
2367 free(keys);
2368 free(comments);
2369 }
2370#endif /* ENABLE_PKCS11 */
2371 for (i = 0; i < options.num_identity_files; i++) {
2372 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2373 strcasecmp(options.identity_files[i], "none") == 0) {
2374 free(options.identity_files[i]);
2375 options.identity_files[i] = NULL;
2376 continue;
2377 }
2378 cp = tilde_expand_filename(options.identity_files[i], getuid());
2379 filename = default_client_percent_dollar_expand(cp, cinfo);
2380 free(cp);
2381 check_load(sshkey_load_public(filename, &public, NULL),
2382 &public, filename, "pubkey");
2383 debug("identity file %s type %d", filename,
2384 public ? public->type : -1);
2385 free(options.identity_files[i]);
2386 identity_files[n_ids] = filename;
2387 identity_keys[n_ids] = public;
2388 identity_file_userprovided[n_ids] =
2389 options.identity_file_userprovided[i];
2390 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2391 continue;
2392
2393 /*
2394 * If no certificates have been explicitly listed then try
2395 * to add the default certificate variant too.
2396 */
2397 if (options.num_certificate_files != 0)
2398 continue;
2399 xasprintf(&cp, "%s-cert", filename);
2400 check_load(sshkey_load_public(cp, &public, NULL),
2401 &public, filename, "identity pubkey");
2402 if (public == NULL) {
2403 free(cp);
2404 continue;
2405 }
2406 if (!sshkey_is_cert(public)) {
2407 debug_f("key %s type %s is not a certificate",
2408 cp, sshkey_type(public));
2409 sshkey_free(public);
2410 free(cp);
2411 continue;
2412 }
2413 free(cp);
2414 /* NB. leave filename pointing to private key */
2415 identity_files[n_ids] = xstrdup(filename);
2416 identity_keys[n_ids] = public;
2417 identity_file_userprovided[n_ids] =
2418 options.identity_file_userprovided[i];
2419 n_ids++;
2420 }
2421
2422 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2423 fatal_f("too many certificates");
2424 for (i = 0; i < options.num_certificate_files; i++) {
2425 cp = tilde_expand_filename(options.certificate_files[i],
2426 getuid());
2427 filename = default_client_percent_dollar_expand(cp, cinfo);
2428 free(cp);
2429
2430 check_load(sshkey_load_public(filename, &public, NULL),
2431 &public, filename, "identity cert");
2432 free(options.certificate_files[i]);
2433 options.certificate_files[i] = NULL;
2434 if (public == NULL) {
2435 free(filename);
2436 continue;
2437 }
2438 if (!sshkey_is_cert(public)) {
2439 debug_f("key %s type %s is not a certificate",
2440 filename, sshkey_type(public));
2441 sshkey_free(public);
2442 free(filename);
2443 continue;
2444 }
2445 certificate_files[n_certs] = filename;
2446 certificates[n_certs] = public;
2447 certificate_file_userprovided[n_certs] =
2448 options.certificate_file_userprovided[i];
2449 ++n_certs;
2450 }
2451
2452 options.num_identity_files = n_ids;
2453 memcpy(options.identity_files, identity_files, sizeof(identity_files));
2454 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2455 memcpy(options.identity_file_userprovided,
2456 identity_file_userprovided, sizeof(identity_file_userprovided));
2457
2458 options.num_certificate_files = n_certs;
2459 memcpy(options.certificate_files,
2460 certificate_files, sizeof(certificate_files));
2461 memcpy(options.certificates, certificates, sizeof(certificates));
2462 memcpy(options.certificate_file_userprovided,
2463 certificate_file_userprovided,
2464 sizeof(certificate_file_userprovided));
2465}
2466
2467static void
2468main_sigchld_handler(int sig)
2469{
2470 int save_errno = errno;
2471 pid_t pid;
2472 int status;
2473
2474 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2475 (pid == -1 && errno == EINTR))
2476 ;
2477 errno = save_errno;
2478}