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