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