Import OpenSSH-5.1p1.
[dragonfly.git] / crypto / openssh-3.9p1 / ssh.c
blob1419f98749aa5e910fbce7d65d0ad7765328d9d5
1 /*
2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
5 * Ssh client program. This program can be used to log into a remote machine.
6 * The software supports strong authentication, encryption, and forwarding
7 * of X11, TCP/IP, and authentication connections.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 1999 Niels Provos. All rights reserved.
16 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
18 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
19 * in Canada (German citizen).
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
23 * are met:
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 #include "includes.h"
43 RCSID("$OpenBSD: ssh.c,v 1.224 2004/07/28 09:40:29 markus Exp $");
45 #include <openssl/evp.h>
46 #include <openssl/err.h>
48 #include "ssh.h"
49 #include "ssh1.h"
50 #include "ssh2.h"
51 #include "compat.h"
52 #include "cipher.h"
53 #include "xmalloc.h"
54 #include "packet.h"
55 #include "buffer.h"
56 #include "bufaux.h"
57 #include "channels.h"
58 #include "key.h"
59 #include "authfd.h"
60 #include "authfile.h"
61 #include "pathnames.h"
62 #include "dispatch.h"
63 #include "clientloop.h"
64 #include "log.h"
65 #include "readconf.h"
66 #include "sshconnect.h"
67 #include "misc.h"
68 #include "kex.h"
69 #include "mac.h"
70 #include "sshpty.h"
71 #include "match.h"
72 #include "msg.h"
73 #include "monitor_fdpass.h"
74 #include "uidswap.h"
76 #ifdef SMARTCARD
77 #include "scard.h"
78 #endif
80 extern char *__progname;
82 /* Flag indicating whether debug mode is on. This can be set on the command line. */
83 int debug_flag = 0;
85 /* Flag indicating whether a tty should be allocated */
86 int tty_flag = 0;
87 int no_tty_flag = 0;
88 int force_tty_flag = 0;
90 /* don't exec a shell */
91 int no_shell_flag = 0;
94 * Flag indicating that nothing should be read from stdin. This can be set
95 * on the command line.
97 int stdin_null_flag = 0;
100 * Flag indicating that ssh should fork after authentication. This is useful
101 * so that the passphrase can be entered manually, and then ssh goes to the
102 * background.
104 int fork_after_authentication_flag = 0;
107 * General data structure for command line options and options configurable
108 * in configuration files. See readconf.h.
110 Options options;
112 /* optional user configfile */
113 char *config = NULL;
116 * Name of the host we are connecting to. This is the name given on the
117 * command line, or the HostName specified for the user-supplied name in a
118 * configuration file.
120 char *host;
122 /* socket address the host resolves to */
123 struct sockaddr_storage hostaddr;
125 /* Private host keys. */
126 Sensitive sensitive_data;
128 /* Original real UID. */
129 uid_t original_real_uid;
130 uid_t original_effective_uid;
132 /* command to be executed */
133 Buffer command;
135 /* Should we execute a command or invoke a subsystem? */
136 int subsystem_flag = 0;
138 /* # of replies received for global requests */
139 static int client_global_request_id = 0;
141 /* pid of proxycommand child process */
142 pid_t proxy_command_pid = 0;
144 /* fd to control socket */
145 int control_fd = -1;
147 /* Only used in control client mode */
148 volatile sig_atomic_t control_client_terminate = 0;
149 u_int control_server_pid = 0;
151 /* Prints a help message to the user. This function never returns. */
153 static void
154 usage(void)
156 fprintf(stderr,
157 "usage: ssh [-1246AaCfghkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
158 " [-D port] [-e escape_char] [-F configfile] [-i identity_file]\n"
159 " [-L port:host:hostport] [-l login_name] [-m mac_spec] [-o option]\n"
160 " [-p port] [-R port:host:hostport] [-S ctl] [user@]hostname [command]\n"
162 exit(1);
165 static int ssh_session(void);
166 static int ssh_session2(void);
167 static void load_public_identity_files(void);
168 static void control_client(const char *path);
171 * Main program for the ssh client.
174 main(int ac, char **av)
176 int i, opt, exit_status;
177 u_short fwd_port, fwd_host_port;
178 char sfwd_port[6], sfwd_host_port[6];
179 char *p, *cp, *line, buf[256];
180 struct stat st;
181 struct passwd *pw;
182 int dummy;
183 extern int optind, optreset;
184 extern char *optarg;
186 __progname = ssh_get_progname(av[0]);
187 init_rng();
190 * Save the original real uid. It will be needed later (uid-swapping
191 * may clobber the real uid).
193 original_real_uid = getuid();
194 original_effective_uid = geteuid();
197 * Use uid-swapping to give up root privileges for the duration of
198 * option processing. We will re-instantiate the rights when we are
199 * ready to create the privileged port, and will permanently drop
200 * them when the port has been created (actually, when the connection
201 * has been made, as we may need to create the port several times).
203 PRIV_END;
205 #ifdef HAVE_SETRLIMIT
206 /* If we are installed setuid root be careful to not drop core. */
207 if (original_real_uid != original_effective_uid) {
208 struct rlimit rlim;
209 rlim.rlim_cur = rlim.rlim_max = 0;
210 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
211 fatal("setrlimit failed: %.100s", strerror(errno));
213 #endif
214 /* Get user data. */
215 pw = getpwuid(original_real_uid);
216 if (!pw) {
217 logit("You don't exist, go away!");
218 exit(1);
220 /* Take a copy of the returned structure. */
221 pw = pwcopy(pw);
224 * Set our umask to something reasonable, as some files are created
225 * with the default umask. This will make them world-readable but
226 * writable only by the owner, which is ok for all files for which we
227 * don't set the modes explicitly.
229 umask(022);
231 /* Initialize option structure to indicate that no values have been set. */
232 initialize_options(&options);
234 /* Parse command-line arguments. */
235 host = NULL;
237 again:
238 while ((opt = getopt(ac, av,
239 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNPR:S:TVXY")) != -1) {
240 switch (opt) {
241 case '1':
242 options.protocol = SSH_PROTO_1;
243 break;
244 case '2':
245 options.protocol = SSH_PROTO_2;
246 break;
247 case '4':
248 options.address_family = AF_INET;
249 break;
250 case '6':
251 options.address_family = AF_INET6;
252 break;
253 case 'n':
254 stdin_null_flag = 1;
255 break;
256 case 'f':
257 fork_after_authentication_flag = 1;
258 stdin_null_flag = 1;
259 break;
260 case 'x':
261 options.forward_x11 = 0;
262 break;
263 case 'X':
264 options.forward_x11 = 1;
265 break;
266 case 'Y':
267 options.forward_x11 = 1;
268 options.forward_x11_trusted = 1;
269 break;
270 case 'g':
271 options.gateway_ports = 1;
272 break;
273 case 'P': /* deprecated */
274 options.use_privileged_port = 0;
275 break;
276 case 'a':
277 options.forward_agent = 0;
278 break;
279 case 'A':
280 options.forward_agent = 1;
281 break;
282 case 'k':
283 options.gss_deleg_creds = 0;
284 break;
285 case 'i':
286 if (stat(optarg, &st) < 0) {
287 fprintf(stderr, "Warning: Identity file %s "
288 "does not exist.\n", optarg);
289 break;
291 if (options.num_identity_files >=
292 SSH_MAX_IDENTITY_FILES)
293 fatal("Too many identity files specified "
294 "(max %d)", SSH_MAX_IDENTITY_FILES);
295 options.identity_files[options.num_identity_files++] =
296 xstrdup(optarg);
297 break;
298 case 'I':
299 #ifdef SMARTCARD
300 options.smartcard_device = xstrdup(optarg);
301 #else
302 fprintf(stderr, "no support for smartcards.\n");
303 #endif
304 break;
305 case 't':
306 if (tty_flag)
307 force_tty_flag = 1;
308 tty_flag = 1;
309 break;
310 case 'v':
311 if (debug_flag == 0) {
312 debug_flag = 1;
313 options.log_level = SYSLOG_LEVEL_DEBUG1;
314 } else {
315 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
316 options.log_level++;
317 break;
319 /* fallthrough */
320 case 'V':
321 fprintf(stderr, "%s, %s\n",
322 SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
323 if (opt == 'V')
324 exit(0);
325 break;
326 case 'q':
327 options.log_level = SYSLOG_LEVEL_QUIET;
328 break;
329 case 'e':
330 if (optarg[0] == '^' && optarg[2] == 0 &&
331 (u_char) optarg[1] >= 64 &&
332 (u_char) optarg[1] < 128)
333 options.escape_char = (u_char) optarg[1] & 31;
334 else if (strlen(optarg) == 1)
335 options.escape_char = (u_char) optarg[0];
336 else if (strcmp(optarg, "none") == 0)
337 options.escape_char = SSH_ESCAPECHAR_NONE;
338 else {
339 fprintf(stderr, "Bad escape character '%s'.\n",
340 optarg);
341 exit(1);
343 break;
344 case 'c':
345 if (ciphers_valid(optarg)) {
346 /* SSH2 only */
347 options.ciphers = xstrdup(optarg);
348 options.cipher = SSH_CIPHER_INVALID;
349 } else {
350 /* SSH1 only */
351 options.cipher = cipher_number(optarg);
352 if (options.cipher == -1) {
353 fprintf(stderr,
354 "Unknown cipher type '%s'\n",
355 optarg);
356 exit(1);
358 if (options.cipher == SSH_CIPHER_3DES)
359 options.ciphers = "3des-cbc";
360 else if (options.cipher == SSH_CIPHER_BLOWFISH)
361 options.ciphers = "blowfish-cbc";
362 else
363 options.ciphers = (char *)-1;
365 break;
366 case 'm':
367 if (mac_valid(optarg))
368 options.macs = xstrdup(optarg);
369 else {
370 fprintf(stderr, "Unknown mac type '%s'\n",
371 optarg);
372 exit(1);
374 break;
375 case 'M':
376 options.control_master =
377 (options.control_master >= 1) ? 2 : 1;
378 break;
379 case 'p':
380 options.port = a2port(optarg);
381 if (options.port == 0) {
382 fprintf(stderr, "Bad port '%s'\n", optarg);
383 exit(1);
385 break;
386 case 'l':
387 options.user = optarg;
388 break;
390 case 'L':
391 case 'R':
392 if (sscanf(optarg, "%5[0123456789]:%255[^:]:%5[0123456789]",
393 sfwd_port, buf, sfwd_host_port) != 3 &&
394 sscanf(optarg, "%5[0123456789]/%255[^/]/%5[0123456789]",
395 sfwd_port, buf, sfwd_host_port) != 3) {
396 fprintf(stderr,
397 "Bad forwarding specification '%s'\n",
398 optarg);
399 usage();
400 /* NOTREACHED */
402 if ((fwd_port = a2port(sfwd_port)) == 0 ||
403 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
404 fprintf(stderr,
405 "Bad forwarding port(s) '%s'\n", optarg);
406 exit(1);
408 if (opt == 'L')
409 add_local_forward(&options, fwd_port, buf,
410 fwd_host_port);
411 else if (opt == 'R')
412 add_remote_forward(&options, fwd_port, buf,
413 fwd_host_port);
414 break;
416 case 'D':
417 fwd_port = a2port(optarg);
418 if (fwd_port == 0) {
419 fprintf(stderr, "Bad dynamic port '%s'\n",
420 optarg);
421 exit(1);
423 add_local_forward(&options, fwd_port, "socks", 0);
424 break;
426 case 'C':
427 options.compression = 1;
428 break;
429 case 'N':
430 no_shell_flag = 1;
431 no_tty_flag = 1;
432 break;
433 case 'T':
434 no_tty_flag = 1;
435 break;
436 case 'o':
437 dummy = 1;
438 line = xstrdup(optarg);
439 if (process_config_line(&options, host ? host : "",
440 line, "command-line", 0, &dummy) != 0)
441 exit(1);
442 xfree(line);
443 break;
444 case 's':
445 subsystem_flag = 1;
446 break;
447 case 'S':
448 if (options.control_path != NULL)
449 free(options.control_path);
450 options.control_path = xstrdup(optarg);
451 break;
452 case 'b':
453 options.bind_address = optarg;
454 break;
455 case 'F':
456 config = optarg;
457 break;
458 default:
459 usage();
463 ac -= optind;
464 av += optind;
466 if (ac > 0 && !host && **av != '-') {
467 if (strrchr(*av, '@')) {
468 p = xstrdup(*av);
469 cp = strrchr(p, '@');
470 if (cp == NULL || cp == p)
471 usage();
472 options.user = p;
473 *cp = '\0';
474 host = ++cp;
475 } else
476 host = *av;
477 if (ac > 1) {
478 optind = optreset = 1;
479 goto again;
481 ac--, av++;
484 /* Check that we got a host name. */
485 if (!host)
486 usage();
488 SSLeay_add_all_algorithms();
489 ERR_load_crypto_strings();
491 /* Initialize the command to execute on remote host. */
492 buffer_init(&command);
495 * Save the command to execute on the remote host in a buffer. There
496 * is no limit on the length of the command, except by the maximum
497 * packet size. Also sets the tty flag if there is no command.
499 if (!ac) {
500 /* No command specified - execute shell on a tty. */
501 tty_flag = 1;
502 if (subsystem_flag) {
503 fprintf(stderr,
504 "You must specify a subsystem to invoke.\n");
505 usage();
507 } else {
508 /* A command has been specified. Store it into the buffer. */
509 for (i = 0; i < ac; i++) {
510 if (i)
511 buffer_append(&command, " ", 1);
512 buffer_append(&command, av[i], strlen(av[i]));
516 /* Cannot fork to background if no command. */
517 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
518 fatal("Cannot fork into background without a command to execute.");
520 /* Allocate a tty by default if no command specified. */
521 if (buffer_len(&command) == 0)
522 tty_flag = 1;
524 /* Force no tty */
525 if (no_tty_flag)
526 tty_flag = 0;
527 /* Do not allocate a tty if stdin is not a tty. */
528 if (!isatty(fileno(stdin)) && !force_tty_flag) {
529 if (tty_flag)
530 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
531 tty_flag = 0;
535 * Initialize "log" output. Since we are the client all output
536 * actually goes to stderr.
538 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
539 SYSLOG_FACILITY_USER, 1);
542 * Read per-user configuration file. Ignore the system wide config
543 * file if the user specifies a config file on the command line.
545 if (config != NULL) {
546 if (!read_config_file(config, host, &options, 0))
547 fatal("Can't open user config file %.100s: "
548 "%.100s", config, strerror(errno));
549 } else {
550 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
551 _PATH_SSH_USER_CONFFILE);
552 (void)read_config_file(buf, host, &options, 1);
554 /* Read systemwide configuration file after use config. */
555 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
556 &options, 0);
559 /* Fill configuration defaults. */
560 fill_default_options(&options);
562 channel_set_af(options.address_family);
564 /* reinit */
565 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
567 seed_rng();
569 if (options.user == NULL)
570 options.user = xstrdup(pw->pw_name);
572 if (options.hostname != NULL)
573 host = options.hostname;
575 /* force lowercase for hostkey matching */
576 if (options.host_key_alias != NULL) {
577 for (p = options.host_key_alias; *p; p++)
578 if (isupper(*p))
579 *p = tolower(*p);
582 if (options.proxy_command != NULL &&
583 strcmp(options.proxy_command, "none") == 0)
584 options.proxy_command = NULL;
586 if (options.control_path != NULL) {
587 options.control_path = tilde_expand_filename(
588 options.control_path, original_real_uid);
590 if (options.control_path != NULL && options.control_master == 0)
591 control_client(options.control_path); /* This doesn't return */
593 /* Open a connection to the remote host. */
594 if (ssh_connect(host, &hostaddr, options.port,
595 options.address_family, options.connection_attempts,
596 #ifdef HAVE_CYGWIN
597 options.use_privileged_port,
598 #else
599 original_effective_uid == 0 && options.use_privileged_port,
600 #endif
601 options.proxy_command) != 0)
602 exit(1);
605 * If we successfully made the connection, load the host private key
606 * in case we will need it later for combined rsa-rhosts
607 * authentication. This must be done before releasing extra
608 * privileges, because the file is only readable by root.
609 * If we cannot access the private keys, load the public keys
610 * instead and try to execute the ssh-keysign helper instead.
612 sensitive_data.nkeys = 0;
613 sensitive_data.keys = NULL;
614 sensitive_data.external_keysign = 0;
615 if (options.rhosts_rsa_authentication ||
616 options.hostbased_authentication) {
617 sensitive_data.nkeys = 3;
618 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
619 sizeof(Key));
621 PRIV_START;
622 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
623 _PATH_HOST_KEY_FILE, "", NULL);
624 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
625 _PATH_HOST_DSA_KEY_FILE, "", NULL);
626 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
627 _PATH_HOST_RSA_KEY_FILE, "", NULL);
628 PRIV_END;
630 if (options.hostbased_authentication == 1 &&
631 sensitive_data.keys[0] == NULL &&
632 sensitive_data.keys[1] == NULL &&
633 sensitive_data.keys[2] == NULL) {
634 sensitive_data.keys[1] = key_load_public(
635 _PATH_HOST_DSA_KEY_FILE, NULL);
636 sensitive_data.keys[2] = key_load_public(
637 _PATH_HOST_RSA_KEY_FILE, NULL);
638 sensitive_data.external_keysign = 1;
642 * Get rid of any extra privileges that we may have. We will no
643 * longer need them. Also, extra privileges could make it very hard
644 * to read identity files and other non-world-readable files from the
645 * user's home directory if it happens to be on a NFS volume where
646 * root is mapped to nobody.
648 if (original_effective_uid == 0) {
649 PRIV_START;
650 permanently_set_uid(pw);
654 * Now that we are back to our own permissions, create ~/.ssh
655 * directory if it doesn\'t already exist.
657 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
658 if (stat(buf, &st) < 0)
659 if (mkdir(buf, 0700) < 0)
660 error("Could not create directory '%.200s'.", buf);
662 /* load options.identity_files */
663 load_public_identity_files();
665 /* Expand ~ in known host file names. */
666 /* XXX mem-leaks: */
667 options.system_hostfile =
668 tilde_expand_filename(options.system_hostfile, original_real_uid);
669 options.user_hostfile =
670 tilde_expand_filename(options.user_hostfile, original_real_uid);
671 options.system_hostfile2 =
672 tilde_expand_filename(options.system_hostfile2, original_real_uid);
673 options.user_hostfile2 =
674 tilde_expand_filename(options.user_hostfile2, original_real_uid);
676 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
678 /* Log into the remote system. This never returns if the login fails. */
679 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
681 /* We no longer need the private host keys. Clear them now. */
682 if (sensitive_data.nkeys != 0) {
683 for (i = 0; i < sensitive_data.nkeys; i++) {
684 if (sensitive_data.keys[i] != NULL) {
685 /* Destroys contents safely */
686 debug3("clear hostkey %d", i);
687 key_free(sensitive_data.keys[i]);
688 sensitive_data.keys[i] = NULL;
691 xfree(sensitive_data.keys);
693 for (i = 0; i < options.num_identity_files; i++) {
694 if (options.identity_files[i]) {
695 xfree(options.identity_files[i]);
696 options.identity_files[i] = NULL;
698 if (options.identity_keys[i]) {
699 key_free(options.identity_keys[i]);
700 options.identity_keys[i] = NULL;
704 exit_status = compat20 ? ssh_session2() : ssh_session();
705 packet_close();
707 if (options.control_path != NULL && control_fd != -1)
708 unlink(options.control_path);
711 * Send SIGHUP to proxy command if used. We don't wait() in
712 * case it hangs and instead rely on init to reap the child
714 if (proxy_command_pid > 1)
715 kill(proxy_command_pid, SIGHUP);
717 return exit_status;
720 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
722 static void
723 x11_get_proto(char **_proto, char **_data)
725 char cmd[1024];
726 char line[512];
727 char xdisplay[512];
728 static char proto[512], data[512];
729 FILE *f;
730 int got_data = 0, generated = 0, do_unlink = 0, i;
731 char *display, *xauthdir, *xauthfile;
732 struct stat st;
734 xauthdir = xauthfile = NULL;
735 *_proto = proto;
736 *_data = data;
737 proto[0] = data[0] = '\0';
739 if (!options.xauth_location ||
740 (stat(options.xauth_location, &st) == -1)) {
741 debug("No xauth program.");
742 } else {
743 if ((display = getenv("DISPLAY")) == NULL) {
744 debug("x11_get_proto: DISPLAY not set");
745 return;
748 * Handle FamilyLocal case where $DISPLAY does
749 * not match an authorization entry. For this we
750 * just try "xauth list unix:displaynum.screennum".
751 * XXX: "localhost" match to determine FamilyLocal
752 * is not perfect.
754 if (strncmp(display, "localhost:", 10) == 0) {
755 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
756 display + 10);
757 display = xdisplay;
759 if (options.forward_x11_trusted == 0) {
760 xauthdir = xmalloc(MAXPATHLEN);
761 xauthfile = xmalloc(MAXPATHLEN);
762 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
763 if (mkdtemp(xauthdir) != NULL) {
764 do_unlink = 1;
765 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
766 xauthdir);
767 snprintf(cmd, sizeof(cmd),
768 "%s -f %s generate %s " SSH_X11_PROTO
769 " untrusted timeout 1200 2>" _PATH_DEVNULL,
770 options.xauth_location, xauthfile, display);
771 debug2("x11_get_proto: %s", cmd);
772 if (system(cmd) == 0)
773 generated = 1;
776 snprintf(cmd, sizeof(cmd),
777 "%s %s%s list %s . 2>" _PATH_DEVNULL,
778 options.xauth_location,
779 generated ? "-f " : "" ,
780 generated ? xauthfile : "",
781 display);
782 debug2("x11_get_proto: %s", cmd);
783 f = popen(cmd, "r");
784 if (f && fgets(line, sizeof(line), f) &&
785 sscanf(line, "%*s %511s %511s", proto, data) == 2)
786 got_data = 1;
787 if (f)
788 pclose(f);
791 if (do_unlink) {
792 unlink(xauthfile);
793 rmdir(xauthdir);
795 if (xauthdir)
796 xfree(xauthdir);
797 if (xauthfile)
798 xfree(xauthfile);
801 * If we didn't get authentication data, just make up some
802 * data. The forwarding code will check the validity of the
803 * response anyway, and substitute this data. The X11
804 * server, however, will ignore this fake data and use
805 * whatever authentication mechanisms it was using otherwise
806 * for the local connection.
808 if (!got_data) {
809 u_int32_t rnd = 0;
811 logit("Warning: No xauth data; "
812 "using fake authentication data for X11 forwarding.");
813 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
814 for (i = 0; i < 16; i++) {
815 if (i % 4 == 0)
816 rnd = arc4random();
817 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
818 rnd & 0xff);
819 rnd >>= 8;
824 static void
825 ssh_init_forwarding(void)
827 int success = 0;
828 int i;
830 /* Initiate local TCP/IP port forwardings. */
831 for (i = 0; i < options.num_local_forwards; i++) {
832 debug("Connections to local port %d forwarded to remote address %.200s:%d",
833 options.local_forwards[i].port,
834 options.local_forwards[i].host,
835 options.local_forwards[i].host_port);
836 success += channel_setup_local_fwd_listener(
837 options.local_forwards[i].port,
838 options.local_forwards[i].host,
839 options.local_forwards[i].host_port,
840 options.gateway_ports);
842 if (i > 0 && success == 0)
843 error("Could not request local forwarding.");
845 /* Initiate remote TCP/IP port forwardings. */
846 for (i = 0; i < options.num_remote_forwards; i++) {
847 debug("Connections to remote port %d forwarded to local address %.200s:%d",
848 options.remote_forwards[i].port,
849 options.remote_forwards[i].host,
850 options.remote_forwards[i].host_port);
851 channel_request_remote_forwarding(
852 options.remote_forwards[i].port,
853 options.remote_forwards[i].host,
854 options.remote_forwards[i].host_port);
858 static void
859 check_agent_present(void)
861 if (options.forward_agent) {
862 /* Clear agent forwarding if we don\'t have an agent. */
863 if (!ssh_agent_present())
864 options.forward_agent = 0;
868 static int
869 ssh_session(void)
871 int type;
872 int interactive = 0;
873 int have_tty = 0;
874 struct winsize ws;
875 char *cp;
877 /* Enable compression if requested. */
878 if (options.compression) {
879 debug("Requesting compression at level %d.", options.compression_level);
881 if (options.compression_level < 1 || options.compression_level > 9)
882 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
884 /* Send the request. */
885 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
886 packet_put_int(options.compression_level);
887 packet_send();
888 packet_write_wait();
889 type = packet_read();
890 if (type == SSH_SMSG_SUCCESS)
891 packet_start_compression(options.compression_level);
892 else if (type == SSH_SMSG_FAILURE)
893 logit("Warning: Remote host refused compression.");
894 else
895 packet_disconnect("Protocol error waiting for compression response.");
897 /* Allocate a pseudo tty if appropriate. */
898 if (tty_flag) {
899 debug("Requesting pty.");
901 /* Start the packet. */
902 packet_start(SSH_CMSG_REQUEST_PTY);
904 /* Store TERM in the packet. There is no limit on the
905 length of the string. */
906 cp = getenv("TERM");
907 if (!cp)
908 cp = "";
909 packet_put_cstring(cp);
911 /* Store window size in the packet. */
912 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
913 memset(&ws, 0, sizeof(ws));
914 packet_put_int(ws.ws_row);
915 packet_put_int(ws.ws_col);
916 packet_put_int(ws.ws_xpixel);
917 packet_put_int(ws.ws_ypixel);
919 /* Store tty modes in the packet. */
920 tty_make_modes(fileno(stdin), NULL);
922 /* Send the packet, and wait for it to leave. */
923 packet_send();
924 packet_write_wait();
926 /* Read response from the server. */
927 type = packet_read();
928 if (type == SSH_SMSG_SUCCESS) {
929 interactive = 1;
930 have_tty = 1;
931 } else if (type == SSH_SMSG_FAILURE)
932 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
933 else
934 packet_disconnect("Protocol error waiting for pty request response.");
936 /* Request X11 forwarding if enabled and DISPLAY is set. */
937 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
938 char *proto, *data;
939 /* Get reasonable local authentication information. */
940 x11_get_proto(&proto, &data);
941 /* Request forwarding with authentication spoofing. */
942 debug("Requesting X11 forwarding with authentication spoofing.");
943 x11_request_forwarding_with_spoofing(0, proto, data);
945 /* Read response from the server. */
946 type = packet_read();
947 if (type == SSH_SMSG_SUCCESS) {
948 interactive = 1;
949 } else if (type == SSH_SMSG_FAILURE) {
950 logit("Warning: Remote host denied X11 forwarding.");
951 } else {
952 packet_disconnect("Protocol error waiting for X11 forwarding");
955 /* Tell the packet module whether this is an interactive session. */
956 packet_set_interactive(interactive);
958 /* Request authentication agent forwarding if appropriate. */
959 check_agent_present();
961 if (options.forward_agent) {
962 debug("Requesting authentication agent forwarding.");
963 auth_request_forwarding();
965 /* Read response from the server. */
966 type = packet_read();
967 packet_check_eom();
968 if (type != SSH_SMSG_SUCCESS)
969 logit("Warning: Remote host denied authentication agent forwarding.");
972 /* Initiate port forwardings. */
973 ssh_init_forwarding();
975 /* If requested, let ssh continue in the background. */
976 if (fork_after_authentication_flag)
977 if (daemon(1, 1) < 0)
978 fatal("daemon() failed: %.200s", strerror(errno));
981 * If a command was specified on the command line, execute the
982 * command now. Otherwise request the server to start a shell.
984 if (buffer_len(&command) > 0) {
985 int len = buffer_len(&command);
986 if (len > 900)
987 len = 900;
988 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
989 packet_start(SSH_CMSG_EXEC_CMD);
990 packet_put_string(buffer_ptr(&command), buffer_len(&command));
991 packet_send();
992 packet_write_wait();
993 } else {
994 debug("Requesting shell.");
995 packet_start(SSH_CMSG_EXEC_SHELL);
996 packet_send();
997 packet_write_wait();
1000 /* Enter the interactive session. */
1001 return client_loop(have_tty, tty_flag ?
1002 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1005 static void
1006 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1008 int id, len;
1010 id = packet_get_int();
1011 len = buffer_len(&command);
1012 if (len > 900)
1013 len = 900;
1014 packet_check_eom();
1015 if (type == SSH2_MSG_CHANNEL_FAILURE)
1016 fatal("Request for subsystem '%.*s' failed on channel %d",
1017 len, (u_char *)buffer_ptr(&command), id);
1020 void
1021 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1023 int i;
1025 i = client_global_request_id++;
1026 if (i >= options.num_remote_forwards)
1027 return;
1028 debug("remote forward %s for: listen %d, connect %s:%d",
1029 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1030 options.remote_forwards[i].port,
1031 options.remote_forwards[i].host,
1032 options.remote_forwards[i].host_port);
1033 if (type == SSH2_MSG_REQUEST_FAILURE)
1034 logit("Warning: remote port forwarding failed for listen port %d",
1035 options.remote_forwards[i].port);
1038 static void
1039 ssh_control_listener(void)
1041 struct sockaddr_un addr;
1042 mode_t old_umask;
1043 int addr_len;
1045 if (options.control_path == NULL || options.control_master <= 0)
1046 return;
1048 memset(&addr, '\0', sizeof(addr));
1049 addr.sun_family = AF_UNIX;
1050 addr_len = offsetof(struct sockaddr_un, sun_path) +
1051 strlen(options.control_path) + 1;
1053 if (strlcpy(addr.sun_path, options.control_path,
1054 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1055 fatal("ControlPath too long");
1057 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1058 fatal("%s socket(): %s\n", __func__, strerror(errno));
1060 old_umask = umask(0177);
1061 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1062 control_fd = -1;
1063 if (errno == EINVAL)
1064 fatal("ControlSocket %s already exists",
1065 options.control_path);
1066 else
1067 fatal("%s bind(): %s\n", __func__, strerror(errno));
1069 umask(old_umask);
1071 if (listen(control_fd, 64) == -1)
1072 fatal("%s listen(): %s\n", __func__, strerror(errno));
1074 set_nonblock(control_fd);
1077 /* request pty/x11/agent/tcpfwd/shell for channel */
1078 static void
1079 ssh_session2_setup(int id, void *arg)
1081 extern char **environ;
1083 int interactive = tty_flag;
1084 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1085 char *proto, *data;
1086 /* Get reasonable local authentication information. */
1087 x11_get_proto(&proto, &data);
1088 /* Request forwarding with authentication spoofing. */
1089 debug("Requesting X11 forwarding with authentication spoofing.");
1090 x11_request_forwarding_with_spoofing(id, proto, data);
1091 interactive = 1;
1092 /* XXX wait for reply */
1095 check_agent_present();
1096 if (options.forward_agent) {
1097 debug("Requesting authentication agent forwarding.");
1098 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1099 packet_send();
1102 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1103 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1105 packet_set_interactive(interactive);
1108 /* open new channel for a session */
1109 static int
1110 ssh_session2_open(void)
1112 Channel *c;
1113 int window, packetmax, in, out, err;
1115 if (stdin_null_flag) {
1116 in = open(_PATH_DEVNULL, O_RDONLY);
1117 } else {
1118 in = dup(STDIN_FILENO);
1120 out = dup(STDOUT_FILENO);
1121 err = dup(STDERR_FILENO);
1123 if (in < 0 || out < 0 || err < 0)
1124 fatal("dup() in/out/err failed");
1126 /* enable nonblocking unless tty */
1127 if (!isatty(in))
1128 set_nonblock(in);
1129 if (!isatty(out))
1130 set_nonblock(out);
1131 if (!isatty(err))
1132 set_nonblock(err);
1134 window = CHAN_SES_WINDOW_DEFAULT;
1135 packetmax = CHAN_SES_PACKET_DEFAULT;
1136 if (tty_flag) {
1137 window >>= 1;
1138 packetmax >>= 1;
1140 c = channel_new(
1141 "session", SSH_CHANNEL_OPENING, in, out, err,
1142 window, packetmax, CHAN_EXTENDED_WRITE,
1143 "client-session", /*nonblock*/0);
1145 debug3("ssh_session2_open: channel_new: %d", c->self);
1147 channel_send_open(c->self);
1148 if (!no_shell_flag)
1149 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1151 return c->self;
1154 static int
1155 ssh_session2(void)
1157 int id = -1;
1159 /* XXX should be pre-session */
1160 ssh_init_forwarding();
1161 ssh_control_listener();
1163 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1164 id = ssh_session2_open();
1166 /* If requested, let ssh continue in the background. */
1167 if (fork_after_authentication_flag)
1168 if (daemon(1, 1) < 0)
1169 fatal("daemon() failed: %.200s", strerror(errno));
1171 return client_loop(tty_flag, tty_flag ?
1172 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1175 static void
1176 load_public_identity_files(void)
1178 char *filename;
1179 int i = 0;
1180 Key *public;
1181 #ifdef SMARTCARD
1182 Key **keys;
1184 if (options.smartcard_device != NULL &&
1185 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1186 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1187 int count = 0;
1188 for (i = 0; keys[i] != NULL; i++) {
1189 count++;
1190 memmove(&options.identity_files[1], &options.identity_files[0],
1191 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1192 memmove(&options.identity_keys[1], &options.identity_keys[0],
1193 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1194 options.num_identity_files++;
1195 options.identity_keys[0] = keys[i];
1196 options.identity_files[0] = sc_get_key_label(keys[i]);
1198 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1199 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1200 i = count;
1201 xfree(keys);
1203 #endif /* SMARTCARD */
1204 for (; i < options.num_identity_files; i++) {
1205 filename = tilde_expand_filename(options.identity_files[i],
1206 original_real_uid);
1207 public = key_load_public(filename, NULL);
1208 debug("identity file %s type %d", filename,
1209 public ? public->type : -1);
1210 xfree(options.identity_files[i]);
1211 options.identity_files[i] = filename;
1212 options.identity_keys[i] = public;
1216 static void
1217 control_client_sighandler(int signo)
1219 control_client_terminate = signo;
1222 static void
1223 control_client_sigrelay(int signo)
1225 if (control_server_pid > 1)
1226 kill(control_server_pid, signo);
1229 static int
1230 env_permitted(char *env)
1232 int i;
1233 char name[1024], *cp;
1235 strlcpy(name, env, sizeof(name));
1236 if ((cp = strchr(name, '=')) == NULL)
1237 return (0);
1239 *cp = '\0';
1241 for (i = 0; i < options.num_send_env; i++)
1242 if (match_pattern(name, options.send_env[i]))
1243 return (1);
1245 return (0);
1248 static void
1249 control_client(const char *path)
1251 struct sockaddr_un addr;
1252 int i, r, sock, exitval, num_env, addr_len;
1253 Buffer m;
1254 char *cp;
1255 extern char **environ;
1257 memset(&addr, '\0', sizeof(addr));
1258 addr.sun_family = AF_UNIX;
1259 addr_len = offsetof(struct sockaddr_un, sun_path) +
1260 strlen(path) + 1;
1262 if (strlcpy(addr.sun_path, path,
1263 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1264 fatal("ControlPath too long");
1266 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1267 fatal("%s socket(): %s", __func__, strerror(errno));
1269 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1)
1270 fatal("Couldn't connect to %s: %s", path, strerror(errno));
1272 if ((cp = getenv("TERM")) == NULL)
1273 cp = "";
1275 buffer_init(&m);
1277 /* Get PID of controlee */
1278 if (ssh_msg_recv(sock, &m) == -1)
1279 fatal("%s: msg_recv", __func__);
1280 if (buffer_get_char(&m) != 0)
1281 fatal("%s: wrong version", __func__);
1282 /* Connection allowed? */
1283 if (buffer_get_int(&m) != 1)
1284 fatal("Connection to master denied");
1285 control_server_pid = buffer_get_int(&m);
1287 buffer_clear(&m);
1288 buffer_put_int(&m, tty_flag);
1289 buffer_put_int(&m, subsystem_flag);
1290 buffer_put_cstring(&m, cp);
1292 buffer_append(&command, "\0", 1);
1293 buffer_put_cstring(&m, buffer_ptr(&command));
1295 if (options.num_send_env == 0 || environ == NULL) {
1296 buffer_put_int(&m, 0);
1297 } else {
1298 /* Pass environment */
1299 num_env = 0;
1300 for (i = 0; environ[i] != NULL; i++)
1301 if (env_permitted(environ[i]))
1302 num_env++; /* Count */
1304 buffer_put_int(&m, num_env);
1306 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1307 if (env_permitted(environ[i])) {
1308 num_env--;
1309 buffer_put_cstring(&m, environ[i]);
1313 if (ssh_msg_send(sock, /* version */0, &m) == -1)
1314 fatal("%s: msg_send", __func__);
1316 mm_send_fd(sock, STDIN_FILENO);
1317 mm_send_fd(sock, STDOUT_FILENO);
1318 mm_send_fd(sock, STDERR_FILENO);
1320 /* Wait for reply, so master has a chance to gather ttymodes */
1321 buffer_clear(&m);
1322 if (ssh_msg_recv(sock, &m) == -1)
1323 fatal("%s: msg_recv", __func__);
1324 if (buffer_get_char(&m) != 0)
1325 fatal("%s: master returned error", __func__);
1326 buffer_free(&m);
1328 signal(SIGINT, control_client_sighandler);
1329 signal(SIGTERM, control_client_sighandler);
1330 signal(SIGWINCH, control_client_sigrelay);
1332 if (tty_flag)
1333 enter_raw_mode();
1335 /* Stick around until the controlee closes the client_fd */
1336 exitval = 0;
1337 for (;!control_client_terminate;) {
1338 r = read(sock, &exitval, sizeof(exitval));
1339 if (r == 0) {
1340 debug2("Received EOF from master");
1341 break;
1343 if (r > 0)
1344 debug2("Received exit status from master %d", exitval);
1345 if (r == -1 && errno != EINTR)
1346 fatal("%s: read %s", __func__, strerror(errno));
1349 if (control_client_terminate)
1350 debug2("Exiting on signal %d", control_client_terminate);
1352 close(sock);
1354 leave_raw_mode();
1356 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1357 fprintf(stderr, "Connection to master closed.\r\n");
1359 exit(exitval);