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