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