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