No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / external / bsd / openssh / dist / ssh.c
blob8167acabd049c5b5b3f156c91e01a9e96986dda7
1 /* $NetBSD: ssh.c,v 1.1.1.2 2009/12/27 01:07:12 christos Exp $ */
2 /* $OpenBSD: ssh.c,v 1.326 2009/07/02 02:11:47 dtucker Exp $ */
3 /*
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * All rights reserved
7 * Ssh client program. This program can be used to log into a remote machine.
8 * The software supports strong authentication, encryption, and forwarding
9 * of X11, TCP/IP, and authentication connections.
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
17 * Copyright (c) 1999 Niels Provos. All rights reserved.
18 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
20 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
21 * in Canada (German citizen).
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include "includes.h"
45 __RCSID("$NetBSD: ssh.c,v 1.2 2009/06/07 22:38:47 christos Exp $");
46 #include <sys/types.h>
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
49 #include <sys/param.h>
50 #include <sys/queue.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <sys/stat.h>
54 #include <sys/time.h>
56 #include <ctype.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <netdb.h>
60 #include <paths.h>
61 #include <pwd.h>
62 #include <signal.h>
63 #include <stddef.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
69 #include <openssl/evp.h>
70 #include <openssl/err.h>
72 #include "xmalloc.h"
73 #include "ssh.h"
74 #include "ssh1.h"
75 #include "ssh2.h"
76 #include "compat.h"
77 #include "cipher.h"
78 #include "packet.h"
79 #include "buffer.h"
80 #include "channels.h"
81 #include "key.h"
82 #include "authfd.h"
83 #include "authfile.h"
84 #include "pathnames.h"
85 #include "dispatch.h"
86 #include "clientloop.h"
87 #include "log.h"
88 #include "readconf.h"
89 #include "sshconnect.h"
90 #include "misc.h"
91 #include "kex.h"
92 #include "mac.h"
93 #include "sshpty.h"
94 #include "match.h"
95 #include "msg.h"
96 #include "uidswap.h"
97 #include "version.h"
99 #ifdef SMARTCARD
100 #include "scard.h"
101 #endif
103 extern char *__progname;
105 /* Flag indicating whether debug mode is on. May be set on the command line. */
106 int debug_flag = 0;
108 /* Flag indicating whether a tty should be allocated */
109 int tty_flag = 0;
110 int no_tty_flag = 0;
111 int force_tty_flag = 0;
113 /* don't exec a shell */
114 int no_shell_flag = 0;
117 * Flag indicating that nothing should be read from stdin. This can be set
118 * on the command line.
120 int stdin_null_flag = 0;
123 * Flag indicating that ssh should fork after authentication. This is useful
124 * so that the passphrase can be entered manually, and then ssh goes to the
125 * background.
127 int fork_after_authentication_flag = 0;
130 * General data structure for command line options and options configurable
131 * in configuration files. See readconf.h.
133 Options options;
135 /* optional user configfile */
136 char *config = NULL;
139 * Name of the host we are connecting to. This is the name given on the
140 * command line, or the HostName specified for the user-supplied name in a
141 * configuration file.
143 char *host;
145 /* socket address the host resolves to */
146 struct sockaddr_storage hostaddr;
148 /* Private host keys. */
149 Sensitive sensitive_data;
151 /* Original real UID. */
152 uid_t original_real_uid;
153 uid_t original_effective_uid;
155 /* command to be executed */
156 Buffer command;
158 /* Should we execute a command or invoke a subsystem? */
159 int subsystem_flag = 0;
161 /* # of replies received for global requests */
162 static int remote_forward_confirms_received = 0;
164 /* pid of proxycommand child process */
165 pid_t proxy_command_pid = 0;
167 /* mux.c */
168 extern int muxserver_sock;
169 extern u_int muxclient_command;
172 /* Prints a help message to the user. This function never returns. */
174 static void
175 usage(void)
177 fprintf(stderr,
178 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
179 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
180 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
181 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
182 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
183 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
185 exit(255);
188 static int ssh_session(void);
189 static int ssh_session2(void);
190 static void load_public_identity_files(void);
192 /* from muxclient.c */
193 void muxclient(const char *);
194 void muxserver_listen(void);
197 * Main program for the ssh client.
200 main(int ac, char **av)
202 int i, r, opt, exit_status, use_syslog;
203 char *p, *cp, *line, *argv0, buf[MAXPATHLEN];
204 struct stat st;
205 struct passwd *pw;
206 int dummy, timeout_ms;
207 extern int optind, optreset;
208 extern char *optarg;
209 struct servent *sp;
210 Forward fwd;
212 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
213 sanitise_stdfd();
216 * Save the original real uid. It will be needed later (uid-swapping
217 * may clobber the real uid).
219 original_real_uid = getuid();
220 original_effective_uid = geteuid();
223 * Use uid-swapping to give up root privileges for the duration of
224 * option processing. We will re-instantiate the rights when we are
225 * ready to create the privileged port, and will permanently drop
226 * them when the port has been created (actually, when the connection
227 * has been made, as we may need to create the port several times).
229 PRIV_END;
231 /* If we are installed setuid root be careful to not drop core. */
232 if (original_real_uid != original_effective_uid) {
233 struct rlimit rlim;
234 rlim.rlim_cur = rlim.rlim_max = 0;
235 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
236 fatal("setrlimit failed: %.100s", strerror(errno));
238 /* Get user data. */
239 pw = getpwuid(original_real_uid);
240 if (!pw) {
241 logit("You don't exist, go away!");
242 exit(255);
244 /* Take a copy of the returned structure. */
245 pw = pwcopy(pw);
248 * Set our umask to something reasonable, as some files are created
249 * with the default umask. This will make them world-readable but
250 * writable only by the owner, which is ok for all files for which we
251 * don't set the modes explicitly.
253 umask(022);
256 * Initialize option structure to indicate that no values have been
257 * set.
259 initialize_options(&options);
261 /* Parse command-line arguments. */
262 host = NULL;
263 use_syslog = 0;
264 argv0 = av[0];
266 again:
267 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
268 "ACD:F:I:KL:MNO:PR:S:TVw:XYy")) != -1) {
269 switch (opt) {
270 case '1':
271 options.protocol = SSH_PROTO_1;
272 break;
273 case '2':
274 options.protocol = SSH_PROTO_2;
275 break;
276 case '4':
277 options.address_family = AF_INET;
278 break;
279 case '6':
280 options.address_family = AF_INET6;
281 break;
282 case 'n':
283 stdin_null_flag = 1;
284 break;
285 case 'f':
286 fork_after_authentication_flag = 1;
287 stdin_null_flag = 1;
288 break;
289 case 'x':
290 options.forward_x11 = 0;
291 break;
292 case 'X':
293 options.forward_x11 = 1;
294 break;
295 case 'y':
296 use_syslog = 1;
297 break;
298 case 'Y':
299 options.forward_x11 = 1;
300 options.forward_x11_trusted = 1;
301 break;
302 case 'g':
303 options.gateway_ports = 1;
304 break;
305 case 'O':
306 if (strcmp(optarg, "check") == 0)
307 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
308 else if (strcmp(optarg, "exit") == 0)
309 muxclient_command = SSHMUX_COMMAND_TERMINATE;
310 else
311 fatal("Invalid multiplex command.");
312 break;
313 case 'P': /* deprecated */
314 options.use_privileged_port = 0;
315 break;
316 case 'a':
317 options.forward_agent = 0;
318 break;
319 case 'A':
320 options.forward_agent = 1;
321 break;
322 case 'k':
323 options.gss_deleg_creds = 0;
324 break;
325 case 'K':
326 options.gss_authentication = 1;
327 options.gss_deleg_creds = 1;
328 break;
329 case 'i':
330 if (stat(optarg, &st) < 0) {
331 fprintf(stderr, "Warning: Identity file %s "
332 "not accessible: %s.\n", optarg,
333 strerror(errno));
334 break;
336 if (options.num_identity_files >=
337 SSH_MAX_IDENTITY_FILES)
338 fatal("Too many identity files specified "
339 "(max %d)", SSH_MAX_IDENTITY_FILES);
340 options.identity_files[options.num_identity_files++] =
341 xstrdup(optarg);
342 break;
343 case 'I':
344 #ifdef SMARTCARD
345 options.smartcard_device = xstrdup(optarg);
346 #else
347 fprintf(stderr, "no support for smartcards.\n");
348 #endif
349 break;
350 case 't':
351 if (tty_flag)
352 force_tty_flag = 1;
353 tty_flag = 1;
354 break;
355 case 'v':
356 if (debug_flag == 0) {
357 debug_flag = 1;
358 options.log_level = SYSLOG_LEVEL_DEBUG1;
359 } else {
360 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
361 options.log_level++;
362 break;
364 /* FALLTHROUGH */
365 case 'V':
366 fprintf(stderr, "%s, %s\n",
367 SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
368 if (opt == 'V')
369 exit(0);
370 break;
371 case 'w':
372 if (options.tun_open == -1)
373 options.tun_open = SSH_TUNMODE_DEFAULT;
374 options.tun_local = a2tun(optarg, &options.tun_remote);
375 if (options.tun_local == SSH_TUNID_ERR) {
376 fprintf(stderr,
377 "Bad tun device '%s'\n", optarg);
378 exit(255);
380 break;
381 case 'q':
382 options.log_level = SYSLOG_LEVEL_QUIET;
383 break;
384 case 'e':
385 if (optarg[0] == '^' && optarg[2] == 0 &&
386 (u_char) optarg[1] >= 64 &&
387 (u_char) optarg[1] < 128)
388 options.escape_char = (u_char) optarg[1] & 31;
389 else if (strlen(optarg) == 1)
390 options.escape_char = (u_char) optarg[0];
391 else if (strcmp(optarg, "none") == 0)
392 options.escape_char = SSH_ESCAPECHAR_NONE;
393 else {
394 fprintf(stderr, "Bad escape character '%s'.\n",
395 optarg);
396 exit(255);
398 break;
399 case 'c':
400 if (ciphers_valid(optarg)) {
401 /* SSH2 only */
402 options.ciphers = xstrdup(optarg);
403 options.cipher = SSH_CIPHER_INVALID;
404 } else {
405 /* SSH1 only */
406 options.cipher = cipher_number(optarg);
407 if (options.cipher == -1) {
408 fprintf(stderr,
409 "Unknown cipher type '%s'\n",
410 optarg);
411 exit(255);
413 if (options.cipher == SSH_CIPHER_3DES)
414 options.ciphers = "3des-cbc";
415 else if (options.cipher == SSH_CIPHER_BLOWFISH)
416 options.ciphers = "blowfish-cbc";
417 else
418 options.ciphers = (char *)-1;
420 break;
421 case 'm':
422 if (mac_valid(optarg))
423 options.macs = xstrdup(optarg);
424 else {
425 fprintf(stderr, "Unknown mac type '%s'\n",
426 optarg);
427 exit(255);
429 break;
430 case 'M':
431 if (options.control_master == SSHCTL_MASTER_YES)
432 options.control_master = SSHCTL_MASTER_ASK;
433 else
434 options.control_master = SSHCTL_MASTER_YES;
435 break;
436 case 'p':
437 options.port = a2port(optarg);
438 if (options.port <= 0) {
439 fprintf(stderr, "Bad port '%s'\n", optarg);
440 exit(255);
442 break;
443 case 'l':
444 options.user = optarg;
445 break;
447 case 'L':
448 if (parse_forward(&fwd, optarg, 0, 0))
449 add_local_forward(&options, &fwd);
450 else {
451 fprintf(stderr,
452 "Bad local forwarding specification '%s'\n",
453 optarg);
454 exit(255);
456 break;
458 case 'R':
459 if (parse_forward(&fwd, optarg, 0, 1)) {
460 add_remote_forward(&options, &fwd);
461 } else {
462 fprintf(stderr,
463 "Bad remote forwarding specification "
464 "'%s'\n", optarg);
465 exit(255);
467 break;
469 case 'D':
470 if (parse_forward(&fwd, optarg, 1, 0)) {
471 add_local_forward(&options, &fwd);
472 } else {
473 fprintf(stderr,
474 "Bad dynamic forwarding specification "
475 "'%s'\n", optarg);
476 exit(255);
478 break;
480 case 'C':
481 options.compression = 1;
482 break;
483 case 'N':
484 no_shell_flag = 1;
485 no_tty_flag = 1;
486 break;
487 case 'T':
488 no_tty_flag = 1;
489 /* ensure that the user doesn't try to backdoor a */
490 /* null cipher switch on an interactive session */
491 /* so explicitly disable it no matter what */
492 options.none_switch=0;
493 break;
494 case 'o':
495 dummy = 1;
496 line = xstrdup(optarg);
497 if (process_config_line(&options, host ? host : "",
498 line, "command-line", 0, &dummy) != 0)
499 exit(255);
500 xfree(line);
501 break;
502 case 's':
503 subsystem_flag = 1;
504 break;
505 case 'S':
506 if (options.control_path != NULL)
507 free(options.control_path);
508 options.control_path = xstrdup(optarg);
509 break;
510 case 'b':
511 options.bind_address = optarg;
512 break;
513 case 'F':
514 config = optarg;
515 break;
516 default:
517 usage();
521 ac -= optind;
522 av += optind;
524 if (ac > 0 && !host && **av != '-') {
525 if (strrchr(*av, '@')) {
526 p = xstrdup(*av);
527 cp = strrchr(p, '@');
528 if (cp == NULL || cp == p)
529 usage();
530 options.user = p;
531 *cp = '\0';
532 host = ++cp;
533 } else
534 host = *av;
535 if (ac > 1) {
536 optind = optreset = 1;
537 goto again;
539 ac--, av++;
542 /* Check that we got a host name. */
543 if (!host)
544 usage();
546 SSLeay_add_all_algorithms();
547 ERR_load_crypto_strings();
549 /* Initialize the command to execute on remote host. */
550 buffer_init(&command);
553 * Save the command to execute on the remote host in a buffer. There
554 * is no limit on the length of the command, except by the maximum
555 * packet size. Also sets the tty flag if there is no command.
557 if (!ac) {
558 /* No command specified - execute shell on a tty. */
559 tty_flag = 1;
560 if (subsystem_flag) {
561 fprintf(stderr,
562 "You must specify a subsystem to invoke.\n");
563 usage();
565 } else {
566 /* A command has been specified. Store it into the buffer. */
567 for (i = 0; i < ac; i++) {
568 if (i)
569 buffer_append(&command, " ", 1);
570 buffer_append(&command, av[i], strlen(av[i]));
574 /* Cannot fork to background if no command. */
575 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
576 !no_shell_flag)
577 fatal("Cannot fork into background without a command "
578 "to execute.");
580 /* Allocate a tty by default if no command specified. */
581 if (buffer_len(&command) == 0)
582 tty_flag = 1;
584 /* Force no tty */
585 if (no_tty_flag)
586 tty_flag = 0;
587 /* Do not allocate a tty if stdin is not a tty. */
588 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
589 if (tty_flag)
590 logit("Pseudo-terminal will not be allocated because "
591 "stdin is not a terminal.");
592 tty_flag = 0;
596 * Initialize "log" output. Since we are the client all output
597 * actually goes to stderr.
599 log_init(argv0,
600 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
601 SYSLOG_FACILITY_USER, !use_syslog);
604 * Read per-user configuration file. Ignore the system wide config
605 * file if the user specifies a config file on the command line.
607 if (config != NULL) {
608 if (!read_config_file(config, host, &options, 0))
609 fatal("Can't open user config file %.100s: "
610 "%.100s", config, strerror(errno));
611 } else {
612 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
613 _PATH_SSH_USER_CONFFILE);
614 if (r > 0 && (size_t)r < sizeof(buf))
615 (void)read_config_file(buf, host, &options, 1);
617 /* Read systemwide configuration file after use config. */
618 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
619 &options, 0);
622 /* Fill configuration defaults. */
623 fill_default_options(&options);
625 channel_set_af(options.address_family);
627 /* reinit */
628 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
630 if (options.user == NULL)
631 options.user = xstrdup(pw->pw_name);
633 /* Get default port if port has not been set. */
634 if (options.port == 0) {
635 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
636 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
639 if (options.local_command != NULL) {
640 char thishost[NI_MAXHOST];
642 if (gethostname(thishost, sizeof(thishost)) == -1)
643 fatal("gethostname: %s", strerror(errno));
644 snprintf(buf, sizeof(buf), "%d", options.port);
645 debug3("expanding LocalCommand: %s", options.local_command);
646 cp = options.local_command;
647 options.local_command = percent_expand(cp, "d", pw->pw_dir,
648 "h", options.hostname? options.hostname : host,
649 "l", thishost, "n", host, "r", options.user, "p", buf,
650 "u", pw->pw_name, (char *)NULL);
651 debug3("expanded LocalCommand: %s", options.local_command);
652 xfree(cp);
655 if (options.hostname != NULL)
656 host = options.hostname;
658 /* force lowercase for hostkey matching */
659 if (options.host_key_alias != NULL) {
660 for (p = options.host_key_alias; *p; p++)
661 if (isupper((unsigned char)*p))
662 *p = (char)tolower((unsigned char)*p);
665 if (options.proxy_command != NULL &&
666 strcmp(options.proxy_command, "none") == 0) {
667 xfree(options.proxy_command);
668 options.proxy_command = NULL;
670 if (options.control_path != NULL &&
671 strcmp(options.control_path, "none") == 0) {
672 xfree(options.control_path);
673 options.control_path = NULL;
676 if (options.control_path != NULL) {
677 char thishost[NI_MAXHOST];
679 if (gethostname(thishost, sizeof(thishost)) == -1)
680 fatal("gethostname: %s", strerror(errno));
681 snprintf(buf, sizeof(buf), "%d", options.port);
682 cp = tilde_expand_filename(options.control_path,
683 original_real_uid);
684 xfree(options.control_path);
685 options.control_path = percent_expand(cp, "p", buf, "h", host,
686 "r", options.user, "l", thishost, (char *)NULL);
687 xfree(cp);
689 if (muxclient_command != 0 && options.control_path == NULL)
690 fatal("No ControlPath specified for \"-O\" command");
691 if (options.control_path != NULL)
692 muxclient(options.control_path);
694 timeout_ms = options.connection_timeout * 1000;
696 /* Open a connection to the remote host. */
697 if (ssh_connect(host, &hostaddr, options.port,
698 options.address_family, options.connection_attempts, &timeout_ms,
699 options.tcp_keep_alive,
700 original_effective_uid == 0 && options.use_privileged_port,
701 options.proxy_command) != 0)
702 exit(255);
704 if (timeout_ms > 0)
705 debug3("timeout: %d ms remain after connect", timeout_ms);
708 * If we successfully made the connection, load the host private key
709 * in case we will need it later for combined rsa-rhosts
710 * authentication. This must be done before releasing extra
711 * privileges, because the file is only readable by root.
712 * If we cannot access the private keys, load the public keys
713 * instead and try to execute the ssh-keysign helper instead.
715 sensitive_data.nkeys = 0;
716 sensitive_data.keys = NULL;
717 sensitive_data.external_keysign = 0;
718 if (options.rhosts_rsa_authentication ||
719 options.hostbased_authentication) {
720 sensitive_data.nkeys = 3;
721 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
722 sizeof(Key));
724 PRIV_START;
725 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
726 _PATH_HOST_KEY_FILE, "", NULL, NULL);
727 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
728 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
729 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
730 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
731 PRIV_END;
733 if (options.hostbased_authentication == 1 &&
734 sensitive_data.keys[0] == NULL &&
735 sensitive_data.keys[1] == NULL &&
736 sensitive_data.keys[2] == NULL) {
737 sensitive_data.keys[1] = key_load_public(
738 _PATH_HOST_DSA_KEY_FILE, NULL);
739 sensitive_data.keys[2] = key_load_public(
740 _PATH_HOST_RSA_KEY_FILE, NULL);
741 sensitive_data.external_keysign = 1;
745 * Get rid of any extra privileges that we may have. We will no
746 * longer need them. Also, extra privileges could make it very hard
747 * to read identity files and other non-world-readable files from the
748 * user's home directory if it happens to be on a NFS volume where
749 * root is mapped to nobody.
751 if (original_effective_uid == 0) {
752 PRIV_START;
753 permanently_set_uid(pw);
757 * Now that we are back to our own permissions, create ~/.ssh
758 * directory if it doesn't already exist.
760 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
761 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
762 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
763 if (mkdir(buf, 0700) < 0)
764 error("Could not create directory '%.200s'.", buf);
766 /* load options.identity_files */
767 load_public_identity_files();
769 /* Expand ~ in known host file names. */
770 /* XXX mem-leaks: */
771 options.system_hostfile =
772 tilde_expand_filename(options.system_hostfile, original_real_uid);
773 options.user_hostfile =
774 tilde_expand_filename(options.user_hostfile, original_real_uid);
775 options.system_hostfile2 =
776 tilde_expand_filename(options.system_hostfile2, original_real_uid);
777 options.user_hostfile2 =
778 tilde_expand_filename(options.user_hostfile2, original_real_uid);
780 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
782 /* Log into the remote system. Never returns if the login fails. */
783 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
784 pw, timeout_ms);
786 /* We no longer need the private host keys. Clear them now. */
787 if (sensitive_data.nkeys != 0) {
788 for (i = 0; i < sensitive_data.nkeys; i++) {
789 if (sensitive_data.keys[i] != NULL) {
790 /* Destroys contents safely */
791 debug3("clear hostkey %d", i);
792 key_free(sensitive_data.keys[i]);
793 sensitive_data.keys[i] = NULL;
796 xfree(sensitive_data.keys);
798 for (i = 0; i < options.num_identity_files; i++) {
799 if (options.identity_files[i]) {
800 xfree(options.identity_files[i]);
801 options.identity_files[i] = NULL;
803 if (options.identity_keys[i]) {
804 key_free(options.identity_keys[i]);
805 options.identity_keys[i] = NULL;
809 exit_status = compat20 ? ssh_session2() : ssh_session();
810 packet_close();
812 if (options.control_path != NULL && muxserver_sock != -1)
813 unlink(options.control_path);
816 * Send SIGHUP to proxy command if used. We don't wait() in
817 * case it hangs and instead rely on init to reap the child
819 if (proxy_command_pid > 1)
820 kill(proxy_command_pid, SIGHUP);
822 return exit_status;
825 /* Callback for remote forward global requests */
826 static void
827 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
829 Forward *rfwd = (Forward *)ctxt;
831 /* XXX verbose() on failure? */
832 debug("remote forward %s for: listen %d, connect %s:%d",
833 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
834 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
835 if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
836 logit("Allocated port %u for remote forward to %s:%d",
837 packet_get_int(),
838 rfwd->connect_host, rfwd->connect_port);
841 if (type == SSH2_MSG_REQUEST_FAILURE) {
842 if (options.exit_on_forward_failure)
843 fatal("Error: remote port forwarding failed for "
844 "listen port %d", rfwd->listen_port);
845 else
846 logit("Warning: remote port forwarding failed for "
847 "listen port %d", rfwd->listen_port);
849 if (++remote_forward_confirms_received == options.num_remote_forwards) {
850 debug("All remote forwarding requests processed");
851 if (fork_after_authentication_flag) {
852 fork_after_authentication_flag = 0;
853 if (daemon(1, 1) < 0)
854 fatal("daemon() failed: %.200s",
855 strerror(errno));
860 static void
861 ssh_init_forwarding(void)
863 int success = 0;
864 int i;
866 /* Initiate local TCP/IP port forwardings. */
867 for (i = 0; i < options.num_local_forwards; i++) {
868 debug("Local connections to %.200s:%d forwarded to remote "
869 "address %.200s:%d",
870 (options.local_forwards[i].listen_host == NULL) ?
871 (options.gateway_ports ? "*" : "LOCALHOST") :
872 options.local_forwards[i].listen_host,
873 options.local_forwards[i].listen_port,
874 options.local_forwards[i].connect_host,
875 options.local_forwards[i].connect_port);
876 success += channel_setup_local_fwd_listener(
877 options.local_forwards[i].listen_host,
878 options.local_forwards[i].listen_port,
879 options.local_forwards[i].connect_host,
880 options.local_forwards[i].connect_port,
881 options.gateway_ports);
883 if (i > 0 && success != i && options.exit_on_forward_failure)
884 fatal("Could not request local forwarding.");
885 if (i > 0 && success == 0)
886 error("Could not request local forwarding.");
888 /* Initiate remote TCP/IP port forwardings. */
889 for (i = 0; i < options.num_remote_forwards; i++) {
890 debug("Remote connections from %.200s:%d forwarded to "
891 "local address %.200s:%d",
892 (options.remote_forwards[i].listen_host == NULL) ?
893 "LOCALHOST" : options.remote_forwards[i].listen_host,
894 options.remote_forwards[i].listen_port,
895 options.remote_forwards[i].connect_host,
896 options.remote_forwards[i].connect_port);
897 if (channel_request_remote_forwarding(
898 options.remote_forwards[i].listen_host,
899 options.remote_forwards[i].listen_port,
900 options.remote_forwards[i].connect_host,
901 options.remote_forwards[i].connect_port) < 0) {
902 if (options.exit_on_forward_failure)
903 fatal("Could not request remote forwarding.");
904 else
905 logit("Warning: Could not request remote "
906 "forwarding.");
908 client_register_global_confirm(ssh_confirm_remote_forward,
909 &options.remote_forwards[i]);
912 /* Initiate tunnel forwarding. */
913 if (options.tun_open != SSH_TUNMODE_NO) {
914 if (client_request_tun_fwd(options.tun_open,
915 options.tun_local, options.tun_remote) == -1) {
916 if (options.exit_on_forward_failure)
917 fatal("Could not request tunnel forwarding.");
918 else
919 error("Could not request tunnel forwarding.");
924 static void
925 check_agent_present(void)
927 if (options.forward_agent) {
928 /* Clear agent forwarding if we don't have an agent. */
929 if (!ssh_agent_present())
930 options.forward_agent = 0;
934 static int
935 ssh_session(void)
937 int type;
938 int interactive = 0;
939 int have_tty = 0;
940 struct winsize ws;
941 char *cp;
942 const char *display;
944 /* Enable compression if requested. */
945 if (options.compression) {
946 debug("Requesting compression at level %d.",
947 options.compression_level);
949 if (options.compression_level < 1 ||
950 options.compression_level > 9)
951 fatal("Compression level must be from 1 (fast) to "
952 "9 (slow, best).");
954 /* Send the request. */
955 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
956 packet_put_int(options.compression_level);
957 packet_send();
958 packet_write_wait();
959 type = packet_read();
960 if (type == SSH_SMSG_SUCCESS)
961 packet_start_compression(options.compression_level);
962 else if (type == SSH_SMSG_FAILURE)
963 logit("Warning: Remote host refused compression.");
964 else
965 packet_disconnect("Protocol error waiting for "
966 "compression response.");
968 /* Allocate a pseudo tty if appropriate. */
969 if (tty_flag) {
970 debug("Requesting pty.");
972 /* Start the packet. */
973 packet_start(SSH_CMSG_REQUEST_PTY);
975 /* Store TERM in the packet. There is no limit on the
976 length of the string. */
977 cp = getenv("TERM");
978 if (!cp)
979 cp = "";
980 packet_put_cstring(cp);
982 /* Store window size in the packet. */
983 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
984 memset(&ws, 0, sizeof(ws));
985 packet_put_int((u_int)ws.ws_row);
986 packet_put_int((u_int)ws.ws_col);
987 packet_put_int((u_int)ws.ws_xpixel);
988 packet_put_int((u_int)ws.ws_ypixel);
990 /* Store tty modes in the packet. */
991 tty_make_modes(fileno(stdin), NULL);
993 /* Send the packet, and wait for it to leave. */
994 packet_send();
995 packet_write_wait();
997 /* Read response from the server. */
998 type = packet_read();
999 if (type == SSH_SMSG_SUCCESS) {
1000 interactive = 1;
1001 have_tty = 1;
1002 } else if (type == SSH_SMSG_FAILURE)
1003 logit("Warning: Remote host failed or refused to "
1004 "allocate a pseudo tty.");
1005 else
1006 packet_disconnect("Protocol error waiting for pty "
1007 "request response.");
1009 /* Request X11 forwarding if enabled and DISPLAY is set. */
1010 display = getenv("DISPLAY");
1011 if (options.forward_x11 && display != NULL) {
1012 char *proto, *data;
1013 /* Get reasonable local authentication information. */
1014 client_x11_get_proto(display, options.xauth_location,
1015 options.forward_x11_trusted, &proto, &data);
1016 /* Request forwarding with authentication spoofing. */
1017 debug("Requesting X11 forwarding with authentication "
1018 "spoofing.");
1019 x11_request_forwarding_with_spoofing(0, display, proto, data);
1021 /* Read response from the server. */
1022 type = packet_read();
1023 if (type == SSH_SMSG_SUCCESS) {
1024 interactive = 1;
1025 } else if (type == SSH_SMSG_FAILURE) {
1026 logit("Warning: Remote host denied X11 forwarding.");
1027 } else {
1028 packet_disconnect("Protocol error waiting for X11 "
1029 "forwarding");
1032 /* Tell the packet module whether this is an interactive session. */
1033 packet_set_interactive(interactive);
1035 /* Request authentication agent forwarding if appropriate. */
1036 check_agent_present();
1038 if (options.forward_agent) {
1039 debug("Requesting authentication agent forwarding.");
1040 auth_request_forwarding();
1042 /* Read response from the server. */
1043 type = packet_read();
1044 packet_check_eom();
1045 if (type != SSH_SMSG_SUCCESS)
1046 logit("Warning: Remote host denied authentication agent forwarding.");
1049 /* Initiate port forwardings. */
1050 ssh_init_forwarding();
1052 /* Execute a local command */
1053 if (options.local_command != NULL &&
1054 options.permit_local_command)
1055 ssh_local_cmd(options.local_command);
1058 * If requested and we are not interested in replies to remote
1059 * forwarding requests, then let ssh continue in the background.
1061 if (fork_after_authentication_flag &&
1062 (!options.exit_on_forward_failure ||
1063 options.num_remote_forwards == 0)) {
1064 fork_after_authentication_flag = 0;
1065 if (daemon(1, 1) < 0)
1066 fatal("daemon() failed: %.200s", strerror(errno));
1070 * If a command was specified on the command line, execute the
1071 * command now. Otherwise request the server to start a shell.
1073 if (buffer_len(&command) > 0) {
1074 int len = buffer_len(&command);
1075 if (len > 900)
1076 len = 900;
1077 debug("Sending command: %.*s", len,
1078 (u_char *)buffer_ptr(&command));
1079 packet_start(SSH_CMSG_EXEC_CMD);
1080 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1081 packet_send();
1082 packet_write_wait();
1083 } else {
1084 debug("Requesting shell.");
1085 packet_start(SSH_CMSG_EXEC_SHELL);
1086 packet_send();
1087 packet_write_wait();
1090 /* Enter the interactive session. */
1091 return client_loop(have_tty, tty_flag ?
1092 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1095 /* request pty/x11/agent/tcpfwd/shell for channel */
1096 static void
1097 ssh_session2_setup(int id, void *arg)
1099 extern char **environ;
1100 const char *display;
1101 int interactive = tty_flag;
1103 display = getenv("DISPLAY");
1104 if (options.forward_x11 && display != NULL) {
1105 char *proto, *data;
1106 /* Get reasonable local authentication information. */
1107 client_x11_get_proto(display, options.xauth_location,
1108 options.forward_x11_trusted, &proto, &data);
1109 /* Request forwarding with authentication spoofing. */
1110 debug("Requesting X11 forwarding with authentication "
1111 "spoofing.");
1112 x11_request_forwarding_with_spoofing(id, display, proto, data);
1113 interactive = 1;
1114 /* XXX wait for reply */
1117 check_agent_present();
1118 if (options.forward_agent) {
1119 debug("Requesting authentication agent forwarding.");
1120 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1121 packet_send();
1124 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1125 NULL, fileno(stdin), &command, environ);
1127 packet_set_interactive(interactive);
1130 /* open new channel for a session */
1131 static int
1132 ssh_session2_open(void)
1134 Channel *c;
1135 int window, packetmax, in, out, err;
1136 int sock;
1137 int socksize;
1138 socklen_t socksizelen = sizeof(int);
1140 if (stdin_null_flag) {
1141 in = open(_PATH_DEVNULL, O_RDONLY);
1142 } else {
1143 in = dup(STDIN_FILENO);
1145 out = dup(STDOUT_FILENO);
1146 err = dup(STDERR_FILENO);
1148 if (in < 0 || out < 0 || err < 0)
1149 fatal("dup() in/out/err failed");
1151 /* enable nonblocking unless tty */
1152 if (!isatty(in))
1153 set_nonblock(in);
1154 if (!isatty(out))
1155 set_nonblock(out);
1156 if (!isatty(err))
1157 set_nonblock(err);
1159 /* we need to check to see if what they want to do about buffer */
1160 /* sizes here. In a hpn to nonhpn connection we want to limit */
1161 /* the window size to something reasonable in case the far side */
1162 /* has the large window bug. In hpn to hpn connection we want to */
1163 /* use the max window size but allow the user to override it */
1164 /* lastly if they disabled hpn then use the ssh std window size */
1166 /* so why don't we just do a getsockopt() here and set the */
1167 /* ssh window to that? In the case of a autotuning receive */
1168 /* window the window would get stuck at the initial buffer */
1169 /* size generally less than 96k. Therefore we need to set the */
1170 /* maximum ssh window size to the maximum hpn buffer size */
1171 /* unless the user has specifically set the tcprcvbufpoll */
1172 /* to no. In which case we *can* just set the window to the */
1173 /* minimum of the hpn buffer size and tcp receive buffer size */
1175 if (tty_flag)
1176 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1177 else
1178 options.hpn_buffer_size = 2*1024*1024;
1180 if (datafellows & SSH_BUG_LARGEWINDOW)
1182 debug("HPN to Non-HPN Connection");
1184 else
1186 if (options.tcp_rcv_buf_poll <= 0)
1188 sock = socket(AF_INET, SOCK_STREAM, 0);
1189 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1190 &socksize, &socksizelen);
1191 close(sock);
1192 debug("socksize %d", socksize);
1193 options.hpn_buffer_size = socksize;
1194 debug ("HPNBufferSize set to TCP RWIN: %d", options.hpn_buffer_size);
1196 else
1198 if (options.tcp_rcv_buf > 0)
1200 /*create a socket but don't connect it */
1201 /* we use that the get the rcv socket size */
1202 sock = socket(AF_INET, SOCK_STREAM, 0);
1203 /* if they are using the tcp_rcv_buf option */
1204 /* attempt to set the buffer size to that */
1205 if (options.tcp_rcv_buf)
1206 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf,
1207 sizeof(options.tcp_rcv_buf));
1208 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1209 &socksize, &socksizelen);
1210 close(sock);
1211 debug("socksize %d", socksize);
1212 options.hpn_buffer_size = socksize;
1213 debug ("HPNBufferSize set to user TCPRcvBuf: %d", options.hpn_buffer_size);
1219 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1221 window = options.hpn_buffer_size;
1223 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1225 packetmax = CHAN_SES_PACKET_DEFAULT;
1226 if (tty_flag) {
1227 window >>= 1;
1228 packetmax >>= 1;
1230 c = channel_new(
1231 "session", SSH_CHANNEL_OPENING, in, out, err,
1232 window, packetmax, CHAN_EXTENDED_WRITE,
1233 "client-session", /*nonblock*/0);
1235 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1236 c->dynamic_window = 1;
1237 debug ("Enabled Dynamic Window Scaling\n");
1239 debug3("ssh_session2_open: channel_new: %d", c->self);
1241 channel_send_open(c->self);
1242 if (!no_shell_flag)
1243 channel_register_open_confirm(c->self,
1244 ssh_session2_setup, NULL);
1246 return c->self;
1249 static int
1250 ssh_session2(void)
1252 int id = -1;
1254 /* XXX should be pre-session */
1255 ssh_init_forwarding();
1257 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1258 id = ssh_session2_open();
1260 /* If we don't expect to open a new session, then disallow it */
1261 if (options.control_master == SSHCTL_MASTER_NO &&
1262 (datafellows & SSH_NEW_OPENSSH)) {
1263 debug("Requesting no-more-sessions@openssh.com");
1264 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1265 packet_put_cstring("no-more-sessions@openssh.com");
1266 packet_put_char(0);
1267 packet_send();
1270 /* Execute a local command */
1271 if (options.local_command != NULL &&
1272 options.permit_local_command)
1273 ssh_local_cmd(options.local_command);
1275 /* Start listening for multiplex clients */
1276 muxserver_listen();
1278 /* If requested, let ssh continue in the background. */
1279 if (fork_after_authentication_flag) {
1280 fork_after_authentication_flag = 0;
1281 if (daemon(1, 1) < 0)
1282 fatal("daemon() failed: %.200s", strerror(errno));
1285 return client_loop(tty_flag, tty_flag ?
1286 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1289 static void
1290 load_public_identity_files(void)
1292 char *filename, *cp, thishost[NI_MAXHOST];
1293 char *pwdir = NULL, *pwname = NULL;
1294 int i = 0;
1295 Key *public;
1296 struct passwd *pw;
1297 #ifdef SMARTCARD
1298 Key **keys;
1300 if (options.smartcard_device != NULL &&
1301 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1302 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1303 int count = 0;
1304 for (i = 0; keys[i] != NULL; i++) {
1305 count++;
1306 memmove(&options.identity_files[1],
1307 &options.identity_files[0],
1308 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1309 memmove(&options.identity_keys[1],
1310 &options.identity_keys[0],
1311 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1312 options.num_identity_files++;
1313 options.identity_keys[0] = keys[i];
1314 options.identity_files[0] = sc_get_key_label(keys[i]);
1316 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1317 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1318 i = count;
1319 xfree(keys);
1321 #endif /* SMARTCARD */
1322 if ((pw = getpwuid(original_real_uid)) == NULL)
1323 fatal("load_public_identity_files: getpwuid failed");
1324 pwname = xstrdup(pw->pw_name);
1325 pwdir = xstrdup(pw->pw_dir);
1326 if (gethostname(thishost, sizeof(thishost)) == -1)
1327 fatal("load_public_identity_files: gethostname: %s",
1328 strerror(errno));
1329 for (; i < options.num_identity_files; i++) {
1330 cp = tilde_expand_filename(options.identity_files[i],
1331 original_real_uid);
1332 filename = percent_expand(cp, "d", pwdir,
1333 "u", pwname, "l", thishost, "h", host,
1334 "r", options.user, (char *)NULL);
1335 xfree(cp);
1336 public = key_load_public(filename, NULL);
1337 debug("identity file %s type %d", filename,
1338 public ? public->type : -1);
1339 xfree(options.identity_files[i]);
1340 options.identity_files[i] = filename;
1341 options.identity_keys[i] = public;
1343 bzero(pwname, strlen(pwname));
1344 xfree(pwname);
1345 bzero(pwdir, strlen(pwdir));
1346 xfree(pwdir);