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