]> andersk Git - openssh.git/blame_incremental - ssh.c
- dtucker@cvs.openbsd.org 2009/02/02 11:15:14
[openssh.git] / ssh.c
... / ...
CommitLineData
1/* $OpenBSD: ssh.c,v 1.323 2009/01/22 10:02:34 djm Exp $ */
2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
9 *
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 *
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
18 *
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 *
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 */
42
43#include "includes.h"
44
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
108extern char *__progname;
109
110/* Flag indicating whether debug mode is on. May be set on the command line. */
111int debug_flag = 0;
112
113/* Flag indicating whether a tty should be allocated */
114int tty_flag = 0;
115int no_tty_flag = 0;
116int force_tty_flag = 0;
117
118/* don't exec a shell */
119int 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 */
125int 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 */
132int 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 */
138Options options;
139
140/* optional user configfile */
141char *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 */
148char *host;
149
150/* socket address the host resolves to */
151struct sockaddr_storage hostaddr;
152
153/* Private host keys. */
154Sensitive sensitive_data;
155
156/* Original real UID. */
157uid_t original_real_uid;
158uid_t original_effective_uid;
159
160/* command to be executed */
161Buffer command;
162
163/* Should we execute a command or invoke a subsystem? */
164int subsystem_flag = 0;
165
166/* # of replies received for global requests */
167static int remote_forward_confirms_received = 0;
168
169/* pid of proxycommand child process */
170pid_t proxy_command_pid = 0;
171
172/* mux.c */
173extern int muxserver_sock;
174extern u_int muxclient_command;
175
176/* Prints a help message to the user. This function never returns. */
177
178static void
179usage(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
192static int ssh_session(void);
193static int ssh_session2(void);
194static void load_public_identity_files(void);
195
196/* from muxclient.c */
197void muxclient(const char *);
198void muxserver_listen(void);
199
200/*
201 * Main program for the ssh client.
202 */
203int
204main(int ac, char **av)
205{
206 int i, opt, exit_status, use_syslog;
207 char *p, *cp, *line, 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
274 again:
275 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
276 "ACD:F:I:KL:MNO:PR:S:TVw:XYy")) != -1) {
277 switch (opt) {
278 case '1':
279 options.protocol = SSH_PROTO_1;
280 break;
281 case '2':
282 options.protocol = SSH_PROTO_2;
283 break;
284 case '4':
285 options.address_family = AF_INET;
286 break;
287 case '6':
288 options.address_family = AF_INET6;
289 break;
290 case 'n':
291 stdin_null_flag = 1;
292 break;
293 case 'f':
294 fork_after_authentication_flag = 1;
295 stdin_null_flag = 1;
296 break;
297 case 'x':
298 options.forward_x11 = 0;
299 break;
300 case 'X':
301 options.forward_x11 = 1;
302 break;
303 case 'y':
304 use_syslog = 1;
305 break;
306 case 'Y':
307 options.forward_x11 = 1;
308 options.forward_x11_trusted = 1;
309 break;
310 case 'g':
311 options.gateway_ports = 1;
312 break;
313 case 'O':
314 if (strcmp(optarg, "check") == 0)
315 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
316 else if (strcmp(optarg, "exit") == 0)
317 muxclient_command = SSHMUX_COMMAND_TERMINATE;
318 else
319 fatal("Invalid multiplex command.");
320 break;
321 case 'P': /* deprecated */
322 options.use_privileged_port = 0;
323 break;
324 case 'a':
325 options.forward_agent = 0;
326 break;
327 case 'A':
328 options.forward_agent = 1;
329 break;
330 case 'k':
331 options.gss_deleg_creds = 0;
332 break;
333 case 'K':
334 options.gss_authentication = 1;
335 options.gss_deleg_creds = 1;
336 break;
337 case 'i':
338 if (stat(optarg, &st) < 0) {
339 fprintf(stderr, "Warning: Identity file %s "
340 "not accessible: %s.\n", optarg,
341 strerror(errno));
342 break;
343 }
344 if (options.num_identity_files >=
345 SSH_MAX_IDENTITY_FILES)
346 fatal("Too many identity files specified "
347 "(max %d)", SSH_MAX_IDENTITY_FILES);
348 options.identity_files[options.num_identity_files++] =
349 xstrdup(optarg);
350 break;
351 case 'I':
352#ifdef SMARTCARD
353 options.smartcard_device = xstrdup(optarg);
354#else
355 fprintf(stderr, "no support for smartcards.\n");
356#endif
357 break;
358 case 't':
359 if (tty_flag)
360 force_tty_flag = 1;
361 tty_flag = 1;
362 break;
363 case 'v':
364 if (debug_flag == 0) {
365 debug_flag = 1;
366 options.log_level = SYSLOG_LEVEL_DEBUG1;
367 } else {
368 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
369 options.log_level++;
370 break;
371 }
372 /* FALLTHROUGH */
373 case 'V':
374 fprintf(stderr, "%s, %s\n",
375 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
376 if (opt == 'V')
377 exit(0);
378 break;
379 case 'w':
380 if (options.tun_open == -1)
381 options.tun_open = SSH_TUNMODE_DEFAULT;
382 options.tun_local = a2tun(optarg, &options.tun_remote);
383 if (options.tun_local == SSH_TUNID_ERR) {
384 fprintf(stderr,
385 "Bad tun device '%s'\n", optarg);
386 exit(255);
387 }
388 break;
389 case 'q':
390 options.log_level = SYSLOG_LEVEL_QUIET;
391 break;
392 case 'e':
393 if (optarg[0] == '^' && optarg[2] == 0 &&
394 (u_char) optarg[1] >= 64 &&
395 (u_char) optarg[1] < 128)
396 options.escape_char = (u_char) optarg[1] & 31;
397 else if (strlen(optarg) == 1)
398 options.escape_char = (u_char) optarg[0];
399 else if (strcmp(optarg, "none") == 0)
400 options.escape_char = SSH_ESCAPECHAR_NONE;
401 else {
402 fprintf(stderr, "Bad escape character '%s'.\n",
403 optarg);
404 exit(255);
405 }
406 break;
407 case 'c':
408 if (ciphers_valid(optarg)) {
409 /* SSH2 only */
410 options.ciphers = xstrdup(optarg);
411 options.cipher = SSH_CIPHER_INVALID;
412 } else {
413 /* SSH1 only */
414 options.cipher = cipher_number(optarg);
415 if (options.cipher == -1) {
416 fprintf(stderr,
417 "Unknown cipher type '%s'\n",
418 optarg);
419 exit(255);
420 }
421 if (options.cipher == SSH_CIPHER_3DES)
422 options.ciphers = "3des-cbc";
423 else if (options.cipher == SSH_CIPHER_BLOWFISH)
424 options.ciphers = "blowfish-cbc";
425 else
426 options.ciphers = (char *)-1;
427 }
428 break;
429 case 'm':
430 if (mac_valid(optarg))
431 options.macs = xstrdup(optarg);
432 else {
433 fprintf(stderr, "Unknown mac type '%s'\n",
434 optarg);
435 exit(255);
436 }
437 break;
438 case 'M':
439 if (options.control_master == SSHCTL_MASTER_YES)
440 options.control_master = SSHCTL_MASTER_ASK;
441 else
442 options.control_master = SSHCTL_MASTER_YES;
443 break;
444 case 'p':
445 options.port = a2port(optarg);
446 if (options.port <= 0) {
447 fprintf(stderr, "Bad port '%s'\n", optarg);
448 exit(255);
449 }
450 break;
451 case 'l':
452 options.user = optarg;
453 break;
454
455 case 'L':
456 if (parse_forward(&fwd, optarg, 0))
457 add_local_forward(&options, &fwd);
458 else {
459 fprintf(stderr,
460 "Bad local forwarding specification '%s'\n",
461 optarg);
462 exit(255);
463 }
464 break;
465
466 case 'R':
467 if (parse_forward(&fwd, optarg, 0)) {
468 add_remote_forward(&options, &fwd);
469 } else {
470 fprintf(stderr,
471 "Bad remote forwarding specification "
472 "'%s'\n", optarg);
473 exit(255);
474 }
475 break;
476
477 case 'D':
478 if (parse_forward(&fwd, optarg, 1)) {
479 add_local_forward(&options, &fwd);
480 } else {
481 fprintf(stderr,
482 "Bad dynamic forwarding specification "
483 "'%s'\n", optarg);
484 exit(255);
485 }
486 break;
487
488 case 'C':
489 options.compression = 1;
490 break;
491 case 'N':
492 no_shell_flag = 1;
493 no_tty_flag = 1;
494 break;
495 case 'T':
496 no_tty_flag = 1;
497 break;
498 case 'o':
499 dummy = 1;
500 line = xstrdup(optarg);
501 if (process_config_line(&options, host ? host : "",
502 line, "command-line", 0, &dummy) != 0)
503 exit(255);
504 xfree(line);
505 break;
506 case 's':
507 subsystem_flag = 1;
508 break;
509 case 'S':
510 if (options.control_path != NULL)
511 free(options.control_path);
512 options.control_path = xstrdup(optarg);
513 break;
514 case 'b':
515 options.bind_address = optarg;
516 break;
517 case 'F':
518 config = optarg;
519 break;
520 default:
521 usage();
522 }
523 }
524
525 ac -= optind;
526 av += optind;
527
528 if (ac > 0 && !host && **av != '-') {
529 if (strrchr(*av, '@')) {
530 p = xstrdup(*av);
531 cp = strrchr(p, '@');
532 if (cp == NULL || cp == p)
533 usage();
534 options.user = p;
535 *cp = '\0';
536 host = ++cp;
537 } else
538 host = *av;
539 if (ac > 1) {
540 optind = optreset = 1;
541 goto again;
542 }
543 ac--, av++;
544 }
545
546 /* Check that we got a host name. */
547 if (!host)
548 usage();
549
550 SSLeay_add_all_algorithms();
551 ERR_load_crypto_strings();
552
553 /* Initialize the command to execute on remote host. */
554 buffer_init(&command);
555
556 /*
557 * Save the command to execute on the remote host in a buffer. There
558 * is no limit on the length of the command, except by the maximum
559 * packet size. Also sets the tty flag if there is no command.
560 */
561 if (!ac) {
562 /* No command specified - execute shell on a tty. */
563 tty_flag = 1;
564 if (subsystem_flag) {
565 fprintf(stderr,
566 "You must specify a subsystem to invoke.\n");
567 usage();
568 }
569 } else {
570 /* A command has been specified. Store it into the buffer. */
571 for (i = 0; i < ac; i++) {
572 if (i)
573 buffer_append(&command, " ", 1);
574 buffer_append(&command, av[i], strlen(av[i]));
575 }
576 }
577
578 /* Cannot fork to background if no command. */
579 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
580 !no_shell_flag)
581 fatal("Cannot fork into background without a command "
582 "to execute.");
583
584 /* Allocate a tty by default if no command specified. */
585 if (buffer_len(&command) == 0)
586 tty_flag = 1;
587
588 /* Force no tty */
589 if (no_tty_flag)
590 tty_flag = 0;
591 /* Do not allocate a tty if stdin is not a tty. */
592 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
593 if (tty_flag)
594 logit("Pseudo-terminal will not be allocated because "
595 "stdin is not a terminal.");
596 tty_flag = 0;
597 }
598
599 /*
600 * Initialize "log" output. Since we are the client all output
601 * actually goes to stderr.
602 */
603 log_init(av[0],
604 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
605 SYSLOG_FACILITY_USER, !use_syslog);
606
607 /*
608 * Read per-user configuration file. Ignore the system wide config
609 * file if the user specifies a config file on the command line.
610 */
611 if (config != NULL) {
612 if (!read_config_file(config, host, &options, 0))
613 fatal("Can't open user config file %.100s: "
614 "%.100s", config, strerror(errno));
615 } else {
616 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
617 _PATH_SSH_USER_CONFFILE);
618 (void)read_config_file(buf, host, &options, 1);
619
620 /* Read systemwide configuration file after use config. */
621 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
622 &options, 0);
623 }
624
625 /* Fill configuration defaults. */
626 fill_default_options(&options);
627
628 channel_set_af(options.address_family);
629
630 /* reinit */
631 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
632
633 seed_rng();
634
635 if (options.user == NULL)
636 options.user = xstrdup(pw->pw_name);
637
638 /* Get default port if port has not been set. */
639 if (options.port == 0) {
640 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
641 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
642 }
643
644 if (options.local_command != NULL) {
645 char thishost[NI_MAXHOST];
646
647 if (gethostname(thishost, sizeof(thishost)) == -1)
648 fatal("gethostname: %s", strerror(errno));
649 snprintf(buf, sizeof(buf), "%d", options.port);
650 debug3("expanding LocalCommand: %s", options.local_command);
651 cp = options.local_command;
652 options.local_command = percent_expand(cp, "d", pw->pw_dir,
653 "h", options.hostname? options.hostname : host,
654 "l", thishost, "n", host, "r", options.user, "p", buf,
655 "u", pw->pw_name, (char *)NULL);
656 debug3("expanded LocalCommand: %s", options.local_command);
657 xfree(cp);
658 }
659
660 if (options.hostname != NULL)
661 host = options.hostname;
662
663 /* force lowercase for hostkey matching */
664 if (options.host_key_alias != NULL) {
665 for (p = options.host_key_alias; *p; p++)
666 if (isupper(*p))
667 *p = (char)tolower(*p);
668 }
669
670 if (options.proxy_command != NULL &&
671 strcmp(options.proxy_command, "none") == 0) {
672 xfree(options.proxy_command);
673 options.proxy_command = NULL;
674 }
675 if (options.control_path != NULL &&
676 strcmp(options.control_path, "none") == 0) {
677 xfree(options.control_path);
678 options.control_path = NULL;
679 }
680
681 if (options.control_path != NULL) {
682 char thishost[NI_MAXHOST];
683
684 if (gethostname(thishost, sizeof(thishost)) == -1)
685 fatal("gethostname: %s", strerror(errno));
686 snprintf(buf, sizeof(buf), "%d", options.port);
687 cp = tilde_expand_filename(options.control_path,
688 original_real_uid);
689 xfree(options.control_path);
690 options.control_path = percent_expand(cp, "p", buf, "h", host,
691 "r", options.user, "l", thishost, (char *)NULL);
692 xfree(cp);
693 }
694 if (muxclient_command != 0 && options.control_path == NULL)
695 fatal("No ControlPath specified for \"-O\" command");
696 if (options.control_path != NULL)
697 muxclient(options.control_path);
698
699 timeout_ms = options.connection_timeout * 1000;
700
701 /* Open a connection to the remote host. */
702 if (ssh_connect(host, &hostaddr, options.port,
703 options.address_family, options.connection_attempts, &timeout_ms,
704 options.tcp_keep_alive,
705#ifdef HAVE_CYGWIN
706 options.use_privileged_port,
707#else
708 original_effective_uid == 0 && options.use_privileged_port,
709#endif
710 options.proxy_command) != 0)
711 exit(255);
712
713 if (timeout_ms > 0)
714 debug3("timeout: %d ms remain after connect", timeout_ms);
715
716 /*
717 * If we successfully made the connection, load the host private key
718 * in case we will need it later for combined rsa-rhosts
719 * authentication. This must be done before releasing extra
720 * privileges, because the file is only readable by root.
721 * If we cannot access the private keys, load the public keys
722 * instead and try to execute the ssh-keysign helper instead.
723 */
724 sensitive_data.nkeys = 0;
725 sensitive_data.keys = NULL;
726 sensitive_data.external_keysign = 0;
727 if (options.rhosts_rsa_authentication ||
728 options.hostbased_authentication) {
729 sensitive_data.nkeys = 3;
730 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
731 sizeof(Key));
732
733 PRIV_START;
734 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
735 _PATH_HOST_KEY_FILE, "", NULL, NULL);
736 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
737 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
738 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
739 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
740 PRIV_END;
741
742 if (options.hostbased_authentication == 1 &&
743 sensitive_data.keys[0] == NULL &&
744 sensitive_data.keys[1] == NULL &&
745 sensitive_data.keys[2] == NULL) {
746 sensitive_data.keys[1] = key_load_public(
747 _PATH_HOST_DSA_KEY_FILE, NULL);
748 sensitive_data.keys[2] = key_load_public(
749 _PATH_HOST_RSA_KEY_FILE, NULL);
750 sensitive_data.external_keysign = 1;
751 }
752 }
753 /*
754 * Get rid of any extra privileges that we may have. We will no
755 * longer need them. Also, extra privileges could make it very hard
756 * to read identity files and other non-world-readable files from the
757 * user's home directory if it happens to be on a NFS volume where
758 * root is mapped to nobody.
759 */
760 if (original_effective_uid == 0) {
761 PRIV_START;
762 permanently_set_uid(pw);
763 }
764
765 /*
766 * Now that we are back to our own permissions, create ~/.ssh
767 * directory if it doesn't already exist.
768 */
769 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir,
770 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
771 if (stat(buf, &st) < 0)
772 if (mkdir(buf, 0700) < 0)
773 error("Could not create directory '%.200s'.", buf);
774
775 /* load options.identity_files */
776 load_public_identity_files();
777
778 /* Expand ~ in known host file names. */
779 /* XXX mem-leaks: */
780 options.system_hostfile =
781 tilde_expand_filename(options.system_hostfile, original_real_uid);
782 options.user_hostfile =
783 tilde_expand_filename(options.user_hostfile, original_real_uid);
784 options.system_hostfile2 =
785 tilde_expand_filename(options.system_hostfile2, original_real_uid);
786 options.user_hostfile2 =
787 tilde_expand_filename(options.user_hostfile2, original_real_uid);
788
789 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
790
791 /* Log into the remote system. Never returns if the login fails. */
792 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
793 pw, timeout_ms);
794
795 /* We no longer need the private host keys. Clear them now. */
796 if (sensitive_data.nkeys != 0) {
797 for (i = 0; i < sensitive_data.nkeys; i++) {
798 if (sensitive_data.keys[i] != NULL) {
799 /* Destroys contents safely */
800 debug3("clear hostkey %d", i);
801 key_free(sensitive_data.keys[i]);
802 sensitive_data.keys[i] = NULL;
803 }
804 }
805 xfree(sensitive_data.keys);
806 }
807 for (i = 0; i < options.num_identity_files; i++) {
808 if (options.identity_files[i]) {
809 xfree(options.identity_files[i]);
810 options.identity_files[i] = NULL;
811 }
812 if (options.identity_keys[i]) {
813 key_free(options.identity_keys[i]);
814 options.identity_keys[i] = NULL;
815 }
816 }
817
818 exit_status = compat20 ? ssh_session2() : ssh_session();
819 packet_close();
820
821 if (options.control_path != NULL && muxserver_sock != -1)
822 unlink(options.control_path);
823
824 /*
825 * Send SIGHUP to proxy command if used. We don't wait() in
826 * case it hangs and instead rely on init to reap the child
827 */
828 if (proxy_command_pid > 1)
829 kill(proxy_command_pid, SIGHUP);
830
831 return exit_status;
832}
833
834/* Callback for remote forward global requests */
835static void
836ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
837{
838 Forward *rfwd = (Forward *)ctxt;
839
840 debug("remote forward %s for: listen %d, connect %s:%d",
841 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
842 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
843 if (type == SSH2_MSG_REQUEST_FAILURE) {
844 if (options.exit_on_forward_failure)
845 fatal("Error: remote port forwarding failed for "
846 "listen port %d", rfwd->listen_port);
847 else
848 logit("Warning: remote port forwarding failed for "
849 "listen port %d", rfwd->listen_port);
850 }
851 if (++remote_forward_confirms_received == options.num_remote_forwards) {
852 debug("All remote forwarding requests processed");
853 if (fork_after_authentication_flag) {
854 fork_after_authentication_flag = 0;
855 if (daemon(1, 1) < 0)
856 fatal("daemon() failed: %.200s",
857 strerror(errno));
858 }
859 }
860}
861
862static void
863ssh_init_forwarding(void)
864{
865 int success = 0;
866 int i;
867
868 /* Initiate local TCP/IP port forwardings. */
869 for (i = 0; i < options.num_local_forwards; i++) {
870 debug("Local connections to %.200s:%d forwarded to remote "
871 "address %.200s:%d",
872 (options.local_forwards[i].listen_host == NULL) ?
873 (options.gateway_ports ? "*" : "LOCALHOST") :
874 options.local_forwards[i].listen_host,
875 options.local_forwards[i].listen_port,
876 options.local_forwards[i].connect_host,
877 options.local_forwards[i].connect_port);
878 success += channel_setup_local_fwd_listener(
879 options.local_forwards[i].listen_host,
880 options.local_forwards[i].listen_port,
881 options.local_forwards[i].connect_host,
882 options.local_forwards[i].connect_port,
883 options.gateway_ports);
884 }
885 if (i > 0 && success != i && options.exit_on_forward_failure)
886 fatal("Could not request local forwarding.");
887 if (i > 0 && success == 0)
888 error("Could not request local forwarding.");
889
890 /* Initiate remote TCP/IP port forwardings. */
891 for (i = 0; i < options.num_remote_forwards; i++) {
892 debug("Remote connections from %.200s:%d forwarded to "
893 "local address %.200s:%d",
894 (options.remote_forwards[i].listen_host == NULL) ?
895 "LOCALHOST" : options.remote_forwards[i].listen_host,
896 options.remote_forwards[i].listen_port,
897 options.remote_forwards[i].connect_host,
898 options.remote_forwards[i].connect_port);
899 if (channel_request_remote_forwarding(
900 options.remote_forwards[i].listen_host,
901 options.remote_forwards[i].listen_port,
902 options.remote_forwards[i].connect_host,
903 options.remote_forwards[i].connect_port) < 0) {
904 if (options.exit_on_forward_failure)
905 fatal("Could not request remote forwarding.");
906 else
907 logit("Warning: Could not request remote "
908 "forwarding.");
909 }
910 client_register_global_confirm(ssh_confirm_remote_forward,
911 &options.remote_forwards[i]);
912 }
913
914 /* Initiate tunnel forwarding. */
915 if (options.tun_open != SSH_TUNMODE_NO) {
916 if (client_request_tun_fwd(options.tun_open,
917 options.tun_local, options.tun_remote) == -1) {
918 if (options.exit_on_forward_failure)
919 fatal("Could not request tunnel forwarding.");
920 else
921 error("Could not request tunnel forwarding.");
922 }
923 }
924}
925
926static void
927check_agent_present(void)
928{
929 if (options.forward_agent) {
930 /* Clear agent forwarding if we don't have an agent. */
931 if (!ssh_agent_present())
932 options.forward_agent = 0;
933 }
934}
935
936static int
937ssh_session(void)
938{
939 int type;
940 int interactive = 0;
941 int have_tty = 0;
942 struct winsize ws;
943 char *cp;
944 const char *display;
945
946 /* Enable compression if requested. */
947 if (options.compression) {
948 debug("Requesting compression at level %d.",
949 options.compression_level);
950
951 if (options.compression_level < 1 ||
952 options.compression_level > 9)
953 fatal("Compression level must be from 1 (fast) to "
954 "9 (slow, best).");
955
956 /* Send the request. */
957 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
958 packet_put_int(options.compression_level);
959 packet_send();
960 packet_write_wait();
961 type = packet_read();
962 if (type == SSH_SMSG_SUCCESS)
963 packet_start_compression(options.compression_level);
964 else if (type == SSH_SMSG_FAILURE)
965 logit("Warning: Remote host refused compression.");
966 else
967 packet_disconnect("Protocol error waiting for "
968 "compression response.");
969 }
970 /* Allocate a pseudo tty if appropriate. */
971 if (tty_flag) {
972 debug("Requesting pty.");
973
974 /* Start the packet. */
975 packet_start(SSH_CMSG_REQUEST_PTY);
976
977 /* Store TERM in the packet. There is no limit on the
978 length of the string. */
979 cp = getenv("TERM");
980 if (!cp)
981 cp = "";
982 packet_put_cstring(cp);
983
984 /* Store window size in the packet. */
985 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
986 memset(&ws, 0, sizeof(ws));
987 packet_put_int((u_int)ws.ws_row);
988 packet_put_int((u_int)ws.ws_col);
989 packet_put_int((u_int)ws.ws_xpixel);
990 packet_put_int((u_int)ws.ws_ypixel);
991
992 /* Store tty modes in the packet. */
993 tty_make_modes(fileno(stdin), NULL);
994
995 /* Send the packet, and wait for it to leave. */
996 packet_send();
997 packet_write_wait();
998
999 /* Read response from the server. */
1000 type = packet_read();
1001 if (type == SSH_SMSG_SUCCESS) {
1002 interactive = 1;
1003 have_tty = 1;
1004 } else if (type == SSH_SMSG_FAILURE)
1005 logit("Warning: Remote host failed or refused to "
1006 "allocate a pseudo tty.");
1007 else
1008 packet_disconnect("Protocol error waiting for pty "
1009 "request response.");
1010 }
1011 /* Request X11 forwarding if enabled and DISPLAY is set. */
1012 display = getenv("DISPLAY");
1013 if (options.forward_x11 && display != NULL) {
1014 char *proto, *data;
1015 /* Get reasonable local authentication information. */
1016 client_x11_get_proto(display, options.xauth_location,
1017 options.forward_x11_trusted, &proto, &data);
1018 /* Request forwarding with authentication spoofing. */
1019 debug("Requesting X11 forwarding with authentication "
1020 "spoofing.");
1021 x11_request_forwarding_with_spoofing(0, display, proto, data);
1022
1023 /* Read response from the server. */
1024 type = packet_read();
1025 if (type == SSH_SMSG_SUCCESS) {
1026 interactive = 1;
1027 } else if (type == SSH_SMSG_FAILURE) {
1028 logit("Warning: Remote host denied X11 forwarding.");
1029 } else {
1030 packet_disconnect("Protocol error waiting for X11 "
1031 "forwarding");
1032 }
1033 }
1034 /* Tell the packet module whether this is an interactive session. */
1035 packet_set_interactive(interactive);
1036
1037 /* Request authentication agent forwarding if appropriate. */
1038 check_agent_present();
1039
1040 if (options.forward_agent) {
1041 debug("Requesting authentication agent forwarding.");
1042 auth_request_forwarding();
1043
1044 /* Read response from the server. */
1045 type = packet_read();
1046 packet_check_eom();
1047 if (type != SSH_SMSG_SUCCESS)
1048 logit("Warning: Remote host denied authentication agent forwarding.");
1049 }
1050
1051 /* Initiate port forwardings. */
1052 ssh_init_forwarding();
1053
1054 /* Execute a local command */
1055 if (options.local_command != NULL &&
1056 options.permit_local_command)
1057 ssh_local_cmd(options.local_command);
1058
1059 /*
1060 * If requested and we are not interested in replies to remote
1061 * forwarding requests, then let ssh continue in the background.
1062 */
1063 if (fork_after_authentication_flag &&
1064 (!options.exit_on_forward_failure ||
1065 options.num_remote_forwards == 0)) {
1066 fork_after_authentication_flag = 0;
1067 if (daemon(1, 1) < 0)
1068 fatal("daemon() failed: %.200s", strerror(errno));
1069 }
1070
1071 /*
1072 * If a command was specified on the command line, execute the
1073 * command now. Otherwise request the server to start a shell.
1074 */
1075 if (buffer_len(&command) > 0) {
1076 int len = buffer_len(&command);
1077 if (len > 900)
1078 len = 900;
1079 debug("Sending command: %.*s", len,
1080 (u_char *)buffer_ptr(&command));
1081 packet_start(SSH_CMSG_EXEC_CMD);
1082 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1083 packet_send();
1084 packet_write_wait();
1085 } else {
1086 debug("Requesting shell.");
1087 packet_start(SSH_CMSG_EXEC_SHELL);
1088 packet_send();
1089 packet_write_wait();
1090 }
1091
1092 /* Enter the interactive session. */
1093 return client_loop(have_tty, tty_flag ?
1094 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1095}
1096
1097/* request pty/x11/agent/tcpfwd/shell for channel */
1098static void
1099ssh_session2_setup(int id, void *arg)
1100{
1101 extern char **environ;
1102 const char *display;
1103 int interactive = tty_flag;
1104
1105 display = getenv("DISPLAY");
1106 if (options.forward_x11 && display != NULL) {
1107 char *proto, *data;
1108 /* Get reasonable local authentication information. */
1109 client_x11_get_proto(display, options.xauth_location,
1110 options.forward_x11_trusted, &proto, &data);
1111 /* Request forwarding with authentication spoofing. */
1112 debug("Requesting X11 forwarding with authentication "
1113 "spoofing.");
1114 x11_request_forwarding_with_spoofing(id, display, proto, data);
1115 interactive = 1;
1116 /* XXX wait for reply */
1117 }
1118
1119 check_agent_present();
1120 if (options.forward_agent) {
1121 debug("Requesting authentication agent forwarding.");
1122 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1123 packet_send();
1124 }
1125
1126 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1127 NULL, fileno(stdin), &command, environ);
1128
1129 packet_set_interactive(interactive);
1130}
1131
1132/* open new channel for a session */
1133static int
1134ssh_session2_open(void)
1135{
1136 Channel *c;
1137 int window, packetmax, in, out, err;
1138
1139 if (stdin_null_flag) {
1140 in = open(_PATH_DEVNULL, O_RDONLY);
1141 } else {
1142 in = dup(STDIN_FILENO);
1143 }
1144 out = dup(STDOUT_FILENO);
1145 err = dup(STDERR_FILENO);
1146
1147 if (in < 0 || out < 0 || err < 0)
1148 fatal("dup() in/out/err failed");
1149
1150 /* enable nonblocking unless tty */
1151 if (!isatty(in))
1152 set_nonblock(in);
1153 if (!isatty(out))
1154 set_nonblock(out);
1155 if (!isatty(err))
1156 set_nonblock(err);
1157
1158 window = CHAN_SES_WINDOW_DEFAULT;
1159 packetmax = CHAN_SES_PACKET_DEFAULT;
1160 if (tty_flag) {
1161 window >>= 1;
1162 packetmax >>= 1;
1163 }
1164 c = channel_new(
1165 "session", SSH_CHANNEL_OPENING, in, out, err,
1166 window, packetmax, CHAN_EXTENDED_WRITE,
1167 "client-session", /*nonblock*/0);
1168
1169 debug3("ssh_session2_open: channel_new: %d", c->self);
1170
1171 channel_send_open(c->self);
1172 if (!no_shell_flag)
1173 channel_register_open_confirm(c->self,
1174 ssh_session2_setup, NULL);
1175
1176 return c->self;
1177}
1178
1179static int
1180ssh_session2(void)
1181{
1182 int id = -1;
1183
1184 /* XXX should be pre-session */
1185 ssh_init_forwarding();
1186
1187 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1188 id = ssh_session2_open();
1189
1190 /* If we don't expect to open a new session, then disallow it */
1191 if (options.control_master == SSHCTL_MASTER_NO &&
1192 (datafellows & SSH_NEW_OPENSSH)) {
1193 debug("Requesting no-more-sessions@openssh.com");
1194 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1195 packet_put_cstring("no-more-sessions@openssh.com");
1196 packet_put_char(0);
1197 packet_send();
1198 }
1199
1200 /* Execute a local command */
1201 if (options.local_command != NULL &&
1202 options.permit_local_command)
1203 ssh_local_cmd(options.local_command);
1204
1205 /* Start listening for multiplex clients */
1206 muxserver_listen();
1207
1208 /* If requested, let ssh continue in the background. */
1209 if (fork_after_authentication_flag) {
1210 fork_after_authentication_flag = 0;
1211 if (daemon(1, 1) < 0)
1212 fatal("daemon() failed: %.200s", strerror(errno));
1213 }
1214
1215 return client_loop(tty_flag, tty_flag ?
1216 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1217}
1218
1219static void
1220load_public_identity_files(void)
1221{
1222 char *filename, *cp, thishost[NI_MAXHOST];
1223 char *pwdir = NULL, *pwname = NULL;
1224 int i = 0;
1225 Key *public;
1226 struct passwd *pw;
1227#ifdef SMARTCARD
1228 Key **keys;
1229
1230 if (options.smartcard_device != NULL &&
1231 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1232 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1233 int count = 0;
1234 for (i = 0; keys[i] != NULL; i++) {
1235 count++;
1236 memmove(&options.identity_files[1],
1237 &options.identity_files[0],
1238 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1239 memmove(&options.identity_keys[1],
1240 &options.identity_keys[0],
1241 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1242 options.num_identity_files++;
1243 options.identity_keys[0] = keys[i];
1244 options.identity_files[0] = sc_get_key_label(keys[i]);
1245 }
1246 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1247 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1248 i = count;
1249 xfree(keys);
1250 }
1251#endif /* SMARTCARD */
1252 if ((pw = getpwuid(original_real_uid)) == NULL)
1253 fatal("load_public_identity_files: getpwuid failed");
1254 pwname = xstrdup(pw->pw_name);
1255 pwdir = xstrdup(pw->pw_dir);
1256 if (gethostname(thishost, sizeof(thishost)) == -1)
1257 fatal("load_public_identity_files: gethostname: %s",
1258 strerror(errno));
1259 for (; i < options.num_identity_files; i++) {
1260 cp = tilde_expand_filename(options.identity_files[i],
1261 original_real_uid);
1262 filename = percent_expand(cp, "d", pwdir,
1263 "u", pwname, "l", thishost, "h", host,
1264 "r", options.user, (char *)NULL);
1265 xfree(cp);
1266 public = key_load_public(filename, NULL);
1267 debug("identity file %s type %d", filename,
1268 public ? public->type : -1);
1269 xfree(options.identity_files[i]);
1270 options.identity_files[i] = filename;
1271 options.identity_keys[i] = public;
1272 }
1273 bzero(pwname, strlen(pwname));
1274 xfree(pwname);
1275 bzero(pwdir, strlen(pwdir));
1276 xfree(pwdir);
1277}
This page took 0.051853 seconds and 5 git commands to generate.