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