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