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