]> andersk Git - openssh.git/blob - ssh.c
- dtucker@cvs.openbsd.org 2010/01/10 07:15:56
[openssh.git] / ssh.c
1 /* $OpenBSD: ssh.c,v 1.330 2010/01/09 23:04:13 dtucker 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
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/param.h>
52 #include <sys/socket.h>
53
54 #include <ctype.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <netdb.h>
58 #ifdef HAVE_PATHS_H
59 #include <paths.h>
60 #endif
61 #include <pwd.h>
62 #include <signal.h>
63 #include <stdarg.h>
64 #include <stddef.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69
70 #include <netinet/in.h>
71 #include <arpa/inet.h>
72
73 #include <openssl/evp.h>
74 #include <openssl/err.h>
75 #include "openbsd-compat/openssl-compat.h"
76 #include "openbsd-compat/sys-queue.h"
77
78 #include "xmalloc.h"
79 #include "ssh.h"
80 #include "ssh1.h"
81 #include "ssh2.h"
82 #include "compat.h"
83 #include "cipher.h"
84 #include "packet.h"
85 #include "buffer.h"
86 #include "channels.h"
87 #include "key.h"
88 #include "authfd.h"
89 #include "authfile.h"
90 #include "pathnames.h"
91 #include "dispatch.h"
92 #include "clientloop.h"
93 #include "log.h"
94 #include "readconf.h"
95 #include "sshconnect.h"
96 #include "misc.h"
97 #include "kex.h"
98 #include "mac.h"
99 #include "sshpty.h"
100 #include "match.h"
101 #include "msg.h"
102 #include "uidswap.h"
103 #include "roaming.h"
104 #include "version.h"
105
106 #ifdef SMARTCARD
107 #include "scard.h"
108 #endif
109
110 extern char *__progname;
111
112 /* Flag indicating whether debug mode is on.  May be set on the command line. */
113 int debug_flag = 0;
114
115 /* Flag indicating whether a tty should be allocated */
116 int tty_flag = 0;
117 int no_tty_flag = 0;
118 int force_tty_flag = 0;
119
120 /* don't exec a shell */
121 int no_shell_flag = 0;
122
123 /*
124  * Flag indicating that nothing should be read from stdin.  This can be set
125  * on the command line.
126  */
127 int stdin_null_flag = 0;
128
129 /*
130  * Flag indicating that ssh should fork after authentication.  This is useful
131  * so that the passphrase can be entered manually, and then ssh goes to the
132  * background.
133  */
134 int fork_after_authentication_flag = 0;
135
136 /*
137  * General data structure for command line options and options configurable
138  * in configuration files.  See readconf.h.
139  */
140 Options options;
141
142 /* optional user configfile */
143 char *config = NULL;
144
145 /*
146  * Name of the host we are connecting to.  This is the name given on the
147  * command line, or the HostName specified for the user-supplied name in a
148  * configuration file.
149  */
150 char *host;
151
152 /* socket address the host resolves to */
153 struct sockaddr_storage hostaddr;
154
155 /* Private host keys. */
156 Sensitive sensitive_data;
157
158 /* Original real UID. */
159 uid_t original_real_uid;
160 uid_t original_effective_uid;
161
162 /* command to be executed */
163 Buffer command;
164
165 /* Should we execute a command or invoke a subsystem? */
166 int subsystem_flag = 0;
167
168 /* # of replies received for global requests */
169 static int remote_forward_confirms_received = 0;
170
171 /* pid of proxycommand child process */
172 pid_t proxy_command_pid = 0;
173
174 /* mux.c */
175 extern int muxserver_sock;
176 extern u_int muxclient_command;
177
178 /* Prints a help message to the user.  This function never returns. */
179
180 static void
181 usage(void)
182 {
183         fprintf(stderr,
184 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
185 "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
186 "           [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
187 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
188 "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
189 "           [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
190         );
191         exit(255);
192 }
193
194 static int ssh_session(void);
195 static int ssh_session2(void);
196 static void load_public_identity_files(void);
197
198 /* from muxclient.c */
199 void muxclient(const char *);
200 void muxserver_listen(void);
201
202 /*
203  * Main program for the ssh client.
204  */
205 int
206 main(int ac, char **av)
207 {
208         int i, r, opt, exit_status, use_syslog;
209         char *p, *cp, *line, *argv0, buf[MAXPATHLEN];
210         struct stat st;
211         struct passwd *pw;
212         int dummy, timeout_ms;
213         extern int optind, optreset;
214         extern char *optarg;
215         struct servent *sp;
216         Forward fwd;
217
218         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
219         sanitise_stdfd();
220
221         __progname = ssh_get_progname(av[0]);
222         init_rng();
223
224         /*
225          * Save the original real uid.  It will be needed later (uid-swapping
226          * may clobber the real uid).
227          */
228         original_real_uid = getuid();
229         original_effective_uid = geteuid();
230
231         /*
232          * Use uid-swapping to give up root privileges for the duration of
233          * option processing.  We will re-instantiate the rights when we are
234          * ready to create the privileged port, and will permanently drop
235          * them when the port has been created (actually, when the connection
236          * has been made, as we may need to create the port several times).
237          */
238         PRIV_END;
239
240 #ifdef HAVE_SETRLIMIT
241         /* If we are installed setuid root be careful to not drop core. */
242         if (original_real_uid != original_effective_uid) {
243                 struct rlimit rlim;
244                 rlim.rlim_cur = rlim.rlim_max = 0;
245                 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
246                         fatal("setrlimit failed: %.100s", strerror(errno));
247         }
248 #endif
249         /* Get user data. */
250         pw = getpwuid(original_real_uid);
251         if (!pw) {
252                 logit("You don't exist, go away!");
253                 exit(255);
254         }
255         /* Take a copy of the returned structure. */
256         pw = pwcopy(pw);
257
258         /*
259          * Set our umask to something reasonable, as some files are created
260          * with the default umask.  This will make them world-readable but
261          * writable only by the owner, which is ok for all files for which we
262          * don't set the modes explicitly.
263          */
264         umask(022);
265
266         /*
267          * Initialize option structure to indicate that no values have been
268          * set.
269          */
270         initialize_options(&options);
271
272         /* Parse command-line arguments. */
273         host = NULL;
274         use_syslog = 0;
275         argv0 = av[0];
276
277  again:
278         while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
279             "ACD:F:I:KL:MNO:PR:S:TVw:XYy")) != -1) {
280                 switch (opt) {
281                 case '1':
282                         options.protocol = SSH_PROTO_1;
283                         break;
284                 case '2':
285                         options.protocol = SSH_PROTO_2;
286                         break;
287                 case '4':
288                         options.address_family = AF_INET;
289                         break;
290                 case '6':
291                         options.address_family = AF_INET6;
292                         break;
293                 case 'n':
294                         stdin_null_flag = 1;
295                         break;
296                 case 'f':
297                         fork_after_authentication_flag = 1;
298                         stdin_null_flag = 1;
299                         break;
300                 case 'x':
301                         options.forward_x11 = 0;
302                         break;
303                 case 'X':
304                         options.forward_x11 = 1;
305                         break;
306                 case 'y':
307                         use_syslog = 1;
308                         break;
309                 case 'Y':
310                         options.forward_x11 = 1;
311                         options.forward_x11_trusted = 1;
312                         break;
313                 case 'g':
314                         options.gateway_ports = 1;
315                         break;
316                 case 'O':
317                         if (strcmp(optarg, "check") == 0)
318                                 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
319                         else if (strcmp(optarg, "exit") == 0)
320                                 muxclient_command = SSHMUX_COMMAND_TERMINATE;
321                         else
322                                 fatal("Invalid multiplex command.");
323                         break;
324                 case 'P':       /* deprecated */
325                         options.use_privileged_port = 0;
326                         break;
327                 case 'a':
328                         options.forward_agent = 0;
329                         break;
330                 case 'A':
331                         options.forward_agent = 1;
332                         break;
333                 case 'k':
334                         options.gss_deleg_creds = 0;
335                         break;
336                 case 'K':
337                         options.gss_authentication = 1;
338                         options.gss_deleg_creds = 1;
339                         break;
340                 case 'i':
341                         if (stat(optarg, &st) < 0) {
342                                 fprintf(stderr, "Warning: Identity file %s "
343                                     "not accessible: %s.\n", optarg,
344                                     strerror(errno));
345                                 break;
346                         }
347                         if (options.num_identity_files >=
348                             SSH_MAX_IDENTITY_FILES)
349                                 fatal("Too many identity files specified "
350                                     "(max %d)", SSH_MAX_IDENTITY_FILES);
351                         options.identity_files[options.num_identity_files++] =
352                             xstrdup(optarg);
353                         break;
354                 case 'I':
355 #ifdef SMARTCARD
356                         options.smartcard_device = xstrdup(optarg);
357 #else
358                         fprintf(stderr, "no support for smartcards.\n");
359 #endif
360                         break;
361                 case 't':
362                         if (tty_flag)
363                                 force_tty_flag = 1;
364                         tty_flag = 1;
365                         break;
366                 case 'v':
367                         if (debug_flag == 0) {
368                                 debug_flag = 1;
369                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
370                         } else {
371                                 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
372                                         options.log_level++;
373                                 break;
374                         }
375                         /* FALLTHROUGH */
376                 case 'V':
377                         fprintf(stderr, "%s, %s\n",
378                             SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
379                         if (opt == 'V')
380                                 exit(0);
381                         break;
382                 case 'w':
383                         if (options.tun_open == -1)
384                                 options.tun_open = SSH_TUNMODE_DEFAULT;
385                         options.tun_local = a2tun(optarg, &options.tun_remote);
386                         if (options.tun_local == SSH_TUNID_ERR) {
387                                 fprintf(stderr,
388                                     "Bad tun device '%s'\n", optarg);
389                                 exit(255);
390                         }
391                         break;
392                 case 'q':
393                         options.log_level = SYSLOG_LEVEL_QUIET;
394                         break;
395                 case 'e':
396                         if (optarg[0] == '^' && optarg[2] == 0 &&
397                             (u_char) optarg[1] >= 64 &&
398                             (u_char) optarg[1] < 128)
399                                 options.escape_char = (u_char) optarg[1] & 31;
400                         else if (strlen(optarg) == 1)
401                                 options.escape_char = (u_char) optarg[0];
402                         else if (strcmp(optarg, "none") == 0)
403                                 options.escape_char = SSH_ESCAPECHAR_NONE;
404                         else {
405                                 fprintf(stderr, "Bad escape character '%s'.\n",
406                                     optarg);
407                                 exit(255);
408                         }
409                         break;
410                 case 'c':
411                         if (ciphers_valid(optarg)) {
412                                 /* SSH2 only */
413                                 options.ciphers = xstrdup(optarg);
414                                 options.cipher = SSH_CIPHER_INVALID;
415                         } else {
416                                 /* SSH1 only */
417                                 options.cipher = cipher_number(optarg);
418                                 if (options.cipher == -1) {
419                                         fprintf(stderr,
420                                             "Unknown cipher type '%s'\n",
421                                             optarg);
422                                         exit(255);
423                                 }
424                                 if (options.cipher == SSH_CIPHER_3DES)
425                                         options.ciphers = "3des-cbc";
426                                 else if (options.cipher == SSH_CIPHER_BLOWFISH)
427                                         options.ciphers = "blowfish-cbc";
428                                 else
429                                         options.ciphers = (char *)-1;
430                         }
431                         break;
432                 case 'm':
433                         if (mac_valid(optarg))
434                                 options.macs = xstrdup(optarg);
435                         else {
436                                 fprintf(stderr, "Unknown mac type '%s'\n",
437                                     optarg);
438                                 exit(255);
439                         }
440                         break;
441                 case 'M':
442                         if (options.control_master == SSHCTL_MASTER_YES)
443                                 options.control_master = SSHCTL_MASTER_ASK;
444                         else
445                                 options.control_master = SSHCTL_MASTER_YES;
446                         break;
447                 case 'p':
448                         options.port = a2port(optarg);
449                         if (options.port <= 0) {
450                                 fprintf(stderr, "Bad port '%s'\n", optarg);
451                                 exit(255);
452                         }
453                         break;
454                 case 'l':
455                         options.user = optarg;
456                         break;
457
458                 case 'L':
459                         if (parse_forward(&fwd, optarg, 0, 0))
460                                 add_local_forward(&options, &fwd);
461                         else {
462                                 fprintf(stderr,
463                                     "Bad local forwarding specification '%s'\n",
464                                     optarg);
465                                 exit(255);
466                         }
467                         break;
468
469                 case 'R':
470                         if (parse_forward(&fwd, optarg, 0, 1)) {
471                                 add_remote_forward(&options, &fwd);
472                         } else {
473                                 fprintf(stderr,
474                                     "Bad remote forwarding specification "
475                                     "'%s'\n", optarg);
476                                 exit(255);
477                         }
478                         break;
479
480                 case 'D':
481                         if (parse_forward(&fwd, optarg, 1, 0)) {
482                                 add_local_forward(&options, &fwd);
483                         } else {
484                                 fprintf(stderr,
485                                     "Bad dynamic forwarding specification "
486                                     "'%s'\n", optarg);
487                                 exit(255);
488                         }
489                         break;
490
491                 case 'C':
492                         options.compression = 1;
493                         break;
494                 case 'N':
495                         no_shell_flag = 1;
496                         no_tty_flag = 1;
497                         break;
498                 case 'T':
499                         no_tty_flag = 1;
500                         break;
501                 case 'o':
502                         dummy = 1;
503                         line = xstrdup(optarg);
504                         if (process_config_line(&options, host ? host : "",
505                             line, "command-line", 0, &dummy) != 0)
506                                 exit(255);
507                         xfree(line);
508                         break;
509                 case 's':
510                         subsystem_flag = 1;
511                         break;
512                 case 'S':
513                         if (options.control_path != NULL)
514                                 free(options.control_path);
515                         options.control_path = xstrdup(optarg);
516                         break;
517                 case 'b':
518                         options.bind_address = optarg;
519                         break;
520                 case 'F':
521                         config = optarg;
522                         break;
523                 default:
524                         usage();
525                 }
526         }
527
528         ac -= optind;
529         av += optind;
530
531         if (ac > 0 && !host) {
532                 if (strrchr(*av, '@')) {
533                         p = xstrdup(*av);
534                         cp = strrchr(p, '@');
535                         if (cp == NULL || cp == p)
536                                 usage();
537                         options.user = p;
538                         *cp = '\0';
539                         host = ++cp;
540                 } else
541                         host = *av;
542                 if (ac > 1) {
543                         optind = optreset = 1;
544                         goto again;
545                 }
546                 ac--, av++;
547         }
548
549         /* Check that we got a host name. */
550         if (!host)
551                 usage();
552
553         SSLeay_add_all_algorithms();
554         ERR_load_crypto_strings();
555
556         /* Initialize the command to execute on remote host. */
557         buffer_init(&command);
558
559         /*
560          * Save the command to execute on the remote host in a buffer. There
561          * is no limit on the length of the command, except by the maximum
562          * packet size.  Also sets the tty flag if there is no command.
563          */
564         if (!ac) {
565                 /* No command specified - execute shell on a tty. */
566                 tty_flag = 1;
567                 if (subsystem_flag) {
568                         fprintf(stderr,
569                             "You must specify a subsystem to invoke.\n");
570                         usage();
571                 }
572         } else {
573                 /* A command has been specified.  Store it into the buffer. */
574                 for (i = 0; i < ac; i++) {
575                         if (i)
576                                 buffer_append(&command, " ", 1);
577                         buffer_append(&command, av[i], strlen(av[i]));
578                 }
579         }
580
581         /* Cannot fork to background if no command. */
582         if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
583             !no_shell_flag)
584                 fatal("Cannot fork into background without a command "
585                     "to execute.");
586
587         /* Allocate a tty by default if no command specified. */
588         if (buffer_len(&command) == 0)
589                 tty_flag = 1;
590
591         /* Force no tty */
592         if (no_tty_flag)
593                 tty_flag = 0;
594         /* Do not allocate a tty if stdin is not a tty. */
595         if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
596                 if (tty_flag)
597                         logit("Pseudo-terminal will not be allocated because "
598                             "stdin is not a terminal.");
599                 tty_flag = 0;
600         }
601
602         /*
603          * Initialize "log" output.  Since we are the client all output
604          * actually goes to stderr.
605          */
606         log_init(argv0,
607             options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
608             SYSLOG_FACILITY_USER, !use_syslog);
609
610         /*
611          * Read per-user configuration file.  Ignore the system wide config
612          * file if the user specifies a config file on the command line.
613          */
614         if (config != NULL) {
615                 if (!read_config_file(config, host, &options, 0))
616                         fatal("Can't open user config file %.100s: "
617                             "%.100s", config, strerror(errno));
618         } else {
619                 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
620                     _PATH_SSH_USER_CONFFILE);
621                 if (r > 0 && (size_t)r < sizeof(buf))
622                         (void)read_config_file(buf, host, &options, 1);
623
624                 /* Read systemwide configuration file after use config. */
625                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
626                     &options, 0);
627         }
628
629         /* Fill configuration defaults. */
630         fill_default_options(&options);
631
632         channel_set_af(options.address_family);
633
634         /* reinit */
635         log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
636
637         seed_rng();
638
639         if (options.user == NULL)
640                 options.user = xstrdup(pw->pw_name);
641
642         /* Get default port if port has not been set. */
643         if (options.port == 0) {
644                 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
645                 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
646         }
647
648         if (options.local_command != NULL) {
649                 char thishost[NI_MAXHOST];
650
651                 if (gethostname(thishost, sizeof(thishost)) == -1)
652                         fatal("gethostname: %s", strerror(errno));
653                 snprintf(buf, sizeof(buf), "%d", options.port);
654                 debug3("expanding LocalCommand: %s", options.local_command);
655                 cp = options.local_command;
656                 options.local_command = percent_expand(cp, "d", pw->pw_dir,
657                     "h", options.hostname? options.hostname : host,
658                     "l", thishost, "n", host, "r", options.user, "p", buf,
659                     "u", pw->pw_name, (char *)NULL);
660                 debug3("expanded LocalCommand: %s", options.local_command);
661                 xfree(cp);
662         }
663
664         if (options.hostname != NULL)
665                 host = options.hostname;
666
667         /* force lowercase for hostkey matching */
668         if (options.host_key_alias != NULL) {
669                 for (p = options.host_key_alias; *p; p++)
670                         if (isupper(*p))
671                                 *p = (char)tolower(*p);
672         }
673
674         if (options.proxy_command != NULL &&
675             strcmp(options.proxy_command, "none") == 0) {
676                 xfree(options.proxy_command);
677                 options.proxy_command = NULL;
678         }
679         if (options.control_path != NULL &&
680             strcmp(options.control_path, "none") == 0) {
681                 xfree(options.control_path);
682                 options.control_path = NULL;
683         }
684
685         if (options.control_path != NULL) {
686                 char thishost[NI_MAXHOST];
687
688                 if (gethostname(thishost, sizeof(thishost)) == -1)
689                         fatal("gethostname: %s", strerror(errno));
690                 snprintf(buf, sizeof(buf), "%d", options.port);
691                 cp = tilde_expand_filename(options.control_path,
692                     original_real_uid);
693                 xfree(options.control_path);
694                 options.control_path = percent_expand(cp, "p", buf, "h", host,
695                     "r", options.user, "l", thishost, (char *)NULL);
696                 xfree(cp);
697         }
698         if (muxclient_command != 0 && options.control_path == NULL)
699                 fatal("No ControlPath specified for \"-O\" command");
700         if (options.control_path != NULL)
701                 muxclient(options.control_path);
702
703         timeout_ms = options.connection_timeout * 1000;
704
705         /* Open a connection to the remote host. */
706         if (ssh_connect(host, &hostaddr, options.port,
707             options.address_family, options.connection_attempts, &timeout_ms,
708             options.tcp_keep_alive, 
709 #ifdef HAVE_CYGWIN
710             options.use_privileged_port,
711 #else
712             original_effective_uid == 0 && options.use_privileged_port,
713 #endif
714             options.proxy_command) != 0)
715                 exit(255);
716
717         if (timeout_ms > 0)
718                 debug3("timeout: %d ms remain after connect", timeout_ms);
719
720         /*
721          * If we successfully made the connection, load the host private key
722          * in case we will need it later for combined rsa-rhosts
723          * authentication. This must be done before releasing extra
724          * privileges, because the file is only readable by root.
725          * If we cannot access the private keys, load the public keys
726          * instead and try to execute the ssh-keysign helper instead.
727          */
728         sensitive_data.nkeys = 0;
729         sensitive_data.keys = NULL;
730         sensitive_data.external_keysign = 0;
731         if (options.rhosts_rsa_authentication ||
732             options.hostbased_authentication) {
733                 sensitive_data.nkeys = 3;
734                 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
735                     sizeof(Key));
736
737                 PRIV_START;
738                 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
739                     _PATH_HOST_KEY_FILE, "", NULL, NULL);
740                 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
741                     _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
742                 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
743                     _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
744                 PRIV_END;
745
746                 if (options.hostbased_authentication == 1 &&
747                     sensitive_data.keys[0] == NULL &&
748                     sensitive_data.keys[1] == NULL &&
749                     sensitive_data.keys[2] == NULL) {
750                         sensitive_data.keys[1] = key_load_public(
751                             _PATH_HOST_DSA_KEY_FILE, NULL);
752                         sensitive_data.keys[2] = key_load_public(
753                             _PATH_HOST_RSA_KEY_FILE, NULL);
754                         sensitive_data.external_keysign = 1;
755                 }
756         }
757         /*
758          * Get rid of any extra privileges that we may have.  We will no
759          * longer need them.  Also, extra privileges could make it very hard
760          * to read identity files and other non-world-readable files from the
761          * user's home directory if it happens to be on a NFS volume where
762          * root is mapped to nobody.
763          */
764         if (original_effective_uid == 0) {
765                 PRIV_START;
766                 permanently_set_uid(pw);
767         }
768
769         /*
770          * Now that we are back to our own permissions, create ~/.ssh
771          * directory if it doesn't already exist.
772          */
773         r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
774             strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
775         if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
776                 if (mkdir(buf, 0700) < 0)
777                         error("Could not create directory '%.200s'.", buf);
778
779         /* load options.identity_files */
780         load_public_identity_files();
781
782         /* Expand ~ in known host file names. */
783         /* XXX mem-leaks: */
784         options.system_hostfile =
785             tilde_expand_filename(options.system_hostfile, original_real_uid);
786         options.user_hostfile =
787             tilde_expand_filename(options.user_hostfile, original_real_uid);
788         options.system_hostfile2 =
789             tilde_expand_filename(options.system_hostfile2, original_real_uid);
790         options.user_hostfile2 =
791             tilde_expand_filename(options.user_hostfile2, original_real_uid);
792
793         signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
794
795         /* Log into the remote system.  Never returns if the login fails. */
796         ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
797             pw, timeout_ms);
798
799         /* We no longer need the private host keys.  Clear them now. */
800         if (sensitive_data.nkeys != 0) {
801                 for (i = 0; i < sensitive_data.nkeys; i++) {
802                         if (sensitive_data.keys[i] != NULL) {
803                                 /* Destroys contents safely */
804                                 debug3("clear hostkey %d", i);
805                                 key_free(sensitive_data.keys[i]);
806                                 sensitive_data.keys[i] = NULL;
807                         }
808                 }
809                 xfree(sensitive_data.keys);
810         }
811         for (i = 0; i < options.num_identity_files; i++) {
812                 if (options.identity_files[i]) {
813                         xfree(options.identity_files[i]);
814                         options.identity_files[i] = NULL;
815                 }
816                 if (options.identity_keys[i]) {
817                         key_free(options.identity_keys[i]);
818                         options.identity_keys[i] = NULL;
819                 }
820         }
821
822         exit_status = compat20 ? ssh_session2() : ssh_session();
823         packet_close();
824
825         if (options.control_path != NULL && muxserver_sock != -1)
826                 unlink(options.control_path);
827
828         /*
829          * Send SIGHUP to proxy command if used. We don't wait() in
830          * case it hangs and instead rely on init to reap the child
831          */
832         if (proxy_command_pid > 1)
833                 kill(proxy_command_pid, SIGHUP);
834
835         return exit_status;
836 }
837
838 /* Callback for remote forward global requests */
839 static void
840 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
841 {
842         Forward *rfwd = (Forward *)ctxt;
843
844         /* XXX verbose() on failure? */
845         debug("remote forward %s for: listen %d, connect %s:%d",
846             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
847             rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
848         if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
849                 logit("Allocated port %u for remote forward to %s:%d",
850                         packet_get_int(),
851                         rfwd->connect_host, rfwd->connect_port);
852         }
853         
854         if (type == SSH2_MSG_REQUEST_FAILURE) {
855                 if (options.exit_on_forward_failure)
856                         fatal("Error: remote port forwarding failed for "
857                             "listen port %d", rfwd->listen_port);
858                 else
859                         logit("Warning: remote port forwarding failed for "
860                             "listen port %d", rfwd->listen_port);
861         }
862         if (++remote_forward_confirms_received == options.num_remote_forwards) {
863                 debug("All remote forwarding requests processed");
864                 if (fork_after_authentication_flag) {
865                         fork_after_authentication_flag = 0;
866                         if (daemon(1, 1) < 0)
867                                 fatal("daemon() failed: %.200s",
868                                     strerror(errno));
869                 }
870         }
871 }
872
873 static void
874 ssh_init_forwarding(void)
875 {
876         int success = 0;
877         int i;
878
879         /* Initiate local TCP/IP port forwardings. */
880         for (i = 0; i < options.num_local_forwards; i++) {
881                 debug("Local connections to %.200s:%d forwarded to remote "
882                     "address %.200s:%d",
883                     (options.local_forwards[i].listen_host == NULL) ?
884                     (options.gateway_ports ? "*" : "LOCALHOST") :
885                     options.local_forwards[i].listen_host,
886                     options.local_forwards[i].listen_port,
887                     options.local_forwards[i].connect_host,
888                     options.local_forwards[i].connect_port);
889                 success += channel_setup_local_fwd_listener(
890                     options.local_forwards[i].listen_host,
891                     options.local_forwards[i].listen_port,
892                     options.local_forwards[i].connect_host,
893                     options.local_forwards[i].connect_port,
894                     options.gateway_ports);
895         }
896         if (i > 0 && success != i && options.exit_on_forward_failure)
897                 fatal("Could not request local forwarding.");
898         if (i > 0 && success == 0)
899                 error("Could not request local forwarding.");
900
901         /* Initiate remote TCP/IP port forwardings. */
902         for (i = 0; i < options.num_remote_forwards; i++) {
903                 debug("Remote connections from %.200s:%d forwarded to "
904                     "local address %.200s:%d",
905                     (options.remote_forwards[i].listen_host == NULL) ?
906                     "LOCALHOST" : options.remote_forwards[i].listen_host,
907                     options.remote_forwards[i].listen_port,
908                     options.remote_forwards[i].connect_host,
909                     options.remote_forwards[i].connect_port);
910                 if (channel_request_remote_forwarding(
911                     options.remote_forwards[i].listen_host,
912                     options.remote_forwards[i].listen_port,
913                     options.remote_forwards[i].connect_host,
914                     options.remote_forwards[i].connect_port) < 0) {
915                         if (options.exit_on_forward_failure)
916                                 fatal("Could not request remote forwarding.");
917                         else
918                                 logit("Warning: Could not request remote "
919                                     "forwarding.");
920                 }
921                 client_register_global_confirm(ssh_confirm_remote_forward,
922                     &options.remote_forwards[i]);
923         }
924
925         /* Initiate tunnel forwarding. */
926         if (options.tun_open != SSH_TUNMODE_NO) {
927                 if (client_request_tun_fwd(options.tun_open,
928                     options.tun_local, options.tun_remote) == -1) {
929                         if (options.exit_on_forward_failure)
930                                 fatal("Could not request tunnel forwarding.");
931                         else
932                                 error("Could not request tunnel forwarding.");
933                 }
934         }                       
935 }
936
937 static void
938 check_agent_present(void)
939 {
940         if (options.forward_agent) {
941                 /* Clear agent forwarding if we don't have an agent. */
942                 if (!ssh_agent_present())
943                         options.forward_agent = 0;
944         }
945 }
946
947 static int
948 ssh_session(void)
949 {
950         int type;
951         int interactive = 0;
952         int have_tty = 0;
953         struct winsize ws;
954         char *cp;
955         const char *display;
956
957         /* Enable compression if requested. */
958         if (options.compression) {
959                 debug("Requesting compression at level %d.",
960                     options.compression_level);
961
962                 if (options.compression_level < 1 ||
963                     options.compression_level > 9)
964                         fatal("Compression level must be from 1 (fast) to "
965                             "9 (slow, best).");
966
967                 /* Send the request. */
968                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
969                 packet_put_int(options.compression_level);
970                 packet_send();
971                 packet_write_wait();
972                 type = packet_read();
973                 if (type == SSH_SMSG_SUCCESS)
974                         packet_start_compression(options.compression_level);
975                 else if (type == SSH_SMSG_FAILURE)
976                         logit("Warning: Remote host refused compression.");
977                 else
978                         packet_disconnect("Protocol error waiting for "
979                             "compression response.");
980         }
981         /* Allocate a pseudo tty if appropriate. */
982         if (tty_flag) {
983                 debug("Requesting pty.");
984
985                 /* Start the packet. */
986                 packet_start(SSH_CMSG_REQUEST_PTY);
987
988                 /* Store TERM in the packet.  There is no limit on the
989                    length of the string. */
990                 cp = getenv("TERM");
991                 if (!cp)
992                         cp = "";
993                 packet_put_cstring(cp);
994
995                 /* Store window size in the packet. */
996                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
997                         memset(&ws, 0, sizeof(ws));
998                 packet_put_int((u_int)ws.ws_row);
999                 packet_put_int((u_int)ws.ws_col);
1000                 packet_put_int((u_int)ws.ws_xpixel);
1001                 packet_put_int((u_int)ws.ws_ypixel);
1002
1003                 /* Store tty modes in the packet. */
1004                 tty_make_modes(fileno(stdin), NULL);
1005
1006                 /* Send the packet, and wait for it to leave. */
1007                 packet_send();
1008                 packet_write_wait();
1009
1010                 /* Read response from the server. */
1011                 type = packet_read();
1012                 if (type == SSH_SMSG_SUCCESS) {
1013                         interactive = 1;
1014                         have_tty = 1;
1015                 } else if (type == SSH_SMSG_FAILURE)
1016                         logit("Warning: Remote host failed or refused to "
1017                             "allocate a pseudo tty.");
1018                 else
1019                         packet_disconnect("Protocol error waiting for pty "
1020                             "request response.");
1021         }
1022         /* Request X11 forwarding if enabled and DISPLAY is set. */
1023         display = getenv("DISPLAY");
1024         if (options.forward_x11 && display != NULL) {
1025                 char *proto, *data;
1026                 /* Get reasonable local authentication information. */
1027                 client_x11_get_proto(display, options.xauth_location,
1028                     options.forward_x11_trusted, &proto, &data);
1029                 /* Request forwarding with authentication spoofing. */
1030                 debug("Requesting X11 forwarding with authentication "
1031                     "spoofing.");
1032                 x11_request_forwarding_with_spoofing(0, display, proto, data);
1033
1034                 /* Read response from the server. */
1035                 type = packet_read();
1036                 if (type == SSH_SMSG_SUCCESS) {
1037                         interactive = 1;
1038                 } else if (type == SSH_SMSG_FAILURE) {
1039                         logit("Warning: Remote host denied X11 forwarding.");
1040                 } else {
1041                         packet_disconnect("Protocol error waiting for X11 "
1042                             "forwarding");
1043                 }
1044         }
1045         /* Tell the packet module whether this is an interactive session. */
1046         packet_set_interactive(interactive);
1047
1048         /* Request authentication agent forwarding if appropriate. */
1049         check_agent_present();
1050
1051         if (options.forward_agent) {
1052                 debug("Requesting authentication agent forwarding.");
1053                 auth_request_forwarding();
1054
1055                 /* Read response from the server. */
1056                 type = packet_read();
1057                 packet_check_eom();
1058                 if (type != SSH_SMSG_SUCCESS)
1059                         logit("Warning: Remote host denied authentication agent forwarding.");
1060         }
1061
1062         /* Initiate port forwardings. */
1063         ssh_init_forwarding();
1064
1065         /* Execute a local command */
1066         if (options.local_command != NULL &&
1067             options.permit_local_command)
1068                 ssh_local_cmd(options.local_command);
1069
1070         /*
1071          * If requested and we are not interested in replies to remote
1072          * forwarding requests, then let ssh continue in the background.
1073          */
1074         if (fork_after_authentication_flag &&
1075             (!options.exit_on_forward_failure ||
1076             options.num_remote_forwards == 0)) {
1077                 fork_after_authentication_flag = 0;
1078                 if (daemon(1, 1) < 0)
1079                         fatal("daemon() failed: %.200s", strerror(errno));
1080         }
1081
1082         /*
1083          * If a command was specified on the command line, execute the
1084          * command now. Otherwise request the server to start a shell.
1085          */
1086         if (buffer_len(&command) > 0) {
1087                 int len = buffer_len(&command);
1088                 if (len > 900)
1089                         len = 900;
1090                 debug("Sending command: %.*s", len,
1091                     (u_char *)buffer_ptr(&command));
1092                 packet_start(SSH_CMSG_EXEC_CMD);
1093                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1094                 packet_send();
1095                 packet_write_wait();
1096         } else {
1097                 debug("Requesting shell.");
1098                 packet_start(SSH_CMSG_EXEC_SHELL);
1099                 packet_send();
1100                 packet_write_wait();
1101         }
1102
1103         /* Enter the interactive session. */
1104         return client_loop(have_tty, tty_flag ?
1105             options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1106 }
1107
1108 /* request pty/x11/agent/tcpfwd/shell for channel */
1109 static void
1110 ssh_session2_setup(int id, void *arg)
1111 {
1112         extern char **environ;
1113         const char *display;
1114         int interactive = tty_flag;
1115
1116         display = getenv("DISPLAY");
1117         if (options.forward_x11 && display != NULL) {
1118                 char *proto, *data;
1119                 /* Get reasonable local authentication information. */
1120                 client_x11_get_proto(display, options.xauth_location,
1121                     options.forward_x11_trusted, &proto, &data);
1122                 /* Request forwarding with authentication spoofing. */
1123                 debug("Requesting X11 forwarding with authentication "
1124                     "spoofing.");
1125                 x11_request_forwarding_with_spoofing(id, display, proto, data);
1126                 interactive = 1;
1127                 /* XXX wait for reply */
1128         }
1129
1130         check_agent_present();
1131         if (options.forward_agent) {
1132                 debug("Requesting authentication agent forwarding.");
1133                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1134                 packet_send();
1135         }
1136
1137         client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1138             NULL, fileno(stdin), &command, environ);
1139
1140         packet_set_interactive(interactive);
1141 }
1142
1143 /* open new channel for a session */
1144 static int
1145 ssh_session2_open(void)
1146 {
1147         Channel *c;
1148         int window, packetmax, in, out, err;
1149
1150         if (stdin_null_flag) {
1151                 in = open(_PATH_DEVNULL, O_RDONLY);
1152         } else {
1153                 in = dup(STDIN_FILENO);
1154         }
1155         out = dup(STDOUT_FILENO);
1156         err = dup(STDERR_FILENO);
1157
1158         if (in < 0 || out < 0 || err < 0)
1159                 fatal("dup() in/out/err failed");
1160
1161         /* enable nonblocking unless tty */
1162         if (!isatty(in))
1163                 set_nonblock(in);
1164         if (!isatty(out))
1165                 set_nonblock(out);
1166         if (!isatty(err))
1167                 set_nonblock(err);
1168
1169         window = CHAN_SES_WINDOW_DEFAULT;
1170         packetmax = CHAN_SES_PACKET_DEFAULT;
1171         if (tty_flag) {
1172                 window >>= 1;
1173                 packetmax >>= 1;
1174         }
1175         c = channel_new(
1176             "session", SSH_CHANNEL_OPENING, in, out, err,
1177             window, packetmax, CHAN_EXTENDED_WRITE,
1178             "client-session", /*nonblock*/0);
1179
1180         debug3("ssh_session2_open: channel_new: %d", c->self);
1181
1182         channel_send_open(c->self);
1183         if (!no_shell_flag)
1184                 channel_register_open_confirm(c->self,
1185                     ssh_session2_setup, NULL);
1186
1187         return c->self;
1188 }
1189
1190 static int
1191 ssh_session2(void)
1192 {
1193         int id = -1;
1194
1195         /* XXX should be pre-session */
1196         ssh_init_forwarding();
1197
1198         if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1199                 id = ssh_session2_open();
1200
1201         /* If we don't expect to open a new session, then disallow it */
1202         if (options.control_master == SSHCTL_MASTER_NO &&
1203             (datafellows & SSH_NEW_OPENSSH)) {
1204                 debug("Requesting no-more-sessions@openssh.com");
1205                 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1206                 packet_put_cstring("no-more-sessions@openssh.com");
1207                 packet_put_char(0);
1208                 packet_send();
1209         }
1210
1211         /* Execute a local command */
1212         if (options.local_command != NULL &&
1213             options.permit_local_command)
1214                 ssh_local_cmd(options.local_command);
1215
1216         /* Start listening for multiplex clients */
1217         muxserver_listen();
1218
1219         /* If requested, let ssh continue in the background. */
1220         if (fork_after_authentication_flag) {
1221                 fork_after_authentication_flag = 0;
1222                 if (daemon(1, 1) < 0)
1223                         fatal("daemon() failed: %.200s", strerror(errno));
1224         }
1225
1226         if (options.use_roaming)
1227                 request_roaming();
1228
1229         return client_loop(tty_flag, tty_flag ?
1230             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1231 }
1232
1233 static void
1234 load_public_identity_files(void)
1235 {
1236         char *filename, *cp, thishost[NI_MAXHOST];
1237         char *pwdir = NULL, *pwname = NULL;
1238         int i = 0;
1239         Key *public;
1240         struct passwd *pw;
1241 #ifdef SMARTCARD
1242         Key **keys;
1243
1244         if (options.smartcard_device != NULL &&
1245             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1246             (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1247                 int count = 0;
1248                 for (i = 0; keys[i] != NULL; i++) {
1249                         count++;
1250                         memmove(&options.identity_files[1],
1251                             &options.identity_files[0],
1252                             sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1253                         memmove(&options.identity_keys[1],
1254                             &options.identity_keys[0],
1255                             sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1256                         options.num_identity_files++;
1257                         options.identity_keys[0] = keys[i];
1258                         options.identity_files[0] = sc_get_key_label(keys[i]);
1259                 }
1260                 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1261                         options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1262                 i = count;
1263                 xfree(keys);
1264         }
1265 #endif /* SMARTCARD */
1266         if ((pw = getpwuid(original_real_uid)) == NULL)
1267                 fatal("load_public_identity_files: getpwuid failed");
1268         pwname = xstrdup(pw->pw_name);
1269         pwdir = xstrdup(pw->pw_dir);
1270         if (gethostname(thishost, sizeof(thishost)) == -1)
1271                 fatal("load_public_identity_files: gethostname: %s",
1272                     strerror(errno));
1273         for (; i < options.num_identity_files; i++) {
1274                 cp = tilde_expand_filename(options.identity_files[i],
1275                     original_real_uid);
1276                 filename = percent_expand(cp, "d", pwdir,
1277                     "u", pwname, "l", thishost, "h", host,
1278                     "r", options.user, (char *)NULL);
1279                 xfree(cp);
1280                 public = key_load_public(filename, NULL);
1281                 debug("identity file %s type %d", filename,
1282                     public ? public->type : -1);
1283                 xfree(options.identity_files[i]);
1284                 options.identity_files[i] = filename;
1285                 options.identity_keys[i] = public;
1286         }
1287         bzero(pwname, strlen(pwname));
1288         xfree(pwname);
1289         bzero(pwdir, strlen(pwdir));
1290         xfree(pwdir);
1291 }
This page took 0.145559 seconds and 5 git commands to generate.