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