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