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