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