Annotation of src/usr.bin/ssh/ssh.c, Revision 1.444
1.444 ! jmc 1: /* $OpenBSD: ssh.c,v 1.443 2016/07/15 00:24:30 djm Exp $ */
1.1 deraadt 2: /*
1.32 deraadt 3: * Author: Tatu Ylonen <ylo@cs.hut.fi>
4: * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5: * All rights reserved
6: * Ssh client program. This program can be used to log into a remote machine.
7: * The software supports strong authentication, encryption, and forwarding
8: * of X11, TCP/IP, and authentication connections.
9: *
1.64 deraadt 10: * As far as I am concerned, the code I have written for this software
11: * can be used freely for any purpose. Any derived versions of this
12: * software must be clearly marked as such, and if the derived work is
13: * incompatible with the protocol description in the RFC file, it must be
14: * called by a name other than "ssh" or "Secure Shell".
15: *
16: * Copyright (c) 1999 Niels Provos. All rights reserved.
1.202 markus 17: * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
1.64 deraadt 18: *
19: * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20: * in Canada (German citizen).
21: *
22: * Redistribution and use in source and binary forms, with or without
23: * modification, are permitted provided that the following conditions
24: * are met:
25: * 1. Redistributions of source code must retain the above copyright
26: * notice, this list of conditions and the following disclaimer.
27: * 2. Redistributions in binary form must reproduce the above copyright
28: * notice, this list of conditions and the following disclaimer in the
29: * documentation and/or other materials provided with the distribution.
30: *
31: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.32 deraadt 41: */
1.1 deraadt 42:
1.293 deraadt 43: #include <sys/types.h>
1.312 djm 44: #include <sys/ioctl.h>
45: #include <sys/queue.h>
1.259 stevesk 46: #include <sys/resource.h>
1.280 stevesk 47: #include <sys/socket.h>
1.264 stevesk 48: #include <sys/stat.h>
1.312 djm 49: #include <sys/time.h>
1.352 djm 50: #include <sys/wait.h>
1.258 stevesk 51:
1.265 stevesk 52: #include <ctype.h>
1.285 stevesk 53: #include <errno.h>
1.281 stevesk 54: #include <fcntl.h>
1.286 stevesk 55: #include <netdb.h>
1.258 stevesk 56: #include <paths.h>
1.279 stevesk 57: #include <pwd.h>
1.263 stevesk 58: #include <signal.h>
1.287 stevesk 59: #include <stddef.h>
1.291 stevesk 60: #include <stdio.h>
1.290 stevesk 61: #include <stdlib.h>
1.289 stevesk 62: #include <string.h>
1.288 stevesk 63: #include <unistd.h>
1.414 deraadt 64: #include <limits.h>
1.49 markus 65:
1.402 markus 66: #ifdef WITH_OPENSSL
1.49 markus 67: #include <openssl/evp.h>
1.72 markus 68: #include <openssl/err.h>
1.402 markus 69: #endif
1.1 deraadt 70:
1.293 deraadt 71: #include "xmalloc.h"
1.84 markus 72: #include "ssh.h"
73: #include "ssh1.h"
74: #include "ssh2.h"
1.341 djm 75: #include "canohost.h"
1.84 markus 76: #include "compat.h"
77: #include "cipher.h"
1.405 djm 78: #include "digest.h"
1.1 deraadt 79: #include "packet.h"
80: #include "buffer.h"
1.123 markus 81: #include "channels.h"
1.49 markus 82: #include "key.h"
1.58 markus 83: #include "authfd.h"
1.49 markus 84: #include "authfile.h"
1.83 markus 85: #include "pathnames.h"
1.214 djm 86: #include "dispatch.h"
1.81 markus 87: #include "clientloop.h"
1.84 markus 88: #include "log.h"
1.406 millert 89: #include "misc.h"
1.84 markus 90: #include "readconf.h"
91: #include "sshconnect.h"
1.95 markus 92: #include "kex.h"
93: #include "mac.h"
1.213 deraadt 94: #include "sshpty.h"
1.212 djm 95: #include "match.h"
1.214 djm 96: #include "msg.h"
1.225 dtucker 97: #include "uidswap.h"
1.278 stevesk 98: #include "version.h"
1.412 djm 99: #include "ssherr.h"
1.420 djm 100: #include "myproposal.h"
1.49 markus 101:
1.333 markus 102: #ifdef ENABLE_PKCS11
103: #include "ssh-pkcs11.h"
1.137 jakob 104: #endif
1.127 markus 105:
1.49 markus 106: extern char *__progname;
1.1 deraadt 107:
1.316 djm 108: /* Flag indicating whether debug mode is on. May be set on the command line. */
1.1 deraadt 109: int debug_flag = 0;
110:
1.359 djm 111: /* Flag indicating whether a tty should be requested */
1.1 deraadt 112: int tty_flag = 0;
113:
1.45 markus 114: /* don't exec a shell */
115: int no_shell_flag = 0;
116:
1.33 markus 117: /*
118: * Flag indicating that nothing should be read from stdin. This can be set
119: * on the command line.
120: */
1.1 deraadt 121: int stdin_null_flag = 0;
122:
1.33 markus 123: /*
1.344 djm 124: * Flag indicating that the current process should be backgrounded and
125: * a new slave launched in the foreground for ControlPersist.
126: */
127: int need_controlpersist_detach = 0;
128:
129: /* Copies of flags for ControlPersist foreground slave */
1.359 djm 130: int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
1.344 djm 131:
132: /*
1.33 markus 133: * Flag indicating that ssh should fork after authentication. This is useful
1.172 deraadt 134: * so that the passphrase can be entered manually, and then ssh goes to the
1.33 markus 135: * background.
136: */
1.1 deraadt 137: int fork_after_authentication_flag = 0;
138:
1.33 markus 139: /*
140: * General data structure for command line options and options configurable
141: * in configuration files. See readconf.h.
142: */
1.1 deraadt 143: Options options;
144:
1.139 markus 145: /* optional user configfile */
146: char *config = NULL;
147:
1.33 markus 148: /*
149: * Name of the host we are connecting to. This is the name given on the
150: * command line, or the HostName specified for the user-supplied name in a
151: * configuration file.
152: */
1.1 deraadt 153: char *host;
154:
1.22 provos 155: /* socket address the host resolves to */
1.37 markus 156: struct sockaddr_storage hostaddr;
1.1 deraadt 157:
1.112 markus 158: /* Private host keys. */
1.173 markus 159: Sensitive sensitive_data;
1.1 deraadt 160:
1.10 dugsong 161: /* Original real UID. */
162: uid_t original_real_uid;
1.177 markus 163: uid_t original_effective_uid;
1.1 deraadt 164:
1.45 markus 165: /* command to be executed */
166: Buffer command;
167:
1.85 djm 168: /* Should we execute a command or invoke a subsystem? */
169: int subsystem_flag = 0;
170:
1.170 markus 171: /* # of replies received for global requests */
1.315 djm 172: static int remote_forward_confirms_received = 0;
1.170 markus 173:
1.313 djm 174: /* mux.c */
175: extern int muxserver_sock;
176: extern u_int muxclient_command;
177:
1.1 deraadt 178: /* Prints a help message to the user. This function never returns. */
179:
1.126 itojun 180: static void
1.93 itojun 181: usage(void)
1.1 deraadt 182: {
1.208 markus 183: fprintf(stderr,
1.409 jmc 184: "usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
1.375 dtucker 185: " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
1.444 ! jmc 186: " [-F configfile] [-I pkcs11] [-i identity_file]\n"
! 187: " [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]\n"
! 188: " [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]\n"
! 189: " [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
! 190: " [user@]hostname [command]\n"
1.208 markus 191: );
1.257 dtucker 192: exit(255);
1.1 deraadt 193: }
194:
1.126 itojun 195: static int ssh_session(void);
196: static int ssh_session2(void);
197: static void load_public_identity_files(void);
1.352 djm 198: static void main_sigchld_handler(int);
1.312 djm 199:
200: /* from muxclient.c */
201: void muxclient(const char *);
202: void muxserver_listen(void);
1.45 markus 203:
1.361 djm 204: /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
205: static void
206: tilde_expand_paths(char **paths, u_int num_paths)
207: {
208: u_int i;
209: char *cp;
210:
211: for (i = 0; i < num_paths; i++) {
212: cp = tilde_expand_filename(paths[i], original_real_uid);
1.378 djm 213: free(paths[i]);
1.361 djm 214: paths[i] = cp;
215: }
216: }
217:
1.400 djm 218: /*
219: * Attempt to resolve a host name / port to a set of addresses and
220: * optionally return any CNAMEs encountered along the way.
221: * Returns NULL on failure.
222: * NB. this function must operate with a options having undefined members.
223: */
1.385 djm 224: static struct addrinfo *
1.400 djm 225: resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
1.385 djm 226: {
227: char strport[NI_MAXSERV];
228: struct addrinfo hints, *res;
229: int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
230:
1.400 djm 231: if (port <= 0)
232: port = default_ssh_port();
233:
1.427 djm 234: snprintf(strport, sizeof strport, "%d", port);
1.398 tedu 235: memset(&hints, 0, sizeof(hints));
1.400 djm 236: hints.ai_family = options.address_family == -1 ?
237: AF_UNSPEC : options.address_family;
1.385 djm 238: hints.ai_socktype = SOCK_STREAM;
239: if (cname != NULL)
240: hints.ai_flags = AI_CANONNAME;
241: if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
242: if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
243: loglevel = SYSLOG_LEVEL_ERROR;
244: do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
245: __progname, name, ssh_gai_strerror(gaierr));
246: return NULL;
247: }
248: if (cname != NULL && res->ai_canonname != NULL) {
249: if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
250: error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
251: __func__, name, res->ai_canonname, (u_long)clen);
252: if (clen > 0)
253: *cname = '\0';
254: }
255: }
256: return res;
257: }
258:
259: /*
1.413 djm 260: * Attempt to resolve a numeric host address / port to a single address.
261: * Returns a canonical address string.
262: * Returns NULL on failure.
263: * NB. this function must operate with a options having undefined members.
264: */
265: static struct addrinfo *
266: resolve_addr(const char *name, int port, char *caddr, size_t clen)
267: {
268: char addr[NI_MAXHOST], strport[NI_MAXSERV];
269: struct addrinfo hints, *res;
270: int gaierr;
271:
272: if (port <= 0)
273: port = default_ssh_port();
274: snprintf(strport, sizeof strport, "%u", port);
275: memset(&hints, 0, sizeof(hints));
276: hints.ai_family = options.address_family == -1 ?
277: AF_UNSPEC : options.address_family;
278: hints.ai_socktype = SOCK_STREAM;
279: hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
280: if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
281: debug2("%s: could not resolve name %.100s as address: %s",
282: __func__, name, ssh_gai_strerror(gaierr));
283: return NULL;
284: }
285: if (res == NULL) {
286: debug("%s: getaddrinfo %.100s returned no addresses",
287: __func__, name);
288: return NULL;
289: }
290: if (res->ai_next != NULL) {
291: debug("%s: getaddrinfo %.100s returned multiple addresses",
292: __func__, name);
293: goto fail;
294: }
295: if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
296: addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
297: debug("%s: Could not format address for name %.100s: %s",
298: __func__, name, ssh_gai_strerror(gaierr));
299: goto fail;
300: }
301: if (strlcpy(caddr, addr, clen) >= clen) {
302: error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
303: __func__, name, addr, (u_long)clen);
304: if (clen > 0)
305: *caddr = '\0';
306: fail:
307: freeaddrinfo(res);
308: return NULL;
309: }
310: return res;
311: }
312:
313: /*
1.385 djm 314: * Check whether the cname is a permitted replacement for the hostname
315: * and perform the replacement if it is.
1.400 djm 316: * NB. this function must operate with a options having undefined members.
1.385 djm 317: */
318: static int
1.443 djm 319: check_follow_cname(int direct, char **namep, const char *cname)
1.385 djm 320: {
321: int i;
322: struct allowed_cname *rule;
323:
324: if (*cname == '\0' || options.num_permitted_cnames == 0 ||
325: strcmp(*namep, cname) == 0)
326: return 0;
1.386 djm 327: if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
1.385 djm 328: return 0;
329: /*
1.386 djm 330: * Don't attempt to canonicalize names that will be interpreted by
1.443 djm 331: * a proxy or jump host unless the user specifically requests so.
1.385 djm 332: */
1.443 djm 333: if (!direct &&
1.386 djm 334: options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
1.385 djm 335: return 0;
336: debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
337: for (i = 0; i < options.num_permitted_cnames; i++) {
338: rule = options.permitted_cnames + i;
1.418 djm 339: if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
340: match_pattern_list(cname, rule->target_list, 1) != 1)
1.385 djm 341: continue;
1.386 djm 342: verbose("Canonicalized DNS aliased hostname "
1.385 djm 343: "\"%s\" => \"%s\"", *namep, cname);
344: free(*namep);
345: *namep = xstrdup(cname);
346: return 1;
347: }
348: return 0;
349: }
350:
351: /*
352: * Attempt to resolve the supplied hostname after applying the user's
1.387 djm 353: * canonicalization rules. Returns the address list for the host or NULL
354: * if no name was found after canonicalization.
1.400 djm 355: * NB. this function must operate with a options having undefined members.
1.385 djm 356: */
357: static struct addrinfo *
1.400 djm 358: resolve_canonicalize(char **hostp, int port)
1.385 djm 359: {
1.443 djm 360: int i, direct, ndots;
1.413 djm 361: char *cp, *fullhost, newname[NI_MAXHOST];
1.385 djm 362: struct addrinfo *addrs;
363:
1.386 djm 364: if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
1.385 djm 365: return NULL;
1.400 djm 366:
1.385 djm 367: /*
1.386 djm 368: * Don't attempt to canonicalize names that will be interpreted by
1.385 djm 369: * a proxy unless the user specifically requests so.
370: */
1.443 djm 371: direct = option_clear_or_none(options.proxy_command) &&
372: options.jump_host == NULL;
373: if (!direct &&
1.386 djm 374: options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
1.385 djm 375: return NULL;
1.400 djm 376:
1.413 djm 377: /* Try numeric hostnames first */
378: if ((addrs = resolve_addr(*hostp, port,
379: newname, sizeof(newname))) != NULL) {
380: debug2("%s: hostname %.100s is address", __func__, *hostp);
381: if (strcasecmp(*hostp, newname) != 0) {
382: debug2("%s: canonicalised address \"%s\" => \"%s\"",
383: __func__, *hostp, newname);
384: free(*hostp);
385: *hostp = xstrdup(newname);
386: }
387: return addrs;
388: }
389:
1.428 djm 390: /* If domain name is anchored, then resolve it now */
391: if ((*hostp)[strlen(*hostp) - 1] == '.') {
392: debug3("%s: name is fully qualified", __func__);
393: fullhost = xstrdup(*hostp);
394: if ((addrs = resolve_host(fullhost, port, 0,
395: newname, sizeof(newname))) != NULL)
396: goto found;
397: free(fullhost);
398: goto notfound;
399: }
400:
1.387 djm 401: /* Don't apply canonicalization to sufficiently-qualified hostnames */
1.385 djm 402: ndots = 0;
403: for (cp = *hostp; *cp != '\0'; cp++) {
404: if (*cp == '.')
405: ndots++;
406: }
1.386 djm 407: if (ndots > options.canonicalize_max_dots) {
408: debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
409: __func__, *hostp, options.canonicalize_max_dots);
1.385 djm 410: return NULL;
411: }
412: /* Attempt each supplied suffix */
413: for (i = 0; i < options.num_canonical_domains; i++) {
1.413 djm 414: *newname = '\0';
1.385 djm 415: xasprintf(&fullhost, "%s.%s.", *hostp,
416: options.canonical_domains[i]);
1.400 djm 417: debug3("%s: attempting \"%s\" => \"%s\"", __func__,
418: *hostp, fullhost);
419: if ((addrs = resolve_host(fullhost, port, 0,
1.413 djm 420: newname, sizeof(newname))) == NULL) {
1.385 djm 421: free(fullhost);
422: continue;
423: }
1.428 djm 424: found:
1.385 djm 425: /* Remove trailing '.' */
426: fullhost[strlen(fullhost) - 1] = '\0';
427: /* Follow CNAME if requested */
1.443 djm 428: if (!check_follow_cname(direct, &fullhost, newname)) {
1.386 djm 429: debug("Canonicalized hostname \"%s\" => \"%s\"",
1.385 djm 430: *hostp, fullhost);
431: }
432: free(*hostp);
433: *hostp = fullhost;
434: return addrs;
435: }
1.428 djm 436: notfound:
1.386 djm 437: if (!options.canonicalize_fallback_local)
1.400 djm 438: fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
439: debug2("%s: host %s not found in any suffix", __func__, *hostp);
1.385 djm 440: return NULL;
441: }
442:
1.32 deraadt 443: /*
1.400 djm 444: * Read per-user configuration file. Ignore the system wide config
445: * file if the user specifies a config file on the command line.
446: */
447: static void
1.408 djm 448: process_config_files(const char *host_arg, struct passwd *pw, int post_canon)
1.400 djm 449: {
1.414 deraadt 450: char buf[PATH_MAX];
1.400 djm 451: int r;
452:
453: if (config != NULL) {
454: if (strcasecmp(config, "none") != 0 &&
1.408 djm 455: !read_config_file(config, pw, host, host_arg, &options,
456: SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
1.400 djm 457: fatal("Can't open user config file %.100s: "
458: "%.100s", config, strerror(errno));
459: } else {
460: r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
461: _PATH_SSH_USER_CONFFILE);
462: if (r > 0 && (size_t)r < sizeof(buf))
1.408 djm 463: (void)read_config_file(buf, pw, host, host_arg,
464: &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
465: (post_canon ? SSHCONF_POSTCANON : 0));
1.400 djm 466:
467: /* Read systemwide configuration file after user config. */
1.408 djm 468: (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
469: host, host_arg, &options,
470: post_canon ? SSHCONF_POSTCANON : 0);
471: }
472: }
473:
474: /* Rewrite the port number in an addrinfo list of addresses */
475: static void
476: set_addrinfo_port(struct addrinfo *addrs, int port)
477: {
478: struct addrinfo *addr;
479:
480: for (addr = addrs; addr != NULL; addr = addr->ai_next) {
481: switch (addr->ai_family) {
482: case AF_INET:
483: ((struct sockaddr_in *)addr->ai_addr)->
484: sin_port = htons(port);
485: break;
486: case AF_INET6:
487: ((struct sockaddr_in6 *)addr->ai_addr)->
488: sin6_port = htons(port);
489: break;
490: }
1.400 djm 491: }
492: }
493:
494: /*
1.32 deraadt 495: * Main program for the ssh client.
496: */
1.2 provos 497: int
498: main(int ac, char **av)
1.1 deraadt 499: {
1.437 djm 500: struct ssh *ssh = NULL;
1.443 djm 501: int i, r, opt, exit_status, use_syslog, direct, config_test = 0;
1.414 deraadt 502: char *p, *cp, *line, *argv0, buf[PATH_MAX], *host_arg, *logfile;
1.358 djm 503: char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
1.423 djm 504: char cname[NI_MAXHOST], uidstr[32], *conn_hash_hex;
1.31 markus 505: struct stat st;
1.98 markus 506: struct passwd *pw;
1.382 djm 507: int timeout_ms;
1.144 stevesk 508: extern int optind, optreset;
509: extern char *optarg;
1.406 millert 510: struct Forward fwd;
1.385 djm 511: struct addrinfo *addrs = NULL;
1.405 djm 512: struct ssh_digest_ctx *md;
513: u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
1.250 djm 514:
1.436 dtucker 515: ssh_malloc_init(); /* must be called before any mallocs */
1.250 djm 516: /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
517: sanitise_stdfd();
1.31 markus 518:
1.33 markus 519: /*
1.346 djm 520: * Discard other fds that are hanging around. These can cause problem
521: * with backgrounded ssh processes started by ControlPersist.
522: */
523: closefrom(STDERR_FILENO + 1);
524:
525: /*
1.33 markus 526: * Save the original real uid. It will be needed later (uid-swapping
527: * may clobber the real uid).
528: */
1.31 markus 529: original_real_uid = getuid();
530: original_effective_uid = geteuid();
531:
1.184 stevesk 532: /*
533: * Use uid-swapping to give up root privileges for the duration of
534: * option processing. We will re-instantiate the rights when we are
535: * ready to create the privileged port, and will permanently drop
536: * them when the port has been created (actually, when the connection
537: * has been made, as we may need to create the port several times).
538: */
539: PRIV_END;
540:
1.31 markus 541: /* If we are installed setuid root be careful to not drop core. */
542: if (original_real_uid != original_effective_uid) {
543: struct rlimit rlim;
544: rlim.rlim_cur = rlim.rlim_max = 0;
545: if (setrlimit(RLIMIT_CORE, &rlim) < 0)
546: fatal("setrlimit failed: %.100s", strerror(errno));
1.1 deraadt 547: }
1.107 markus 548: /* Get user data. */
549: pw = getpwuid(original_real_uid);
550: if (!pw) {
1.380 djm 551: logit("No user exists for uid %lu", (u_long)original_real_uid);
1.257 dtucker 552: exit(255);
1.107 markus 553: }
554: /* Take a copy of the returned structure. */
555: pw = pwcopy(pw);
1.31 markus 556:
1.33 markus 557: /*
558: * Set our umask to something reasonable, as some files are created
559: * with the default umask. This will make them world-readable but
560: * writable only by the owner, which is ok for all files for which we
561: * don't set the modes explicitly.
562: */
1.31 markus 563: umask(022);
564:
1.316 djm 565: /*
566: * Initialize option structure to indicate that no values have been
567: * set.
568: */
1.31 markus 569: initialize_options(&options);
570:
571: /* Parse command-line arguments. */
572: host = NULL;
1.320 djm 573: use_syslog = 0;
1.375 dtucker 574: logfile = NULL;
1.325 markus 575: argv0 = av[0];
1.31 markus 576:
1.266 djm 577: again:
1.316 djm 578: while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
1.443 djm 579: "ACD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
1.31 markus 580: switch (opt) {
1.91 jakob 581: case '1':
582: options.protocol = SSH_PROTO_1;
583: break;
1.47 markus 584: case '2':
585: options.protocol = SSH_PROTO_2;
586: break;
1.37 markus 587: case '4':
1.196 djm 588: options.address_family = AF_INET;
1.37 markus 589: break;
590: case '6':
1.196 djm 591: options.address_family = AF_INET6;
1.37 markus 592: break;
1.31 markus 593: case 'n':
594: stdin_null_flag = 1;
595: break;
596: case 'f':
597: fork_after_authentication_flag = 1;
598: stdin_null_flag = 1;
599: break;
600: case 'x':
601: options.forward_x11 = 0;
602: break;
603: case 'X':
604: options.forward_x11 = 1;
605: break;
1.320 djm 606: case 'y':
607: use_syslog = 1;
608: break;
1.375 dtucker 609: case 'E':
1.422 dtucker 610: logfile = optarg;
1.375 dtucker 611: break;
1.408 djm 612: case 'G':
613: config_test = 1;
614: break;
1.202 markus 615: case 'Y':
616: options.forward_x11 = 1;
617: options.forward_x11_trusted = 1;
618: break;
1.31 markus 619: case 'g':
1.406 millert 620: options.fwd_opts.gateway_ports = 1;
1.31 markus 621: break;
1.229 djm 622: case 'O':
1.441 dtucker 623: if (options.stdio_forward_host != NULL)
1.332 djm 624: fatal("Cannot specify multiplexing "
625: "command with -W");
626: else if (muxclient_command != 0)
627: fatal("Multiplexing command already specified");
1.229 djm 628: if (strcmp(optarg, "check") == 0)
1.312 djm 629: muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
1.338 markus 630: else if (strcmp(optarg, "forward") == 0)
631: muxclient_command = SSHMUX_COMMAND_FORWARD;
1.229 djm 632: else if (strcmp(optarg, "exit") == 0)
1.312 djm 633: muxclient_command = SSHMUX_COMMAND_TERMINATE;
1.357 djm 634: else if (strcmp(optarg, "stop") == 0)
635: muxclient_command = SSHMUX_COMMAND_STOP;
1.365 djm 636: else if (strcmp(optarg, "cancel") == 0)
637: muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
1.229 djm 638: else
639: fatal("Invalid multiplex command.");
640: break;
1.183 stevesk 641: case 'P': /* deprecated */
1.31 markus 642: options.use_privileged_port = 0;
1.376 djm 643: break;
1.394 deraadt 644: case 'Q':
1.376 djm 645: cp = NULL;
1.394 deraadt 646: if (strcmp(optarg, "cipher") == 0)
1.393 djm 647: cp = cipher_alg_list('\n', 0);
1.394 deraadt 648: else if (strcmp(optarg, "cipher-auth") == 0)
1.393 djm 649: cp = cipher_alg_list('\n', 1);
1.394 deraadt 650: else if (strcmp(optarg, "mac") == 0)
1.392 dtucker 651: cp = mac_alg_list('\n');
1.394 deraadt 652: else if (strcmp(optarg, "kex") == 0)
1.392 dtucker 653: cp = kex_alg_list('\n');
1.394 deraadt 654: else if (strcmp(optarg, "key") == 0)
1.396 markus 655: cp = key_alg_list(0, 0);
656: else if (strcmp(optarg, "key-cert") == 0)
657: cp = key_alg_list(1, 0);
658: else if (strcmp(optarg, "key-plain") == 0)
659: cp = key_alg_list(0, 1);
1.416 djm 660: else if (strcmp(optarg, "protocol-version") == 0) {
661: #ifdef WITH_SSH1
662: cp = xstrdup("1\n2");
663: #else
664: cp = xstrdup("2");
665: #endif
666: }
1.376 djm 667: if (cp == NULL)
668: fatal("Unsupported query \"%s\"", optarg);
669: printf("%s\n", cp);
670: free(cp);
671: exit(0);
1.31 markus 672: break;
673: case 'a':
674: options.forward_agent = 0;
1.53 markus 675: break;
676: case 'A':
677: options.forward_agent = 1;
1.31 markus 678: break;
679: case 'k':
1.204 dtucker 680: options.gss_deleg_creds = 0;
1.297 djm 681: break;
682: case 'K':
683: options.gss_authentication = 1;
684: options.gss_deleg_creds = 1;
1.31 markus 685: break;
686: case 'i':
1.429 dtucker 687: p = tilde_expand_filename(optarg, original_real_uid);
688: if (stat(p, &st) < 0)
1.128 fgsch 689: fprintf(stderr, "Warning: Identity file %s "
1.429 dtucker 690: "not accessible: %s.\n", p,
1.231 otto 691: strerror(errno));
1.429 dtucker 692: else
693: add_identity_file(&options, NULL, p, 1);
694: free(p);
1.31 markus 695: break;
1.127 markus 696: case 'I':
1.333 markus 697: #ifdef ENABLE_PKCS11
1.422 dtucker 698: free(options.pkcs11_provider);
1.333 markus 699: options.pkcs11_provider = xstrdup(optarg);
1.137 jakob 700: #else
1.333 markus 701: fprintf(stderr, "no support for PKCS#11.\n");
1.137 jakob 702: #endif
1.127 markus 703: break;
1.443 djm 704: case 'J':
705: if (options.jump_host != NULL)
706: fatal("Only a single -J option permitted");
707: if (options.proxy_command != NULL)
708: fatal("Cannot specify -J with ProxyCommand");
709: if (parse_jump(optarg, &options, 1) == -1)
710: fatal("Invalid -J argument");
711: options.proxy_command = xstrdup("none");
712: break;
1.31 markus 713: case 't':
1.359 djm 714: if (options.request_tty == REQUEST_TTY_YES)
715: options.request_tty = REQUEST_TTY_FORCE;
716: else
717: options.request_tty = REQUEST_TTY_YES;
1.31 markus 718: break;
719: case 'v':
1.197 markus 720: if (debug_flag == 0) {
1.66 markus 721: debug_flag = 1;
722: options.log_level = SYSLOG_LEVEL_DEBUG1;
1.197 markus 723: } else {
1.443 djm 724: if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
725: debug_flag++;
1.197 markus 726: options.log_level++;
1.443 djm 727: }
1.197 markus 728: }
1.375 dtucker 729: break;
1.31 markus 730: case 'V':
1.209 markus 731: fprintf(stderr, "%s, %s\n",
1.402 markus 732: SSH_VERSION,
733: #ifdef WITH_OPENSSL
734: SSLeay_version(SSLEAY_VERSION)
735: #else
736: "without OpenSSL"
737: #endif
738: );
1.31 markus 739: if (opt == 'V')
740: exit(0);
741: break;
1.255 reyk 742: case 'w':
1.256 reyk 743: if (options.tun_open == -1)
744: options.tun_open = SSH_TUNMODE_DEFAULT;
1.255 reyk 745: options.tun_local = a2tun(optarg, &options.tun_remote);
1.256 reyk 746: if (options.tun_local == SSH_TUNID_ERR) {
1.316 djm 747: fprintf(stderr,
748: "Bad tun device '%s'\n", optarg);
1.257 dtucker 749: exit(255);
1.255 reyk 750: }
751: break;
1.331 dtucker 752: case 'W':
1.441 dtucker 753: if (options.stdio_forward_host != NULL)
1.332 djm 754: fatal("stdio forward already specified");
755: if (muxclient_command != 0)
756: fatal("Cannot specify stdio forward with -O");
1.331 dtucker 757: if (parse_forward(&fwd, optarg, 1, 0)) {
1.441 dtucker 758: options.stdio_forward_host = fwd.listen_host;
759: options.stdio_forward_port = fwd.listen_port;
1.378 djm 760: free(fwd.connect_host);
1.331 dtucker 761: } else {
762: fprintf(stderr,
763: "Bad stdio forwarding specification '%s'\n",
764: optarg);
765: exit(255);
766: }
1.359 djm 767: options.request_tty = REQUEST_TTY_NO;
1.331 dtucker 768: no_shell_flag = 1;
769: break;
1.31 markus 770: case 'q':
771: options.log_level = SYSLOG_LEVEL_QUIET;
772: break;
773: case 'e':
774: if (optarg[0] == '^' && optarg[2] == 0 &&
1.128 fgsch 775: (u_char) optarg[1] >= 64 &&
776: (u_char) optarg[1] < 128)
1.78 markus 777: options.escape_char = (u_char) optarg[1] & 31;
1.31 markus 778: else if (strlen(optarg) == 1)
1.78 markus 779: options.escape_char = (u_char) optarg[0];
1.31 markus 780: else if (strcmp(optarg, "none") == 0)
1.119 stevesk 781: options.escape_char = SSH_ESCAPECHAR_NONE;
1.31 markus 782: else {
1.128 fgsch 783: fprintf(stderr, "Bad escape character '%s'.\n",
784: optarg);
1.257 dtucker 785: exit(255);
1.31 markus 786: }
787: break;
788: case 'c':
1.420 djm 789: if (ciphers_valid(*optarg == '+' ?
790: optarg + 1 : optarg)) {
1.49 markus 791: /* SSH2 only */
1.422 dtucker 792: free(options.ciphers);
1.49 markus 793: options.ciphers = xstrdup(optarg);
1.224 markus 794: options.cipher = SSH_CIPHER_INVALID;
1.420 djm 795: break;
796: }
797: /* SSH1 only */
798: options.cipher = cipher_number(optarg);
799: if (options.cipher == -1) {
800: fprintf(stderr, "Unknown cipher type '%s'\n",
801: optarg);
802: exit(255);
1.95 markus 803: }
1.420 djm 804: if (options.cipher == SSH_CIPHER_3DES)
805: options.ciphers = xstrdup("3des-cbc");
806: else if (options.cipher == SSH_CIPHER_BLOWFISH)
807: options.ciphers = xstrdup("blowfish-cbc");
808: else
809: options.ciphers = xstrdup(KEX_CLIENT_ENCRYPT);
1.95 markus 810: break;
811: case 'm':
1.422 dtucker 812: if (mac_valid(optarg)) {
813: free(options.macs);
1.95 markus 814: options.macs = xstrdup(optarg);
1.422 dtucker 815: } else {
1.128 fgsch 816: fprintf(stderr, "Unknown mac type '%s'\n",
817: optarg);
1.257 dtucker 818: exit(255);
1.31 markus 819: }
820: break;
1.214 djm 821: case 'M':
1.242 djm 822: if (options.control_master == SSHCTL_MASTER_YES)
823: options.control_master = SSHCTL_MASTER_ASK;
824: else
825: options.control_master = SSHCTL_MASTER_YES;
1.214 djm 826: break;
1.31 markus 827: case 'p':
1.113 stevesk 828: options.port = a2port(optarg);
1.323 djm 829: if (options.port <= 0) {
1.109 markus 830: fprintf(stderr, "Bad port '%s'\n", optarg);
1.257 dtucker 831: exit(255);
1.109 markus 832: }
1.31 markus 833: break;
834: case 'l':
835: options.user = optarg;
836: break;
1.141 stevesk 837:
838: case 'L':
1.324 djm 839: if (parse_forward(&fwd, optarg, 0, 0))
1.232 djm 840: add_local_forward(&options, &fwd);
841: else {
1.128 fgsch 842: fprintf(stderr,
1.232 djm 843: "Bad local forwarding specification '%s'\n",
1.128 fgsch 844: optarg);
1.257 dtucker 845: exit(255);
1.31 markus 846: }
1.232 djm 847: break;
848:
849: case 'R':
1.324 djm 850: if (parse_forward(&fwd, optarg, 0, 1)) {
1.232 djm 851: add_remote_forward(&options, &fwd);
852: } else {
1.128 fgsch 853: fprintf(stderr,
1.232 djm 854: "Bad remote forwarding specification "
855: "'%s'\n", optarg);
1.257 dtucker 856: exit(255);
1.31 markus 857: }
858: break;
1.108 markus 859:
860: case 'D':
1.324 djm 861: if (parse_forward(&fwd, optarg, 1, 0)) {
1.322 stevesk 862: add_local_forward(&options, &fwd);
1.232 djm 863: } else {
1.322 stevesk 864: fprintf(stderr,
865: "Bad dynamic forwarding specification "
866: "'%s'\n", optarg);
1.257 dtucker 867: exit(255);
1.109 markus 868: }
1.108 markus 869: break;
870:
1.31 markus 871: case 'C':
872: options.compression = 1;
873: break;
1.45 markus 874: case 'N':
875: no_shell_flag = 1;
1.359 djm 876: options.request_tty = REQUEST_TTY_NO;
1.45 markus 877: break;
878: case 'T':
1.359 djm 879: options.request_tty = REQUEST_TTY_NO;
1.45 markus 880: break;
1.31 markus 881: case 'o':
1.205 markus 882: line = xstrdup(optarg);
1.408 djm 883: if (process_config_line(&options, pw,
884: host ? host : "", host ? host : "", line,
885: "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1.257 dtucker 886: exit(255);
1.378 djm 887: free(line);
1.31 markus 888: break;
1.85 djm 889: case 's':
890: subsystem_flag = 1;
1.117 markus 891: break;
1.214 djm 892: case 'S':
1.431 mmcc 893: free(options.control_path);
1.214 djm 894: options.control_path = xstrdup(optarg);
895: break;
1.117 markus 896: case 'b':
897: options.bind_address = optarg;
1.85 djm 898: break;
1.139 markus 899: case 'F':
900: config = optarg;
901: break;
1.31 markus 902: default:
903: usage();
1.1 deraadt 904: }
1.31 markus 905: }
906:
1.128 fgsch 907: ac -= optind;
908: av += optind;
909:
1.329 guenther 910: if (ac > 0 && !host) {
1.188 markus 911: if (strrchr(*av, '@')) {
1.128 fgsch 912: p = xstrdup(*av);
1.188 markus 913: cp = strrchr(p, '@');
1.128 fgsch 914: if (cp == NULL || cp == p)
915: usage();
916: options.user = p;
917: *cp = '\0';
1.385 djm 918: host = xstrdup(++cp);
1.128 fgsch 919: } else
1.385 djm 920: host = xstrdup(*av);
1.189 millert 921: if (ac > 1) {
922: optind = optreset = 1;
1.128 fgsch 923: goto again;
924: }
1.189 millert 925: ac--, av++;
1.128 fgsch 926: }
927:
1.31 markus 928: /* Check that we got a host name. */
929: if (!host)
930: usage();
931:
1.385 djm 932: host_arg = xstrdup(host);
933:
1.402 markus 934: #ifdef WITH_OPENSSL
1.350 djm 935: OpenSSL_add_all_algorithms();
1.72 markus 936: ERR_load_crypto_strings();
1.402 markus 937: #endif
1.31 markus 938:
939: /* Initialize the command to execute on remote host. */
940: buffer_init(&command);
1.1 deraadt 941:
1.33 markus 942: /*
943: * Save the command to execute on the remote host in a buffer. There
944: * is no limit on the length of the command, except by the maximum
945: * packet size. Also sets the tty flag if there is no command.
946: */
1.128 fgsch 947: if (!ac) {
1.31 markus 948: /* No command specified - execute shell on a tty. */
1.85 djm 949: if (subsystem_flag) {
1.128 fgsch 950: fprintf(stderr,
951: "You must specify a subsystem to invoke.\n");
1.85 djm 952: usage();
953: }
1.31 markus 954: } else {
1.128 fgsch 955: /* A command has been specified. Store it into the buffer. */
956: for (i = 0; i < ac; i++) {
957: if (i)
1.31 markus 958: buffer_append(&command, " ", 1);
959: buffer_append(&command, av[i], strlen(av[i]));
960: }
961: }
962:
963: /* Cannot fork to background if no command. */
1.316 djm 964: if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
965: !no_shell_flag)
966: fatal("Cannot fork into background without a command "
967: "to execute.");
1.31 markus 968:
1.101 markus 969: /*
970: * Initialize "log" output. Since we are the client all output
1.375 dtucker 971: * goes to stderr unless otherwise specified by -y or -E.
1.101 markus 972: */
1.375 dtucker 973: if (use_syslog && logfile != NULL)
974: fatal("Can't specify both -y and -E");
1.422 dtucker 975: if (logfile != NULL)
1.375 dtucker 976: log_redirect_stderr_to(logfile);
1.325 markus 977: log_init(argv0,
1.316 djm 978: options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
1.320 djm 979: SYSLOG_FACILITY_USER, !use_syslog);
1.375 dtucker 980:
981: if (debug_flag)
1.402 markus 982: logit("%s, %s", SSH_VERSION,
983: #ifdef WITH_OPENSSL
984: SSLeay_version(SSLEAY_VERSION)
985: #else
986: "without OpenSSL"
987: #endif
988: );
1.31 markus 989:
1.400 djm 990: /* Parse the configuration files */
1.408 djm 991: process_config_files(host_arg, pw, 0);
1.400 djm 992:
993: /* Hostname canonicalisation needs a few options filled. */
994: fill_default_options_for_canonicalization(&options);
995:
996: /* If the user has replaced the hostname then take it into use now */
997: if (options.hostname != NULL) {
998: /* NB. Please keep in sync with readconf.c:match_cfg_line() */
999: cp = percent_expand(options.hostname,
1000: "h", host, (char *)NULL);
1001: free(host);
1002: host = cp;
1.408 djm 1003: free(options.hostname);
1004: options.hostname = xstrdup(host);
1.400 djm 1005: }
1006:
1007: /* If canonicalization requested then try to apply it */
1008: lowercase(host);
1009: if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
1010: addrs = resolve_canonicalize(&host, options.port);
1011:
1.139 markus 1012: /*
1.401 djm 1013: * If CanonicalizePermittedCNAMEs have been specified but
1014: * other canonicalization did not happen (by not being requested
1015: * or by failing with fallback) then the hostname may still be changed
1016: * as a result of CNAME following.
1017: *
1018: * Try to resolve the bare hostname name using the system resolver's
1019: * usual search rules and then apply the CNAME follow rules.
1020: *
1021: * Skip the lookup if a ProxyCommand is being used unless the user
1022: * has specifically requested canonicalisation for this case via
1023: * CanonicalizeHostname=always
1.139 markus 1024: */
1.443 djm 1025: direct = option_clear_or_none(options.proxy_command) &&
1026: options.jump_host == NULL;
1027: if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1028: options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1.403 djm 1029: if ((addrs = resolve_host(host, options.port,
1030: option_clear_or_none(options.proxy_command),
1031: cname, sizeof(cname))) == NULL) {
1032: /* Don't fatal proxied host names not in the DNS */
1033: if (option_clear_or_none(options.proxy_command))
1034: cleanup_exit(255); /* logged in resolve_host */
1035: } else
1.443 djm 1036: check_follow_cname(direct, &host, cname);
1.400 djm 1037: }
1.139 markus 1038:
1.400 djm 1039: /*
1.408 djm 1040: * If canonicalisation is enabled then re-parse the configuration
1041: * files as new stanzas may match.
1.400 djm 1042: */
1.408 djm 1043: if (options.canonicalize_hostname != 0) {
1044: debug("Re-reading configuration after hostname "
1045: "canonicalisation");
1046: free(options.hostname);
1047: options.hostname = xstrdup(host);
1048: process_config_files(host_arg, pw, 1);
1049: /*
1050: * Address resolution happens early with canonicalisation
1051: * enabled and the port number may have changed since, so
1052: * reset it in address list
1053: */
1054: if (addrs != NULL && options.port > 0)
1055: set_addrinfo_port(addrs, options.port);
1.139 markus 1056: }
1.31 markus 1057:
1058: /* Fill configuration defaults. */
1059: fill_default_options(&options);
1.443 djm 1060:
1061: /*
1062: * If ProxyJump option specified, then construct a ProxyCommand now.
1063: */
1064: if (options.jump_host != NULL) {
1065: char port_s[8];
1066:
1067: /* Consistency check */
1068: if (options.proxy_command != NULL)
1069: fatal("inconsistent options: ProxyCommand+ProxyJump");
1070: /* Never use FD passing for ProxyJump */
1071: options.proxy_use_fdpass = 0;
1072: snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1073: xasprintf(&options.proxy_command,
1074: "ssh%s%s%s%s%s%s%s%s%s%.*s -W %%h:%%p %s",
1075: /* Optional "-l user" argument if jump_user set */
1076: options.jump_user == NULL ? "" : " -l ",
1077: options.jump_user == NULL ? "" : options.jump_user,
1078: /* Optional "-p port" argument if jump_port set */
1079: options.jump_port <= 0 ? "" : " -p ",
1080: options.jump_port <= 0 ? "" : port_s,
1081: /* Optional additional jump hosts ",..." */
1082: options.jump_extra == NULL ? "" : " -J ",
1083: options.jump_extra == NULL ? "" : options.jump_extra,
1084: /* Optional "-F" argumment if -F specified */
1085: config == NULL ? "" : " -F ",
1086: config == NULL ? "" : config,
1087: /* Optional "-v" arguments if -v set */
1088: debug_flag ? " -" : "",
1089: debug_flag, "vvv",
1090: /* Mandatory hostname */
1091: options.jump_host);
1092: debug("Setting implicit ProxyCommand from ProxyJump: %s",
1093: options.proxy_command);
1094: }
1.31 markus 1095:
1.400 djm 1096: if (options.port == 0)
1097: options.port = default_ssh_port();
1.196 djm 1098: channel_set_af(options.address_family);
1099:
1.383 djm 1100: /* Tidy and check options */
1101: if (options.host_key_alias != NULL)
1102: lowercase(options.host_key_alias);
1103: if (options.proxy_command != NULL &&
1104: strcmp(options.proxy_command, "-") == 0 &&
1105: options.proxy_use_fdpass)
1106: fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1.415 djm 1107: if (options.control_persist &&
1108: options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1109: debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1110: "disabling");
1111: options.update_hostkeys = 0;
1112: }
1.430 djm 1113: if (options.connection_attempts <= 0)
1114: fatal("Invalid number of ConnectionAttempts");
1115:
1.388 djm 1116: if (original_effective_uid != 0)
1117: options.use_privileged_port = 0;
1.383 djm 1118:
1.31 markus 1119: /* reinit */
1.325 markus 1120: log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
1.370 djm 1121:
1122: if (options.request_tty == REQUEST_TTY_YES ||
1123: options.request_tty == REQUEST_TTY_FORCE)
1124: tty_flag = 1;
1125:
1126: /* Allocate a tty by default if no command specified. */
1127: if (buffer_len(&command) == 0)
1128: tty_flag = options.request_tty != REQUEST_TTY_NO;
1129:
1130: /* Force no tty */
1131: if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
1132: tty_flag = 0;
1133: /* Do not allocate a tty if stdin is not a tty. */
1134: if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1135: options.request_tty != REQUEST_TTY_FORCE) {
1136: if (tty_flag)
1137: logit("Pseudo-terminal will not be allocated because "
1138: "stdin is not a terminal.");
1139: tty_flag = 0;
1140: }
1.31 markus 1141:
1142: if (options.user == NULL)
1143: options.user = xstrdup(pw->pw_name);
1.343 djm 1144:
1.358 djm 1145: if (gethostname(thishost, sizeof(thishost)) == -1)
1146: fatal("gethostname: %s", strerror(errno));
1147: strlcpy(shorthost, thishost, sizeof(shorthost));
1148: shorthost[strcspn(thishost, ".")] = '\0';
1149: snprintf(portstr, sizeof(portstr), "%d", options.port);
1.423 djm 1150: snprintf(uidstr, sizeof(uidstr), "%d", pw->pw_uid);
1.358 djm 1151:
1.405 djm 1152: if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1153: ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1154: ssh_digest_update(md, host, strlen(host)) < 0 ||
1155: ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1156: ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1157: ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1158: fatal("%s: mux digest failed", __func__);
1159: ssh_digest_free(md);
1160: conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1161:
1.317 dtucker 1162: if (options.local_command != NULL) {
1163: debug3("expanding LocalCommand: %s", options.local_command);
1164: cp = options.local_command;
1.405 djm 1165: options.local_command = percent_expand(cp,
1166: "C", conn_hash_hex,
1167: "L", shorthost,
1168: "d", pw->pw_dir,
1169: "h", host,
1170: "l", thishost,
1171: "n", host_arg,
1172: "p", portstr,
1173: "r", options.user,
1174: "u", pw->pw_name,
1.358 djm 1175: (char *)NULL);
1.317 dtucker 1176: debug3("expanded LocalCommand: %s", options.local_command);
1.378 djm 1177: free(cp);
1.304 dtucker 1178: }
1.31 markus 1179:
1.214 djm 1180: if (options.control_path != NULL) {
1.241 djm 1181: cp = tilde_expand_filename(options.control_path,
1182: original_real_uid);
1.378 djm 1183: free(options.control_path);
1.405 djm 1184: options.control_path = percent_expand(cp,
1185: "C", conn_hash_hex,
1186: "L", shorthost,
1187: "h", host,
1188: "l", thishost,
1189: "n", host_arg,
1190: "p", portstr,
1191: "r", options.user,
1192: "u", pw->pw_name,
1.423 djm 1193: "i", uidstr,
1.358 djm 1194: (char *)NULL);
1.378 djm 1195: free(cp);
1.214 djm 1196: }
1.405 djm 1197: free(conn_hash_hex);
1.408 djm 1198:
1199: if (config_test) {
1200: dump_client_config(&options, host);
1201: exit(0);
1202: }
1.405 djm 1203:
1.312 djm 1204: if (muxclient_command != 0 && options.control_path == NULL)
1.240 djm 1205: fatal("No ControlPath specified for \"-O\" command");
1.242 djm 1206: if (options.control_path != NULL)
1.312 djm 1207: muxclient(options.control_path);
1.401 djm 1208:
1209: /*
1210: * If hostname canonicalisation was not enabled, then we may not
1211: * have yet resolved the hostname. Do so now.
1212: */
1213: if (addrs == NULL && options.proxy_command == NULL) {
1.421 djm 1214: debug2("resolving \"%s\" port %d", host, options.port);
1.401 djm 1215: if ((addrs = resolve_host(host, options.port, 1,
1216: cname, sizeof(cname))) == NULL)
1217: cleanup_exit(255); /* resolve_host logs the error */
1218: }
1.214 djm 1219:
1.303 djm 1220: timeout_ms = options.connection_timeout * 1000;
1221:
1.77 markus 1222: /* Open a connection to the remote host. */
1.385 djm 1223: if (ssh_connect(host, addrs, &hostaddr, options.port,
1224: options.address_family, options.connection_attempts,
1225: &timeout_ms, options.tcp_keep_alive,
1.388 djm 1226: options.use_privileged_port) != 0)
1.257 dtucker 1227: exit(255);
1.31 markus 1228:
1.391 djm 1229: if (addrs != NULL)
1230: freeaddrinfo(addrs);
1231:
1.385 djm 1232: packet_set_timeout(options.server_alive_interval,
1233: options.server_alive_count_max);
1234:
1.437 djm 1235: ssh = active_state; /* XXX */
1236:
1.303 djm 1237: if (timeout_ms > 0)
1238: debug3("timeout: %d ms remain after connect", timeout_ms);
1239:
1.33 markus 1240: /*
1241: * If we successfully made the connection, load the host private key
1242: * in case we will need it later for combined rsa-rhosts
1243: * authentication. This must be done before releasing extra
1244: * privileges, because the file is only readable by root.
1.174 markus 1245: * If we cannot access the private keys, load the public keys
1246: * instead and try to execute the ssh-keysign helper instead.
1.33 markus 1247: */
1.112 markus 1248: sensitive_data.nkeys = 0;
1249: sensitive_data.keys = NULL;
1.173 markus 1250: sensitive_data.external_keysign = 0;
1.178 markus 1251: if (options.rhosts_rsa_authentication ||
1252: options.hostbased_authentication) {
1.397 djm 1253: sensitive_data.nkeys = 9;
1.274 deraadt 1254: sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1.180 deraadt 1255: sizeof(Key));
1.177 markus 1256:
1257: PRIV_START;
1.432 djm 1258: #if WITH_SSH1
1.112 markus 1259: sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1.276 dtucker 1260: _PATH_HOST_KEY_FILE, "", NULL, NULL);
1.432 djm 1261: #endif
1.411 djm 1262: sensitive_data.keys[1] = key_load_private_cert(KEY_ECDSA,
1.349 djm 1263: _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1.411 djm 1264: sensitive_data.keys[2] = key_load_private_cert(KEY_ED25519,
1265: _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1.349 djm 1266: sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1.345 djm 1267: _PATH_HOST_RSA_KEY_FILE, "", NULL);
1.411 djm 1268: sensitive_data.keys[4] = key_load_private_cert(KEY_DSA,
1269: _PATH_HOST_DSA_KEY_FILE, "", NULL);
1270: sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
1.349 djm 1271: _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1.411 djm 1272: sensitive_data.keys[6] = key_load_private_type(KEY_ED25519,
1273: _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1.397 djm 1274: sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1.276 dtucker 1275: _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1.411 djm 1276: sensitive_data.keys[8] = key_load_private_type(KEY_DSA,
1277: _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1.177 markus 1278: PRIV_END;
1.173 markus 1279:
1.181 markus 1280: if (options.hostbased_authentication == 1 &&
1281: sensitive_data.keys[0] == NULL &&
1.349 djm 1282: sensitive_data.keys[5] == NULL &&
1.396 markus 1283: sensitive_data.keys[6] == NULL &&
1.397 djm 1284: sensitive_data.keys[7] == NULL &&
1285: sensitive_data.keys[8] == NULL) {
1.345 djm 1286: sensitive_data.keys[1] = key_load_cert(
1.411 djm 1287: _PATH_HOST_ECDSA_KEY_FILE);
1.345 djm 1288: sensitive_data.keys[2] = key_load_cert(
1.411 djm 1289: _PATH_HOST_ED25519_KEY_FILE);
1.349 djm 1290: sensitive_data.keys[3] = key_load_cert(
1.345 djm 1291: _PATH_HOST_RSA_KEY_FILE);
1.397 djm 1292: sensitive_data.keys[4] = key_load_cert(
1.411 djm 1293: _PATH_HOST_DSA_KEY_FILE);
1.397 djm 1294: sensitive_data.keys[5] = key_load_public(
1.411 djm 1295: _PATH_HOST_ECDSA_KEY_FILE, NULL);
1.397 djm 1296: sensitive_data.keys[6] = key_load_public(
1.411 djm 1297: _PATH_HOST_ED25519_KEY_FILE, NULL);
1.397 djm 1298: sensitive_data.keys[7] = key_load_public(
1.173 markus 1299: _PATH_HOST_RSA_KEY_FILE, NULL);
1.397 djm 1300: sensitive_data.keys[8] = key_load_public(
1.411 djm 1301: _PATH_HOST_DSA_KEY_FILE, NULL);
1.173 markus 1302: sensitive_data.external_keysign = 1;
1303: }
1.31 markus 1304: }
1.33 markus 1305: /*
1306: * Get rid of any extra privileges that we may have. We will no
1307: * longer need them. Also, extra privileges could make it very hard
1308: * to read identity files and other non-world-readable files from the
1309: * user's home directory if it happens to be on a NFS volume where
1310: * root is mapped to nobody.
1311: */
1.225 dtucker 1312: if (original_effective_uid == 0) {
1313: PRIV_START;
1314: permanently_set_uid(pw);
1315: }
1.31 markus 1316:
1.33 markus 1317: /*
1318: * Now that we are back to our own permissions, create ~/.ssh
1.254 djm 1319: * directory if it doesn't already exist.
1.33 markus 1320: */
1.367 djm 1321: if (config == NULL) {
1322: r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1323: strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1324: if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
1325: if (mkdir(buf, 0700) < 0)
1326: error("Could not create directory '%.200s'.",
1327: buf);
1328: }
1.31 markus 1329:
1.104 markus 1330: /* load options.identity_files */
1331: load_public_identity_files();
1.439 markus 1332:
1333: /* optionally set the SSH_AUTHSOCKET_ENV_NAME varibale */
1.440 markus 1334: if (options.identity_agent &&
1335: strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1.439 markus 1336: if (strcmp(options.identity_agent, "none") == 0) {
1337: unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1338: } else {
1339: p = tilde_expand_filename(options.identity_agent,
1340: original_real_uid);
1341: cp = percent_expand(p, "d", pw->pw_dir,
1342: "u", pw->pw_name, "l", thishost, "h", host,
1343: "r", options.user, (char *)NULL);
1344: setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1345: free(cp);
1346: free(p);
1347: }
1348: }
1.104 markus 1349:
1350: /* Expand ~ in known host file names. */
1.361 djm 1351: tilde_expand_paths(options.system_hostfiles,
1352: options.num_system_hostfiles);
1353: tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1.149 markus 1354:
1355: signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.352 djm 1356: signal(SIGCHLD, main_sigchld_handler);
1.31 markus 1357:
1.316 djm 1358: /* Log into the remote system. Never returns if the login fails. */
1.303 djm 1359: ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1.355 djm 1360: options.port, pw, timeout_ms);
1.339 djm 1361:
1362: if (packet_connection_is_on_socket()) {
1363: verbose("Authenticated to %s ([%s]:%d).", host,
1.437 djm 1364: ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.339 djm 1365: } else {
1366: verbose("Authenticated to %s (via proxy).", host);
1367: }
1.31 markus 1368:
1.112 markus 1369: /* We no longer need the private host keys. Clear them now. */
1370: if (sensitive_data.nkeys != 0) {
1371: for (i = 0; i < sensitive_data.nkeys; i++) {
1372: if (sensitive_data.keys[i] != NULL) {
1373: /* Destroys contents safely */
1374: debug3("clear hostkey %d", i);
1375: key_free(sensitive_data.keys[i]);
1376: sensitive_data.keys[i] = NULL;
1377: }
1378: }
1.378 djm 1379: free(sensitive_data.keys);
1.134 markus 1380: }
1381: for (i = 0; i < options.num_identity_files; i++) {
1.378 djm 1382: free(options.identity_files[i]);
1383: options.identity_files[i] = NULL;
1.134 markus 1384: if (options.identity_keys[i]) {
1385: key_free(options.identity_keys[i]);
1386: options.identity_keys[i] = NULL;
1387: }
1.112 markus 1388: }
1.426 djm 1389: for (i = 0; i < options.num_certificate_files; i++) {
1390: free(options.certificate_files[i]);
1391: options.certificate_files[i] = NULL;
1392: }
1.31 markus 1393:
1.45 markus 1394: exit_status = compat20 ? ssh_session2() : ssh_session();
1395: packet_close();
1.186 djm 1396:
1.312 djm 1397: if (options.control_path != NULL && muxserver_sock != -1)
1.214 djm 1398: unlink(options.control_path);
1399:
1.353 djm 1400: /* Kill ProxyCommand if it is running. */
1401: ssh_kill_proxy_command();
1.186 djm 1402:
1.45 markus 1403: return exit_status;
1404: }
1405:
1.344 djm 1406: static void
1407: control_persist_detach(void)
1408: {
1409: pid_t pid;
1.438 djm 1410: int devnull, keep_stderr;
1.344 djm 1411:
1412: debug("%s: backgrounding master process", __func__);
1413:
1414: /*
1415: * master (current process) into the background, and make the
1416: * foreground process a client of the backgrounded master.
1417: */
1418: switch ((pid = fork())) {
1419: case -1:
1420: fatal("%s: fork: %s", __func__, strerror(errno));
1421: case 0:
1422: /* Child: master process continues mainloop */
1423: break;
1424: default:
1425: /* Parent: set up mux slave to connect to backgrounded master */
1426: debug2("%s: background process is %ld", __func__, (long)pid);
1427: stdin_null_flag = ostdin_null_flag;
1.359 djm 1428: options.request_tty = orequest_tty;
1.344 djm 1429: tty_flag = otty_flag;
1430: close(muxserver_sock);
1431: muxserver_sock = -1;
1.351 markus 1432: options.control_master = SSHCTL_MASTER_NO;
1.344 djm 1433: muxclient(options.control_path);
1434: /* muxclient() doesn't return on success. */
1435: fatal("Failed to connect to new control master");
1436: }
1.346 djm 1437: if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1438: error("%s: open(\"/dev/null\"): %s", __func__,
1439: strerror(errno));
1440: } else {
1.438 djm 1441: keep_stderr = log_is_on_stderr() && debug_flag;
1.346 djm 1442: if (dup2(devnull, STDIN_FILENO) == -1 ||
1.438 djm 1443: dup2(devnull, STDOUT_FILENO) == -1 ||
1444: (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
1.346 djm 1445: error("%s: dup2: %s", __func__, strerror(errno));
1446: if (devnull > STDERR_FILENO)
1447: close(devnull);
1448: }
1.381 djm 1449: daemon(1, 1);
1.362 djm 1450: setproctitle("%s [mux]", options.control_path);
1.344 djm 1451: }
1452:
1453: /* Do fork() after authentication. Used by "ssh -f" */
1454: static void
1455: fork_postauth(void)
1456: {
1457: if (need_controlpersist_detach)
1458: control_persist_detach();
1459: debug("forking to background");
1460: fork_after_authentication_flag = 0;
1461: if (daemon(1, 1) < 0)
1462: fatal("daemon() failed: %.200s", strerror(errno));
1463: }
1464:
1.315 djm 1465: /* Callback for remote forward global requests */
1466: static void
1467: ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1468: {
1.406 millert 1469: struct Forward *rfwd = (struct Forward *)ctxt;
1.315 djm 1470:
1.324 djm 1471: /* XXX verbose() on failure? */
1.404 markus 1472: debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1.315 djm 1473: type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1.406 millert 1474: rfwd->listen_path ? rfwd->listen_path :
1475: rfwd->listen_host ? rfwd->listen_host : "",
1476: (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1477: rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1478: rfwd->connect_host, rfwd->connect_port);
1479: if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1.366 markus 1480: if (type == SSH2_MSG_REQUEST_SUCCESS) {
1481: rfwd->allocated_port = packet_get_int();
1482: logit("Allocated port %u for remote forward to %s:%d",
1483: rfwd->allocated_port,
1484: rfwd->connect_host, rfwd->connect_port);
1485: channel_update_permitted_opens(rfwd->handle,
1486: rfwd->allocated_port);
1487: } else {
1488: channel_update_permitted_opens(rfwd->handle, -1);
1489: }
1.324 djm 1490: }
1491:
1.315 djm 1492: if (type == SSH2_MSG_REQUEST_FAILURE) {
1.406 millert 1493: if (options.exit_on_forward_failure) {
1494: if (rfwd->listen_path != NULL)
1495: fatal("Error: remote port forwarding failed "
1496: "for listen path %s", rfwd->listen_path);
1497: else
1498: fatal("Error: remote port forwarding failed "
1499: "for listen port %d", rfwd->listen_port);
1500: } else {
1501: if (rfwd->listen_path != NULL)
1502: logit("Warning: remote port forwarding failed "
1503: "for listen path %s", rfwd->listen_path);
1504: else
1505: logit("Warning: remote port forwarding failed "
1506: "for listen port %d", rfwd->listen_port);
1507: }
1.315 djm 1508: }
1.318 djm 1509: if (++remote_forward_confirms_received == options.num_remote_forwards) {
1.315 djm 1510: debug("All remote forwarding requests processed");
1.344 djm 1511: if (fork_after_authentication_flag)
1512: fork_postauth();
1.318 djm 1513: }
1.315 djm 1514: }
1515:
1.126 itojun 1516: static void
1.331 dtucker 1517: client_cleanup_stdio_fwd(int id, void *arg)
1518: {
1519: debug("stdio forwarding: done");
1520: cleanup_exit(0);
1521: }
1522:
1.368 djm 1523: static void
1.407 djm 1524: ssh_stdio_confirm(int id, int success, void *arg)
1525: {
1526: if (!success)
1527: fatal("stdio forwarding failed");
1528: }
1529:
1530: static void
1.368 djm 1531: ssh_init_stdio_forwarding(void)
1.331 dtucker 1532: {
1533: Channel *c;
1.332 djm 1534: int in, out;
1.331 dtucker 1535:
1.441 dtucker 1536: if (options.stdio_forward_host == NULL)
1.368 djm 1537: return;
1.384 djm 1538: if (!compat20)
1.368 djm 1539: fatal("stdio forwarding require Protocol 2");
1540:
1.441 dtucker 1541: debug3("%s: %s:%d", __func__, options.stdio_forward_host,
1542: options.stdio_forward_port);
1.332 djm 1543:
1.368 djm 1544: if ((in = dup(STDIN_FILENO)) < 0 ||
1545: (out = dup(STDOUT_FILENO)) < 0)
1.332 djm 1546: fatal("channel_connect_stdio_fwd: dup() in/out failed");
1.441 dtucker 1547: if ((c = channel_connect_stdio_fwd(options.stdio_forward_host,
1548: options.stdio_forward_port, in, out)) == NULL)
1.368 djm 1549: fatal("%s: channel_connect_stdio_fwd failed", __func__);
1.331 dtucker 1550: channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1.407 djm 1551: channel_register_open_confirm(c->self, ssh_stdio_confirm, NULL);
1.331 dtucker 1552: }
1553:
1554: static void
1.70 markus 1555: ssh_init_forwarding(void)
1556: {
1.86 markus 1557: int success = 0;
1.70 markus 1558: int i;
1.331 dtucker 1559:
1.70 markus 1560: /* Initiate local TCP/IP port forwardings. */
1561: for (i = 0; i < options.num_local_forwards; i++) {
1.232 djm 1562: debug("Local connections to %.200s:%d forwarded to remote "
1563: "address %.200s:%d",
1.406 millert 1564: (options.local_forwards[i].listen_path != NULL) ?
1565: options.local_forwards[i].listen_path :
1.234 deraadt 1566: (options.local_forwards[i].listen_host == NULL) ?
1.406 millert 1567: (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1.232 djm 1568: options.local_forwards[i].listen_host,
1569: options.local_forwards[i].listen_port,
1.406 millert 1570: (options.local_forwards[i].connect_path != NULL) ?
1571: options.local_forwards[i].connect_path :
1.232 djm 1572: options.local_forwards[i].connect_host,
1573: options.local_forwards[i].connect_port);
1.158 markus 1574: success += channel_setup_local_fwd_listener(
1.406 millert 1575: &options.local_forwards[i], &options.fwd_opts);
1.70 markus 1576: }
1.283 markus 1577: if (i > 0 && success != i && options.exit_on_forward_failure)
1578: fatal("Could not request local forwarding.");
1.86 markus 1579: if (i > 0 && success == 0)
1580: error("Could not request local forwarding.");
1.70 markus 1581:
1582: /* Initiate remote TCP/IP port forwardings. */
1583: for (i = 0; i < options.num_remote_forwards; i++) {
1.232 djm 1584: debug("Remote connections from %.200s:%d forwarded to "
1585: "local address %.200s:%d",
1.406 millert 1586: (options.remote_forwards[i].listen_path != NULL) ?
1587: options.remote_forwards[i].listen_path :
1.248 djm 1588: (options.remote_forwards[i].listen_host == NULL) ?
1.253 djm 1589: "LOCALHOST" : options.remote_forwards[i].listen_host,
1.232 djm 1590: options.remote_forwards[i].listen_port,
1.406 millert 1591: (options.remote_forwards[i].connect_path != NULL) ?
1592: options.remote_forwards[i].connect_path :
1.232 djm 1593: options.remote_forwards[i].connect_host,
1594: options.remote_forwards[i].connect_port);
1.366 markus 1595: options.remote_forwards[i].handle =
1596: channel_request_remote_forwarding(
1.406 millert 1597: &options.remote_forwards[i]);
1.366 markus 1598: if (options.remote_forwards[i].handle < 0) {
1.283 markus 1599: if (options.exit_on_forward_failure)
1600: fatal("Could not request remote forwarding.");
1601: else
1602: logit("Warning: Could not request remote "
1603: "forwarding.");
1.366 markus 1604: } else {
1605: client_register_global_confirm(ssh_confirm_remote_forward,
1606: &options.remote_forwards[i]);
1.283 markus 1607: }
1.70 markus 1608: }
1.301 djm 1609:
1610: /* Initiate tunnel forwarding. */
1611: if (options.tun_open != SSH_TUNMODE_NO) {
1612: if (client_request_tun_fwd(options.tun_open,
1613: options.tun_local, options.tun_remote) == -1) {
1614: if (options.exit_on_forward_failure)
1615: fatal("Could not request tunnel forwarding.");
1616: else
1617: error("Could not request tunnel forwarding.");
1618: }
1619: }
1.70 markus 1620: }
1621:
1.126 itojun 1622: static void
1.70 markus 1623: check_agent_present(void)
1624: {
1.412 djm 1625: int r;
1626:
1.70 markus 1627: if (options.forward_agent) {
1.254 djm 1628: /* Clear agent forwarding if we don't have an agent. */
1.412 djm 1629: if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1.70 markus 1630: options.forward_agent = 0;
1.412 djm 1631: if (r != SSH_ERR_AGENT_NOT_PRESENT)
1632: debug("ssh_get_authentication_socket: %s",
1633: ssh_err(r));
1634: }
1.70 markus 1635: }
1636: }
1637:
1.126 itojun 1638: static int
1.45 markus 1639: ssh_session(void)
1640: {
1641: int type;
1642: int interactive = 0;
1643: int have_tty = 0;
1644: struct winsize ws;
1645: char *cp;
1.243 djm 1646: const char *display;
1.433 djm 1647: char *proto = NULL, *data = NULL;
1.45 markus 1648:
1.31 markus 1649: /* Enable compression if requested. */
1650: if (options.compression) {
1.316 djm 1651: debug("Requesting compression at level %d.",
1652: options.compression_level);
1.31 markus 1653:
1.316 djm 1654: if (options.compression_level < 1 ||
1655: options.compression_level > 9)
1656: fatal("Compression level must be from 1 (fast) to "
1657: "9 (slow, best).");
1.31 markus 1658:
1659: /* Send the request. */
1660: packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1661: packet_put_int(options.compression_level);
1662: packet_send();
1663: packet_write_wait();
1.156 markus 1664: type = packet_read();
1.31 markus 1665: if (type == SSH_SMSG_SUCCESS)
1666: packet_start_compression(options.compression_level);
1667: else if (type == SSH_SMSG_FAILURE)
1.191 itojun 1668: logit("Warning: Remote host refused compression.");
1.31 markus 1669: else
1.316 djm 1670: packet_disconnect("Protocol error waiting for "
1671: "compression response.");
1.31 markus 1672: }
1673: /* Allocate a pseudo tty if appropriate. */
1674: if (tty_flag) {
1675: debug("Requesting pty.");
1676:
1677: /* Start the packet. */
1678: packet_start(SSH_CMSG_REQUEST_PTY);
1679:
1680: /* Store TERM in the packet. There is no limit on the
1681: length of the string. */
1682: cp = getenv("TERM");
1683: if (!cp)
1684: cp = "";
1.124 markus 1685: packet_put_cstring(cp);
1.31 markus 1686:
1687: /* Store window size in the packet. */
1688: if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1689: memset(&ws, 0, sizeof(ws));
1.269 deraadt 1690: packet_put_int((u_int)ws.ws_row);
1691: packet_put_int((u_int)ws.ws_col);
1692: packet_put_int((u_int)ws.ws_xpixel);
1693: packet_put_int((u_int)ws.ws_ypixel);
1.31 markus 1694:
1695: /* Store tty modes in the packet. */
1.115 stevesk 1696: tty_make_modes(fileno(stdin), NULL);
1.31 markus 1697:
1698: /* Send the packet, and wait for it to leave. */
1699: packet_send();
1700: packet_write_wait();
1701:
1702: /* Read response from the server. */
1.156 markus 1703: type = packet_read();
1.43 markus 1704: if (type == SSH_SMSG_SUCCESS) {
1.31 markus 1705: interactive = 1;
1.45 markus 1706: have_tty = 1;
1.43 markus 1707: } else if (type == SSH_SMSG_FAILURE)
1.316 djm 1708: logit("Warning: Remote host failed or refused to "
1709: "allocate a pseudo tty.");
1.31 markus 1710: else
1.316 djm 1711: packet_disconnect("Protocol error waiting for pty "
1712: "request response.");
1.31 markus 1713: }
1714: /* Request X11 forwarding if enabled and DISPLAY is set. */
1.243 djm 1715: display = getenv("DISPLAY");
1.417 djm 1716: if (display == NULL && options.forward_x11)
1717: debug("X11 forwarding requested but DISPLAY not set");
1.433 djm 1718: if (options.forward_x11 && client_x11_get_proto(display,
1719: options.xauth_location, options.forward_x11_trusted,
1720: options.forward_x11_timeout, &proto, &data) == 0) {
1.50 markus 1721: /* Request forwarding with authentication spoofing. */
1.316 djm 1722: debug("Requesting X11 forwarding with authentication "
1723: "spoofing.");
1.363 djm 1724: x11_request_forwarding_with_spoofing(0, display, proto,
1725: data, 0);
1.31 markus 1726: /* Read response from the server. */
1.156 markus 1727: type = packet_read();
1.31 markus 1728: if (type == SSH_SMSG_SUCCESS) {
1729: interactive = 1;
1.50 markus 1730: } else if (type == SSH_SMSG_FAILURE) {
1.191 itojun 1731: logit("Warning: Remote host denied X11 forwarding.");
1.50 markus 1732: } else {
1.316 djm 1733: packet_disconnect("Protocol error waiting for X11 "
1734: "forwarding");
1.50 markus 1735: }
1.31 markus 1736: }
1737: /* Tell the packet module whether this is an interactive session. */
1.354 djm 1738: packet_set_interactive(interactive,
1739: options.ip_qos_interactive, options.ip_qos_bulk);
1.31 markus 1740:
1741: /* Request authentication agent forwarding if appropriate. */
1.70 markus 1742: check_agent_present();
1743:
1.31 markus 1744: if (options.forward_agent) {
1745: debug("Requesting authentication agent forwarding.");
1746: auth_request_forwarding();
1747:
1748: /* Read response from the server. */
1.156 markus 1749: type = packet_read();
1.155 markus 1750: packet_check_eom();
1.31 markus 1751: if (type != SSH_SMSG_SUCCESS)
1.191 itojun 1752: logit("Warning: Remote host denied authentication agent forwarding.");
1.31 markus 1753: }
1754:
1.70 markus 1755: /* Initiate port forwardings. */
1.368 djm 1756: ssh_init_stdio_forwarding();
1.70 markus 1757: ssh_init_forwarding();
1.305 dtucker 1758:
1759: /* Execute a local command */
1760: if (options.local_command != NULL &&
1761: options.permit_local_command)
1762: ssh_local_cmd(options.local_command);
1.34 markus 1763:
1.318 djm 1764: /*
1765: * If requested and we are not interested in replies to remote
1766: * forwarding requests, then let ssh continue in the background.
1767: */
1.344 djm 1768: if (fork_after_authentication_flag) {
1769: if (options.exit_on_forward_failure &&
1770: options.num_remote_forwards > 0) {
1771: debug("deferring postauth fork until remote forward "
1772: "confirmation received");
1773: } else
1774: fork_postauth();
1.318 djm 1775: }
1.31 markus 1776:
1.33 markus 1777: /*
1778: * If a command was specified on the command line, execute the
1779: * command now. Otherwise request the server to start a shell.
1780: */
1.31 markus 1781: if (buffer_len(&command) > 0) {
1782: int len = buffer_len(&command);
1783: if (len > 900)
1784: len = 900;
1.316 djm 1785: debug("Sending command: %.*s", len,
1786: (u_char *)buffer_ptr(&command));
1.31 markus 1787: packet_start(SSH_CMSG_EXEC_CMD);
1788: packet_put_string(buffer_ptr(&command), buffer_len(&command));
1789: packet_send();
1790: packet_write_wait();
1791: } else {
1792: debug("Requesting shell.");
1793: packet_start(SSH_CMSG_EXEC_SHELL);
1794: packet_send();
1795: packet_write_wait();
1796: }
1797:
1798: /* Enter the interactive session. */
1.119 stevesk 1799: return client_loop(have_tty, tty_flag ?
1800: options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1.89 markus 1801: }
1802:
1.214 djm 1803: /* request pty/x11/agent/tcpfwd/shell for channel */
1804: static void
1.337 djm 1805: ssh_session2_setup(int id, int success, void *arg)
1.214 djm 1806: {
1.215 djm 1807: extern char **environ;
1.243 djm 1808: const char *display;
1809: int interactive = tty_flag;
1.433 djm 1810: char *proto = NULL, *data = NULL;
1.337 djm 1811:
1812: if (!success)
1813: return; /* No need for error message, channels code sens one */
1.215 djm 1814:
1.248 djm 1815: display = getenv("DISPLAY");
1.417 djm 1816: if (display == NULL && options.forward_x11)
1817: debug("X11 forwarding requested but DISPLAY not set");
1.433 djm 1818: if (options.forward_x11 && client_x11_get_proto(display,
1819: options.xauth_location, options.forward_x11_trusted,
1820: options.forward_x11_timeout, &proto, &data) == 0) {
1.50 markus 1821: /* Request forwarding with authentication spoofing. */
1.316 djm 1822: debug("Requesting X11 forwarding with authentication "
1823: "spoofing.");
1.363 djm 1824: x11_request_forwarding_with_spoofing(id, display, proto,
1825: data, 1);
1826: client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1827: /* XXX exit_on_forward_failure */
1.80 markus 1828: interactive = 1;
1.50 markus 1829: }
1830:
1.70 markus 1831: check_agent_present();
1832: if (options.forward_agent) {
1833: debug("Requesting authentication agent forwarding.");
1834: channel_request_start(id, "auth-agent-req@openssh.com", 0);
1835: packet_send();
1.212 djm 1836: }
1.369 dtucker 1837:
1838: /* Tell the packet module whether this is an interactive session. */
1839: packet_set_interactive(interactive,
1840: options.ip_qos_interactive, options.ip_qos_bulk);
1.212 djm 1841:
1.214 djm 1842: client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1.311 djm 1843: NULL, fileno(stdin), &command, environ);
1.45 markus 1844: }
1845:
1.143 markus 1846: /* open new channel for a session */
1.126 itojun 1847: static int
1.143 markus 1848: ssh_session2_open(void)
1.45 markus 1849: {
1.118 markus 1850: Channel *c;
1851: int window, packetmax, in, out, err;
1.60 markus 1852:
1.62 markus 1853: if (stdin_null_flag) {
1.93 itojun 1854: in = open(_PATH_DEVNULL, O_RDONLY);
1.62 markus 1855: } else {
1856: in = dup(STDIN_FILENO);
1857: }
1.60 markus 1858: out = dup(STDOUT_FILENO);
1859: err = dup(STDERR_FILENO);
1.45 markus 1860:
1861: if (in < 0 || out < 0 || err < 0)
1.62 markus 1862: fatal("dup() in/out/err failed");
1.45 markus 1863:
1.69 markus 1864: /* enable nonblocking unless tty */
1865: if (!isatty(in))
1866: set_nonblock(in);
1867: if (!isatty(out))
1868: set_nonblock(out);
1869: if (!isatty(err))
1870: set_nonblock(err);
1871:
1.65 markus 1872: window = CHAN_SES_WINDOW_DEFAULT;
1873: packetmax = CHAN_SES_PACKET_DEFAULT;
1.164 markus 1874: if (tty_flag) {
1875: window >>= 1;
1876: packetmax >>= 1;
1.45 markus 1877: }
1.118 markus 1878: c = channel_new(
1.45 markus 1879: "session", SSH_CHANNEL_OPENING, in, out, err,
1.65 markus 1880: window, packetmax, CHAN_EXTENDED_WRITE,
1.192 markus 1881: "client-session", /*nonblock*/0);
1.45 markus 1882:
1.143 markus 1883: debug3("ssh_session2_open: channel_new: %d", c->self);
1.106 markus 1884:
1.122 markus 1885: channel_send_open(c->self);
1.143 markus 1886: if (!no_shell_flag)
1.310 djm 1887: channel_register_open_confirm(c->self,
1888: ssh_session2_setup, NULL);
1.106 markus 1889:
1.118 markus 1890: return c->self;
1.106 markus 1891: }
1892:
1.126 itojun 1893: static int
1.106 markus 1894: ssh_session2(void)
1895: {
1.143 markus 1896: int id = -1;
1.106 markus 1897:
1898: /* XXX should be pre-session */
1.368 djm 1899: if (!options.control_persist)
1900: ssh_init_stdio_forwarding();
1.106 markus 1901: ssh_init_forwarding();
1902:
1.344 djm 1903: /* Start listening for multiplex clients */
1904: muxserver_listen();
1905:
1906: /*
1.368 djm 1907: * If we are in control persist mode and have a working mux listen
1908: * socket, then prepare to background ourselves and have a foreground
1909: * client attach as a control slave.
1910: * NB. we must save copies of the flags that we override for
1.344 djm 1911: * the backgrounding, since we defer attachment of the slave until
1912: * after the connection is fully established (in particular,
1913: * async rfwd replies have been received for ExitOnForwardFailure).
1914: */
1915: if (options.control_persist && muxserver_sock != -1) {
1916: ostdin_null_flag = stdin_null_flag;
1917: ono_shell_flag = no_shell_flag;
1.359 djm 1918: orequest_tty = options.request_tty;
1.344 djm 1919: otty_flag = tty_flag;
1920: stdin_null_flag = 1;
1921: no_shell_flag = 1;
1922: tty_flag = 0;
1923: if (!fork_after_authentication_flag)
1924: need_controlpersist_detach = 1;
1925: fork_after_authentication_flag = 1;
1926: }
1.368 djm 1927: /*
1928: * ControlPersist mux listen socket setup failed, attempt the
1929: * stdio forward setup that we skipped earlier.
1930: */
1931: if (options.control_persist && muxserver_sock == -1)
1932: ssh_init_stdio_forwarding();
1.344 djm 1933:
1.143 markus 1934: if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1935: id = ssh_session2_open();
1.379 djm 1936: else {
1937: packet_set_interactive(
1938: options.control_master == SSHCTL_MASTER_NO,
1939: options.ip_qos_interactive, options.ip_qos_bulk);
1940: }
1.314 djm 1941:
1942: /* If we don't expect to open a new session, then disallow it */
1.319 markus 1943: if (options.control_master == SSHCTL_MASTER_NO &&
1944: (datafellows & SSH_NEW_OPENSSH)) {
1.314 djm 1945: debug("Requesting no-more-sessions@openssh.com");
1946: packet_start(SSH2_MSG_GLOBAL_REQUEST);
1947: packet_put_cstring("no-more-sessions@openssh.com");
1948: packet_put_char(0);
1949: packet_send();
1950: }
1.255 reyk 1951:
1952: /* Execute a local command */
1953: if (options.local_command != NULL &&
1954: options.permit_local_command)
1955: ssh_local_cmd(options.local_command);
1.301 djm 1956:
1.342 djm 1957: /*
1958: * If requested and we are not interested in replies to remote
1959: * forwarding requests, then let ssh continue in the background.
1960: */
1.344 djm 1961: if (fork_after_authentication_flag) {
1962: if (options.exit_on_forward_failure &&
1963: options.num_remote_forwards > 0) {
1964: debug("deferring postauth fork until remote forward "
1965: "confirmation received");
1966: } else
1967: fork_postauth();
1.318 djm 1968: }
1.31 markus 1969:
1.119 stevesk 1970: return client_loop(tty_flag, tty_flag ?
1971: options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72 markus 1972: }
1973:
1.426 djm 1974: /* Loads all IdentityFile and CertificateFile keys */
1.126 itojun 1975: static void
1.104 markus 1976: load_public_identity_files(void)
1977: {
1.275 djm 1978: char *filename, *cp, thishost[NI_MAXHOST];
1.306 deraadt 1979: char *pwdir = NULL, *pwname = NULL;
1.104 markus 1980: Key *public;
1.275 djm 1981: struct passwd *pw;
1.426 djm 1982: int i;
1983: u_int n_ids, n_certs;
1.335 djm 1984: char *identity_files[SSH_MAX_IDENTITY_FILES];
1985: Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1.426 djm 1986: char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
1987: struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
1.333 markus 1988: #ifdef ENABLE_PKCS11
1.167 markus 1989: Key **keys;
1.333 markus 1990: int nkeys;
1.335 djm 1991: #endif /* PKCS11 */
1.104 markus 1992:
1.426 djm 1993: n_ids = n_certs = 0;
1.398 tedu 1994: memset(identity_files, 0, sizeof(identity_files));
1995: memset(identity_keys, 0, sizeof(identity_keys));
1.426 djm 1996: memset(certificate_files, 0, sizeof(certificate_files));
1997: memset(certificates, 0, sizeof(certificates));
1.335 djm 1998:
1999: #ifdef ENABLE_PKCS11
1.333 markus 2000: if (options.pkcs11_provider != NULL &&
1.167 markus 2001: options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1.333 markus 2002: (pkcs11_init(!options.batch_mode) == 0) &&
2003: (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2004: &keys)) > 0) {
2005: for (i = 0; i < nkeys; i++) {
1.335 djm 2006: if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2007: key_free(keys[i]);
2008: continue;
2009: }
2010: identity_keys[n_ids] = keys[i];
2011: identity_files[n_ids] =
1.333 markus 2012: xstrdup(options.pkcs11_provider); /* XXX */
1.335 djm 2013: n_ids++;
1.167 markus 2014: }
1.378 djm 2015: free(keys);
1.127 markus 2016: }
1.333 markus 2017: #endif /* ENABLE_PKCS11 */
1.275 djm 2018: if ((pw = getpwuid(original_real_uid)) == NULL)
2019: fatal("load_public_identity_files: getpwuid failed");
1.307 dtucker 2020: pwname = xstrdup(pw->pw_name);
2021: pwdir = xstrdup(pw->pw_dir);
1.275 djm 2022: if (gethostname(thishost, sizeof(thishost)) == -1)
2023: fatal("load_public_identity_files: gethostname: %s",
2024: strerror(errno));
1.335 djm 2025: for (i = 0; i < options.num_identity_files; i++) {
1.373 djm 2026: if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2027: strcasecmp(options.identity_files[i], "none") == 0) {
1.378 djm 2028: free(options.identity_files[i]);
1.426 djm 2029: options.identity_files[i] = NULL;
1.335 djm 2030: continue;
2031: }
1.275 djm 2032: cp = tilde_expand_filename(options.identity_files[i],
1.131 millert 2033: original_real_uid);
1.306 deraadt 2034: filename = percent_expand(cp, "d", pwdir,
2035: "u", pwname, "l", thishost, "h", host,
1.275 djm 2036: "r", options.user, (char *)NULL);
1.378 djm 2037: free(cp);
1.131 millert 2038: public = key_load_public(filename, NULL);
2039: debug("identity file %s type %d", filename,
2040: public ? public->type : -1);
1.378 djm 2041: free(options.identity_files[i]);
1.335 djm 2042: identity_files[n_ids] = filename;
2043: identity_keys[n_ids] = public;
2044:
2045: if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2046: continue;
2047:
1.426 djm 2048: /*
2049: * If no certificates have been explicitly listed then try
2050: * to add the default certificate variant too.
2051: */
2052: if (options.num_certificate_files != 0)
2053: continue;
1.335 djm 2054: xasprintf(&cp, "%s-cert", filename);
2055: public = key_load_public(cp, NULL);
2056: debug("identity file %s type %d", cp,
2057: public ? public->type : -1);
2058: if (public == NULL) {
1.378 djm 2059: free(cp);
1.335 djm 2060: continue;
2061: }
2062: if (!key_is_cert(public)) {
2063: debug("%s: key %s type %s is not a certificate",
2064: __func__, cp, key_type(public));
2065: key_free(public);
1.378 djm 2066: free(cp);
1.335 djm 2067: continue;
2068: }
2069: identity_keys[n_ids] = public;
1.426 djm 2070: identity_files[n_ids] = cp;
1.335 djm 2071: n_ids++;
2072: }
1.426 djm 2073:
2074: if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2075: fatal("%s: too many certificates", __func__);
2076: for (i = 0; i < options.num_certificate_files; i++) {
2077: cp = tilde_expand_filename(options.certificate_files[i],
2078: original_real_uid);
2079: filename = percent_expand(cp, "d", pwdir,
2080: "u", pwname, "l", thishost, "h", host,
2081: "r", options.user, (char *)NULL);
2082: free(cp);
2083:
2084: public = key_load_public(filename, NULL);
2085: debug("certificate file %s type %d", filename,
2086: public ? public->type : -1);
2087: free(options.certificate_files[i]);
2088: options.certificate_files[i] = NULL;
2089: if (public == NULL) {
2090: free(filename);
2091: continue;
2092: }
2093: if (!key_is_cert(public)) {
2094: debug("%s: key %s type %s is not a certificate",
2095: __func__, filename, key_type(public));
2096: key_free(public);
2097: free(filename);
2098: continue;
2099: }
2100: certificate_files[n_certs] = filename;
2101: certificates[n_certs] = public;
2102: ++n_certs;
2103: }
2104:
1.335 djm 2105: options.num_identity_files = n_ids;
2106: memcpy(options.identity_files, identity_files, sizeof(identity_files));
2107: memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1.426 djm 2108:
2109: options.num_certificate_files = n_certs;
2110: memcpy(options.certificate_files,
2111: certificate_files, sizeof(certificate_files));
2112: memcpy(options.certificates, certificates, sizeof(certificates));
1.335 djm 2113:
1.398 tedu 2114: explicit_bzero(pwname, strlen(pwname));
1.378 djm 2115: free(pwname);
1.398 tedu 2116: explicit_bzero(pwdir, strlen(pwdir));
1.378 djm 2117: free(pwdir);
1.214 djm 2118: }
1.352 djm 2119:
2120: static void
2121: main_sigchld_handler(int sig)
2122: {
2123: int save_errno = errno;
2124: pid_t pid;
2125: int status;
2126:
2127: while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2128: (pid < 0 && errno == EINTR))
2129: ;
2130:
2131: signal(sig, main_sigchld_handler);
2132: errno = save_errno;
2133: }