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