]> andersk Git - openssh.git/blame_incremental - ssh.c
tidy
[openssh.git] / ssh.c
... / ...
CommitLineData
1/* $OpenBSD: ssh.c,v 1.286 2006/07/12 22:28:52 stevesk 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#include <sys/un.h>
53
54#include <ctype.h>
55#include <errno.h>
56#include <fcntl.h>
57#if defined(HAVE_NETDB_H)
58# include <netdb.h>
59#endif
60#ifdef HAVE_PATHS_H
61#include <paths.h>
62#endif
63#include <pwd.h>
64#include <signal.h>
65
66#include <openssl/evp.h>
67#include <openssl/err.h>
68
69#include "ssh.h"
70#include "ssh1.h"
71#include "ssh2.h"
72#include "compat.h"
73#include "cipher.h"
74#include "xmalloc.h"
75#include "packet.h"
76#include "buffer.h"
77#include "bufaux.h"
78#include "channels.h"
79#include "key.h"
80#include "authfd.h"
81#include "authfile.h"
82#include "pathnames.h"
83#include "dispatch.h"
84#include "clientloop.h"
85#include "log.h"
86#include "readconf.h"
87#include "sshconnect.h"
88#include "misc.h"
89#include "kex.h"
90#include "mac.h"
91#include "sshpty.h"
92#include "match.h"
93#include "msg.h"
94#include "monitor_fdpass.h"
95#include "uidswap.h"
96#include "version.h"
97
98#ifdef SMARTCARD
99#include "scard.h"
100#endif
101
102extern char *__progname;
103
104/* Flag indicating whether debug mode is on. This can be set on the command line. */
105int debug_flag = 0;
106
107/* Flag indicating whether a tty should be allocated */
108int tty_flag = 0;
109int no_tty_flag = 0;
110int force_tty_flag = 0;
111
112/* don't exec a shell */
113int no_shell_flag = 0;
114
115/*
116 * Flag indicating that nothing should be read from stdin. This can be set
117 * on the command line.
118 */
119int stdin_null_flag = 0;
120
121/*
122 * Flag indicating that ssh should fork after authentication. This is useful
123 * so that the passphrase can be entered manually, and then ssh goes to the
124 * background.
125 */
126int fork_after_authentication_flag = 0;
127
128/*
129 * General data structure for command line options and options configurable
130 * in configuration files. See readconf.h.
131 */
132Options options;
133
134/* optional user configfile */
135char *config = NULL;
136
137/*
138 * Name of the host we are connecting to. This is the name given on the
139 * command line, or the HostName specified for the user-supplied name in a
140 * configuration file.
141 */
142char *host;
143
144/* socket address the host resolves to */
145struct sockaddr_storage hostaddr;
146
147/* Private host keys. */
148Sensitive sensitive_data;
149
150/* Original real UID. */
151uid_t original_real_uid;
152uid_t original_effective_uid;
153
154/* command to be executed */
155Buffer command;
156
157/* Should we execute a command or invoke a subsystem? */
158int subsystem_flag = 0;
159
160/* # of replies received for global requests */
161static int client_global_request_id = 0;
162
163/* pid of proxycommand child process */
164pid_t proxy_command_pid = 0;
165
166/* fd to control socket */
167int control_fd = -1;
168
169/* Multiplexing control command */
170static u_int mux_command = 0;
171
172/* Only used in control client mode */
173volatile sig_atomic_t control_client_terminate = 0;
174u_int control_server_pid = 0;
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 [-1246AaCfgkMNnqsTtVvXxY] [-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);
195static void control_client(const char *path);
196
197/*
198 * Main program for the ssh client.
199 */
200int
201main(int ac, char **av)
202{
203 int i, opt, exit_status;
204 char *p, *cp, *line, buf[256];
205 struct stat st;
206 struct passwd *pw;
207 int dummy;
208 extern int optind, optreset;
209 extern char *optarg;
210 struct servent *sp;
211 Forward fwd;
212
213 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
214 sanitise_stdfd();
215
216 __progname = ssh_get_progname(av[0]);
217 init_rng();
218
219 /*
220 * Save the original real uid. It will be needed later (uid-swapping
221 * may clobber the real uid).
222 */
223 original_real_uid = getuid();
224 original_effective_uid = geteuid();
225
226 /*
227 * Use uid-swapping to give up root privileges for the duration of
228 * option processing. We will re-instantiate the rights when we are
229 * ready to create the privileged port, and will permanently drop
230 * them when the port has been created (actually, when the connection
231 * has been made, as we may need to create the port several times).
232 */
233 PRIV_END;
234
235#ifdef HAVE_SETRLIMIT
236 /* If we are installed setuid root be careful to not drop core. */
237 if (original_real_uid != original_effective_uid) {
238 struct rlimit rlim;
239 rlim.rlim_cur = rlim.rlim_max = 0;
240 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
241 fatal("setrlimit failed: %.100s", strerror(errno));
242 }
243#endif
244 /* Get user data. */
245 pw = getpwuid(original_real_uid);
246 if (!pw) {
247 logit("You don't exist, go away!");
248 exit(255);
249 }
250 /* Take a copy of the returned structure. */
251 pw = pwcopy(pw);
252
253 /*
254 * Set our umask to something reasonable, as some files are created
255 * with the default umask. This will make them world-readable but
256 * writable only by the owner, which is ok for all files for which we
257 * don't set the modes explicitly.
258 */
259 umask(022);
260
261 /* Initialize option structure to indicate that no values have been set. */
262 initialize_options(&options);
263
264 /* Parse command-line arguments. */
265 host = NULL;
266
267 again:
268 while ((opt = getopt(ac, av,
269 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
270 switch (opt) {
271 case '1':
272 options.protocol = SSH_PROTO_1;
273 break;
274 case '2':
275 options.protocol = SSH_PROTO_2;
276 break;
277 case '4':
278 options.address_family = AF_INET;
279 break;
280 case '6':
281 options.address_family = AF_INET6;
282 break;
283 case 'n':
284 stdin_null_flag = 1;
285 break;
286 case 'f':
287 fork_after_authentication_flag = 1;
288 stdin_null_flag = 1;
289 break;
290 case 'x':
291 options.forward_x11 = 0;
292 break;
293 case 'X':
294 options.forward_x11 = 1;
295 break;
296 case 'Y':
297 options.forward_x11 = 1;
298 options.forward_x11_trusted = 1;
299 break;
300 case 'g':
301 options.gateway_ports = 1;
302 break;
303 case 'O':
304 if (strcmp(optarg, "check") == 0)
305 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
306 else if (strcmp(optarg, "exit") == 0)
307 mux_command = SSHMUX_COMMAND_TERMINATE;
308 else
309 fatal("Invalid multiplex command.");
310 break;
311 case 'P': /* deprecated */
312 options.use_privileged_port = 0;
313 break;
314 case 'a':
315 options.forward_agent = 0;
316 break;
317 case 'A':
318 options.forward_agent = 1;
319 break;
320 case 'k':
321 options.gss_deleg_creds = 0;
322 break;
323 case 'i':
324 if (stat(optarg, &st) < 0) {
325 fprintf(stderr, "Warning: Identity file %s "
326 "not accessible: %s.\n", optarg,
327 strerror(errno));
328 break;
329 }
330 if (options.num_identity_files >=
331 SSH_MAX_IDENTITY_FILES)
332 fatal("Too many identity files specified "
333 "(max %d)", SSH_MAX_IDENTITY_FILES);
334 options.identity_files[options.num_identity_files++] =
335 xstrdup(optarg);
336 break;
337 case 'I':
338#ifdef SMARTCARD
339 options.smartcard_device = xstrdup(optarg);
340#else
341 fprintf(stderr, "no support for smartcards.\n");
342#endif
343 break;
344 case 't':
345 if (tty_flag)
346 force_tty_flag = 1;
347 tty_flag = 1;
348 break;
349 case 'v':
350 if (debug_flag == 0) {
351 debug_flag = 1;
352 options.log_level = SYSLOG_LEVEL_DEBUG1;
353 } else {
354 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
355 options.log_level++;
356 break;
357 }
358 /* FALLTHROUGH */
359 case 'V':
360 fprintf(stderr, "%s, %s\n",
361 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
362 if (opt == 'V')
363 exit(0);
364 break;
365 case 'w':
366 if (options.tun_open == -1)
367 options.tun_open = SSH_TUNMODE_DEFAULT;
368 options.tun_local = a2tun(optarg, &options.tun_remote);
369 if (options.tun_local == SSH_TUNID_ERR) {
370 fprintf(stderr, "Bad tun device '%s'\n", optarg);
371 exit(255);
372 }
373 break;
374 case 'q':
375 options.log_level = SYSLOG_LEVEL_QUIET;
376 break;
377 case 'e':
378 if (optarg[0] == '^' && optarg[2] == 0 &&
379 (u_char) optarg[1] >= 64 &&
380 (u_char) optarg[1] < 128)
381 options.escape_char = (u_char) optarg[1] & 31;
382 else if (strlen(optarg) == 1)
383 options.escape_char = (u_char) optarg[0];
384 else if (strcmp(optarg, "none") == 0)
385 options.escape_char = SSH_ESCAPECHAR_NONE;
386 else {
387 fprintf(stderr, "Bad escape character '%s'.\n",
388 optarg);
389 exit(255);
390 }
391 break;
392 case 'c':
393 if (ciphers_valid(optarg)) {
394 /* SSH2 only */
395 options.ciphers = xstrdup(optarg);
396 options.cipher = SSH_CIPHER_INVALID;
397 } else {
398 /* SSH1 only */
399 options.cipher = cipher_number(optarg);
400 if (options.cipher == -1) {
401 fprintf(stderr,
402 "Unknown cipher type '%s'\n",
403 optarg);
404 exit(255);
405 }
406 if (options.cipher == SSH_CIPHER_3DES)
407 options.ciphers = "3des-cbc";
408 else if (options.cipher == SSH_CIPHER_BLOWFISH)
409 options.ciphers = "blowfish-cbc";
410 else
411 options.ciphers = (char *)-1;
412 }
413 break;
414 case 'm':
415 if (mac_valid(optarg))
416 options.macs = xstrdup(optarg);
417 else {
418 fprintf(stderr, "Unknown mac type '%s'\n",
419 optarg);
420 exit(255);
421 }
422 break;
423 case 'M':
424 if (options.control_master == SSHCTL_MASTER_YES)
425 options.control_master = SSHCTL_MASTER_ASK;
426 else
427 options.control_master = SSHCTL_MASTER_YES;
428 break;
429 case 'p':
430 options.port = a2port(optarg);
431 if (options.port == 0) {
432 fprintf(stderr, "Bad port '%s'\n", optarg);
433 exit(255);
434 }
435 break;
436 case 'l':
437 options.user = optarg;
438 break;
439
440 case 'L':
441 if (parse_forward(&fwd, optarg))
442 add_local_forward(&options, &fwd);
443 else {
444 fprintf(stderr,
445 "Bad local forwarding specification '%s'\n",
446 optarg);
447 exit(255);
448 }
449 break;
450
451 case 'R':
452 if (parse_forward(&fwd, optarg)) {
453 add_remote_forward(&options, &fwd);
454 } else {
455 fprintf(stderr,
456 "Bad remote forwarding specification "
457 "'%s'\n", optarg);
458 exit(255);
459 }
460 break;
461
462 case 'D':
463 cp = p = xstrdup(optarg);
464 memset(&fwd, '\0', sizeof(fwd));
465 fwd.connect_host = "socks";
466 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
467 fprintf(stderr, "Bad dynamic forwarding "
468 "specification '%.100s'\n", optarg);
469 exit(255);
470 }
471 if (cp != NULL) {
472 fwd.listen_port = a2port(cp);
473 fwd.listen_host = cleanhostname(fwd.listen_host);
474 } else {
475 fwd.listen_port = a2port(fwd.listen_host);
476 fwd.listen_host = NULL;
477 }
478
479 if (fwd.listen_port == 0) {
480 fprintf(stderr, "Bad dynamic port '%s'\n",
481 optarg);
482 exit(255);
483 }
484 add_local_forward(&options, &fwd);
485 xfree(p);
486 break;
487
488 case 'C':
489 options.compression = 1;
490 break;
491 case 'N':
492 no_shell_flag = 1;
493 no_tty_flag = 1;
494 break;
495 case 'T':
496 no_tty_flag = 1;
497 break;
498 case 'o':
499 dummy = 1;
500 line = xstrdup(optarg);
501 if (process_config_line(&options, host ? host : "",
502 line, "command-line", 0, &dummy) != 0)
503 exit(255);
504 xfree(line);
505 break;
506 case 's':
507 subsystem_flag = 1;
508 break;
509 case 'S':
510 if (options.control_path != NULL)
511 free(options.control_path);
512 options.control_path = xstrdup(optarg);
513 break;
514 case 'b':
515 options.bind_address = optarg;
516 break;
517 case 'F':
518 config = optarg;
519 break;
520 default:
521 usage();
522 }
523 }
524
525 ac -= optind;
526 av += optind;
527
528 if (ac > 0 && !host && **av != '-') {
529 if (strrchr(*av, '@')) {
530 p = xstrdup(*av);
531 cp = strrchr(p, '@');
532 if (cp == NULL || cp == p)
533 usage();
534 options.user = p;
535 *cp = '\0';
536 host = ++cp;
537 } else
538 host = *av;
539 if (ac > 1) {
540 optind = optreset = 1;
541 goto again;
542 }
543 ac--, av++;
544 }
545
546 /* Check that we got a host name. */
547 if (!host)
548 usage();
549
550 SSLeay_add_all_algorithms();
551 ERR_load_crypto_strings();
552
553 /* Initialize the command to execute on remote host. */
554 buffer_init(&command);
555
556 /*
557 * Save the command to execute on the remote host in a buffer. There
558 * is no limit on the length of the command, except by the maximum
559 * packet size. Also sets the tty flag if there is no command.
560 */
561 if (!ac) {
562 /* No command specified - execute shell on a tty. */
563 tty_flag = 1;
564 if (subsystem_flag) {
565 fprintf(stderr,
566 "You must specify a subsystem to invoke.\n");
567 usage();
568 }
569 } else {
570 /* A command has been specified. Store it into the buffer. */
571 for (i = 0; i < ac; i++) {
572 if (i)
573 buffer_append(&command, " ", 1);
574 buffer_append(&command, av[i], strlen(av[i]));
575 }
576 }
577
578 /* Cannot fork to background if no command. */
579 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
580 fatal("Cannot fork into background without a command to execute.");
581
582 /* Allocate a tty by default if no command specified. */
583 if (buffer_len(&command) == 0)
584 tty_flag = 1;
585
586 /* Force no tty */
587 if (no_tty_flag)
588 tty_flag = 0;
589 /* Do not allocate a tty if stdin is not a tty. */
590 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
591 if (tty_flag)
592 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
593 tty_flag = 0;
594 }
595
596 /*
597 * Initialize "log" output. Since we are the client all output
598 * actually goes to stderr.
599 */
600 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
601 SYSLOG_FACILITY_USER, 1);
602
603 /*
604 * Read per-user configuration file. Ignore the system wide config
605 * file if the user specifies a config file on the command line.
606 */
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 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
613 _PATH_SSH_USER_CONFFILE);
614 (void)read_config_file(buf, host, &options, 1);
615
616 /* Read systemwide configuration file after use config. */
617 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
618 &options, 0);
619 }
620
621 /* Fill configuration defaults. */
622 fill_default_options(&options);
623
624 channel_set_af(options.address_family);
625
626 /* reinit */
627 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
628
629 seed_rng();
630
631 if (options.user == NULL)
632 options.user = xstrdup(pw->pw_name);
633
634 if (options.hostname != NULL)
635 host = options.hostname;
636
637 /* force lowercase for hostkey matching */
638 if (options.host_key_alias != NULL) {
639 for (p = options.host_key_alias; *p; p++)
640 if (isupper(*p))
641 *p = (char)tolower(*p);
642 }
643
644 /* Get default port if port has not been set. */
645 if (options.port == 0) {
646 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
647 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
648 }
649
650 if (options.proxy_command != NULL &&
651 strcmp(options.proxy_command, "none") == 0)
652 options.proxy_command = NULL;
653 if (options.control_path != NULL &&
654 strcmp(options.control_path, "none") == 0)
655 options.control_path = NULL;
656
657 if (options.control_path != NULL) {
658 char thishost[NI_MAXHOST];
659
660 if (gethostname(thishost, sizeof(thishost)) == -1)
661 fatal("gethostname: %s", strerror(errno));
662 snprintf(buf, sizeof(buf), "%d", options.port);
663 cp = tilde_expand_filename(options.control_path,
664 original_real_uid);
665 options.control_path = percent_expand(cp, "p", buf, "h", host,
666 "r", options.user, "l", thishost, (char *)NULL);
667 xfree(cp);
668 }
669 if (mux_command != 0 && options.control_path == NULL)
670 fatal("No ControlPath specified for \"-O\" command");
671 if (options.control_path != NULL)
672 control_client(options.control_path);
673
674 /* Open a connection to the remote host. */
675 if (ssh_connect(host, &hostaddr, options.port,
676 options.address_family, options.connection_attempts,
677#ifdef HAVE_CYGWIN
678 options.use_privileged_port,
679#else
680 original_effective_uid == 0 && options.use_privileged_port,
681#endif
682 options.proxy_command) != 0)
683 exit(255);
684
685 /*
686 * If we successfully made the connection, load the host private key
687 * in case we will need it later for combined rsa-rhosts
688 * authentication. This must be done before releasing extra
689 * privileges, because the file is only readable by root.
690 * If we cannot access the private keys, load the public keys
691 * instead and try to execute the ssh-keysign helper instead.
692 */
693 sensitive_data.nkeys = 0;
694 sensitive_data.keys = NULL;
695 sensitive_data.external_keysign = 0;
696 if (options.rhosts_rsa_authentication ||
697 options.hostbased_authentication) {
698 sensitive_data.nkeys = 3;
699 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
700 sizeof(Key));
701
702 PRIV_START;
703 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
704 _PATH_HOST_KEY_FILE, "", NULL, NULL);
705 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
706 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
707 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
708 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
709 PRIV_END;
710
711 if (options.hostbased_authentication == 1 &&
712 sensitive_data.keys[0] == NULL &&
713 sensitive_data.keys[1] == NULL &&
714 sensitive_data.keys[2] == NULL) {
715 sensitive_data.keys[1] = key_load_public(
716 _PATH_HOST_DSA_KEY_FILE, NULL);
717 sensitive_data.keys[2] = key_load_public(
718 _PATH_HOST_RSA_KEY_FILE, NULL);
719 sensitive_data.external_keysign = 1;
720 }
721 }
722 /*
723 * Get rid of any extra privileges that we may have. We will no
724 * longer need them. Also, extra privileges could make it very hard
725 * to read identity files and other non-world-readable files from the
726 * user's home directory if it happens to be on a NFS volume where
727 * root is mapped to nobody.
728 */
729 if (original_effective_uid == 0) {
730 PRIV_START;
731 permanently_set_uid(pw);
732 }
733
734 /*
735 * Now that we are back to our own permissions, create ~/.ssh
736 * directory if it doesn't already exist.
737 */
738 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
739 if (stat(buf, &st) < 0)
740 if (mkdir(buf, 0700) < 0)
741 error("Could not create directory '%.200s'.", buf);
742
743 /* load options.identity_files */
744 load_public_identity_files();
745
746 /* Expand ~ in known host file names. */
747 /* XXX mem-leaks: */
748 options.system_hostfile =
749 tilde_expand_filename(options.system_hostfile, original_real_uid);
750 options.user_hostfile =
751 tilde_expand_filename(options.user_hostfile, original_real_uid);
752 options.system_hostfile2 =
753 tilde_expand_filename(options.system_hostfile2, original_real_uid);
754 options.user_hostfile2 =
755 tilde_expand_filename(options.user_hostfile2, original_real_uid);
756
757 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
758
759 /* Log into the remote system. This never returns if the login fails. */
760 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
761
762 /* We no longer need the private host keys. Clear them now. */
763 if (sensitive_data.nkeys != 0) {
764 for (i = 0; i < sensitive_data.nkeys; i++) {
765 if (sensitive_data.keys[i] != NULL) {
766 /* Destroys contents safely */
767 debug3("clear hostkey %d", i);
768 key_free(sensitive_data.keys[i]);
769 sensitive_data.keys[i] = NULL;
770 }
771 }
772 xfree(sensitive_data.keys);
773 }
774 for (i = 0; i < options.num_identity_files; i++) {
775 if (options.identity_files[i]) {
776 xfree(options.identity_files[i]);
777 options.identity_files[i] = NULL;
778 }
779 if (options.identity_keys[i]) {
780 key_free(options.identity_keys[i]);
781 options.identity_keys[i] = NULL;
782 }
783 }
784
785 exit_status = compat20 ? ssh_session2() : ssh_session();
786 packet_close();
787
788 if (options.control_path != NULL && control_fd != -1)
789 unlink(options.control_path);
790
791 /*
792 * Send SIGHUP to proxy command if used. We don't wait() in
793 * case it hangs and instead rely on init to reap the child
794 */
795 if (proxy_command_pid > 1)
796 kill(proxy_command_pid, SIGHUP);
797
798 return exit_status;
799}
800
801static void
802ssh_init_forwarding(void)
803{
804 int success = 0;
805 int i;
806
807 /* Initiate local TCP/IP port forwardings. */
808 for (i = 0; i < options.num_local_forwards; i++) {
809 debug("Local connections to %.200s:%d forwarded to remote "
810 "address %.200s:%d",
811 (options.local_forwards[i].listen_host == NULL) ?
812 (options.gateway_ports ? "*" : "LOCALHOST") :
813 options.local_forwards[i].listen_host,
814 options.local_forwards[i].listen_port,
815 options.local_forwards[i].connect_host,
816 options.local_forwards[i].connect_port);
817 success += channel_setup_local_fwd_listener(
818 options.local_forwards[i].listen_host,
819 options.local_forwards[i].listen_port,
820 options.local_forwards[i].connect_host,
821 options.local_forwards[i].connect_port,
822 options.gateway_ports);
823 }
824 if (i > 0 && success != i && options.exit_on_forward_failure)
825 fatal("Could not request local forwarding.");
826 if (i > 0 && success == 0)
827 error("Could not request local forwarding.");
828
829 /* Initiate remote TCP/IP port forwardings. */
830 for (i = 0; i < options.num_remote_forwards; i++) {
831 debug("Remote connections from %.200s:%d forwarded to "
832 "local address %.200s:%d",
833 (options.remote_forwards[i].listen_host == NULL) ?
834 "LOCALHOST" : options.remote_forwards[i].listen_host,
835 options.remote_forwards[i].listen_port,
836 options.remote_forwards[i].connect_host,
837 options.remote_forwards[i].connect_port);
838 if (channel_request_remote_forwarding(
839 options.remote_forwards[i].listen_host,
840 options.remote_forwards[i].listen_port,
841 options.remote_forwards[i].connect_host,
842 options.remote_forwards[i].connect_port) < 0) {
843 if (options.exit_on_forward_failure)
844 fatal("Could not request remote forwarding.");
845 else
846 logit("Warning: Could not request remote "
847 "forwarding.");
848 }
849 }
850}
851
852static void
853check_agent_present(void)
854{
855 if (options.forward_agent) {
856 /* Clear agent forwarding if we don't have an agent. */
857 if (!ssh_agent_present())
858 options.forward_agent = 0;
859 }
860}
861
862static int
863ssh_session(void)
864{
865 int type;
866 int interactive = 0;
867 int have_tty = 0;
868 struct winsize ws;
869 char *cp;
870 const char *display;
871
872 /* Enable compression if requested. */
873 if (options.compression) {
874 debug("Requesting compression at level %d.", options.compression_level);
875
876 if (options.compression_level < 1 || options.compression_level > 9)
877 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
878
879 /* Send the request. */
880 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
881 packet_put_int(options.compression_level);
882 packet_send();
883 packet_write_wait();
884 type = packet_read();
885 if (type == SSH_SMSG_SUCCESS)
886 packet_start_compression(options.compression_level);
887 else if (type == SSH_SMSG_FAILURE)
888 logit("Warning: Remote host refused compression.");
889 else
890 packet_disconnect("Protocol error waiting for compression response.");
891 }
892 /* Allocate a pseudo tty if appropriate. */
893 if (tty_flag) {
894 debug("Requesting pty.");
895
896 /* Start the packet. */
897 packet_start(SSH_CMSG_REQUEST_PTY);
898
899 /* Store TERM in the packet. There is no limit on the
900 length of the string. */
901 cp = getenv("TERM");
902 if (!cp)
903 cp = "";
904 packet_put_cstring(cp);
905
906 /* Store window size in the packet. */
907 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
908 memset(&ws, 0, sizeof(ws));
909 packet_put_int((u_int)ws.ws_row);
910 packet_put_int((u_int)ws.ws_col);
911 packet_put_int((u_int)ws.ws_xpixel);
912 packet_put_int((u_int)ws.ws_ypixel);
913
914 /* Store tty modes in the packet. */
915 tty_make_modes(fileno(stdin), NULL);
916
917 /* Send the packet, and wait for it to leave. */
918 packet_send();
919 packet_write_wait();
920
921 /* Read response from the server. */
922 type = packet_read();
923 if (type == SSH_SMSG_SUCCESS) {
924 interactive = 1;
925 have_tty = 1;
926 } else if (type == SSH_SMSG_FAILURE)
927 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
928 else
929 packet_disconnect("Protocol error waiting for pty request response.");
930 }
931 /* Request X11 forwarding if enabled and DISPLAY is set. */
932 display = getenv("DISPLAY");
933 if (options.forward_x11 && display != NULL) {
934 char *proto, *data;
935 /* Get reasonable local authentication information. */
936 client_x11_get_proto(display, options.xauth_location,
937 options.forward_x11_trusted, &proto, &data);
938 /* Request forwarding with authentication spoofing. */
939 debug("Requesting X11 forwarding with authentication spoofing.");
940 x11_request_forwarding_with_spoofing(0, display, proto, data);
941
942 /* Read response from the server. */
943 type = packet_read();
944 if (type == SSH_SMSG_SUCCESS) {
945 interactive = 1;
946 } else if (type == SSH_SMSG_FAILURE) {
947 logit("Warning: Remote host denied X11 forwarding.");
948 } else {
949 packet_disconnect("Protocol error waiting for X11 forwarding");
950 }
951 }
952 /* Tell the packet module whether this is an interactive session. */
953 packet_set_interactive(interactive);
954
955 /* Request authentication agent forwarding if appropriate. */
956 check_agent_present();
957
958 if (options.forward_agent) {
959 debug("Requesting authentication agent forwarding.");
960 auth_request_forwarding();
961
962 /* Read response from the server. */
963 type = packet_read();
964 packet_check_eom();
965 if (type != SSH_SMSG_SUCCESS)
966 logit("Warning: Remote host denied authentication agent forwarding.");
967 }
968
969 /* Initiate port forwardings. */
970 ssh_init_forwarding();
971
972 /* If requested, let ssh continue in the background. */
973 if (fork_after_authentication_flag)
974 if (daemon(1, 1) < 0)
975 fatal("daemon() failed: %.200s", strerror(errno));
976
977 /*
978 * If a command was specified on the command line, execute the
979 * command now. Otherwise request the server to start a shell.
980 */
981 if (buffer_len(&command) > 0) {
982 int len = buffer_len(&command);
983 if (len > 900)
984 len = 900;
985 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
986 packet_start(SSH_CMSG_EXEC_CMD);
987 packet_put_string(buffer_ptr(&command), buffer_len(&command));
988 packet_send();
989 packet_write_wait();
990 } else {
991 debug("Requesting shell.");
992 packet_start(SSH_CMSG_EXEC_SHELL);
993 packet_send();
994 packet_write_wait();
995 }
996
997 /* Enter the interactive session. */
998 return client_loop(have_tty, tty_flag ?
999 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1000}
1001
1002static void
1003ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1004{
1005 int id, len;
1006
1007 id = packet_get_int();
1008 len = buffer_len(&command);
1009 if (len > 900)
1010 len = 900;
1011 packet_check_eom();
1012 if (type == SSH2_MSG_CHANNEL_FAILURE)
1013 fatal("Request for subsystem '%.*s' failed on channel %d",
1014 len, (u_char *)buffer_ptr(&command), id);
1015}
1016
1017void
1018client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1019{
1020 int i;
1021
1022 i = client_global_request_id++;
1023 if (i >= options.num_remote_forwards)
1024 return;
1025 debug("remote forward %s for: listen %d, connect %s:%d",
1026 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1027 options.remote_forwards[i].listen_port,
1028 options.remote_forwards[i].connect_host,
1029 options.remote_forwards[i].connect_port);
1030 if (type == SSH2_MSG_REQUEST_FAILURE) {
1031 if (options.exit_on_forward_failure)
1032 fatal("Error: remote port forwarding failed for "
1033 "listen port %d",
1034 options.remote_forwards[i].listen_port);
1035 else
1036 logit("Warning: remote port forwarding failed for "
1037 "listen port %d",
1038 options.remote_forwards[i].listen_port);
1039 }
1040}
1041
1042static void
1043ssh_control_listener(void)
1044{
1045 struct sockaddr_un addr;
1046 mode_t old_umask;
1047 int addr_len;
1048
1049 if (options.control_path == NULL ||
1050 options.control_master == SSHCTL_MASTER_NO)
1051 return;
1052
1053 debug("setting up multiplex master socket");
1054
1055 memset(&addr, '\0', sizeof(addr));
1056 addr.sun_family = AF_UNIX;
1057 addr_len = offsetof(struct sockaddr_un, sun_path) +
1058 strlen(options.control_path) + 1;
1059
1060 if (strlcpy(addr.sun_path, options.control_path,
1061 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1062 fatal("ControlPath too long");
1063
1064 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1065 fatal("%s socket(): %s", __func__, strerror(errno));
1066
1067 old_umask = umask(0177);
1068 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1069 control_fd = -1;
1070 if (errno == EINVAL || errno == EADDRINUSE)
1071 fatal("ControlSocket %s already exists",
1072 options.control_path);
1073 else
1074 fatal("%s bind(): %s", __func__, strerror(errno));
1075 }
1076 umask(old_umask);
1077
1078 if (listen(control_fd, 64) == -1)
1079 fatal("%s listen(): %s", __func__, strerror(errno));
1080
1081 set_nonblock(control_fd);
1082}
1083
1084/* request pty/x11/agent/tcpfwd/shell for channel */
1085static void
1086ssh_session2_setup(int id, void *arg)
1087{
1088 extern char **environ;
1089 const char *display;
1090 int interactive = tty_flag;
1091
1092 display = getenv("DISPLAY");
1093 if (options.forward_x11 && display != NULL) {
1094 char *proto, *data;
1095 /* Get reasonable local authentication information. */
1096 client_x11_get_proto(display, options.xauth_location,
1097 options.forward_x11_trusted, &proto, &data);
1098 /* Request forwarding with authentication spoofing. */
1099 debug("Requesting X11 forwarding with authentication spoofing.");
1100 x11_request_forwarding_with_spoofing(id, display, proto, data);
1101 interactive = 1;
1102 /* XXX wait for reply */
1103 }
1104
1105 check_agent_present();
1106 if (options.forward_agent) {
1107 debug("Requesting authentication agent forwarding.");
1108 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1109 packet_send();
1110 }
1111
1112 if (options.tun_open != SSH_TUNMODE_NO) {
1113 Channel *c;
1114 int fd;
1115
1116 debug("Requesting tun.");
1117 if ((fd = tun_open(options.tun_local,
1118 options.tun_open)) >= 0) {
1119 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1120 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1121 0, "tun", 1);
1122 c->datagram = 1;
1123#if defined(SSH_TUN_FILTER)
1124 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1125 channel_register_filter(c->self, sys_tun_infilter,
1126 sys_tun_outfilter);
1127#endif
1128 packet_start(SSH2_MSG_CHANNEL_OPEN);
1129 packet_put_cstring("tun@openssh.com");
1130 packet_put_int(c->self);
1131 packet_put_int(c->local_window_max);
1132 packet_put_int(c->local_maxpacket);
1133 packet_put_int(options.tun_open);
1134 packet_put_int(options.tun_remote);
1135 packet_send();
1136 }
1137 }
1138
1139 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1140 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1141
1142 packet_set_interactive(interactive);
1143}
1144
1145/* open new channel for a session */
1146static int
1147ssh_session2_open(void)
1148{
1149 Channel *c;
1150 int window, packetmax, in, out, err;
1151
1152 if (stdin_null_flag) {
1153 in = open(_PATH_DEVNULL, O_RDONLY);
1154 } else {
1155 in = dup(STDIN_FILENO);
1156 }
1157 out = dup(STDOUT_FILENO);
1158 err = dup(STDERR_FILENO);
1159
1160 if (in < 0 || out < 0 || err < 0)
1161 fatal("dup() in/out/err failed");
1162
1163 /* enable nonblocking unless tty */
1164 if (!isatty(in))
1165 set_nonblock(in);
1166 if (!isatty(out))
1167 set_nonblock(out);
1168 if (!isatty(err))
1169 set_nonblock(err);
1170
1171 window = CHAN_SES_WINDOW_DEFAULT;
1172 packetmax = CHAN_SES_PACKET_DEFAULT;
1173 if (tty_flag) {
1174 window >>= 1;
1175 packetmax >>= 1;
1176 }
1177 c = channel_new(
1178 "session", SSH_CHANNEL_OPENING, in, out, err,
1179 window, packetmax, CHAN_EXTENDED_WRITE,
1180 "client-session", /*nonblock*/0);
1181
1182 debug3("ssh_session2_open: channel_new: %d", c->self);
1183
1184 channel_send_open(c->self);
1185 if (!no_shell_flag)
1186 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1187
1188 return c->self;
1189}
1190
1191static int
1192ssh_session2(void)
1193{
1194 int id = -1;
1195
1196 /* XXX should be pre-session */
1197 ssh_init_forwarding();
1198 ssh_control_listener();
1199
1200 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1201 id = ssh_session2_open();
1202
1203 /* Execute a local command */
1204 if (options.local_command != NULL &&
1205 options.permit_local_command)
1206 ssh_local_cmd(options.local_command);
1207
1208 /* If requested, let ssh continue in the background. */
1209 if (fork_after_authentication_flag)
1210 if (daemon(1, 1) < 0)
1211 fatal("daemon() failed: %.200s", strerror(errno));
1212
1213 return client_loop(tty_flag, tty_flag ?
1214 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1215}
1216
1217static void
1218load_public_identity_files(void)
1219{
1220 char *filename, *cp, thishost[NI_MAXHOST];
1221 int i = 0;
1222 Key *public;
1223 struct passwd *pw;
1224#ifdef SMARTCARD
1225 Key **keys;
1226
1227 if (options.smartcard_device != NULL &&
1228 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1229 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1230 int count = 0;
1231 for (i = 0; keys[i] != NULL; i++) {
1232 count++;
1233 memmove(&options.identity_files[1], &options.identity_files[0],
1234 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1235 memmove(&options.identity_keys[1], &options.identity_keys[0],
1236 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1237 options.num_identity_files++;
1238 options.identity_keys[0] = keys[i];
1239 options.identity_files[0] = sc_get_key_label(keys[i]);
1240 }
1241 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1242 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1243 i = count;
1244 xfree(keys);
1245 }
1246#endif /* SMARTCARD */
1247 if ((pw = getpwuid(original_real_uid)) == NULL)
1248 fatal("load_public_identity_files: getpwuid failed");
1249 if (gethostname(thishost, sizeof(thishost)) == -1)
1250 fatal("load_public_identity_files: gethostname: %s",
1251 strerror(errno));
1252 for (; i < options.num_identity_files; i++) {
1253 cp = tilde_expand_filename(options.identity_files[i],
1254 original_real_uid);
1255 filename = percent_expand(cp, "d", pw->pw_dir,
1256 "u", pw->pw_name, "l", thishost, "h", host,
1257 "r", options.user, (char *)NULL);
1258 xfree(cp);
1259 public = key_load_public(filename, NULL);
1260 debug("identity file %s type %d", filename,
1261 public ? public->type : -1);
1262 xfree(options.identity_files[i]);
1263 options.identity_files[i] = filename;
1264 options.identity_keys[i] = public;
1265 }
1266}
1267
1268static void
1269control_client_sighandler(int signo)
1270{
1271 control_client_terminate = signo;
1272}
1273
1274static void
1275control_client_sigrelay(int signo)
1276{
1277 if (control_server_pid > 1)
1278 kill(control_server_pid, signo);
1279}
1280
1281static int
1282env_permitted(char *env)
1283{
1284 int i, ret;
1285 char name[1024], *cp;
1286
1287 if ((cp = strchr(env, '=')) == NULL || cp == env)
1288 return (0);
1289 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1290 if (ret <= 0 || (size_t)ret >= sizeof(name))
1291 fatal("env_permitted: name '%.100s...' too long", env);
1292
1293 for (i = 0; i < options.num_send_env; i++)
1294 if (match_pattern(name, options.send_env[i]))
1295 return (1);
1296
1297 return (0);
1298}
1299
1300static void
1301control_client(const char *path)
1302{
1303 struct sockaddr_un addr;
1304 int i, r, fd, sock, exitval, num_env, addr_len;
1305 Buffer m;
1306 char *term;
1307 extern char **environ;
1308 u_int flags;
1309
1310 if (mux_command == 0)
1311 mux_command = SSHMUX_COMMAND_OPEN;
1312
1313 switch (options.control_master) {
1314 case SSHCTL_MASTER_AUTO:
1315 case SSHCTL_MASTER_AUTO_ASK:
1316 debug("auto-mux: Trying existing master");
1317 /* FALLTHROUGH */
1318 case SSHCTL_MASTER_NO:
1319 break;
1320 default:
1321 return;
1322 }
1323
1324 memset(&addr, '\0', sizeof(addr));
1325 addr.sun_family = AF_UNIX;
1326 addr_len = offsetof(struct sockaddr_un, sun_path) +
1327 strlen(path) + 1;
1328
1329 if (strlcpy(addr.sun_path, path,
1330 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1331 fatal("ControlPath too long");
1332
1333 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1334 fatal("%s socket(): %s", __func__, strerror(errno));
1335
1336 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1337 if (mux_command != SSHMUX_COMMAND_OPEN) {
1338 fatal("Control socket connect(%.100s): %s", path,
1339 strerror(errno));
1340 }
1341 if (errno == ENOENT)
1342 debug("Control socket \"%.100s\" does not exist", path);
1343 else {
1344 error("Control socket connect(%.100s): %s", path,
1345 strerror(errno));
1346 }
1347 close(sock);
1348 return;
1349 }
1350
1351 if (stdin_null_flag) {
1352 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1353 fatal("open(/dev/null): %s", strerror(errno));
1354 if (dup2(fd, STDIN_FILENO) == -1)
1355 fatal("dup2: %s", strerror(errno));
1356 if (fd > STDERR_FILENO)
1357 close(fd);
1358 }
1359
1360 term = getenv("TERM");
1361
1362 flags = 0;
1363 if (tty_flag)
1364 flags |= SSHMUX_FLAG_TTY;
1365 if (subsystem_flag)
1366 flags |= SSHMUX_FLAG_SUBSYS;
1367 if (options.forward_x11)
1368 flags |= SSHMUX_FLAG_X11_FWD;
1369 if (options.forward_agent)
1370 flags |= SSHMUX_FLAG_AGENT_FWD;
1371
1372 buffer_init(&m);
1373
1374 /* Send our command to server */
1375 buffer_put_int(&m, mux_command);
1376 buffer_put_int(&m, flags);
1377 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1378 fatal("%s: msg_send", __func__);
1379 buffer_clear(&m);
1380
1381 /* Get authorisation status and PID of controlee */
1382 if (ssh_msg_recv(sock, &m) == -1)
1383 fatal("%s: msg_recv", __func__);
1384 if (buffer_get_char(&m) != SSHMUX_VER)
1385 fatal("%s: wrong version", __func__);
1386 if (buffer_get_int(&m) != 1)
1387 fatal("Connection to master denied");
1388 control_server_pid = buffer_get_int(&m);
1389
1390 buffer_clear(&m);
1391
1392 switch (mux_command) {
1393 case SSHMUX_COMMAND_ALIVE_CHECK:
1394 fprintf(stderr, "Master running (pid=%d)\r\n",
1395 control_server_pid);
1396 exit(0);
1397 case SSHMUX_COMMAND_TERMINATE:
1398 fprintf(stderr, "Exit request sent.\r\n");
1399 exit(0);
1400 case SSHMUX_COMMAND_OPEN:
1401 /* continue below */
1402 break;
1403 default:
1404 fatal("silly mux_command %d", mux_command);
1405 }
1406
1407 /* SSHMUX_COMMAND_OPEN */
1408 buffer_put_cstring(&m, term ? term : "");
1409 buffer_append(&command, "\0", 1);
1410 buffer_put_cstring(&m, buffer_ptr(&command));
1411
1412 if (options.num_send_env == 0 || environ == NULL) {
1413 buffer_put_int(&m, 0);
1414 } else {
1415 /* Pass environment */
1416 num_env = 0;
1417 for (i = 0; environ[i] != NULL; i++)
1418 if (env_permitted(environ[i]))
1419 num_env++; /* Count */
1420
1421 buffer_put_int(&m, num_env);
1422
1423 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1424 if (env_permitted(environ[i])) {
1425 num_env--;
1426 buffer_put_cstring(&m, environ[i]);
1427 }
1428 }
1429
1430 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1431 fatal("%s: msg_send", __func__);
1432
1433 mm_send_fd(sock, STDIN_FILENO);
1434 mm_send_fd(sock, STDOUT_FILENO);
1435 mm_send_fd(sock, STDERR_FILENO);
1436
1437 /* Wait for reply, so master has a chance to gather ttymodes */
1438 buffer_clear(&m);
1439 if (ssh_msg_recv(sock, &m) == -1)
1440 fatal("%s: msg_recv", __func__);
1441 if (buffer_get_char(&m) != SSHMUX_VER)
1442 fatal("%s: wrong version", __func__);
1443 buffer_free(&m);
1444
1445 signal(SIGHUP, control_client_sighandler);
1446 signal(SIGINT, control_client_sighandler);
1447 signal(SIGTERM, control_client_sighandler);
1448 signal(SIGWINCH, control_client_sigrelay);
1449
1450 if (tty_flag)
1451 enter_raw_mode();
1452
1453 /* Stick around until the controlee closes the client_fd */
1454 exitval = 0;
1455 for (;!control_client_terminate;) {
1456 r = read(sock, &exitval, sizeof(exitval));
1457 if (r == 0) {
1458 debug2("Received EOF from master");
1459 break;
1460 }
1461 if (r > 0)
1462 debug2("Received exit status from master %d", exitval);
1463 if (r == -1 && errno != EINTR)
1464 fatal("%s: read %s", __func__, strerror(errno));
1465 }
1466
1467 if (control_client_terminate)
1468 debug2("Exiting on signal %d", control_client_terminate);
1469
1470 close(sock);
1471
1472 leave_raw_mode();
1473
1474 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1475 fprintf(stderr, "Connection to master closed.\r\n");
1476
1477 exit(exitval);
1478}
This page took 0.05087 seconds and 5 git commands to generate.