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