Import OpenSSH-6.7p1.
[dragonfly.git] / crypto / openssh / ssh.c
blob26e9681b70008556e3750f3998aa3008961973e0
1 /* $OpenBSD: ssh.c,v 1.407 2014/07/17 07:22:19 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.
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".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
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.
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.
43 #include "includes.h"
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/param.h>
52 #include <sys/socket.h>
53 #include <sys/wait.h>
55 #include <ctype.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <netdb.h>
59 #ifdef HAVE_PATHS_H
60 #include <paths.h>
61 #endif
62 #include <pwd.h>
63 #include <signal.h>
64 #include <stdarg.h>
65 #include <stddef.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
71 #include <netinet/in.h>
72 #include <arpa/inet.h>
74 #ifdef WITH_OPENSSL
75 #include <openssl/evp.h>
76 #include <openssl/err.h>
77 #endif
78 #include "openbsd-compat/openssl-compat.h"
79 #include "openbsd-compat/sys-queue.h"
81 #include "xmalloc.h"
82 #include "ssh.h"
83 #include "ssh1.h"
84 #include "ssh2.h"
85 #include "canohost.h"
86 #include "compat.h"
87 #include "cipher.h"
88 #include "digest.h"
89 #include "packet.h"
90 #include "buffer.h"
91 #include "channels.h"
92 #include "key.h"
93 #include "authfd.h"
94 #include "authfile.h"
95 #include "pathnames.h"
96 #include "dispatch.h"
97 #include "clientloop.h"
98 #include "log.h"
99 #include "misc.h"
100 #include "readconf.h"
101 #include "sshconnect.h"
102 #include "kex.h"
103 #include "mac.h"
104 #include "sshpty.h"
105 #include "match.h"
106 #include "msg.h"
107 #include "uidswap.h"
108 #include "roaming.h"
109 #include "version.h"
111 #ifdef ENABLE_PKCS11
112 #include "ssh-pkcs11.h"
113 #endif
115 extern char *__progname;
117 /* Saves a copy of argv for setproctitle emulation */
118 #ifndef HAVE_SETPROCTITLE
119 static char **saved_av;
120 #endif
122 /* Flag indicating whether debug mode is on. May be set on the command line. */
123 int debug_flag = 0;
125 /* Flag indicating whether a tty should be requested */
126 int tty_flag = 0;
128 /* don't exec a shell */
129 int no_shell_flag = 0;
132 * Flag indicating that nothing should be read from stdin. This can be set
133 * on the command line.
135 int stdin_null_flag = 0;
138 * Flag indicating that the current process should be backgrounded and
139 * a new slave launched in the foreground for ControlPersist.
141 int need_controlpersist_detach = 0;
143 /* Copies of flags for ControlPersist foreground slave */
144 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
147 * Flag indicating that ssh should fork after authentication. This is useful
148 * so that the passphrase can be entered manually, and then ssh goes to the
149 * background.
151 int fork_after_authentication_flag = 0;
153 /* forward stdio to remote host and port */
154 char *stdio_forward_host = NULL;
155 int stdio_forward_port = 0;
158 * General data structure for command line options and options configurable
159 * in configuration files. See readconf.h.
161 Options options;
163 /* optional user configfile */
164 char *config = NULL;
167 * Name of the host we are connecting to. This is the name given on the
168 * command line, or the HostName specified for the user-supplied name in a
169 * configuration file.
171 char *host;
173 /* socket address the host resolves to */
174 struct sockaddr_storage hostaddr;
176 /* Private host keys. */
177 Sensitive sensitive_data;
179 /* Original real UID. */
180 uid_t original_real_uid;
181 uid_t original_effective_uid;
183 /* command to be executed */
184 Buffer command;
186 /* Should we execute a command or invoke a subsystem? */
187 int subsystem_flag = 0;
189 /* # of replies received for global requests */
190 static int remote_forward_confirms_received = 0;
192 /* mux.c */
193 extern int muxserver_sock;
194 extern u_int muxclient_command;
196 /* Prints a help message to the user. This function never returns. */
198 static void
199 usage(void)
201 fprintf(stderr,
202 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
203 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
204 " [-F configfile] [-I pkcs11] [-i identity_file]\n"
205 " [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]\n"
206 " [-O ctl_cmd] [-o option] [-p port]\n"
207 " [-Q cipher | cipher-auth | mac | kex | key]\n"
208 " [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]\n"
209 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
211 exit(255);
214 static int ssh_session(void);
215 static int ssh_session2(void);
216 static void load_public_identity_files(void);
217 static void main_sigchld_handler(int);
219 /* from muxclient.c */
220 void muxclient(const char *);
221 void muxserver_listen(void);
223 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
224 static void
225 tilde_expand_paths(char **paths, u_int num_paths)
227 u_int i;
228 char *cp;
230 for (i = 0; i < num_paths; i++) {
231 cp = tilde_expand_filename(paths[i], original_real_uid);
232 free(paths[i]);
233 paths[i] = cp;
238 * Attempt to resolve a host name / port to a set of addresses and
239 * optionally return any CNAMEs encountered along the way.
240 * Returns NULL on failure.
241 * NB. this function must operate with a options having undefined members.
243 static struct addrinfo *
244 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
246 char strport[NI_MAXSERV];
247 struct addrinfo hints, *res;
248 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
250 if (port <= 0)
251 port = default_ssh_port();
253 snprintf(strport, sizeof strport, "%u", port);
254 memset(&hints, 0, sizeof(hints));
255 hints.ai_family = options.address_family == -1 ?
256 AF_UNSPEC : options.address_family;
257 hints.ai_socktype = SOCK_STREAM;
258 if (cname != NULL)
259 hints.ai_flags = AI_CANONNAME;
260 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
261 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
262 loglevel = SYSLOG_LEVEL_ERROR;
263 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
264 __progname, name, ssh_gai_strerror(gaierr));
265 return NULL;
267 if (cname != NULL && res->ai_canonname != NULL) {
268 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
269 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
270 __func__, name, res->ai_canonname, (u_long)clen);
271 if (clen > 0)
272 *cname = '\0';
275 return res;
279 * Check whether the cname is a permitted replacement for the hostname
280 * and perform the replacement if it is.
281 * NB. this function must operate with a options having undefined members.
283 static int
284 check_follow_cname(char **namep, const char *cname)
286 int i;
287 struct allowed_cname *rule;
289 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
290 strcmp(*namep, cname) == 0)
291 return 0;
292 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
293 return 0;
295 * Don't attempt to canonicalize names that will be interpreted by
296 * a proxy unless the user specifically requests so.
298 if (!option_clear_or_none(options.proxy_command) &&
299 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
300 return 0;
301 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
302 for (i = 0; i < options.num_permitted_cnames; i++) {
303 rule = options.permitted_cnames + i;
304 if (match_pattern_list(*namep, rule->source_list,
305 strlen(rule->source_list), 1) != 1 ||
306 match_pattern_list(cname, rule->target_list,
307 strlen(rule->target_list), 1) != 1)
308 continue;
309 verbose("Canonicalized DNS aliased hostname "
310 "\"%s\" => \"%s\"", *namep, cname);
311 free(*namep);
312 *namep = xstrdup(cname);
313 return 1;
315 return 0;
319 * Attempt to resolve the supplied hostname after applying the user's
320 * canonicalization rules. Returns the address list for the host or NULL
321 * if no name was found after canonicalization.
322 * NB. this function must operate with a options having undefined members.
324 static struct addrinfo *
325 resolve_canonicalize(char **hostp, int port)
327 int i, ndots;
328 char *cp, *fullhost, cname_target[NI_MAXHOST];
329 struct addrinfo *addrs;
331 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
332 return NULL;
335 * Don't attempt to canonicalize names that will be interpreted by
336 * a proxy unless the user specifically requests so.
338 if (!option_clear_or_none(options.proxy_command) &&
339 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
340 return NULL;
342 /* Don't apply canonicalization to sufficiently-qualified hostnames */
343 ndots = 0;
344 for (cp = *hostp; *cp != '\0'; cp++) {
345 if (*cp == '.')
346 ndots++;
348 if (ndots > options.canonicalize_max_dots) {
349 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
350 __func__, *hostp, options.canonicalize_max_dots);
351 return NULL;
353 /* Attempt each supplied suffix */
354 for (i = 0; i < options.num_canonical_domains; i++) {
355 *cname_target = '\0';
356 xasprintf(&fullhost, "%s.%s.", *hostp,
357 options.canonical_domains[i]);
358 debug3("%s: attempting \"%s\" => \"%s\"", __func__,
359 *hostp, fullhost);
360 if ((addrs = resolve_host(fullhost, port, 0,
361 cname_target, sizeof(cname_target))) == NULL) {
362 free(fullhost);
363 continue;
365 /* Remove trailing '.' */
366 fullhost[strlen(fullhost) - 1] = '\0';
367 /* Follow CNAME if requested */
368 if (!check_follow_cname(&fullhost, cname_target)) {
369 debug("Canonicalized hostname \"%s\" => \"%s\"",
370 *hostp, fullhost);
372 free(*hostp);
373 *hostp = fullhost;
374 return addrs;
376 if (!options.canonicalize_fallback_local)
377 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
378 debug2("%s: host %s not found in any suffix", __func__, *hostp);
379 return NULL;
383 * Read per-user configuration file. Ignore the system wide config
384 * file if the user specifies a config file on the command line.
386 static void
387 process_config_files(struct passwd *pw)
389 char buf[MAXPATHLEN];
390 int r;
392 if (config != NULL) {
393 if (strcasecmp(config, "none") != 0 &&
394 !read_config_file(config, pw, host, &options,
395 SSHCONF_USERCONF))
396 fatal("Can't open user config file %.100s: "
397 "%.100s", config, strerror(errno));
398 } else {
399 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
400 _PATH_SSH_USER_CONFFILE);
401 if (r > 0 && (size_t)r < sizeof(buf))
402 (void)read_config_file(buf, pw, host, &options,
403 SSHCONF_CHECKPERM|SSHCONF_USERCONF);
405 /* Read systemwide configuration file after user config. */
406 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host,
407 &options, 0);
412 * Main program for the ssh client.
415 main(int ac, char **av)
417 int i, r, opt, exit_status, use_syslog;
418 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile;
419 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
420 char cname[NI_MAXHOST];
421 struct stat st;
422 struct passwd *pw;
423 int timeout_ms;
424 extern int optind, optreset;
425 extern char *optarg;
426 struct Forward fwd;
427 struct addrinfo *addrs = NULL;
428 struct ssh_digest_ctx *md;
429 u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
430 char *conn_hash_hex;
432 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
433 sanitise_stdfd();
435 __progname = ssh_get_progname(av[0]);
437 #ifndef HAVE_SETPROCTITLE
438 /* Prepare for later setproctitle emulation */
439 /* Save argv so it isn't clobbered by setproctitle() emulation */
440 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
441 for (i = 0; i < ac; i++)
442 saved_av[i] = xstrdup(av[i]);
443 saved_av[i] = NULL;
444 compat_init_setproctitle(ac, av);
445 av = saved_av;
446 #endif
449 * Discard other fds that are hanging around. These can cause problem
450 * with backgrounded ssh processes started by ControlPersist.
452 closefrom(STDERR_FILENO + 1);
455 * Save the original real uid. It will be needed later (uid-swapping
456 * may clobber the real uid).
458 original_real_uid = getuid();
459 original_effective_uid = geteuid();
462 * Use uid-swapping to give up root privileges for the duration of
463 * option processing. We will re-instantiate the rights when we are
464 * ready to create the privileged port, and will permanently drop
465 * them when the port has been created (actually, when the connection
466 * has been made, as we may need to create the port several times).
468 PRIV_END;
470 #ifdef HAVE_SETRLIMIT
471 /* If we are installed setuid root be careful to not drop core. */
472 if (original_real_uid != original_effective_uid) {
473 struct rlimit rlim;
474 rlim.rlim_cur = rlim.rlim_max = 0;
475 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
476 fatal("setrlimit failed: %.100s", strerror(errno));
478 #endif
479 /* Get user data. */
480 pw = getpwuid(original_real_uid);
481 if (!pw) {
482 logit("No user exists for uid %lu", (u_long)original_real_uid);
483 exit(255);
485 /* Take a copy of the returned structure. */
486 pw = pwcopy(pw);
489 * Set our umask to something reasonable, as some files are created
490 * with the default umask. This will make them world-readable but
491 * writable only by the owner, which is ok for all files for which we
492 * don't set the modes explicitly.
494 umask(022);
497 * Initialize option structure to indicate that no values have been
498 * set.
500 initialize_options(&options);
502 /* Parse command-line arguments. */
503 host = NULL;
504 use_syslog = 0;
505 logfile = NULL;
506 argv0 = av[0];
508 again:
509 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
510 "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
511 switch (opt) {
512 case '1':
513 options.protocol = SSH_PROTO_1;
514 break;
515 case '2':
516 options.protocol = SSH_PROTO_2;
517 break;
518 case '4':
519 options.address_family = AF_INET;
520 break;
521 case '6':
522 options.address_family = AF_INET6;
523 break;
524 case 'n':
525 stdin_null_flag = 1;
526 break;
527 case 'f':
528 fork_after_authentication_flag = 1;
529 stdin_null_flag = 1;
530 break;
531 case 'x':
532 options.forward_x11 = 0;
533 break;
534 case 'X':
535 options.forward_x11 = 1;
536 break;
537 case 'y':
538 use_syslog = 1;
539 break;
540 case 'E':
541 logfile = xstrdup(optarg);
542 break;
543 case 'Y':
544 options.forward_x11 = 1;
545 options.forward_x11_trusted = 1;
546 break;
547 case 'g':
548 options.fwd_opts.gateway_ports = 1;
549 break;
550 case 'O':
551 if (stdio_forward_host != NULL)
552 fatal("Cannot specify multiplexing "
553 "command with -W");
554 else if (muxclient_command != 0)
555 fatal("Multiplexing command already specified");
556 if (strcmp(optarg, "check") == 0)
557 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
558 else if (strcmp(optarg, "forward") == 0)
559 muxclient_command = SSHMUX_COMMAND_FORWARD;
560 else if (strcmp(optarg, "exit") == 0)
561 muxclient_command = SSHMUX_COMMAND_TERMINATE;
562 else if (strcmp(optarg, "stop") == 0)
563 muxclient_command = SSHMUX_COMMAND_STOP;
564 else if (strcmp(optarg, "cancel") == 0)
565 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
566 else
567 fatal("Invalid multiplex command.");
568 break;
569 case 'P': /* deprecated */
570 options.use_privileged_port = 0;
571 break;
572 case 'Q':
573 cp = NULL;
574 if (strcmp(optarg, "cipher") == 0)
575 cp = cipher_alg_list('\n', 0);
576 else if (strcmp(optarg, "cipher-auth") == 0)
577 cp = cipher_alg_list('\n', 1);
578 else if (strcmp(optarg, "mac") == 0)
579 cp = mac_alg_list('\n');
580 else if (strcmp(optarg, "kex") == 0)
581 cp = kex_alg_list('\n');
582 else if (strcmp(optarg, "key") == 0)
583 cp = key_alg_list(0, 0);
584 else if (strcmp(optarg, "key-cert") == 0)
585 cp = key_alg_list(1, 0);
586 else if (strcmp(optarg, "key-plain") == 0)
587 cp = key_alg_list(0, 1);
588 if (cp == NULL)
589 fatal("Unsupported query \"%s\"", optarg);
590 printf("%s\n", cp);
591 free(cp);
592 exit(0);
593 break;
594 case 'a':
595 options.forward_agent = 0;
596 break;
597 case 'A':
598 options.forward_agent = 1;
599 break;
600 case 'k':
601 options.gss_deleg_creds = 0;
602 break;
603 case 'K':
604 options.gss_authentication = 1;
605 options.gss_deleg_creds = 1;
606 break;
607 case 'i':
608 if (stat(optarg, &st) < 0) {
609 fprintf(stderr, "Warning: Identity file %s "
610 "not accessible: %s.\n", optarg,
611 strerror(errno));
612 break;
614 add_identity_file(&options, NULL, optarg, 1);
615 break;
616 case 'I':
617 #ifdef ENABLE_PKCS11
618 options.pkcs11_provider = xstrdup(optarg);
619 #else
620 fprintf(stderr, "no support for PKCS#11.\n");
621 #endif
622 break;
623 case 't':
624 if (options.request_tty == REQUEST_TTY_YES)
625 options.request_tty = REQUEST_TTY_FORCE;
626 else
627 options.request_tty = REQUEST_TTY_YES;
628 break;
629 case 'v':
630 if (debug_flag == 0) {
631 debug_flag = 1;
632 options.log_level = SYSLOG_LEVEL_DEBUG1;
633 } else {
634 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
635 options.log_level++;
637 break;
638 case 'V':
639 fprintf(stderr, "%s, %s\n",
640 SSH_RELEASE,
641 #ifdef WITH_OPENSSL
642 SSLeay_version(SSLEAY_VERSION)
643 #else
644 "without OpenSSL"
645 #endif
647 if (opt == 'V')
648 exit(0);
649 break;
650 case 'w':
651 if (options.tun_open == -1)
652 options.tun_open = SSH_TUNMODE_DEFAULT;
653 options.tun_local = a2tun(optarg, &options.tun_remote);
654 if (options.tun_local == SSH_TUNID_ERR) {
655 fprintf(stderr,
656 "Bad tun device '%s'\n", optarg);
657 exit(255);
659 break;
660 case 'W':
661 if (stdio_forward_host != NULL)
662 fatal("stdio forward already specified");
663 if (muxclient_command != 0)
664 fatal("Cannot specify stdio forward with -O");
665 if (parse_forward(&fwd, optarg, 1, 0)) {
666 stdio_forward_host = fwd.listen_host;
667 stdio_forward_port = fwd.listen_port;
668 free(fwd.connect_host);
669 } else {
670 fprintf(stderr,
671 "Bad stdio forwarding specification '%s'\n",
672 optarg);
673 exit(255);
675 options.request_tty = REQUEST_TTY_NO;
676 no_shell_flag = 1;
677 options.clear_forwardings = 1;
678 options.exit_on_forward_failure = 1;
679 break;
680 case 'q':
681 options.log_level = SYSLOG_LEVEL_QUIET;
682 break;
683 case 'e':
684 if (optarg[0] == '^' && optarg[2] == 0 &&
685 (u_char) optarg[1] >= 64 &&
686 (u_char) optarg[1] < 128)
687 options.escape_char = (u_char) optarg[1] & 31;
688 else if (strlen(optarg) == 1)
689 options.escape_char = (u_char) optarg[0];
690 else if (strcmp(optarg, "none") == 0)
691 options.escape_char = SSH_ESCAPECHAR_NONE;
692 else {
693 fprintf(stderr, "Bad escape character '%s'.\n",
694 optarg);
695 exit(255);
697 break;
698 case 'c':
699 if (ciphers_valid(optarg)) {
700 /* SSH2 only */
701 options.ciphers = xstrdup(optarg);
702 options.cipher = SSH_CIPHER_INVALID;
703 } else {
704 /* SSH1 only */
705 options.cipher = cipher_number(optarg);
706 if (options.cipher == -1) {
707 fprintf(stderr,
708 "Unknown cipher type '%s'\n",
709 optarg);
710 exit(255);
712 if (options.cipher == SSH_CIPHER_3DES)
713 options.ciphers = "3des-cbc";
714 else if (options.cipher == SSH_CIPHER_BLOWFISH)
715 options.ciphers = "blowfish-cbc";
716 else
717 options.ciphers = (char *)-1;
719 break;
720 case 'm':
721 if (mac_valid(optarg))
722 options.macs = xstrdup(optarg);
723 else {
724 fprintf(stderr, "Unknown mac type '%s'\n",
725 optarg);
726 exit(255);
728 break;
729 case 'M':
730 if (options.control_master == SSHCTL_MASTER_YES)
731 options.control_master = SSHCTL_MASTER_ASK;
732 else
733 options.control_master = SSHCTL_MASTER_YES;
734 break;
735 case 'p':
736 options.port = a2port(optarg);
737 if (options.port <= 0) {
738 fprintf(stderr, "Bad port '%s'\n", optarg);
739 exit(255);
741 break;
742 case 'l':
743 options.user = optarg;
744 break;
746 case 'L':
747 if (parse_forward(&fwd, optarg, 0, 0))
748 add_local_forward(&options, &fwd);
749 else {
750 fprintf(stderr,
751 "Bad local forwarding specification '%s'\n",
752 optarg);
753 exit(255);
755 break;
757 case 'R':
758 if (parse_forward(&fwd, optarg, 0, 1)) {
759 add_remote_forward(&options, &fwd);
760 } else {
761 fprintf(stderr,
762 "Bad remote forwarding specification "
763 "'%s'\n", optarg);
764 exit(255);
766 break;
768 case 'D':
769 if (parse_forward(&fwd, optarg, 1, 0)) {
770 add_local_forward(&options, &fwd);
771 } else {
772 fprintf(stderr,
773 "Bad dynamic forwarding specification "
774 "'%s'\n", optarg);
775 exit(255);
777 break;
779 case 'C':
780 options.compression = 1;
781 break;
782 case 'N':
783 no_shell_flag = 1;
784 options.request_tty = REQUEST_TTY_NO;
785 break;
786 case 'T':
787 options.request_tty = REQUEST_TTY_NO;
788 break;
789 case 'o':
790 line = xstrdup(optarg);
791 if (process_config_line(&options, pw, host ? host : "",
792 line, "command-line", 0, NULL, SSHCONF_USERCONF)
793 != 0)
794 exit(255);
795 free(line);
796 break;
797 case 's':
798 subsystem_flag = 1;
799 break;
800 case 'S':
801 if (options.control_path != NULL)
802 free(options.control_path);
803 options.control_path = xstrdup(optarg);
804 break;
805 case 'b':
806 options.bind_address = optarg;
807 break;
808 case 'F':
809 config = optarg;
810 break;
811 default:
812 usage();
816 ac -= optind;
817 av += optind;
819 if (ac > 0 && !host) {
820 if (strrchr(*av, '@')) {
821 p = xstrdup(*av);
822 cp = strrchr(p, '@');
823 if (cp == NULL || cp == p)
824 usage();
825 options.user = p;
826 *cp = '\0';
827 host = xstrdup(++cp);
828 } else
829 host = xstrdup(*av);
830 if (ac > 1) {
831 optind = optreset = 1;
832 goto again;
834 ac--, av++;
837 /* Check that we got a host name. */
838 if (!host)
839 usage();
841 host_arg = xstrdup(host);
843 #ifdef WITH_OPENSSL
844 OpenSSL_add_all_algorithms();
845 ERR_load_crypto_strings();
846 #endif
848 /* Initialize the command to execute on remote host. */
849 buffer_init(&command);
852 * Save the command to execute on the remote host in a buffer. There
853 * is no limit on the length of the command, except by the maximum
854 * packet size. Also sets the tty flag if there is no command.
856 if (!ac) {
857 /* No command specified - execute shell on a tty. */
858 if (subsystem_flag) {
859 fprintf(stderr,
860 "You must specify a subsystem to invoke.\n");
861 usage();
863 } else {
864 /* A command has been specified. Store it into the buffer. */
865 for (i = 0; i < ac; i++) {
866 if (i)
867 buffer_append(&command, " ", 1);
868 buffer_append(&command, av[i], strlen(av[i]));
872 /* Cannot fork to background if no command. */
873 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
874 !no_shell_flag)
875 fatal("Cannot fork into background without a command "
876 "to execute.");
879 * Initialize "log" output. Since we are the client all output
880 * goes to stderr unless otherwise specified by -y or -E.
882 if (use_syslog && logfile != NULL)
883 fatal("Can't specify both -y and -E");
884 if (logfile != NULL) {
885 log_redirect_stderr_to(logfile);
886 free(logfile);
888 log_init(argv0,
889 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
890 SYSLOG_FACILITY_USER, !use_syslog);
892 if (debug_flag)
893 logit("%s, %s", SSH_RELEASE,
894 #ifdef WITH_OPENSSL
895 SSLeay_version(SSLEAY_VERSION)
896 #else
897 "without OpenSSL"
898 #endif
901 /* Parse the configuration files */
902 process_config_files(pw);
904 /* Hostname canonicalisation needs a few options filled. */
905 fill_default_options_for_canonicalization(&options);
907 /* If the user has replaced the hostname then take it into use now */
908 if (options.hostname != NULL) {
909 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
910 cp = percent_expand(options.hostname,
911 "h", host, (char *)NULL);
912 free(host);
913 host = cp;
916 /* If canonicalization requested then try to apply it */
917 lowercase(host);
918 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
919 addrs = resolve_canonicalize(&host, options.port);
922 * If CanonicalizePermittedCNAMEs have been specified but
923 * other canonicalization did not happen (by not being requested
924 * or by failing with fallback) then the hostname may still be changed
925 * as a result of CNAME following.
927 * Try to resolve the bare hostname name using the system resolver's
928 * usual search rules and then apply the CNAME follow rules.
930 * Skip the lookup if a ProxyCommand is being used unless the user
931 * has specifically requested canonicalisation for this case via
932 * CanonicalizeHostname=always
934 if (addrs == NULL && options.num_permitted_cnames != 0 &&
935 (option_clear_or_none(options.proxy_command) ||
936 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
937 if ((addrs = resolve_host(host, options.port,
938 option_clear_or_none(options.proxy_command),
939 cname, sizeof(cname))) == NULL) {
940 /* Don't fatal proxied host names not in the DNS */
941 if (option_clear_or_none(options.proxy_command))
942 cleanup_exit(255); /* logged in resolve_host */
943 } else
944 check_follow_cname(&host, cname);
948 * If the target hostname has changed as a result of canonicalisation
949 * then re-parse the configuration files as new stanzas may match.
951 if (strcasecmp(host_arg, host) != 0) {
952 debug("Hostname has changed; re-reading configuration");
953 process_config_files(pw);
956 /* Fill configuration defaults. */
957 fill_default_options(&options);
959 if (options.port == 0)
960 options.port = default_ssh_port();
961 channel_set_af(options.address_family);
963 /* Tidy and check options */
964 if (options.host_key_alias != NULL)
965 lowercase(options.host_key_alias);
966 if (options.proxy_command != NULL &&
967 strcmp(options.proxy_command, "-") == 0 &&
968 options.proxy_use_fdpass)
969 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
970 #ifndef HAVE_CYGWIN
971 if (original_effective_uid != 0)
972 options.use_privileged_port = 0;
973 #endif
975 /* reinit */
976 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
978 if (options.request_tty == REQUEST_TTY_YES ||
979 options.request_tty == REQUEST_TTY_FORCE)
980 tty_flag = 1;
982 /* Allocate a tty by default if no command specified. */
983 if (buffer_len(&command) == 0)
984 tty_flag = options.request_tty != REQUEST_TTY_NO;
986 /* Force no tty */
987 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
988 tty_flag = 0;
989 /* Do not allocate a tty if stdin is not a tty. */
990 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
991 options.request_tty != REQUEST_TTY_FORCE) {
992 if (tty_flag)
993 logit("Pseudo-terminal will not be allocated because "
994 "stdin is not a terminal.");
995 tty_flag = 0;
998 seed_rng();
1000 if (options.user == NULL)
1001 options.user = xstrdup(pw->pw_name);
1003 if (gethostname(thishost, sizeof(thishost)) == -1)
1004 fatal("gethostname: %s", strerror(errno));
1005 strlcpy(shorthost, thishost, sizeof(shorthost));
1006 shorthost[strcspn(thishost, ".")] = '\0';
1007 snprintf(portstr, sizeof(portstr), "%d", options.port);
1009 if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1010 ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1011 ssh_digest_update(md, host, strlen(host)) < 0 ||
1012 ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1013 ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1014 ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1015 fatal("%s: mux digest failed", __func__);
1016 ssh_digest_free(md);
1017 conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1019 if (options.local_command != NULL) {
1020 debug3("expanding LocalCommand: %s", options.local_command);
1021 cp = options.local_command;
1022 options.local_command = percent_expand(cp,
1023 "C", conn_hash_hex,
1024 "L", shorthost,
1025 "d", pw->pw_dir,
1026 "h", host,
1027 "l", thishost,
1028 "n", host_arg,
1029 "p", portstr,
1030 "r", options.user,
1031 "u", pw->pw_name,
1032 (char *)NULL);
1033 debug3("expanded LocalCommand: %s", options.local_command);
1034 free(cp);
1037 if (options.control_path != NULL) {
1038 cp = tilde_expand_filename(options.control_path,
1039 original_real_uid);
1040 free(options.control_path);
1041 options.control_path = percent_expand(cp,
1042 "C", conn_hash_hex,
1043 "L", shorthost,
1044 "h", host,
1045 "l", thishost,
1046 "n", host_arg,
1047 "p", portstr,
1048 "r", options.user,
1049 "u", pw->pw_name,
1050 (char *)NULL);
1051 free(cp);
1053 free(conn_hash_hex);
1055 if (muxclient_command != 0 && options.control_path == NULL)
1056 fatal("No ControlPath specified for \"-O\" command");
1057 if (options.control_path != NULL)
1058 muxclient(options.control_path);
1061 * If hostname canonicalisation was not enabled, then we may not
1062 * have yet resolved the hostname. Do so now.
1064 if (addrs == NULL && options.proxy_command == NULL) {
1065 if ((addrs = resolve_host(host, options.port, 1,
1066 cname, sizeof(cname))) == NULL)
1067 cleanup_exit(255); /* resolve_host logs the error */
1070 timeout_ms = options.connection_timeout * 1000;
1072 /* Open a connection to the remote host. */
1073 if (ssh_connect(host, addrs, &hostaddr, options.port,
1074 options.address_family, options.connection_attempts,
1075 &timeout_ms, options.tcp_keep_alive,
1076 options.use_privileged_port) != 0)
1077 exit(255);
1079 if (addrs != NULL)
1080 freeaddrinfo(addrs);
1082 packet_set_timeout(options.server_alive_interval,
1083 options.server_alive_count_max);
1085 if (timeout_ms > 0)
1086 debug3("timeout: %d ms remain after connect", timeout_ms);
1089 * If we successfully made the connection, load the host private key
1090 * in case we will need it later for combined rsa-rhosts
1091 * authentication. This must be done before releasing extra
1092 * privileges, because the file is only readable by root.
1093 * If we cannot access the private keys, load the public keys
1094 * instead and try to execute the ssh-keysign helper instead.
1096 sensitive_data.nkeys = 0;
1097 sensitive_data.keys = NULL;
1098 sensitive_data.external_keysign = 0;
1099 if (options.rhosts_rsa_authentication ||
1100 options.hostbased_authentication) {
1101 sensitive_data.nkeys = 9;
1102 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1103 sizeof(Key));
1104 for (i = 0; i < sensitive_data.nkeys; i++)
1105 sensitive_data.keys[i] = NULL;
1107 PRIV_START;
1108 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1109 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1110 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
1111 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1112 #ifdef OPENSSL_HAS_ECC
1113 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
1114 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1115 #endif
1116 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1117 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1118 sensitive_data.keys[4] = key_load_private_cert(KEY_ED25519,
1119 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1120 sensitive_data.keys[5] = key_load_private_type(KEY_DSA,
1121 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1122 #ifdef OPENSSL_HAS_ECC
1123 sensitive_data.keys[6] = key_load_private_type(KEY_ECDSA,
1124 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1125 #endif
1126 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1127 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1128 sensitive_data.keys[8] = key_load_private_type(KEY_ED25519,
1129 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1130 PRIV_END;
1132 if (options.hostbased_authentication == 1 &&
1133 sensitive_data.keys[0] == NULL &&
1134 sensitive_data.keys[5] == NULL &&
1135 sensitive_data.keys[6] == NULL &&
1136 sensitive_data.keys[7] == NULL &&
1137 sensitive_data.keys[8] == NULL) {
1138 sensitive_data.keys[1] = key_load_cert(
1139 _PATH_HOST_DSA_KEY_FILE);
1140 #ifdef OPENSSL_HAS_ECC
1141 sensitive_data.keys[2] = key_load_cert(
1142 _PATH_HOST_ECDSA_KEY_FILE);
1143 #endif
1144 sensitive_data.keys[3] = key_load_cert(
1145 _PATH_HOST_RSA_KEY_FILE);
1146 sensitive_data.keys[4] = key_load_cert(
1147 _PATH_HOST_ED25519_KEY_FILE);
1148 sensitive_data.keys[5] = key_load_public(
1149 _PATH_HOST_DSA_KEY_FILE, NULL);
1150 #ifdef OPENSSL_HAS_ECC
1151 sensitive_data.keys[6] = key_load_public(
1152 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1153 #endif
1154 sensitive_data.keys[7] = key_load_public(
1155 _PATH_HOST_RSA_KEY_FILE, NULL);
1156 sensitive_data.keys[8] = key_load_public(
1157 _PATH_HOST_ED25519_KEY_FILE, NULL);
1158 sensitive_data.external_keysign = 1;
1162 * Get rid of any extra privileges that we may have. We will no
1163 * longer need them. Also, extra privileges could make it very hard
1164 * to read identity files and other non-world-readable files from the
1165 * user's home directory if it happens to be on a NFS volume where
1166 * root is mapped to nobody.
1168 if (original_effective_uid == 0) {
1169 PRIV_START;
1170 permanently_set_uid(pw);
1174 * Now that we are back to our own permissions, create ~/.ssh
1175 * directory if it doesn't already exist.
1177 if (config == NULL) {
1178 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1179 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1180 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1181 #ifdef WITH_SELINUX
1182 ssh_selinux_setfscreatecon(buf);
1183 #endif
1184 if (mkdir(buf, 0700) < 0)
1185 error("Could not create directory '%.200s'.",
1186 buf);
1187 #ifdef WITH_SELINUX
1188 ssh_selinux_setfscreatecon(NULL);
1189 #endif
1192 /* load options.identity_files */
1193 load_public_identity_files();
1195 /* Expand ~ in known host file names. */
1196 tilde_expand_paths(options.system_hostfiles,
1197 options.num_system_hostfiles);
1198 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1200 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1201 signal(SIGCHLD, main_sigchld_handler);
1203 /* Log into the remote system. Never returns if the login fails. */
1204 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1205 options.port, pw, timeout_ms);
1207 if (packet_connection_is_on_socket()) {
1208 verbose("Authenticated to %s ([%s]:%d).", host,
1209 get_remote_ipaddr(), get_remote_port());
1210 } else {
1211 verbose("Authenticated to %s (via proxy).", host);
1214 /* We no longer need the private host keys. Clear them now. */
1215 if (sensitive_data.nkeys != 0) {
1216 for (i = 0; i < sensitive_data.nkeys; i++) {
1217 if (sensitive_data.keys[i] != NULL) {
1218 /* Destroys contents safely */
1219 debug3("clear hostkey %d", i);
1220 key_free(sensitive_data.keys[i]);
1221 sensitive_data.keys[i] = NULL;
1224 free(sensitive_data.keys);
1226 for (i = 0; i < options.num_identity_files; i++) {
1227 free(options.identity_files[i]);
1228 options.identity_files[i] = NULL;
1229 if (options.identity_keys[i]) {
1230 key_free(options.identity_keys[i]);
1231 options.identity_keys[i] = NULL;
1235 exit_status = compat20 ? ssh_session2() : ssh_session();
1236 packet_close();
1238 if (options.control_path != NULL && muxserver_sock != -1)
1239 unlink(options.control_path);
1241 /* Kill ProxyCommand if it is running. */
1242 ssh_kill_proxy_command();
1244 return exit_status;
1247 static void
1248 control_persist_detach(void)
1250 pid_t pid;
1251 int devnull;
1253 debug("%s: backgrounding master process", __func__);
1256 * master (current process) into the background, and make the
1257 * foreground process a client of the backgrounded master.
1259 switch ((pid = fork())) {
1260 case -1:
1261 fatal("%s: fork: %s", __func__, strerror(errno));
1262 case 0:
1263 /* Child: master process continues mainloop */
1264 break;
1265 default:
1266 /* Parent: set up mux slave to connect to backgrounded master */
1267 debug2("%s: background process is %ld", __func__, (long)pid);
1268 stdin_null_flag = ostdin_null_flag;
1269 options.request_tty = orequest_tty;
1270 tty_flag = otty_flag;
1271 close(muxserver_sock);
1272 muxserver_sock = -1;
1273 options.control_master = SSHCTL_MASTER_NO;
1274 muxclient(options.control_path);
1275 /* muxclient() doesn't return on success. */
1276 fatal("Failed to connect to new control master");
1278 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1279 error("%s: open(\"/dev/null\"): %s", __func__,
1280 strerror(errno));
1281 } else {
1282 if (dup2(devnull, STDIN_FILENO) == -1 ||
1283 dup2(devnull, STDOUT_FILENO) == -1)
1284 error("%s: dup2: %s", __func__, strerror(errno));
1285 if (devnull > STDERR_FILENO)
1286 close(devnull);
1288 daemon(1, 1);
1289 setproctitle("%s [mux]", options.control_path);
1292 /* Do fork() after authentication. Used by "ssh -f" */
1293 static void
1294 fork_postauth(void)
1296 if (need_controlpersist_detach)
1297 control_persist_detach();
1298 debug("forking to background");
1299 fork_after_authentication_flag = 0;
1300 if (daemon(1, 1) < 0)
1301 fatal("daemon() failed: %.200s", strerror(errno));
1304 /* Callback for remote forward global requests */
1305 static void
1306 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1308 struct Forward *rfwd = (struct Forward *)ctxt;
1310 /* XXX verbose() on failure? */
1311 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1312 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1313 rfwd->listen_path ? rfwd->listen_path :
1314 rfwd->listen_host ? rfwd->listen_host : "",
1315 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1316 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1317 rfwd->connect_host, rfwd->connect_port);
1318 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1319 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1320 rfwd->allocated_port = packet_get_int();
1321 logit("Allocated port %u for remote forward to %s:%d",
1322 rfwd->allocated_port,
1323 rfwd->connect_host, rfwd->connect_port);
1324 channel_update_permitted_opens(rfwd->handle,
1325 rfwd->allocated_port);
1326 } else {
1327 channel_update_permitted_opens(rfwd->handle, -1);
1331 if (type == SSH2_MSG_REQUEST_FAILURE) {
1332 if (options.exit_on_forward_failure) {
1333 if (rfwd->listen_path != NULL)
1334 fatal("Error: remote port forwarding failed "
1335 "for listen path %s", rfwd->listen_path);
1336 else
1337 fatal("Error: remote port forwarding failed "
1338 "for listen port %d", rfwd->listen_port);
1339 } else {
1340 if (rfwd->listen_path != NULL)
1341 logit("Warning: remote port forwarding failed "
1342 "for listen path %s", rfwd->listen_path);
1343 else
1344 logit("Warning: remote port forwarding failed "
1345 "for listen port %d", rfwd->listen_port);
1348 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1349 debug("All remote forwarding requests processed");
1350 if (fork_after_authentication_flag)
1351 fork_postauth();
1355 static void
1356 client_cleanup_stdio_fwd(int id, void *arg)
1358 debug("stdio forwarding: done");
1359 cleanup_exit(0);
1362 static void
1363 ssh_stdio_confirm(int id, int success, void *arg)
1365 if (!success)
1366 fatal("stdio forwarding failed");
1369 static void
1370 ssh_init_stdio_forwarding(void)
1372 Channel *c;
1373 int in, out;
1375 if (stdio_forward_host == NULL)
1376 return;
1377 if (!compat20)
1378 fatal("stdio forwarding require Protocol 2");
1380 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1382 if ((in = dup(STDIN_FILENO)) < 0 ||
1383 (out = dup(STDOUT_FILENO)) < 0)
1384 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1385 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1386 stdio_forward_port, in, out)) == NULL)
1387 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1388 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1389 channel_register_open_confirm(c->self, ssh_stdio_confirm, NULL);
1392 static void
1393 ssh_init_forwarding(void)
1395 int success = 0;
1396 int i;
1398 /* Initiate local TCP/IP port forwardings. */
1399 for (i = 0; i < options.num_local_forwards; i++) {
1400 debug("Local connections to %.200s:%d forwarded to remote "
1401 "address %.200s:%d",
1402 (options.local_forwards[i].listen_path != NULL) ?
1403 options.local_forwards[i].listen_path :
1404 (options.local_forwards[i].listen_host == NULL) ?
1405 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1406 options.local_forwards[i].listen_host,
1407 options.local_forwards[i].listen_port,
1408 (options.local_forwards[i].connect_path != NULL) ?
1409 options.local_forwards[i].connect_path :
1410 options.local_forwards[i].connect_host,
1411 options.local_forwards[i].connect_port);
1412 success += channel_setup_local_fwd_listener(
1413 &options.local_forwards[i], &options.fwd_opts);
1415 if (i > 0 && success != i && options.exit_on_forward_failure)
1416 fatal("Could not request local forwarding.");
1417 if (i > 0 && success == 0)
1418 error("Could not request local forwarding.");
1420 /* Initiate remote TCP/IP port forwardings. */
1421 for (i = 0; i < options.num_remote_forwards; i++) {
1422 debug("Remote connections from %.200s:%d forwarded to "
1423 "local address %.200s:%d",
1424 (options.remote_forwards[i].listen_path != NULL) ?
1425 options.remote_forwards[i].listen_path :
1426 (options.remote_forwards[i].listen_host == NULL) ?
1427 "LOCALHOST" : options.remote_forwards[i].listen_host,
1428 options.remote_forwards[i].listen_port,
1429 (options.remote_forwards[i].connect_path != NULL) ?
1430 options.remote_forwards[i].connect_path :
1431 options.remote_forwards[i].connect_host,
1432 options.remote_forwards[i].connect_port);
1433 options.remote_forwards[i].handle =
1434 channel_request_remote_forwarding(
1435 &options.remote_forwards[i]);
1436 if (options.remote_forwards[i].handle < 0) {
1437 if (options.exit_on_forward_failure)
1438 fatal("Could not request remote forwarding.");
1439 else
1440 logit("Warning: Could not request remote "
1441 "forwarding.");
1442 } else {
1443 client_register_global_confirm(ssh_confirm_remote_forward,
1444 &options.remote_forwards[i]);
1448 /* Initiate tunnel forwarding. */
1449 if (options.tun_open != SSH_TUNMODE_NO) {
1450 if (client_request_tun_fwd(options.tun_open,
1451 options.tun_local, options.tun_remote) == -1) {
1452 if (options.exit_on_forward_failure)
1453 fatal("Could not request tunnel forwarding.");
1454 else
1455 error("Could not request tunnel forwarding.");
1460 static void
1461 check_agent_present(void)
1463 if (options.forward_agent) {
1464 /* Clear agent forwarding if we don't have an agent. */
1465 if (!ssh_agent_present())
1466 options.forward_agent = 0;
1470 static int
1471 ssh_session(void)
1473 int type;
1474 int interactive = 0;
1475 int have_tty = 0;
1476 struct winsize ws;
1477 char *cp;
1478 const char *display;
1480 /* Enable compression if requested. */
1481 if (options.compression) {
1482 debug("Requesting compression at level %d.",
1483 options.compression_level);
1485 if (options.compression_level < 1 ||
1486 options.compression_level > 9)
1487 fatal("Compression level must be from 1 (fast) to "
1488 "9 (slow, best).");
1490 /* Send the request. */
1491 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1492 packet_put_int(options.compression_level);
1493 packet_send();
1494 packet_write_wait();
1495 type = packet_read();
1496 if (type == SSH_SMSG_SUCCESS)
1497 packet_start_compression(options.compression_level);
1498 else if (type == SSH_SMSG_FAILURE)
1499 logit("Warning: Remote host refused compression.");
1500 else
1501 packet_disconnect("Protocol error waiting for "
1502 "compression response.");
1504 /* Allocate a pseudo tty if appropriate. */
1505 if (tty_flag) {
1506 debug("Requesting pty.");
1508 /* Start the packet. */
1509 packet_start(SSH_CMSG_REQUEST_PTY);
1511 /* Store TERM in the packet. There is no limit on the
1512 length of the string. */
1513 cp = getenv("TERM");
1514 if (!cp)
1515 cp = "";
1516 packet_put_cstring(cp);
1518 /* Store window size in the packet. */
1519 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1520 memset(&ws, 0, sizeof(ws));
1521 packet_put_int((u_int)ws.ws_row);
1522 packet_put_int((u_int)ws.ws_col);
1523 packet_put_int((u_int)ws.ws_xpixel);
1524 packet_put_int((u_int)ws.ws_ypixel);
1526 /* Store tty modes in the packet. */
1527 tty_make_modes(fileno(stdin), NULL);
1529 /* Send the packet, and wait for it to leave. */
1530 packet_send();
1531 packet_write_wait();
1533 /* Read response from the server. */
1534 type = packet_read();
1535 if (type == SSH_SMSG_SUCCESS) {
1536 interactive = 1;
1537 have_tty = 1;
1538 } else if (type == SSH_SMSG_FAILURE)
1539 logit("Warning: Remote host failed or refused to "
1540 "allocate a pseudo tty.");
1541 else
1542 packet_disconnect("Protocol error waiting for pty "
1543 "request response.");
1545 /* Request X11 forwarding if enabled and DISPLAY is set. */
1546 display = getenv("DISPLAY");
1547 if (options.forward_x11 && display != NULL) {
1548 char *proto, *data;
1549 /* Get reasonable local authentication information. */
1550 client_x11_get_proto(display, options.xauth_location,
1551 options.forward_x11_trusted,
1552 options.forward_x11_timeout,
1553 &proto, &data);
1554 /* Request forwarding with authentication spoofing. */
1555 debug("Requesting X11 forwarding with authentication "
1556 "spoofing.");
1557 x11_request_forwarding_with_spoofing(0, display, proto,
1558 data, 0);
1559 /* Read response from the server. */
1560 type = packet_read();
1561 if (type == SSH_SMSG_SUCCESS) {
1562 interactive = 1;
1563 } else if (type == SSH_SMSG_FAILURE) {
1564 logit("Warning: Remote host denied X11 forwarding.");
1565 } else {
1566 packet_disconnect("Protocol error waiting for X11 "
1567 "forwarding");
1570 /* Tell the packet module whether this is an interactive session. */
1571 packet_set_interactive(interactive,
1572 options.ip_qos_interactive, options.ip_qos_bulk);
1574 /* Request authentication agent forwarding if appropriate. */
1575 check_agent_present();
1577 if (options.forward_agent) {
1578 debug("Requesting authentication agent forwarding.");
1579 auth_request_forwarding();
1581 /* Read response from the server. */
1582 type = packet_read();
1583 packet_check_eom();
1584 if (type != SSH_SMSG_SUCCESS)
1585 logit("Warning: Remote host denied authentication agent forwarding.");
1588 /* Initiate port forwardings. */
1589 ssh_init_stdio_forwarding();
1590 ssh_init_forwarding();
1592 /* Execute a local command */
1593 if (options.local_command != NULL &&
1594 options.permit_local_command)
1595 ssh_local_cmd(options.local_command);
1598 * If requested and we are not interested in replies to remote
1599 * forwarding requests, then let ssh continue in the background.
1601 if (fork_after_authentication_flag) {
1602 if (options.exit_on_forward_failure &&
1603 options.num_remote_forwards > 0) {
1604 debug("deferring postauth fork until remote forward "
1605 "confirmation received");
1606 } else
1607 fork_postauth();
1611 * If a command was specified on the command line, execute the
1612 * command now. Otherwise request the server to start a shell.
1614 if (buffer_len(&command) > 0) {
1615 int len = buffer_len(&command);
1616 if (len > 900)
1617 len = 900;
1618 debug("Sending command: %.*s", len,
1619 (u_char *)buffer_ptr(&command));
1620 packet_start(SSH_CMSG_EXEC_CMD);
1621 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1622 packet_send();
1623 packet_write_wait();
1624 } else {
1625 debug("Requesting shell.");
1626 packet_start(SSH_CMSG_EXEC_SHELL);
1627 packet_send();
1628 packet_write_wait();
1631 /* Enter the interactive session. */
1632 return client_loop(have_tty, tty_flag ?
1633 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1636 /* request pty/x11/agent/tcpfwd/shell for channel */
1637 static void
1638 ssh_session2_setup(int id, int success, void *arg)
1640 extern char **environ;
1641 const char *display;
1642 int interactive = tty_flag;
1644 if (!success)
1645 return; /* No need for error message, channels code sens one */
1647 display = getenv("DISPLAY");
1648 if (options.forward_x11 && display != NULL) {
1649 char *proto, *data;
1650 /* Get reasonable local authentication information. */
1651 client_x11_get_proto(display, options.xauth_location,
1652 options.forward_x11_trusted,
1653 options.forward_x11_timeout, &proto, &data);
1654 /* Request forwarding with authentication spoofing. */
1655 debug("Requesting X11 forwarding with authentication "
1656 "spoofing.");
1657 x11_request_forwarding_with_spoofing(id, display, proto,
1658 data, 1);
1659 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1660 /* XXX exit_on_forward_failure */
1661 interactive = 1;
1664 check_agent_present();
1665 if (options.forward_agent) {
1666 debug("Requesting authentication agent forwarding.");
1667 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1668 packet_send();
1671 /* Tell the packet module whether this is an interactive session. */
1672 packet_set_interactive(interactive,
1673 options.ip_qos_interactive, options.ip_qos_bulk);
1675 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1676 NULL, fileno(stdin), &command, environ);
1679 /* open new channel for a session */
1680 static int
1681 ssh_session2_open(void)
1683 Channel *c;
1684 int window, packetmax, in, out, err;
1686 if (stdin_null_flag) {
1687 in = open(_PATH_DEVNULL, O_RDONLY);
1688 } else {
1689 in = dup(STDIN_FILENO);
1691 out = dup(STDOUT_FILENO);
1692 err = dup(STDERR_FILENO);
1694 if (in < 0 || out < 0 || err < 0)
1695 fatal("dup() in/out/err failed");
1697 /* enable nonblocking unless tty */
1698 if (!isatty(in))
1699 set_nonblock(in);
1700 if (!isatty(out))
1701 set_nonblock(out);
1702 if (!isatty(err))
1703 set_nonblock(err);
1705 window = CHAN_SES_WINDOW_DEFAULT;
1706 packetmax = CHAN_SES_PACKET_DEFAULT;
1707 if (tty_flag) {
1708 window >>= 1;
1709 packetmax >>= 1;
1711 c = channel_new(
1712 "session", SSH_CHANNEL_OPENING, in, out, err,
1713 window, packetmax, CHAN_EXTENDED_WRITE,
1714 "client-session", /*nonblock*/0);
1716 debug3("ssh_session2_open: channel_new: %d", c->self);
1718 channel_send_open(c->self);
1719 if (!no_shell_flag)
1720 channel_register_open_confirm(c->self,
1721 ssh_session2_setup, NULL);
1723 return c->self;
1726 static int
1727 ssh_session2(void)
1729 int id = -1;
1731 /* XXX should be pre-session */
1732 if (!options.control_persist)
1733 ssh_init_stdio_forwarding();
1734 ssh_init_forwarding();
1736 /* Start listening for multiplex clients */
1737 muxserver_listen();
1740 * If we are in control persist mode and have a working mux listen
1741 * socket, then prepare to background ourselves and have a foreground
1742 * client attach as a control slave.
1743 * NB. we must save copies of the flags that we override for
1744 * the backgrounding, since we defer attachment of the slave until
1745 * after the connection is fully established (in particular,
1746 * async rfwd replies have been received for ExitOnForwardFailure).
1748 if (options.control_persist && muxserver_sock != -1) {
1749 ostdin_null_flag = stdin_null_flag;
1750 ono_shell_flag = no_shell_flag;
1751 orequest_tty = options.request_tty;
1752 otty_flag = tty_flag;
1753 stdin_null_flag = 1;
1754 no_shell_flag = 1;
1755 tty_flag = 0;
1756 if (!fork_after_authentication_flag)
1757 need_controlpersist_detach = 1;
1758 fork_after_authentication_flag = 1;
1761 * ControlPersist mux listen socket setup failed, attempt the
1762 * stdio forward setup that we skipped earlier.
1764 if (options.control_persist && muxserver_sock == -1)
1765 ssh_init_stdio_forwarding();
1767 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1768 id = ssh_session2_open();
1769 else {
1770 packet_set_interactive(
1771 options.control_master == SSHCTL_MASTER_NO,
1772 options.ip_qos_interactive, options.ip_qos_bulk);
1775 /* If we don't expect to open a new session, then disallow it */
1776 if (options.control_master == SSHCTL_MASTER_NO &&
1777 (datafellows & SSH_NEW_OPENSSH)) {
1778 debug("Requesting no-more-sessions@openssh.com");
1779 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1780 packet_put_cstring("no-more-sessions@openssh.com");
1781 packet_put_char(0);
1782 packet_send();
1785 /* Execute a local command */
1786 if (options.local_command != NULL &&
1787 options.permit_local_command)
1788 ssh_local_cmd(options.local_command);
1791 * If requested and we are not interested in replies to remote
1792 * forwarding requests, then let ssh continue in the background.
1794 if (fork_after_authentication_flag) {
1795 if (options.exit_on_forward_failure &&
1796 options.num_remote_forwards > 0) {
1797 debug("deferring postauth fork until remote forward "
1798 "confirmation received");
1799 } else
1800 fork_postauth();
1803 if (options.use_roaming)
1804 request_roaming();
1806 return client_loop(tty_flag, tty_flag ?
1807 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1810 static void
1811 load_public_identity_files(void)
1813 char *filename, *cp, thishost[NI_MAXHOST];
1814 char *pwdir = NULL, *pwname = NULL;
1815 int i = 0;
1816 Key *public;
1817 struct passwd *pw;
1818 u_int n_ids;
1819 char *identity_files[SSH_MAX_IDENTITY_FILES];
1820 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1821 #ifdef ENABLE_PKCS11
1822 Key **keys;
1823 int nkeys;
1824 #endif /* PKCS11 */
1826 n_ids = 0;
1827 memset(identity_files, 0, sizeof(identity_files));
1828 memset(identity_keys, 0, sizeof(identity_keys));
1830 #ifdef ENABLE_PKCS11
1831 if (options.pkcs11_provider != NULL &&
1832 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1833 (pkcs11_init(!options.batch_mode) == 0) &&
1834 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1835 &keys)) > 0) {
1836 for (i = 0; i < nkeys; i++) {
1837 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1838 key_free(keys[i]);
1839 continue;
1841 identity_keys[n_ids] = keys[i];
1842 identity_files[n_ids] =
1843 xstrdup(options.pkcs11_provider); /* XXX */
1844 n_ids++;
1846 free(keys);
1848 #endif /* ENABLE_PKCS11 */
1849 if ((pw = getpwuid(original_real_uid)) == NULL)
1850 fatal("load_public_identity_files: getpwuid failed");
1851 pwname = xstrdup(pw->pw_name);
1852 pwdir = xstrdup(pw->pw_dir);
1853 if (gethostname(thishost, sizeof(thishost)) == -1)
1854 fatal("load_public_identity_files: gethostname: %s",
1855 strerror(errno));
1856 for (i = 0; i < options.num_identity_files; i++) {
1857 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
1858 strcasecmp(options.identity_files[i], "none") == 0) {
1859 free(options.identity_files[i]);
1860 continue;
1862 cp = tilde_expand_filename(options.identity_files[i],
1863 original_real_uid);
1864 filename = percent_expand(cp, "d", pwdir,
1865 "u", pwname, "l", thishost, "h", host,
1866 "r", options.user, (char *)NULL);
1867 free(cp);
1868 public = key_load_public(filename, NULL);
1869 debug("identity file %s type %d", filename,
1870 public ? public->type : -1);
1871 free(options.identity_files[i]);
1872 identity_files[n_ids] = filename;
1873 identity_keys[n_ids] = public;
1875 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1876 continue;
1878 /* Try to add the certificate variant too */
1879 xasprintf(&cp, "%s-cert", filename);
1880 public = key_load_public(cp, NULL);
1881 debug("identity file %s type %d", cp,
1882 public ? public->type : -1);
1883 if (public == NULL) {
1884 free(cp);
1885 continue;
1887 if (!key_is_cert(public)) {
1888 debug("%s: key %s type %s is not a certificate",
1889 __func__, cp, key_type(public));
1890 key_free(public);
1891 free(cp);
1892 continue;
1894 identity_keys[n_ids] = public;
1895 /* point to the original path, most likely the private key */
1896 identity_files[n_ids] = xstrdup(filename);
1897 n_ids++;
1899 options.num_identity_files = n_ids;
1900 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1901 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1903 explicit_bzero(pwname, strlen(pwname));
1904 free(pwname);
1905 explicit_bzero(pwdir, strlen(pwdir));
1906 free(pwdir);
1909 static void
1910 main_sigchld_handler(int sig)
1912 int save_errno = errno;
1913 pid_t pid;
1914 int status;
1916 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1917 (pid < 0 && errno == EINTR))
1920 signal(sig, main_sigchld_handler);
1921 errno = save_errno;