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