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