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