]> andersk Git - openssh.git/blame - ssh.c
- (stevesk) OpenBSD CVS updates:
[openssh.git] / ssh.c
CommitLineData
8efc0c15 1/*
5260325f 2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
5260325f 5 * Ssh client program. This program can be used to log into a remote machine.
6 * The software supports strong authentication, encryption, and forwarding
7 * of X11, TCP/IP, and authentication connections.
8 *
bcbf86ec 9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
14 *
15 * Copyright (c) 1999 Niels Provos. All rights reserved.
16 *
17 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
18 * in Canada (German citizen).
19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5260325f 39 */
8efc0c15 40
41#include "includes.h"
6ffc9c88 42RCSID("$OpenBSD: ssh.c,v 1.77 2000/12/12 23:11:48 markus Exp $");
8efc0c15 43
a306f2dd 44#include <openssl/evp.h>
45#include <openssl/dsa.h>
46#include <openssl/rsa.h>
fa08c86b 47#include <openssl/err.h>
a306f2dd 48
8efc0c15 49#include "xmalloc.h"
50#include "ssh.h"
51#include "packet.h"
52#include "buffer.h"
8efc0c15 53#include "readconf.h"
54#include "uidswap.h"
8ce64345 55
56#include "ssh2.h"
57#include "compat.h"
7368a6c8 58#include "channels.h"
a306f2dd 59#include "key.h"
4c8722d9 60#include "authfd.h"
a306f2dd 61#include "authfile.h"
8efc0c15 62
f601d847 63#ifdef HAVE___PROGNAME
64extern char *__progname;
260d427b 65#else
66char *__progname;
67#endif
f601d847 68
48e671d5 69/* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
70 Default value is AF_UNSPEC means both IPv4 and IPv6. */
59e76f33 71#ifdef IPV4_DEFAULT
72int IPv4or6 = AF_INET;
73#else
48e671d5 74int IPv4or6 = AF_UNSPEC;
59e76f33 75#endif
48e671d5 76
5260325f 77/* Flag indicating whether debug mode is on. This can be set on the command line. */
8efc0c15 78int debug_flag = 0;
79
a8be9f80 80/* Flag indicating whether a tty should be allocated */
8efc0c15 81int tty_flag = 0;
82
8ce64345 83/* don't exec a shell */
84int no_shell_flag = 0;
85int no_tty_flag = 0;
86
aa3378df 87/*
88 * Flag indicating that nothing should be read from stdin. This can be set
89 * on the command line.
90 */
8efc0c15 91int stdin_null_flag = 0;
92
aa3378df 93/*
94 * Flag indicating that ssh should fork after authentication. This is useful
95 * so that the pasphrase can be entered manually, and then ssh goes to the
96 * background.
97 */
8efc0c15 98int fork_after_authentication_flag = 0;
99
aa3378df 100/*
101 * General data structure for command line options and options configurable
102 * in configuration files. See readconf.h.
103 */
8efc0c15 104Options options;
105
aa3378df 106/*
107 * Name of the host we are connecting to. This is the name given on the
108 * command line, or the HostName specified for the user-supplied name in a
109 * configuration file.
110 */
8efc0c15 111char *host;
112
113/* socket address the host resolves to */
48e671d5 114struct sockaddr_storage hostaddr;
8efc0c15 115
aa3378df 116/*
117 * Flag to indicate that we have received a window change signal which has
118 * not yet been processed. This will cause a message indicating the new
119 * window size to be sent to the server a little later. This is volatile
120 * because this is updated in a signal handler.
121 */
8efc0c15 122volatile int received_window_change_signal = 0;
123
8efc0c15 124/* Flag indicating whether we have a valid host private key loaded. */
125int host_private_key_loaded = 0;
126
127/* Host private key. */
128RSA *host_private_key = NULL;
129
130/* Original real UID. */
131uid_t original_real_uid;
132
8ce64345 133/* command to be executed */
134Buffer command;
135
8efc0c15 136/* Prints a help message to the user. This function never returns. */
137
138void
139usage()
140{
1fe6a48f 141 fprintf(stderr, "Usage: %s [options] host [command]\n", __progname);
5260325f 142 fprintf(stderr, "Options:\n");
143 fprintf(stderr, " -l user Log in using this user name.\n");
144 fprintf(stderr, " -n Redirect input from /dev/null.\n");
71276795 145 fprintf(stderr, " -A Enable authentication agent forwarding.\n");
5260325f 146 fprintf(stderr, " -a Disable authentication agent forwarding.\n");
8efc0c15 147#ifdef AFS
5260325f 148 fprintf(stderr, " -k Disable Kerberos ticket and AFS token forwarding.\n");
149#endif /* AFS */
0e73cc53 150 fprintf(stderr, " -X Enable X11 connection forwarding.\n");
5260325f 151 fprintf(stderr, " -x Disable X11 connection forwarding.\n");
152 fprintf(stderr, " -i file Identity for RSA authentication (default: ~/.ssh/identity).\n");
153 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n");
8ce64345 154 fprintf(stderr, " -T Do not allocate a tty.\n");
5260325f 155 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
bcbf86ec 156 fprintf(stderr, " Multiple -v increases verbosity.\n");
5260325f 157 fprintf(stderr, " -V Display version number only.\n");
158 fprintf(stderr, " -P Don't allocate a privileged port.\n");
159 fprintf(stderr, " -q Quiet; don't display any warning messages.\n");
160 fprintf(stderr, " -f Fork into background after authentication.\n");
161 fprintf(stderr, " -e char Set escape character; ``none'' = disable (default: ~).\n");
162
163 fprintf(stderr, " -c cipher Select encryption algorithm: "
164 "``3des'', "
165 "``blowfish''\n");
166 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n");
167 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n");
168 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n");
1fe6a48f 169 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", __progname);
5260325f 170 fprintf(stderr, " forward them to the other side by connecting to host:port.\n");
171 fprintf(stderr, " -C Enable compression.\n");
8ce64345 172 fprintf(stderr, " -N Do not execute a shell or command.\n");
5260325f 173 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n");
48e671d5 174 fprintf(stderr, " -4 Use IPv4 only.\n");
175 fprintf(stderr, " -6 Use IPv6 only.\n");
6ae2364d 176 fprintf(stderr, " -2 Force protocol version 2.\n");
5260325f 177 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n");
178 exit(1);
8efc0c15 179}
180
5260325f 181/*
182 * Connects to the given host using rsh (or prints an error message and exits
183 * if rsh is not available). This function never returns.
184 */
8efc0c15 185void
5260325f 186rsh_connect(char *host, char *user, Buffer * command)
8efc0c15 187{
5260325f 188 char *args[10];
189 int i;
190
191 log("Using rsh. WARNING: Connection will not be encrypted.");
192 /* Build argument list for rsh. */
193 i = 0;
194 args[i++] = _PATH_RSH;
195 /* host may have to come after user on some systems */
196 args[i++] = host;
197 if (user) {
198 args[i++] = "-l";
199 args[i++] = user;
200 }
201 if (buffer_len(command) > 0) {
202 buffer_append(command, "\0", 1);
203 args[i++] = buffer_ptr(command);
204 }
205 args[i++] = NULL;
206 if (debug_flag) {
207 for (i = 0; args[i]; i++) {
208 if (i != 0)
209 fprintf(stderr, " ");
210 fprintf(stderr, "%s", args[i]);
211 }
212 fprintf(stderr, "\n");
8efc0c15 213 }
5260325f 214 execv(_PATH_RSH, args);
215 perror(_PATH_RSH);
216 exit(1);
8efc0c15 217}
218
fa08c86b 219int ssh_session(void);
220int ssh_session2(void);
221int guess_identity_file_type(const char *filename);
8ce64345 222
5260325f 223/*
224 * Main program for the ssh client.
225 */
8efc0c15 226int
227main(int ac, char **av)
228{
8ce64345 229 int i, opt, optind, exit_status, ok;
57112b5a 230 u_short fwd_port, fwd_host_port;
5260325f 231 char *optarg, *cp, buf[256];
5260325f 232 struct stat st;
233 struct passwd *pw, pwcopy;
8ce64345 234 int dummy;
5260325f 235 uid_t original_effective_uid;
5260325f 236
260d427b 237 __progname = get_progname(av[0]);
264dce47 238 init_rng();
239
aa3378df 240 /*
241 * Save the original real uid. It will be needed later (uid-swapping
242 * may clobber the real uid).
243 */
5260325f 244 original_real_uid = getuid();
245 original_effective_uid = geteuid();
246
7322ef0e 247#ifdef HAVE_SETRLIMIT
5260325f 248 /* If we are installed setuid root be careful to not drop core. */
249 if (original_real_uid != original_effective_uid) {
250 struct rlimit rlim;
251 rlim.rlim_cur = rlim.rlim_max = 0;
252 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
253 fatal("setrlimit failed: %.100s", strerror(errno));
8efc0c15 254 }
3c62e7eb 255#endif
aa3378df 256 /*
257 * Use uid-swapping to give up root privileges for the duration of
258 * option processing. We will re-instantiate the rights when we are
259 * ready to create the privileged port, and will permanently drop
260 * them when the port has been created (actually, when the connection
261 * has been made, as we may need to create the port several times).
262 */
5260325f 263 temporarily_use_uid(original_real_uid);
264
aa3378df 265 /*
266 * Set our umask to something reasonable, as some files are created
267 * with the default umask. This will make them world-readable but
268 * writable only by the owner, which is ok for all files for which we
269 * don't set the modes explicitly.
270 */
5260325f 271 umask(022);
272
5260325f 273 /* Initialize option structure to indicate that no values have been set. */
274 initialize_options(&options);
275
276 /* Parse command-line arguments. */
277 host = NULL;
278
279 /* If program name is not one of the standard names, use it as host name. */
1fe6a48f 280 cp = __progname;
3c62e7eb 281#ifdef HAVE_CYGWIN
282 if (strcasecmp(cp, "rsh") && strcasecmp(cp, "ssh") &&
283 strcasecmp(cp, "rlogin") && strcasecmp(cp, "slogin") &&
284 strcasecmp(cp, "remsh") &&
285 strcasecmp(cp, "rsh.exe") && strcasecmp(cp, "ssh.exe") &&
286 strcasecmp(cp, "rlogin.exe") && strcasecmp(cp, "slogin.exe") &&
287 strcasecmp(cp, "remsh.exe"))
288#else
2e73a022 289 if (strcmp(cp, "rsh") && strcmp(cp, "ssh") && strcmp(cp, "rlogin") &&
290 strcmp(cp, "slogin") && strcmp(cp, "remsh"))
3c62e7eb 291#endif
5260325f 292 host = cp;
293
294 for (optind = 1; optind < ac; optind++) {
295 if (av[optind][0] != '-') {
296 if (host)
297 break;
298 if ((cp = strchr(av[optind], '@'))) {
6ae2364d 299 if(cp == av[optind])
300 usage();
5260325f 301 options.user = av[optind];
302 *cp = '\0';
303 host = ++cp;
304 } else
305 host = av[optind];
306 continue;
307 }
308 opt = av[optind][1];
309 if (!opt)
310 usage();
311 if (strchr("eilcpLRo", opt)) { /* options with arguments */
312 optarg = av[optind] + 2;
313 if (strcmp(optarg, "") == 0) {
314 if (optind >= ac - 1)
315 usage();
316 optarg = av[++optind];
317 }
318 } else {
319 if (av[optind][2])
320 usage();
321 optarg = NULL;
322 }
323 switch (opt) {
6ae2364d 324 case '2':
325 options.protocol = SSH_PROTO_2;
326 break;
48e671d5 327 case '4':
328 IPv4or6 = AF_INET;
329 break;
48e671d5 330 case '6':
331 IPv4or6 = AF_INET6;
332 break;
5260325f 333 case 'n':
334 stdin_null_flag = 1;
335 break;
5260325f 336 case 'f':
337 fork_after_authentication_flag = 1;
338 stdin_null_flag = 1;
339 break;
5260325f 340 case 'x':
341 options.forward_x11 = 0;
342 break;
5260325f 343 case 'X':
344 options.forward_x11 = 1;
345 break;
5260325f 346 case 'g':
347 options.gateway_ports = 1;
348 break;
5260325f 349 case 'P':
350 options.use_privileged_port = 0;
351 break;
5260325f 352 case 'a':
353 options.forward_agent = 0;
354 break;
71276795 355 case 'A':
356 options.forward_agent = 1;
357 break;
5260325f 358#ifdef AFS
359 case 'k':
360 options.kerberos_tgt_passing = 0;
361 options.afs_token_passing = 0;
362 break;
363#endif
364 case 'i':
365 if (stat(optarg, &st) < 0) {
366 fprintf(stderr, "Warning: Identity file %s does not exist.\n",
fa08c86b 367 optarg);
5260325f 368 break;
369 }
370 if (options.num_identity_files >= SSH_MAX_IDENTITY_FILES)
371 fatal("Too many identity files specified (max %d)",
fa08c86b 372 SSH_MAX_IDENTITY_FILES);
373 options.identity_files[options.num_identity_files++] = xstrdup(optarg);
5260325f 374 break;
5260325f 375 case 't':
376 tty_flag = 1;
377 break;
5260325f 378 case 'v':
bcbf86ec 379 if (0 == debug_flag) {
380 debug_flag = 1;
381 options.log_level = SYSLOG_LEVEL_DEBUG1;
382 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
383 options.log_level++;
384 break;
385 } else {
386 fatal("Too high debugging level.\n");
387 }
388 /* fallthrough */
5260325f 389 case 'V':
a8be9f80 390 fprintf(stderr, "SSH Version %s, protocol versions %d.%d/%d.%d.\n",
391 SSH_VERSION,
392 PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1,
393 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
8ce64345 394 fprintf(stderr, "Compiled with SSL (0x%8.8lx).\n", SSLeay());
5260325f 395 if (opt == 'V')
396 exit(0);
5260325f 397 break;
5260325f 398 case 'q':
399 options.log_level = SYSLOG_LEVEL_QUIET;
400 break;
5260325f 401 case 'e':
402 if (optarg[0] == '^' && optarg[2] == 0 &&
403 (unsigned char) optarg[1] >= 64 && (unsigned char) optarg[1] < 128)
404 options.escape_char = (unsigned char) optarg[1] & 31;
405 else if (strlen(optarg) == 1)
406 options.escape_char = (unsigned char) optarg[0];
407 else if (strcmp(optarg, "none") == 0)
408 options.escape_char = -2;
409 else {
410 fprintf(stderr, "Bad escape character '%s'.\n", optarg);
411 exit(1);
412 }
413 break;
5260325f 414 case 'c':
a306f2dd 415 if (ciphers_valid(optarg)) {
416 /* SSH2 only */
417 options.ciphers = xstrdup(optarg);
d0c832f3 418 options.cipher = SSH_CIPHER_ILLEGAL;
a306f2dd 419 } else {
420 /* SSH1 only */
c523303b 421 options.cipher = cipher_number(optarg);
422 if (options.cipher == -1) {
a306f2dd 423 fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
424 exit(1);
425 }
c523303b 426 if (options.cipher == SSH_CIPHER_3DES) {
427 options.ciphers = "3des-cbc";
428 } else if (options.cipher == SSH_CIPHER_BLOWFISH) {
429 options.ciphers = "blowfish-cbc";
430 } else {
431 options.ciphers = (char *)-1;
432 }
5260325f 433 }
434 break;
5260325f 435 case 'p':
436 options.port = atoi(optarg);
5260325f 437 break;
5260325f 438 case 'l':
439 options.user = optarg;
440 break;
5260325f 441 case 'R':
48e671d5 442 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
443 &fwd_host_port) != 3 &&
444 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
445 &fwd_host_port) != 3) {
5260325f 446 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
447 usage();
448 /* NOTREACHED */
449 }
450 add_remote_forward(&options, fwd_port, buf, fwd_host_port);
451 break;
5260325f 452 case 'L':
48e671d5 453 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
454 &fwd_host_port) != 3 &&
455 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
456 &fwd_host_port) != 3) {
5260325f 457 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
458 usage();
459 /* NOTREACHED */
460 }
461 add_local_forward(&options, fwd_port, buf, fwd_host_port);
462 break;
5260325f 463 case 'C':
464 options.compression = 1;
465 break;
8ce64345 466 case 'N':
467 no_shell_flag = 1;
468 no_tty_flag = 1;
469 break;
8ce64345 470 case 'T':
471 no_tty_flag = 1;
472 break;
5260325f 473 case 'o':
474 dummy = 1;
475 if (process_config_line(&options, host ? host : "", optarg,
476 "command-line", 0, &dummy) != 0)
477 exit(1);
478 break;
5260325f 479 default:
480 usage();
481 }
482 }
483
484 /* Check that we got a host name. */
485 if (!host)
8efc0c15 486 usage();
5260325f 487
22d89d24 488 SSLeay_add_all_algorithms();
fa08c86b 489 ERR_load_crypto_strings();
22d89d24 490
5260325f 491 /* Initialize the command to execute on remote host. */
492 buffer_init(&command);
493
aa3378df 494 /*
495 * Save the command to execute on the remote host in a buffer. There
496 * is no limit on the length of the command, except by the maximum
497 * packet size. Also sets the tty flag if there is no command.
498 */
5260325f 499 if (optind == ac) {
500 /* No command specified - execute shell on a tty. */
501 tty_flag = 1;
502 } else {
503 /* A command has been specified. Store it into the
504 buffer. */
505 for (i = optind; i < ac; i++) {
506 if (i > optind)
507 buffer_append(&command, " ", 1);
508 buffer_append(&command, av[i], strlen(av[i]));
509 }
8efc0c15 510 }
5260325f 511
512 /* Cannot fork to background if no command. */
14a9a859 513 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
5260325f 514 fatal("Cannot fork into background without a command to execute.");
515
516 /* Allocate a tty by default if no command specified. */
517 if (buffer_len(&command) == 0)
518 tty_flag = 1;
519
0b6fbf03 520 /* Force no tty*/
521 if (no_tty_flag)
522 tty_flag = 0;
5260325f 523 /* Do not allocate a tty if stdin is not a tty. */
524 if (!isatty(fileno(stdin))) {
525 if (tty_flag)
526 fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n");
527 tty_flag = 0;
528 }
8ce64345 529
5260325f 530 /* Get user data. */
531 pw = getpwuid(original_real_uid);
532 if (!pw) {
533 fprintf(stderr, "You don't exist, go away!\n");
534 exit(1);
535 }
536 /* Take a copy of the returned structure. */
537 memset(&pwcopy, 0, sizeof(pwcopy));
538 pwcopy.pw_name = xstrdup(pw->pw_name);
539 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
540 pwcopy.pw_uid = pw->pw_uid;
541 pwcopy.pw_gid = pw->pw_gid;
2e73a022 542#ifdef HAVE_PW_CLASS_IN_PASSWD
543 pwcopy.pw_class = xstrdup(pw->pw_class);
544#endif
5260325f 545 pwcopy.pw_dir = xstrdup(pw->pw_dir);
546 pwcopy.pw_shell = xstrdup(pw->pw_shell);
547 pw = &pwcopy;
548
549 /* Initialize "log" output. Since we are the client all output
550 actually goes to the terminal. */
551 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
552
553 /* Read per-user configuration file. */
554 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE);
555 read_config_file(buf, host, &options);
556
557 /* Read systemwide configuration file. */
558 read_config_file(HOST_CONFIG_FILE, host, &options);
559
560 /* Fill configuration defaults. */
561 fill_default_options(&options);
562
563 /* reinit */
564 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
565
566 if (options.user == NULL)
567 options.user = xstrdup(pw->pw_name);
568
569 if (options.hostname != NULL)
570 host = options.hostname;
571
5260325f 572 /* Disable rhosts authentication if not running as root. */
3c62e7eb 573#ifdef HAVE_CYGWIN
574 /* Ignore uid if running under Windows */
575 if (!options.use_privileged_port) {
576#else
5260325f 577 if (original_effective_uid != 0 || !options.use_privileged_port) {
3c62e7eb 578#endif
6ffc9c88 579 debug("Rhosts Authentication disabled, "
580 "originating port will not be trusted.");
5260325f 581 options.rhosts_authentication = 0;
5260325f 582 }
aa3378df 583 /*
584 * If using rsh has been selected, exec it now (without trying
585 * anything else). Note that we must release privileges first.
586 */
5260325f 587 if (options.use_rsh) {
aa3378df 588 /*
589 * Restore our superuser privileges. This must be done
590 * before permanently setting the uid.
591 */
5260325f 592 restore_uid();
593
594 /* Switch to the original uid permanently. */
595 permanently_set_uid(original_real_uid);
596
597 /* Execute rsh. */
598 rsh_connect(host, options.user, &command);
599 fatal("rsh_connect returned");
8efc0c15 600 }
5260325f 601 /* Restore our superuser privileges. */
602 restore_uid();
603
6ffc9c88 604 /* Open a connection to the remote host. */
5260325f 605
606 ok = ssh_connect(host, &hostaddr, options.port,
6ffc9c88 607 options.connection_attempts,
608 original_effective_uid != 0 || !options.use_privileged_port,
609 original_real_uid,
610 options.proxy_command);
5260325f 611
aa3378df 612 /*
613 * If we successfully made the connection, load the host private key
614 * in case we will need it later for combined rsa-rhosts
615 * authentication. This must be done before releasing extra
616 * privileges, because the file is only readable by root.
617 */
a306f2dd 618 if (ok && (options.protocol & SSH_PROTO_1)) {
619 Key k;
5260325f 620 host_private_key = RSA_new();
fa08c86b 621 k.type = KEY_RSA1;
a306f2dd 622 k.rsa = host_private_key;
623 if (load_private_key(HOST_KEY_FILE, "", &k, NULL))
5260325f 624 host_private_key_loaded = 1;
625 }
aa3378df 626 /*
627 * Get rid of any extra privileges that we may have. We will no
628 * longer need them. Also, extra privileges could make it very hard
629 * to read identity files and other non-world-readable files from the
630 * user's home directory if it happens to be on a NFS volume where
631 * root is mapped to nobody.
632 */
633
634 /*
635 * Note that some legacy systems need to postpone the following call
636 * to permanently_set_uid() until the private hostkey is destroyed
637 * with RSA_free(). Otherwise the calling user could ptrace() the
638 * process, read the private hostkey and impersonate the host.
639 * OpenBSD does not allow ptracing of setuid processes.
640 */
5260325f 641 permanently_set_uid(original_real_uid);
642
aa3378df 643 /*
644 * Now that we are back to our own permissions, create ~/.ssh
645 * directory if it doesn\'t already exist.
646 */
5260325f 647 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR);
648 if (stat(buf, &st) < 0)
704b1659 649 if (mkdir(buf, 0700) < 0)
5260325f 650 error("Could not create directory '%.200s'.", buf);
651
652 /* Check if the connection failed, and try "rsh" if appropriate. */
653 if (!ok) {
654 if (options.port != 0)
57112b5a 655 log("Secure connection to %.100s on port %hu refused%.100s.",
5260325f 656 host, options.port,
657 options.fallback_to_rsh ? "; reverting to insecure method" : "");
658 else
659 log("Secure connection to %.100s refused%.100s.", host,
660 options.fallback_to_rsh ? "; reverting to insecure method" : "");
661
662 if (options.fallback_to_rsh) {
663 rsh_connect(host, options.user, &command);
664 fatal("rsh_connect returned");
665 }
666 exit(1);
8efc0c15 667 }
fa08c86b 668 /* Expand ~ in options.identity_files, known host file names. */
a306f2dd 669 /* XXX mem-leaks */
fa08c86b 670 for (i = 0; i < options.num_identity_files; i++) {
5260325f 671 options.identity_files[i] =
fa08c86b 672 tilde_expand_filename(options.identity_files[i], original_real_uid);
673 options.identity_files_type[i] = guess_identity_file_type(options.identity_files[i]);
674 debug("identity file %s type %d", options.identity_files[i],
675 options.identity_files_type[i]);
676 }
677 options.system_hostfile =
678 tilde_expand_filename(options.system_hostfile, original_real_uid);
679 options.user_hostfile =
680 tilde_expand_filename(options.user_hostfile, original_real_uid);
681 options.system_hostfile2 =
682 tilde_expand_filename(options.system_hostfile2, original_real_uid);
683 options.user_hostfile2 =
684 tilde_expand_filename(options.user_hostfile2, original_real_uid);
5260325f 685
686 /* Log into the remote system. This never returns if the login fails. */
687 ssh_login(host_private_key_loaded, host_private_key,
48e671d5 688 host, (struct sockaddr *)&hostaddr, original_real_uid);
5260325f 689
690 /* We no longer need the host private key. Clear it now. */
691 if (host_private_key_loaded)
692 RSA_free(host_private_key); /* Destroys contents safely */
693
8ce64345 694 exit_status = compat20 ? ssh_session2() : ssh_session();
695 packet_close();
696 return exit_status;
697}
698
0b242b12 699void
700x11_get_proto(char *proto, int proto_len, char *data, int data_len)
701{
702 char line[512];
703 FILE *f;
704 int got_data = 0, i;
705
fa649821 706 if (options.xauth_location) {
707 /* Try to get Xauthority information for the display. */
708 snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null",
709 options.xauth_location, getenv("DISPLAY"));
710 f = popen(line, "r");
711 if (f && fgets(line, sizeof(line), f) &&
712 sscanf(line, "%*s %s %s", proto, data) == 2)
713 got_data = 1;
714 if (f)
715 pclose(f);
716 }
0b242b12 717 /*
718 * If we didn't get authentication data, just make up some
719 * data. The forwarding code will check the validity of the
720 * response anyway, and substitute this data. The X11
721 * server, however, will ignore this fake data and use
722 * whatever authentication mechanisms it was using otherwise
723 * for the local connection.
724 */
725 if (!got_data) {
726 u_int32_t rand = 0;
727
728 strlcpy(proto, "MIT-MAGIC-COOKIE-1", proto_len);
729 for (i = 0; i < 16; i++) {
730 if (i % 4 == 0)
731 rand = arc4random();
732 snprintf(data + 2 * i, data_len - 2 * i, "%02x", rand & 0xff);
733 rand >>= 8;
734 }
735 }
736}
737
fa08c86b 738void
739ssh_init_forwarding(void)
740{
741 int i;
742 /* Initiate local TCP/IP port forwardings. */
743 for (i = 0; i < options.num_local_forwards; i++) {
744 debug("Connections to local port %d forwarded to remote address %.200s:%d",
745 options.local_forwards[i].port,
746 options.local_forwards[i].host,
747 options.local_forwards[i].host_port);
748 channel_request_local_forwarding(
749 options.local_forwards[i].port,
750 options.local_forwards[i].host,
751 options.local_forwards[i].host_port,
752 options.gateway_ports);
753 }
754
755 /* Initiate remote TCP/IP port forwardings. */
756 for (i = 0; i < options.num_remote_forwards; i++) {
757 debug("Connections to remote port %d forwarded to local address %.200s:%d",
758 options.remote_forwards[i].port,
759 options.remote_forwards[i].host,
760 options.remote_forwards[i].host_port);
761 channel_request_remote_forwarding(
762 options.remote_forwards[i].port,
763 options.remote_forwards[i].host,
764 options.remote_forwards[i].host_port);
765 }
766}
767
768void
769check_agent_present(void)
770{
771 if (options.forward_agent) {
772 /* Clear agent forwarding if we don\'t have an agent. */
773 int authfd = ssh_get_authentication_socket();
774 if (authfd < 0)
775 options.forward_agent = 0;
776 else
777 ssh_close_authentication_socket(authfd);
778 }
779}
780
8ce64345 781int
782ssh_session(void)
783{
784 int type;
8ce64345 785 int plen;
786 int interactive = 0;
787 int have_tty = 0;
788 struct winsize ws;
8ce64345 789 char *cp;
790
5260325f 791 /* Enable compression if requested. */
792 if (options.compression) {
793 debug("Requesting compression at level %d.", options.compression_level);
794
795 if (options.compression_level < 1 || options.compression_level > 9)
796 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
797
798 /* Send the request. */
799 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
800 packet_put_int(options.compression_level);
801 packet_send();
802 packet_write_wait();
803 type = packet_read(&plen);
804 if (type == SSH_SMSG_SUCCESS)
805 packet_start_compression(options.compression_level);
806 else if (type == SSH_SMSG_FAILURE)
807 log("Warning: Remote host refused compression.");
808 else
809 packet_disconnect("Protocol error waiting for compression response.");
810 }
811 /* Allocate a pseudo tty if appropriate. */
812 if (tty_flag) {
813 debug("Requesting pty.");
814
815 /* Start the packet. */
816 packet_start(SSH_CMSG_REQUEST_PTY);
817
818 /* Store TERM in the packet. There is no limit on the
819 length of the string. */
820 cp = getenv("TERM");
821 if (!cp)
822 cp = "";
823 packet_put_string(cp, strlen(cp));
824
825 /* Store window size in the packet. */
826 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
827 memset(&ws, 0, sizeof(ws));
828 packet_put_int(ws.ws_row);
829 packet_put_int(ws.ws_col);
830 packet_put_int(ws.ws_xpixel);
831 packet_put_int(ws.ws_ypixel);
832
833 /* Store tty modes in the packet. */
834 tty_make_modes(fileno(stdin));
835
836 /* Send the packet, and wait for it to leave. */
837 packet_send();
838 packet_write_wait();
839
840 /* Read response from the server. */
841 type = packet_read(&plen);
4fe2af09 842 if (type == SSH_SMSG_SUCCESS) {
5260325f 843 interactive = 1;
8ce64345 844 have_tty = 1;
4fe2af09 845 } else if (type == SSH_SMSG_FAILURE)
5260325f 846 log("Warning: Remote host failed or refused to allocate a pseudo tty.");
847 else
848 packet_disconnect("Protocol error waiting for pty request response.");
849 }
850 /* Request X11 forwarding if enabled and DISPLAY is set. */
851 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
0b242b12 852 char proto[512], data[512];
853 /* Get reasonable local authentication information. */
854 x11_get_proto(proto, sizeof proto, data, sizeof data);
855 /* Request forwarding with authentication spoofing. */
5260325f 856 debug("Requesting X11 forwarding with authentication spoofing.");
0b242b12 857 x11_request_forwarding_with_spoofing(0, proto, data);
5260325f 858
859 /* Read response from the server. */
860 type = packet_read(&plen);
861 if (type == SSH_SMSG_SUCCESS) {
5260325f 862 interactive = 1;
0b242b12 863 } else if (type == SSH_SMSG_FAILURE) {
5260325f 864 log("Warning: Remote host denied X11 forwarding.");
0b242b12 865 } else {
5260325f 866 packet_disconnect("Protocol error waiting for X11 forwarding");
0b242b12 867 }
5260325f 868 }
869 /* Tell the packet module whether this is an interactive session. */
870 packet_set_interactive(interactive, options.keepalives);
871
5260325f 872
873 /* Request authentication agent forwarding if appropriate. */
fa08c86b 874 check_agent_present();
875
5260325f 876 if (options.forward_agent) {
877 debug("Requesting authentication agent forwarding.");
878 auth_request_forwarding();
879
880 /* Read response from the server. */
881 type = packet_read(&plen);
882 packet_integrity_check(plen, 0, type);
883 if (type != SSH_SMSG_SUCCESS)
884 log("Warning: Remote host denied authentication agent forwarding.");
885 }
8efc0c15 886
fa08c86b 887 /* Initiate port forwardings. */
888 ssh_init_forwarding();
5260325f 889
aa3378df 890 /* If requested, let ssh continue in the background. */
6ae2364d 891 if (fork_after_authentication_flag)
aa3378df 892 if (daemon(1, 1) < 0)
893 fatal("daemon() failed: %.200s", strerror(errno));
894
895 /*
896 * If a command was specified on the command line, execute the
897 * command now. Otherwise request the server to start a shell.
898 */
5260325f 899 if (buffer_len(&command) > 0) {
900 int len = buffer_len(&command);
901 if (len > 900)
902 len = 900;
903 debug("Sending command: %.*s", len, buffer_ptr(&command));
904 packet_start(SSH_CMSG_EXEC_CMD);
905 packet_put_string(buffer_ptr(&command), buffer_len(&command));
906 packet_send();
907 packet_write_wait();
908 } else {
909 debug("Requesting shell.");
910 packet_start(SSH_CMSG_EXEC_SHELL);
911 packet_send();
912 packet_write_wait();
913 }
914
915 /* Enter the interactive session. */
2e73a022 916 return client_loop(have_tty, tty_flag ? options.escape_char : -1, 0);
8ce64345 917}
5260325f 918
8ce64345 919extern void client_set_session_ident(int id);
920
921void
fa08c86b 922ssh_session2_callback(int id, void *arg)
8ce64345 923{
924 int len;
925 debug("client_init id %d arg %d", id, (int)arg);
926
927 if (no_shell_flag)
928 goto done;
929
930 if (tty_flag) {
931 struct winsize ws;
932 char *cp;
933 cp = getenv("TERM");
934 if (!cp)
935 cp = "";
936 /* Store window size in the packet. */
937 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
938 memset(&ws, 0, sizeof(ws));
939
940 channel_request_start(id, "pty-req", 0);
941 packet_put_cstring(cp);
942 packet_put_int(ws.ws_col);
943 packet_put_int(ws.ws_row);
944 packet_put_int(ws.ws_xpixel);
945 packet_put_int(ws.ws_ypixel);
946 packet_put_cstring(""); /* XXX: encode terminal modes */
947 packet_send();
948 /* XXX wait for reply */
949 }
0b242b12 950 if (options.forward_x11 &&
951 getenv("DISPLAY") != NULL) {
952 char proto[512], data[512];
953 /* Get reasonable local authentication information. */
954 x11_get_proto(proto, sizeof proto, data, sizeof data);
955 /* Request forwarding with authentication spoofing. */
956 debug("Requesting X11 forwarding with authentication spoofing.");
957 x11_request_forwarding_with_spoofing(id, proto, data);
958 /* XXX wait for reply */
959 }
960
fa08c86b 961 check_agent_present();
962 if (options.forward_agent) {
963 debug("Requesting authentication agent forwarding.");
964 channel_request_start(id, "auth-agent-req@openssh.com", 0);
965 packet_send();
966 }
967
8ce64345 968 len = buffer_len(&command);
969 if (len > 0) {
970 if (len > 900)
971 len = 900;
972 debug("Sending command: %.*s", len, buffer_ptr(&command));
973 channel_request_start(id, "exec", 0);
974 packet_put_string(buffer_ptr(&command), len);
975 packet_send();
976 } else {
977 channel_request(id, "shell", 0);
978 }
979 /* channel_callback(id, SSH2_MSG_OPEN_CONFIGMATION, client_init, 0); */
980done:
981 /* register different callback, etc. XXX */
982 client_set_session_ident(id);
983}
984
985int
986ssh_session2(void)
987{
988 int window, packetmax, id;
2e73a022 989 int in, out, err;
990
14a9a859 991 if (stdin_null_flag) {
992 in = open("/dev/null", O_RDONLY);
993 } else {
994 in = dup(STDIN_FILENO);
995 }
2e73a022 996 out = dup(STDOUT_FILENO);
997 err = dup(STDERR_FILENO);
8ce64345 998
999 if (in < 0 || out < 0 || err < 0)
14a9a859 1000 fatal("dup() in/out/err failed");
8ce64345 1001
a22aff1f 1002 /* enable nonblocking unless tty */
1003 if (!isatty(in))
1004 set_nonblock(in);
1005 if (!isatty(out))
1006 set_nonblock(out);
1007 if (!isatty(err))
1008 set_nonblock(err);
1009
fa08c86b 1010 /* XXX should be pre-session */
1011 ssh_init_forwarding();
8ce64345 1012
14a9a859 1013 /* If requested, let ssh continue in the background. */
1014 if (fork_after_authentication_flag)
1015 if (daemon(1, 1) < 0)
1016 fatal("daemon() failed: %.200s", strerror(errno));
1017
bcbf86ec 1018 window = CHAN_SES_WINDOW_DEFAULT;
1019 packetmax = CHAN_SES_PACKET_DEFAULT;
1020 if (!tty_flag) {
8ce64345 1021 window *= 2;
bcbf86ec 1022 packetmax *=2;
8ce64345 1023 }
8ce64345 1024 id = channel_new(
1025 "session", SSH_CHANNEL_OPENING, in, out, err,
bcbf86ec 1026 window, packetmax, CHAN_EXTENDED_WRITE,
a22aff1f 1027 xstrdup("client-session"), /*nonblock*/0);
8ce64345 1028
8ce64345 1029 channel_open(id);
fa08c86b 1030 channel_register_callback(id, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION,
1031 ssh_session2_callback, (void *)0);
5260325f 1032
2e73a022 1033 return client_loop(tty_flag, tty_flag ? options.escape_char : -1, id);
8efc0c15 1034}
fa08c86b 1035
1036int
1037guess_identity_file_type(const char *filename)
1038{
1039 struct stat st;
1040 Key *public;
1041 int type = KEY_RSA1; /* default */
1042
1043 if (stat(filename, &st) < 0) {
d343d900 1044 /* ignore this key */
fa08c86b 1045 return KEY_UNSPEC;
1046 }
1047 public = key_new(type);
1048 if (!load_public_key(filename, public, NULL)) {
1049 /* ok, so we will assume this is 'some' key */
1050 type = KEY_UNSPEC;
1051 }
1052 key_free(public);
1053 return type;
1054}
This page took 0.25816 seconds and 5 git commands to generate.