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