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