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