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