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