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