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