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