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