]> andersk Git - openssh.git/blame - ssh.c
20070509
[openssh.git] / ssh.c
CommitLineData
4f6e2ba9 1/* $OpenBSD: ssh.c,v 1.295 2007/01/03 03:01:40 stevesk 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,
aeefce7a 188"usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-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;
8ce64345 213 int dummy;
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,
d20f3c9e 275 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L: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;
5260325f 329 case 'i':
330 if (stat(optarg, &st) < 0) {
f5a1a01a 331 fprintf(stderr, "Warning: Identity file %s "
ec304d66 332 "not accessible: %s.\n", optarg,
333 strerror(errno));
5260325f 334 break;
335 }
f5a1a01a 336 if (options.num_identity_files >=
337 SSH_MAX_IDENTITY_FILES)
338 fatal("Too many identity files specified "
339 "(max %d)", SSH_MAX_IDENTITY_FILES);
340 options.identity_files[options.num_identity_files++] =
341 xstrdup(optarg);
5260325f 342 break;
383546c4 343 case 'I':
344#ifdef SMARTCARD
9ff6f66f 345 options.smartcard_device = xstrdup(optarg);
dd2495cb 346#else
383546c4 347 fprintf(stderr, "no support for smartcards.\n");
dd2495cb 348#endif
383546c4 349 break;
5260325f 350 case 't':
8abcdba4 351 if (tty_flag)
352 force_tty_flag = 1;
5260325f 353 tty_flag = 1;
354 break;
5260325f 355 case 'v':
e053cd2c 356 if (debug_flag == 0) {
bcbf86ec 357 debug_flag = 1;
358 options.log_level = SYSLOG_LEVEL_DEBUG1;
e053cd2c 359 } else {
360 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
361 options.log_level++;
bcbf86ec 362 break;
e053cd2c 363 }
59d4718a 364 /* FALLTHROUGH */
5260325f 365 case 'V':
85ac7a84 366 fprintf(stderr, "%s, %s\n",
4526e8c2 367 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
5260325f 368 if (opt == 'V')
369 exit(0);
5260325f 370 break;
d20f3c9e 371 case 'w':
a4f24bf8 372 if (options.tun_open == -1)
373 options.tun_open = SSH_TUNMODE_DEFAULT;
d20f3c9e 374 options.tun_local = a2tun(optarg, &options.tun_remote);
a4f24bf8 375 if (options.tun_local == SSH_TUNID_ERR) {
d20f3c9e 376 fprintf(stderr, "Bad tun device '%s'\n", optarg);
3aa43b24 377 exit(255);
d20f3c9e 378 }
379 break;
5260325f 380 case 'q':
381 options.log_level = SYSLOG_LEVEL_QUIET;
382 break;
5260325f 383 case 'e':
384 if (optarg[0] == '^' && optarg[2] == 0 &&
f5a1a01a 385 (u_char) optarg[1] >= 64 &&
386 (u_char) optarg[1] < 128)
1e3b8b07 387 options.escape_char = (u_char) optarg[1] & 31;
5260325f 388 else if (strlen(optarg) == 1)
1e3b8b07 389 options.escape_char = (u_char) optarg[0];
5260325f 390 else if (strcmp(optarg, "none") == 0)
4bf9c10e 391 options.escape_char = SSH_ESCAPECHAR_NONE;
5260325f 392 else {
f5a1a01a 393 fprintf(stderr, "Bad escape character '%s'.\n",
394 optarg);
3aa43b24 395 exit(255);
5260325f 396 }
397 break;
5260325f 398 case 'c':
a306f2dd 399 if (ciphers_valid(optarg)) {
400 /* SSH2 only */
401 options.ciphers = xstrdup(optarg);
d77347cc 402 options.cipher = SSH_CIPHER_INVALID;
a306f2dd 403 } else {
404 /* SSH1 only */
c523303b 405 options.cipher = cipher_number(optarg);
406 if (options.cipher == -1) {
f5a1a01a 407 fprintf(stderr,
408 "Unknown cipher type '%s'\n",
409 optarg);
3aa43b24 410 exit(255);
a306f2dd 411 }
f5a1a01a 412 if (options.cipher == SSH_CIPHER_3DES)
c523303b 413 options.ciphers = "3des-cbc";
f5a1a01a 414 else if (options.cipher == SSH_CIPHER_BLOWFISH)
c523303b 415 options.ciphers = "blowfish-cbc";
f5a1a01a 416 else
c523303b 417 options.ciphers = (char *)-1;
5260325f 418 }
419 break;
b2552997 420 case 'm':
421 if (mac_valid(optarg))
422 options.macs = xstrdup(optarg);
423 else {
f5a1a01a 424 fprintf(stderr, "Unknown mac type '%s'\n",
425 optarg);
3aa43b24 426 exit(255);
b2552997 427 }
428 break;
5e96b616 429 case 'M':
9dfd96d6 430 if (options.control_master == SSHCTL_MASTER_YES)
431 options.control_master = SSHCTL_MASTER_ASK;
432 else
433 options.control_master = SSHCTL_MASTER_YES;
5e96b616 434 break;
5260325f 435 case 'p':
2d2a2c65 436 options.port = a2port(optarg);
437 if (options.port == 0) {
6031af8d 438 fprintf(stderr, "Bad port '%s'\n", optarg);
3aa43b24 439 exit(255);
6031af8d 440 }
5260325f 441 break;
5260325f 442 case 'l':
443 options.user = optarg;
444 break;
d2e3df16 445
446 case 'L':
3867aa0a 447 if (parse_forward(&fwd, optarg))
448 add_local_forward(&options, &fwd);
449 else {
f5a1a01a 450 fprintf(stderr,
3867aa0a 451 "Bad local forwarding specification '%s'\n",
f5a1a01a 452 optarg);
3aa43b24 453 exit(255);
5260325f 454 }
3867aa0a 455 break;
456
457 case 'R':
458 if (parse_forward(&fwd, optarg)) {
459 add_remote_forward(&options, &fwd);
460 } else {
f5a1a01a 461 fprintf(stderr,
3867aa0a 462 "Bad remote forwarding specification "
463 "'%s'\n", optarg);
3aa43b24 464 exit(255);
5260325f 465 }
5260325f 466 break;
0490e609 467
468 case 'D':
3867aa0a 469 cp = p = xstrdup(optarg);
470 memset(&fwd, '\0', sizeof(fwd));
471 fwd.connect_host = "socks";
472 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
473 fprintf(stderr, "Bad dynamic forwarding "
474 "specification '%.100s'\n", optarg);
3aa43b24 475 exit(255);
3867aa0a 476 }
477 if (cp != NULL) {
478 fwd.listen_port = a2port(cp);
479 fwd.listen_host = cleanhostname(fwd.listen_host);
480 } else {
481 fwd.listen_port = a2port(fwd.listen_host);
7c840747 482 fwd.listen_host = NULL;
3867aa0a 483 }
484
485 if (fwd.listen_port == 0) {
f5a1a01a 486 fprintf(stderr, "Bad dynamic port '%s'\n",
487 optarg);
3aa43b24 488 exit(255);
6031af8d 489 }
3867aa0a 490 add_local_forward(&options, &fwd);
491 xfree(p);
0490e609 492 break;
493
5260325f 494 case 'C':
495 options.compression = 1;
496 break;
8ce64345 497 case 'N':
498 no_shell_flag = 1;
499 no_tty_flag = 1;
500 break;
8ce64345 501 case 'T':
502 no_tty_flag = 1;
503 break;
5260325f 504 case 'o':
505 dummy = 1;
1aafd17a 506 line = xstrdup(optarg);
f5a1a01a 507 if (process_config_line(&options, host ? host : "",
1aafd17a 508 line, "command-line", 0, &dummy) != 0)
3aa43b24 509 exit(255);
1aafd17a 510 xfree(line);
5260325f 511 break;
ae810de7 512 case 's':
513 subsystem_flag = 1;
514 break;
5e96b616 515 case 'S':
516 if (options.control_path != NULL)
517 free(options.control_path);
518 options.control_path = xstrdup(optarg);
5e96b616 519 break;
3435f5a6 520 case 'b':
521 options.bind_address = optarg;
522 break;
e591b98a 523 case 'F':
524 config = optarg;
525 break;
5260325f 526 default:
527 usage();
528 }
529 }
530
f5a1a01a 531 ac -= optind;
532 av += optind;
533
534 if (ac > 0 && !host && **av != '-') {
15748b4d 535 if (strrchr(*av, '@')) {
f5a1a01a 536 p = xstrdup(*av);
15748b4d 537 cp = strrchr(p, '@');
f5a1a01a 538 if (cp == NULL || cp == p)
539 usage();
540 options.user = p;
541 *cp = '\0';
542 host = ++cp;
543 } else
544 host = *av;
978ebf99 545 if (ac > 1) {
546 optind = optreset = 1;
f5a1a01a 547 goto again;
548 }
978ebf99 549 ac--, av++;
f5a1a01a 550 }
551
5260325f 552 /* Check that we got a host name. */
553 if (!host)
8efc0c15 554 usage();
5260325f 555
22d89d24 556 SSLeay_add_all_algorithms();
fa08c86b 557 ERR_load_crypto_strings();
22d89d24 558
5260325f 559 /* Initialize the command to execute on remote host. */
560 buffer_init(&command);
561
aa3378df 562 /*
563 * Save the command to execute on the remote host in a buffer. There
564 * is no limit on the length of the command, except by the maximum
565 * packet size. Also sets the tty flag if there is no command.
566 */
f5a1a01a 567 if (!ac) {
5260325f 568 /* No command specified - execute shell on a tty. */
569 tty_flag = 1;
ae810de7 570 if (subsystem_flag) {
f5a1a01a 571 fprintf(stderr,
572 "You must specify a subsystem to invoke.\n");
ae810de7 573 usage();
574 }
5260325f 575 } else {
f5a1a01a 576 /* A command has been specified. Store it into the buffer. */
577 for (i = 0; i < ac; i++) {
578 if (i)
5260325f 579 buffer_append(&command, " ", 1);
580 buffer_append(&command, av[i], strlen(av[i]));
581 }
8efc0c15 582 }
5260325f 583
584 /* Cannot fork to background if no command. */
14a9a859 585 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
5260325f 586 fatal("Cannot fork into background without a command to execute.");
587
588 /* Allocate a tty by default if no command specified. */
589 if (buffer_len(&command) == 0)
590 tty_flag = 1;
591
343288b8 592 /* Force no tty */
0b6fbf03 593 if (no_tty_flag)
594 tty_flag = 0;
5260325f 595 /* Do not allocate a tty if stdin is not a tty. */
7697ac2b 596 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
5260325f 597 if (tty_flag)
bbe88b6d 598 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
5260325f 599 tty_flag = 0;
600 }
8ce64345 601
20244695 602 /*
603 * Initialize "log" output. Since we are the client all output
604 * actually goes to stderr.
605 */
cc44f691 606 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
607 SYSLOG_FACILITY_USER, 1);
5260325f 608
e591b98a 609 /*
610 * Read per-user configuration file. Ignore the system wide config
611 * file if the user specifies a config file on the command line.
612 */
613 if (config != NULL) {
f7f14143 614 if (!read_config_file(config, host, &options, 0))
93111dfa 615 fatal("Can't open user config file %.100s: "
616 "%.100s", config, strerror(errno));
4f6e2ba9 617 } else {
e591b98a 618 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
619 _PATH_SSH_USER_CONFFILE);
9f6cab4b 620 (void)read_config_file(buf, host, &options, 1);
e591b98a 621
f67792f2 622 /* Read systemwide configuration file after use config. */
f2107e97 623 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
9f6cab4b 624 &options, 0);
e591b98a 625 }
5260325f 626
627 /* Fill configuration defaults. */
628 fill_default_options(&options);
629
1572b90f 630 channel_set_af(options.address_family);
631
5260325f 632 /* reinit */
20244695 633 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
5260325f 634
e339aa53 635 seed_rng();
636
5260325f 637 if (options.user == NULL)
638 options.user = xstrdup(pw->pw_name);
639
640 if (options.hostname != NULL)
641 host = options.hostname;
642
03c82656 643 /* force lowercase for hostkey matching */
644 if (options.host_key_alias != NULL) {
645 for (p = options.host_key_alias; *p; p++)
646 if (isupper(*p))
9555d258 647 *p = (char)tolower(*p);
03c82656 648 }
649
de574442 650 /* Get default port if port has not been set. */
651 if (options.port == 0) {
652 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
653 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
654 }
655
f78bde70 656 if (options.proxy_command != NULL &&
657 strcmp(options.proxy_command, "none") == 0)
658 options.proxy_command = NULL;
699255b5 659 if (options.control_path != NULL &&
660 strcmp(options.control_path, "none") == 0)
661 options.control_path = NULL;
f78bde70 662
5e96b616 663 if (options.control_path != NULL) {
8cffe22a 664 char thishost[NI_MAXHOST];
f7b8224d 665
8cffe22a 666 if (gethostname(thishost, sizeof(thishost)) == -1)
f7b8224d 667 fatal("gethostname: %s", strerror(errno));
a980cbd7 668 snprintf(buf, sizeof(buf), "%d", options.port);
669 cp = tilde_expand_filename(options.control_path,
670 original_real_uid);
671 options.control_path = percent_expand(cp, "p", buf, "h", host,
8cffe22a 672 "r", options.user, "l", thishost, (char *)NULL);
a980cbd7 673 xfree(cp);
5e96b616 674 }
19186c3d 675 if (mux_command != 0 && options.control_path == NULL)
676 fatal("No ControlPath specified for \"-O\" command");
9dfd96d6 677 if (options.control_path != NULL)
cc8ca1e6 678 control_client(options.control_path);
5e96b616 679
6ffc9c88 680 /* Open a connection to the remote host. */
1572b90f 681 if (ssh_connect(host, &hostaddr, options.port,
682 options.address_family, options.connection_attempts,
d514c907 683#ifdef HAVE_CYGWIN
684 options.use_privileged_port,
685#else
3fb156df 686 original_effective_uid == 0 && options.use_privileged_port,
d514c907 687#endif
de60473e 688 options.proxy_command) != 0)
3aa43b24 689 exit(255);
5260325f 690
aa3378df 691 /*
692 * If we successfully made the connection, load the host private key
693 * in case we will need it later for combined rsa-rhosts
694 * authentication. This must be done before releasing extra
695 * privileges, because the file is only readable by root.
78660ed4 696 * If we cannot access the private keys, load the public keys
697 * instead and try to execute the ssh-keysign helper instead.
aa3378df 698 */
8002af61 699 sensitive_data.nkeys = 0;
700 sensitive_data.keys = NULL;
39c00dc2 701 sensitive_data.external_keysign = 0;
b34bec32 702 if (options.rhosts_rsa_authentication ||
703 options.hostbased_authentication) {
8002af61 704 sensitive_data.nkeys = 3;
19e79961 705 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
343288b8 706 sizeof(Key));
3fb156df 707
708 PRIV_START;
8002af61 709 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
fc231518 710 _PATH_HOST_KEY_FILE, "", NULL, NULL);
8002af61 711 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
fc231518 712 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
8002af61 713 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
fc231518 714 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
3fb156df 715 PRIV_END;
39c00dc2 716
60cd0a97 717 if (options.hostbased_authentication == 1 &&
718 sensitive_data.keys[0] == NULL &&
39c00dc2 719 sensitive_data.keys[1] == NULL &&
720 sensitive_data.keys[2] == NULL) {
721 sensitive_data.keys[1] = key_load_public(
722 _PATH_HOST_DSA_KEY_FILE, NULL);
723 sensitive_data.keys[2] = key_load_public(
724 _PATH_HOST_RSA_KEY_FILE, NULL);
725 sensitive_data.external_keysign = 1;
726 }
5260325f 727 }
aa3378df 728 /*
729 * Get rid of any extra privileges that we may have. We will no
730 * longer need them. Also, extra privileges could make it very hard
731 * to read identity files and other non-world-readable files from the
732 * user's home directory if it happens to be on a NFS volume where
733 * root is mapped to nobody.
734 */
6213295d 735 if (original_effective_uid == 0) {
736 PRIV_START;
737 permanently_set_uid(pw);
738 }
5260325f 739
aa3378df 740 /*
741 * Now that we are back to our own permissions, create ~/.ssh
7b9b0103 742 * directory if it doesn't already exist.
aa3378df 743 */
c3abff07 744 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
5260325f 745 if (stat(buf, &st) < 0)
704b1659 746 if (mkdir(buf, 0700) < 0)
5260325f 747 error("Could not create directory '%.200s'.", buf);
748
fee56204 749 /* load options.identity_files */
750 load_public_identity_files();
751
752 /* Expand ~ in known host file names. */
753 /* XXX mem-leaks: */
fa08c86b 754 options.system_hostfile =
755 tilde_expand_filename(options.system_hostfile, original_real_uid);
756 options.user_hostfile =
757 tilde_expand_filename(options.user_hostfile, original_real_uid);
758 options.system_hostfile2 =
759 tilde_expand_filename(options.system_hostfile2, original_real_uid);
760 options.user_hostfile2 =
761 tilde_expand_filename(options.user_hostfile2, original_real_uid);
5260325f 762
67b75437 763 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
764
5260325f 765 /* Log into the remote system. This never returns if the login fails. */
39c00dc2 766 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
8002af61 767
768 /* We no longer need the private host keys. Clear them now. */
769 if (sensitive_data.nkeys != 0) {
770 for (i = 0; i < sensitive_data.nkeys; i++) {
771 if (sensitive_data.keys[i] != NULL) {
772 /* Destroys contents safely */
773 debug3("clear hostkey %d", i);
774 key_free(sensitive_data.keys[i]);
775 sensitive_data.keys[i] = NULL;
776 }
777 }
778 xfree(sensitive_data.keys);
779 }
05b7537a 780 for (i = 0; i < options.num_identity_files; i++) {
781 if (options.identity_files[i]) {
782 xfree(options.identity_files[i]);
783 options.identity_files[i] = NULL;
784 }
785 if (options.identity_keys[i]) {
786 key_free(options.identity_keys[i]);
787 options.identity_keys[i] = NULL;
788 }
789 }
5260325f 790
8ce64345 791 exit_status = compat20 ? ssh_session2() : ssh_session();
792 packet_close();
6939bbd4 793
5e96b616 794 if (options.control_path != NULL && control_fd != -1)
795 unlink(options.control_path);
796
6939bbd4 797 /*
aff51935 798 * Send SIGHUP to proxy command if used. We don't wait() in
6939bbd4 799 * case it hangs and instead rely on init to reap the child
800 */
801 if (proxy_command_pid > 1)
802 kill(proxy_command_pid, SIGHUP);
803
8ce64345 804 return exit_status;
805}
806
396c147e 807static void
fa08c86b 808ssh_init_forwarding(void)
809{
02a024dd 810 int success = 0;
fa08c86b 811 int i;
02a024dd 812
fa08c86b 813 /* Initiate local TCP/IP port forwardings. */
814 for (i = 0; i < options.num_local_forwards; i++) {
3867aa0a 815 debug("Local connections to %.200s:%d forwarded to remote "
816 "address %.200s:%d",
f8cc7664 817 (options.local_forwards[i].listen_host == NULL) ?
818 (options.gateway_ports ? "*" : "LOCALHOST") :
3867aa0a 819 options.local_forwards[i].listen_host,
820 options.local_forwards[i].listen_port,
821 options.local_forwards[i].connect_host,
822 options.local_forwards[i].connect_port);
5641aefa 823 success += channel_setup_local_fwd_listener(
3867aa0a 824 options.local_forwards[i].listen_host,
825 options.local_forwards[i].listen_port,
826 options.local_forwards[i].connect_host,
827 options.local_forwards[i].connect_port,
fa08c86b 828 options.gateway_ports);
829 }
42ea6f5e 830 if (i > 0 && success != i && options.exit_on_forward_failure)
831 fatal("Could not request local forwarding.");
02a024dd 832 if (i > 0 && success == 0)
833 error("Could not request local forwarding.");
fa08c86b 834
835 /* Initiate remote TCP/IP port forwardings. */
836 for (i = 0; i < options.num_remote_forwards; i++) {
3867aa0a 837 debug("Remote connections from %.200s:%d forwarded to "
838 "local address %.200s:%d",
56964485 839 (options.remote_forwards[i].listen_host == NULL) ?
aa9bc1de 840 "LOCALHOST" : options.remote_forwards[i].listen_host,
3867aa0a 841 options.remote_forwards[i].listen_port,
842 options.remote_forwards[i].connect_host,
843 options.remote_forwards[i].connect_port);
42ea6f5e 844 if (channel_request_remote_forwarding(
3867aa0a 845 options.remote_forwards[i].listen_host,
846 options.remote_forwards[i].listen_port,
847 options.remote_forwards[i].connect_host,
42ea6f5e 848 options.remote_forwards[i].connect_port) < 0) {
849 if (options.exit_on_forward_failure)
850 fatal("Could not request remote forwarding.");
851 else
852 logit("Warning: Could not request remote "
853 "forwarding.");
854 }
fa08c86b 855 }
856}
857
396c147e 858static void
fa08c86b 859check_agent_present(void)
860{
861 if (options.forward_agent) {
7b9b0103 862 /* Clear agent forwarding if we don't have an agent. */
8b10e20e 863 if (!ssh_agent_present())
fa08c86b 864 options.forward_agent = 0;
fa08c86b 865 }
866}
867
396c147e 868static int
8ce64345 869ssh_session(void)
870{
871 int type;
8ce64345 872 int interactive = 0;
873 int have_tty = 0;
874 struct winsize ws;
8ce64345 875 char *cp;
9bf083eb 876 const char *display;
8ce64345 877
5260325f 878 /* Enable compression if requested. */
879 if (options.compression) {
880 debug("Requesting compression at level %d.", options.compression_level);
881
882 if (options.compression_level < 1 || options.compression_level > 9)
883 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
884
885 /* Send the request. */
886 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
887 packet_put_int(options.compression_level);
888 packet_send();
889 packet_write_wait();
54a5250f 890 type = packet_read();
5260325f 891 if (type == SSH_SMSG_SUCCESS)
892 packet_start_compression(options.compression_level);
893 else if (type == SSH_SMSG_FAILURE)
bbe88b6d 894 logit("Warning: Remote host refused compression.");
5260325f 895 else
896 packet_disconnect("Protocol error waiting for compression response.");
897 }
898 /* Allocate a pseudo tty if appropriate. */
899 if (tty_flag) {
900 debug("Requesting pty.");
901
902 /* Start the packet. */
903 packet_start(SSH_CMSG_REQUEST_PTY);
904
905 /* Store TERM in the packet. There is no limit on the
906 length of the string. */
907 cp = getenv("TERM");
908 if (!cp)
909 cp = "";
449c5ba5 910 packet_put_cstring(cp);
5260325f 911
912 /* Store window size in the packet. */
913 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
914 memset(&ws, 0, sizeof(ws));
148de80c 915 packet_put_int((u_int)ws.ws_row);
916 packet_put_int((u_int)ws.ws_col);
917 packet_put_int((u_int)ws.ws_xpixel);
918 packet_put_int((u_int)ws.ws_ypixel);
5260325f 919
920 /* Store tty modes in the packet. */
30dcc918 921 tty_make_modes(fileno(stdin), NULL);
5260325f 922
923 /* Send the packet, and wait for it to leave. */
924 packet_send();
925 packet_write_wait();
926
927 /* Read response from the server. */
54a5250f 928 type = packet_read();
4fe2af09 929 if (type == SSH_SMSG_SUCCESS) {
5260325f 930 interactive = 1;
8ce64345 931 have_tty = 1;
4fe2af09 932 } else if (type == SSH_SMSG_FAILURE)
bbe88b6d 933 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
5260325f 934 else
935 packet_disconnect("Protocol error waiting for pty request response.");
936 }
937 /* Request X11 forwarding if enabled and DISPLAY is set. */
9bf083eb 938 display = getenv("DISPLAY");
939 if (options.forward_x11 && display != NULL) {
b48eeb07 940 char *proto, *data;
0b242b12 941 /* Get reasonable local authentication information. */
9bf083eb 942 client_x11_get_proto(display, options.xauth_location,
943 options.forward_x11_trusted, &proto, &data);
0b242b12 944 /* Request forwarding with authentication spoofing. */
5260325f 945 debug("Requesting X11 forwarding with authentication spoofing.");
9bf083eb 946 x11_request_forwarding_with_spoofing(0, display, proto, data);
5260325f 947
948 /* Read response from the server. */
54a5250f 949 type = packet_read();
5260325f 950 if (type == SSH_SMSG_SUCCESS) {
5260325f 951 interactive = 1;
0b242b12 952 } else if (type == SSH_SMSG_FAILURE) {
bbe88b6d 953 logit("Warning: Remote host denied X11 forwarding.");
0b242b12 954 } else {
5260325f 955 packet_disconnect("Protocol error waiting for X11 forwarding");
0b242b12 956 }
5260325f 957 }
958 /* Tell the packet module whether this is an interactive session. */
b5c334cc 959 packet_set_interactive(interactive);
5260325f 960
961 /* Request authentication agent forwarding if appropriate. */
fa08c86b 962 check_agent_present();
963
5260325f 964 if (options.forward_agent) {
965 debug("Requesting authentication agent forwarding.");
966 auth_request_forwarding();
967
968 /* Read response from the server. */
54a5250f 969 type = packet_read();
95500969 970 packet_check_eom();
5260325f 971 if (type != SSH_SMSG_SUCCESS)
bbe88b6d 972 logit("Warning: Remote host denied authentication agent forwarding.");
5260325f 973 }
8efc0c15 974
fa08c86b 975 /* Initiate port forwardings. */
976 ssh_init_forwarding();
5260325f 977
aa3378df 978 /* If requested, let ssh continue in the background. */
6ae2364d 979 if (fork_after_authentication_flag)
aa3378df 980 if (daemon(1, 1) < 0)
981 fatal("daemon() failed: %.200s", strerror(errno));
982
983 /*
984 * If a command was specified on the command line, execute the
985 * command now. Otherwise request the server to start a shell.
986 */
5260325f 987 if (buffer_len(&command) > 0) {
988 int len = buffer_len(&command);
989 if (len > 900)
990 len = 900;
6c0fa2b1 991 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
5260325f 992 packet_start(SSH_CMSG_EXEC_CMD);
993 packet_put_string(buffer_ptr(&command), buffer_len(&command));
994 packet_send();
995 packet_write_wait();
996 } else {
997 debug("Requesting shell.");
998 packet_start(SSH_CMSG_EXEC_SHELL);
999 packet_send();
1000 packet_write_wait();
1001 }
1002
1003 /* Enter the interactive session. */
4bf9c10e 1004 return client_loop(have_tty, tty_flag ?
1005 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
8ce64345 1006}
5260325f 1007
396c147e 1008static void
5e96b616 1009ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1f3bf5aa 1010{
1011 int id, len;
1012
1013 id = packet_get_int();
1014 len = buffer_len(&command);
ce91d6f8 1015 if (len > 900)
1016 len = 900;
95500969 1017 packet_check_eom();
1f3bf5aa 1018 if (type == SSH2_MSG_CHANNEL_FAILURE)
1019 fatal("Request for subsystem '%.*s' failed on channel %d",
6c0fa2b1 1020 len, (u_char *)buffer_ptr(&command), id);
1f3bf5aa 1021}
1022
e0ae8728 1023void
5d8d32a3 1024client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
e0ae8728 1025{
1026 int i;
1027
1028 i = client_global_request_id++;
5d8d32a3 1029 if (i >= options.num_remote_forwards)
e0ae8728 1030 return;
e0ae8728 1031 debug("remote forward %s for: listen %d, connect %s:%d",
1032 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
3867aa0a 1033 options.remote_forwards[i].listen_port,
1034 options.remote_forwards[i].connect_host,
1035 options.remote_forwards[i].connect_port);
42ea6f5e 1036 if (type == SSH2_MSG_REQUEST_FAILURE) {
1037 if (options.exit_on_forward_failure)
1038 fatal("Error: remote port forwarding failed for "
1039 "listen port %d",
1040 options.remote_forwards[i].listen_port);
1041 else
1042 logit("Warning: remote port forwarding failed for "
1043 "listen port %d",
1044 options.remote_forwards[i].listen_port);
1045 }
e0ae8728 1046}
1047
396c147e 1048static void
5e96b616 1049ssh_control_listener(void)
8ce64345 1050{
5e96b616 1051 struct sockaddr_un addr;
1052 mode_t old_umask;
4b5df124 1053 int addr_len;
1054
9dfd96d6 1055 if (options.control_path == NULL ||
1056 options.control_master == SSHCTL_MASTER_NO)
5e96b616 1057 return;
b5c334cc 1058
9dfd96d6 1059 debug("setting up multiplex master socket");
1060
5e96b616 1061 memset(&addr, '\0', sizeof(addr));
1062 addr.sun_family = AF_UNIX;
4b5df124 1063 addr_len = offsetof(struct sockaddr_un, sun_path) +
5e96b616 1064 strlen(options.control_path) + 1;
8ce64345 1065
5e96b616 1066 if (strlcpy(addr.sun_path, options.control_path,
1067 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1068 fatal("ControlPath too long");
8ce64345 1069
5e96b616 1070 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
17318dd6 1071 fatal("%s socket(): %s", __func__, strerror(errno));
5e96b616 1072
1073 old_umask = umask(0177);
32596c7b 1074 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
5e96b616 1075 control_fd = -1;
05ada1a6 1076 if (errno == EINVAL || errno == EADDRINUSE)
5e96b616 1077 fatal("ControlSocket %s already exists",
1078 options.control_path);
1079 else
17318dd6 1080 fatal("%s bind(): %s", __func__, strerror(errno));
8ce64345 1081 }
5e96b616 1082 umask(old_umask);
1083
1084 if (listen(control_fd, 64) == -1)
17318dd6 1085 fatal("%s listen(): %s", __func__, strerror(errno));
5e96b616 1086
1087 set_nonblock(control_fd);
1088}
1089
1090/* request pty/x11/agent/tcpfwd/shell for channel */
1091static void
1092ssh_session2_setup(int id, void *arg)
1093{
1786be35 1094 extern char **environ;
9bf083eb 1095 const char *display;
5e96b616 1096 int interactive = tty_flag;
9bf083eb 1097
56964485 1098 display = getenv("DISPLAY");
9bf083eb 1099 if (options.forward_x11 && display != NULL) {
b48eeb07 1100 char *proto, *data;
0b242b12 1101 /* Get reasonable local authentication information. */
9bf083eb 1102 client_x11_get_proto(display, options.xauth_location,
1103 options.forward_x11_trusted, &proto, &data);
0b242b12 1104 /* Request forwarding with authentication spoofing. */
1105 debug("Requesting X11 forwarding with authentication spoofing.");
9bf083eb 1106 x11_request_forwarding_with_spoofing(id, display, proto, data);
b5c334cc 1107 interactive = 1;
0b242b12 1108 /* XXX wait for reply */
1109 }
1110
fa08c86b 1111 check_agent_present();
1112 if (options.forward_agent) {
1113 debug("Requesting authentication agent forwarding.");
1114 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1115 packet_send();
1116 }
1117
a4f24bf8 1118 if (options.tun_open != SSH_TUNMODE_NO) {
d20f3c9e 1119 Channel *c;
1120 int fd;
1121
1122 debug("Requesting tun.");
a4f24bf8 1123 if ((fd = tun_open(options.tun_local,
1124 options.tun_open)) >= 0) {
d20f3c9e 1125 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1126 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1127 0, "tun", 1);
1128 c->datagram = 1;
e914f53a 1129#if defined(SSH_TUN_FILTER)
1130 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1131 channel_register_filter(c->self, sys_tun_infilter,
1132 sys_tun_outfilter);
1133#endif
d20f3c9e 1134 packet_start(SSH2_MSG_CHANNEL_OPEN);
1135 packet_put_cstring("tun@openssh.com");
1136 packet_put_int(c->self);
1137 packet_put_int(c->local_window_max);
1138 packet_put_int(c->local_maxpacket);
a4f24bf8 1139 packet_put_int(options.tun_open);
d20f3c9e 1140 packet_put_int(options.tun_remote);
1141 packet_send();
1142 }
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();
5e96b616 1204 ssh_control_listener();
eb0dd41f 1205
bcdb96c2 1206 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1207 id = ssh_session2_open();
eb0dd41f 1208
d20f3c9e 1209 /* Execute a local command */
1210 if (options.local_command != NULL &&
1211 options.permit_local_command)
1212 ssh_local_cmd(options.local_command);
1213
eb0dd41f 1214 /* If requested, let ssh continue in the background. */
1215 if (fork_after_authentication_flag)
1216 if (daemon(1, 1) < 0)
1217 fatal("daemon() failed: %.200s", strerror(errno));
1218
4bf9c10e 1219 return client_loop(tty_flag, tty_flag ?
1220 options.escape_char : SSH_ESCAPECHAR_NONE, id);
8efc0c15 1221}
fa08c86b 1222
396c147e 1223static void
fee56204 1224load_public_identity_files(void)
1225{
8cffe22a 1226 char *filename, *cp, thishost[NI_MAXHOST];
2e23cde0 1227 int i = 0;
0659cace 1228 Key *public;
8cffe22a 1229 struct passwd *pw;
383546c4 1230#ifdef SMARTCARD
0659cace 1231 Key **keys;
1232
9ff6f66f 1233 if (options.smartcard_device != NULL &&
0659cace 1234 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
d4f40d92 1235 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
0659cace 1236 int count = 0;
1237 for (i = 0; keys[i] != NULL; i++) {
1238 count++;
0659cace 1239 memmove(&options.identity_files[1], &options.identity_files[0],
1240 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1241 memmove(&options.identity_keys[1], &options.identity_keys[0],
1242 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1243 options.num_identity_files++;
1244 options.identity_keys[0] = keys[i];
244e796f 1245 options.identity_files[0] = sc_get_key_label(keys[i]);
0659cace 1246 }
1c2deed1 1247 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1248 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
0659cace 1249 i = count;
1250 xfree(keys);
383546c4 1251 }
3e984472 1252#endif /* SMARTCARD */
8cffe22a 1253 if ((pw = getpwuid(original_real_uid)) == NULL)
1254 fatal("load_public_identity_files: getpwuid failed");
1255 if (gethostname(thishost, sizeof(thishost)) == -1)
1256 fatal("load_public_identity_files: gethostname: %s",
1257 strerror(errno));
2e23cde0 1258 for (; i < options.num_identity_files; i++) {
8cffe22a 1259 cp = tilde_expand_filename(options.identity_files[i],
2e23cde0 1260 original_real_uid);
8cffe22a 1261 filename = percent_expand(cp, "d", pw->pw_dir,
31652869 1262 "u", pw->pw_name, "l", thishost, "h", host,
8cffe22a 1263 "r", options.user, (char *)NULL);
1264 xfree(cp);
2e23cde0 1265 public = key_load_public(filename, NULL);
1266 debug("identity file %s type %d", filename,
1267 public ? public->type : -1);
1268 xfree(options.identity_files[i]);
1269 options.identity_files[i] = filename;
1270 options.identity_keys[i] = public;
1271 }
fee56204 1272}
5e96b616 1273
1274static void
1275control_client_sighandler(int signo)
1276{
1277 control_client_terminate = signo;
1278}
1279
1280static void
1281control_client_sigrelay(int signo)
1282{
1283 if (control_server_pid > 1)
1284 kill(control_server_pid, signo);
1285}
1286
67a08279 1287static int
1288env_permitted(char *env)
1289{
0ad62016 1290 int i, ret;
67a08279 1291 char name[1024], *cp;
1292
0ad62016 1293 if ((cp = strchr(env, '=')) == NULL || cp == env)
67a08279 1294 return (0);
00c8971b 1295 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
0ad62016 1296 if (ret <= 0 || (size_t)ret >= sizeof(name))
1297 fatal("env_permitted: name '%.100s...' too long", env);
67a08279 1298
1299 for (i = 0; i < options.num_send_env; i++)
1300 if (match_pattern(name, options.send_env[i]))
1301 return (1);
1302
1303 return (0);
1304}
1305
5e96b616 1306static void
1307control_client(const char *path)
1308{
1309 struct sockaddr_un addr;
a7e124fe 1310 int i, r, fd, sock, exitval, num_env, addr_len;
5e96b616 1311 Buffer m;
f8c6db83 1312 char *term;
1786be35 1313 extern char **environ;
f8c6db83 1314 u_int flags;
f2107e97 1315
9dfd96d6 1316 if (mux_command == 0)
1317 mux_command = SSHMUX_COMMAND_OPEN;
1318
1319 switch (options.control_master) {
1320 case SSHCTL_MASTER_AUTO:
1321 case SSHCTL_MASTER_AUTO_ASK:
1322 debug("auto-mux: Trying existing master");
1323 /* FALLTHROUGH */
1324 case SSHCTL_MASTER_NO:
1325 break;
1326 default:
1327 return;
1328 }
1329
5e96b616 1330 memset(&addr, '\0', sizeof(addr));
1331 addr.sun_family = AF_UNIX;
4b5df124 1332 addr_len = offsetof(struct sockaddr_un, sun_path) +
5e96b616 1333 strlen(path) + 1;
1334
1335 if (strlcpy(addr.sun_path, path,
1336 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1337 fatal("ControlPath too long");
1338
1339 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1340 fatal("%s socket(): %s", __func__, strerror(errno));
1341
32596c7b 1342 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
19186c3d 1343 if (mux_command != SSHMUX_COMMAND_OPEN) {
1344 fatal("Control socket connect(%.100s): %s", path,
1345 strerror(errno));
1346 }
f6740270 1347 if (errno == ENOENT)
7de98c39 1348 debug("Control socket \"%.100s\" does not exist", path);
f6740270 1349 else {
7de98c39 1350 error("Control socket connect(%.100s): %s", path,
f6740270 1351 strerror(errno));
1352 }
7de98c39 1353 close(sock);
1354 return;
1355 }
1356
1357 if (stdin_null_flag) {
1358 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1359 fatal("open(/dev/null): %s", strerror(errno));
1360 if (dup2(fd, STDIN_FILENO) == -1)
1361 fatal("dup2: %s", strerror(errno));
1362 if (fd > STDERR_FILENO)
1363 close(fd);
1364 }
56964485 1365
ef07103c 1366 term = getenv("TERM");
f8c6db83 1367
1368 flags = 0;
1369 if (tty_flag)
1370 flags |= SSHMUX_FLAG_TTY;
1371 if (subsystem_flag)
1372 flags |= SSHMUX_FLAG_SUBSYS;
ef07103c 1373 if (options.forward_x11)
1374 flags |= SSHMUX_FLAG_X11_FWD;
1375 if (options.forward_agent)
1376 flags |= SSHMUX_FLAG_AGENT_FWD;
5e96b616 1377
5e96b616 1378 buffer_init(&m);
1379
f8c6db83 1380 /* Send our command to server */
1381 buffer_put_int(&m, mux_command);
1382 buffer_put_int(&m, flags);
ef07103c 1383 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
f8c6db83 1384 fatal("%s: msg_send", __func__);
1385 buffer_clear(&m);
1386
1387 /* Get authorisation status and PID of controlee */
5e96b616 1388 if (ssh_msg_recv(sock, &m) == -1)
1389 fatal("%s: msg_recv", __func__);
ef07103c 1390 if (buffer_get_char(&m) != SSHMUX_VER)
5e96b616 1391 fatal("%s: wrong version", __func__);
0d34d6ce 1392 if (buffer_get_int(&m) != 1)
1393 fatal("Connection to master denied");
5e96b616 1394 control_server_pid = buffer_get_int(&m);
1395
5e96b616 1396 buffer_clear(&m);
5e96b616 1397
f8c6db83 1398 switch (mux_command) {
1399 case SSHMUX_COMMAND_ALIVE_CHECK:
f8cc7664 1400 fprintf(stderr, "Master running (pid=%d)\r\n",
f8c6db83 1401 control_server_pid);
1402 exit(0);
1403 case SSHMUX_COMMAND_TERMINATE:
1404 fprintf(stderr, "Exit request sent.\r\n");
1405 exit(0);
1406 case SSHMUX_COMMAND_OPEN:
1407 /* continue below */
1408 break;
1409 default:
1410 fatal("silly mux_command %d", mux_command);
1411 }
1412
1413 /* SSHMUX_COMMAND_OPEN */
ef07103c 1414 buffer_put_cstring(&m, term ? term : "");
5e96b616 1415 buffer_append(&command, "\0", 1);
1416 buffer_put_cstring(&m, buffer_ptr(&command));
1417
67a08279 1418 if (options.num_send_env == 0 || environ == NULL) {
1419 buffer_put_int(&m, 0);
f2107e97 1420 } else {
67a08279 1421 /* Pass environment */
1422 num_env = 0;
1423 for (i = 0; environ[i] != NULL; i++)
1424 if (env_permitted(environ[i]))
1425 num_env++; /* Count */
f2107e97 1426
67a08279 1427 buffer_put_int(&m, num_env);
1428
77c50919 1429 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1430 if (env_permitted(environ[i])) {
1431 num_env--;
67a08279 1432 buffer_put_cstring(&m, environ[i]);
77c50919 1433 }
67a08279 1434 }
1786be35 1435
ef07103c 1436 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
5e96b616 1437 fatal("%s: msg_send", __func__);
1438
1439 mm_send_fd(sock, STDIN_FILENO);
1440 mm_send_fd(sock, STDOUT_FILENO);
1441 mm_send_fd(sock, STDERR_FILENO);
1442
1443 /* Wait for reply, so master has a chance to gather ttymodes */
1444 buffer_clear(&m);
1445 if (ssh_msg_recv(sock, &m) == -1)
1446 fatal("%s: msg_recv", __func__);
ef07103c 1447 if (buffer_get_char(&m) != SSHMUX_VER)
f8c6db83 1448 fatal("%s: wrong version", __func__);
5e96b616 1449 buffer_free(&m);
1450
d3e5d1e9 1451 signal(SIGHUP, control_client_sighandler);
78d2b454 1452 signal(SIGINT, control_client_sighandler);
1453 signal(SIGTERM, control_client_sighandler);
1454 signal(SIGWINCH, control_client_sigrelay);
1455
5e96b616 1456 if (tty_flag)
1457 enter_raw_mode();
1458
1459 /* Stick around until the controlee closes the client_fd */
1460 exitval = 0;
1461 for (;!control_client_terminate;) {
1462 r = read(sock, &exitval, sizeof(exitval));
1463 if (r == 0) {
1464 debug2("Received EOF from master");
1465 break;
1466 }
1467 if (r > 0)
1468 debug2("Received exit status from master %d", exitval);
1469 if (r == -1 && errno != EINTR)
1470 fatal("%s: read %s", __func__, strerror(errno));
1471 }
1472
1473 if (control_client_terminate)
1474 debug2("Exiting on signal %d", control_client_terminate);
1475
1476 close(sock);
1477
1478 leave_raw_mode();
1479
1480 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1481 fprintf(stderr, "Connection to master closed.\r\n");
1482
1483 exit(exitval);
1484}
This page took 0.647699 seconds and 5 git commands to generate.