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