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