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