1 /* $OpenBSD: ssh.c,v 1.464 2017/09/21 19:16:53 markus Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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.
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".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
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.
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.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
72 #include <netinet/in.h>
73 #include <arpa/inet.h>
76 #include <openssl/evp.h>
77 #include <openssl/err.h>
79 #include "openbsd-compat/openssl-compat.h"
80 #include "openbsd-compat/sys-queue.h"
95 #include "pathnames.h"
97 #include "clientloop.h"
100 #include "readconf.h"
101 #include "sshconnect.h"
110 #include "myproposal.h"
114 #include "ssh-pkcs11.h"
117 extern char *__progname
;
119 /* Saves a copy of argv for setproctitle emulation */
120 #ifndef HAVE_SETPROCTITLE
121 static char **saved_av
;
124 /* Flag indicating whether debug mode is on. May be set on the command line. */
127 /* Flag indicating whether a tty should be requested */
130 /* don't exec a shell */
131 int no_shell_flag
= 0;
134 * Flag indicating that nothing should be read from stdin. This can be set
135 * on the command line.
137 int stdin_null_flag
= 0;
140 * Flag indicating that the current process should be backgrounded and
141 * a new slave launched in the foreground for ControlPersist.
143 int need_controlpersist_detach
= 0;
145 /* Copies of flags for ControlPersist foreground slave */
146 int ostdin_null_flag
, ono_shell_flag
, otty_flag
, orequest_tty
;
149 * Flag indicating that ssh should fork after authentication. This is useful
150 * so that the passphrase can be entered manually, and then ssh goes to the
153 int fork_after_authentication_flag
= 0;
156 * General data structure for command line options and options configurable
157 * in configuration files. See readconf.h.
161 /* optional user configfile */
165 * Name of the host we are connecting to. This is the name given on the
166 * command line, or the HostName specified for the user-supplied name in a
167 * configuration file.
171 /* socket address the host resolves to */
172 struct sockaddr_storage hostaddr
;
174 /* Private host keys. */
175 Sensitive sensitive_data
;
177 /* Original real UID. */
178 uid_t original_real_uid
;
179 uid_t original_effective_uid
;
181 /* command to be executed */
184 /* Should we execute a command or invoke a subsystem? */
185 int subsystem_flag
= 0;
187 /* # of replies received for global requests */
188 static int remote_forward_confirms_received
= 0;
191 extern int muxserver_sock
;
192 extern u_int muxclient_command
;
194 /* Prints a help message to the user. This function never returns. */
200 "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
201 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
202 " [-F configfile] [-I pkcs11] [-i identity_file]\n"
203 " [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]\n"
204 " [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]\n"
205 " [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
206 " [user@]hostname [command]\n"
211 static int ssh_session2(struct ssh
*);
212 static void load_public_identity_files(void);
213 static void main_sigchld_handler(int);
215 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
217 tilde_expand_paths(char **paths
, u_int num_paths
)
222 for (i
= 0; i
< num_paths
; i
++) {
223 cp
= tilde_expand_filename(paths
[i
], original_real_uid
);
230 * Attempt to resolve a host name / port to a set of addresses and
231 * optionally return any CNAMEs encountered along the way.
232 * Returns NULL on failure.
233 * NB. this function must operate with a options having undefined members.
235 static struct addrinfo
*
236 resolve_host(const char *name
, int port
, int logerr
, char *cname
, size_t clen
)
238 char strport
[NI_MAXSERV
];
239 struct addrinfo hints
, *res
;
240 int gaierr
, loglevel
= SYSLOG_LEVEL_DEBUG1
;
243 port
= default_ssh_port();
245 snprintf(strport
, sizeof strport
, "%d", port
);
246 memset(&hints
, 0, sizeof(hints
));
247 hints
.ai_family
= options
.address_family
== -1 ?
248 AF_UNSPEC
: options
.address_family
;
249 hints
.ai_socktype
= SOCK_STREAM
;
251 hints
.ai_flags
= AI_CANONNAME
;
252 if ((gaierr
= getaddrinfo(name
, strport
, &hints
, &res
)) != 0) {
253 if (logerr
|| (gaierr
!= EAI_NONAME
&& gaierr
!= EAI_NODATA
))
254 loglevel
= SYSLOG_LEVEL_ERROR
;
255 do_log2(loglevel
, "%s: Could not resolve hostname %.100s: %s",
256 __progname
, name
, ssh_gai_strerror(gaierr
));
259 if (cname
!= NULL
&& res
->ai_canonname
!= NULL
) {
260 if (strlcpy(cname
, res
->ai_canonname
, clen
) >= clen
) {
261 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
262 __func__
, name
, res
->ai_canonname
, (u_long
)clen
);
271 * Attempt to resolve a numeric host address / port to a single address.
272 * Returns a canonical address string.
273 * Returns NULL on failure.
274 * NB. this function must operate with a options having undefined members.
276 static struct addrinfo
*
277 resolve_addr(const char *name
, int port
, char *caddr
, size_t clen
)
279 char addr
[NI_MAXHOST
], strport
[NI_MAXSERV
];
280 struct addrinfo hints
, *res
;
284 port
= default_ssh_port();
285 snprintf(strport
, sizeof strport
, "%u", port
);
286 memset(&hints
, 0, sizeof(hints
));
287 hints
.ai_family
= options
.address_family
== -1 ?
288 AF_UNSPEC
: options
.address_family
;
289 hints
.ai_socktype
= SOCK_STREAM
;
290 hints
.ai_flags
= AI_NUMERICHOST
|AI_NUMERICSERV
;
291 if ((gaierr
= getaddrinfo(name
, strport
, &hints
, &res
)) != 0) {
292 debug2("%s: could not resolve name %.100s as address: %s",
293 __func__
, name
, ssh_gai_strerror(gaierr
));
297 debug("%s: getaddrinfo %.100s returned no addresses",
301 if (res
->ai_next
!= NULL
) {
302 debug("%s: getaddrinfo %.100s returned multiple addresses",
306 if ((gaierr
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
307 addr
, sizeof(addr
), NULL
, 0, NI_NUMERICHOST
)) != 0) {
308 debug("%s: Could not format address for name %.100s: %s",
309 __func__
, name
, ssh_gai_strerror(gaierr
));
312 if (strlcpy(caddr
, addr
, clen
) >= clen
) {
313 error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
314 __func__
, name
, addr
, (u_long
)clen
);
325 * Check whether the cname is a permitted replacement for the hostname
326 * and perform the replacement if it is.
327 * NB. this function must operate with a options having undefined members.
330 check_follow_cname(int direct
, char **namep
, const char *cname
)
333 struct allowed_cname
*rule
;
335 if (*cname
== '\0' || options
.num_permitted_cnames
== 0 ||
336 strcmp(*namep
, cname
) == 0)
338 if (options
.canonicalize_hostname
== SSH_CANONICALISE_NO
)
341 * Don't attempt to canonicalize names that will be interpreted by
342 * a proxy or jump host unless the user specifically requests so.
345 options
.canonicalize_hostname
!= SSH_CANONICALISE_ALWAYS
)
347 debug3("%s: check \"%s\" CNAME \"%s\"", __func__
, *namep
, cname
);
348 for (i
= 0; i
< options
.num_permitted_cnames
; i
++) {
349 rule
= options
.permitted_cnames
+ i
;
350 if (match_pattern_list(*namep
, rule
->source_list
, 1) != 1 ||
351 match_pattern_list(cname
, rule
->target_list
, 1) != 1)
353 verbose("Canonicalized DNS aliased hostname "
354 "\"%s\" => \"%s\"", *namep
, cname
);
356 *namep
= xstrdup(cname
);
363 * Attempt to resolve the supplied hostname after applying the user's
364 * canonicalization rules. Returns the address list for the host or NULL
365 * if no name was found after canonicalization.
366 * NB. this function must operate with a options having undefined members.
368 static struct addrinfo
*
369 resolve_canonicalize(char **hostp
, int port
)
371 int i
, direct
, ndots
;
372 char *cp
, *fullhost
, newname
[NI_MAXHOST
];
373 struct addrinfo
*addrs
;
375 if (options
.canonicalize_hostname
== SSH_CANONICALISE_NO
)
379 * Don't attempt to canonicalize names that will be interpreted by
380 * a proxy unless the user specifically requests so.
382 direct
= option_clear_or_none(options
.proxy_command
) &&
383 options
.jump_host
== NULL
;
385 options
.canonicalize_hostname
!= SSH_CANONICALISE_ALWAYS
)
388 /* Try numeric hostnames first */
389 if ((addrs
= resolve_addr(*hostp
, port
,
390 newname
, sizeof(newname
))) != NULL
) {
391 debug2("%s: hostname %.100s is address", __func__
, *hostp
);
392 if (strcasecmp(*hostp
, newname
) != 0) {
393 debug2("%s: canonicalised address \"%s\" => \"%s\"",
394 __func__
, *hostp
, newname
);
396 *hostp
= xstrdup(newname
);
401 /* If domain name is anchored, then resolve it now */
402 if ((*hostp
)[strlen(*hostp
) - 1] == '.') {
403 debug3("%s: name is fully qualified", __func__
);
404 fullhost
= xstrdup(*hostp
);
405 if ((addrs
= resolve_host(fullhost
, port
, 0,
406 newname
, sizeof(newname
))) != NULL
)
412 /* Don't apply canonicalization to sufficiently-qualified hostnames */
414 for (cp
= *hostp
; *cp
!= '\0'; cp
++) {
418 if (ndots
> options
.canonicalize_max_dots
) {
419 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
420 __func__
, *hostp
, options
.canonicalize_max_dots
);
423 /* Attempt each supplied suffix */
424 for (i
= 0; i
< options
.num_canonical_domains
; i
++) {
426 xasprintf(&fullhost
, "%s.%s.", *hostp
,
427 options
.canonical_domains
[i
]);
428 debug3("%s: attempting \"%s\" => \"%s\"", __func__
,
430 if ((addrs
= resolve_host(fullhost
, port
, 0,
431 newname
, sizeof(newname
))) == NULL
) {
436 /* Remove trailing '.' */
437 fullhost
[strlen(fullhost
) - 1] = '\0';
438 /* Follow CNAME if requested */
439 if (!check_follow_cname(direct
, &fullhost
, newname
)) {
440 debug("Canonicalized hostname \"%s\" => \"%s\"",
448 if (!options
.canonicalize_fallback_local
)
449 fatal("%s: Could not resolve host \"%s\"", __progname
, *hostp
);
450 debug2("%s: host %s not found in any suffix", __func__
, *hostp
);
455 * Read per-user configuration file. Ignore the system wide config
456 * file if the user specifies a config file on the command line.
459 process_config_files(const char *host_arg
, struct passwd
*pw
, int post_canon
)
464 if (config
!= NULL
) {
465 if (strcasecmp(config
, "none") != 0 &&
466 !read_config_file(config
, pw
, host
, host_arg
, &options
,
467 SSHCONF_USERCONF
| (post_canon
? SSHCONF_POSTCANON
: 0)))
468 fatal("Can't open user config file %.100s: "
469 "%.100s", config
, strerror(errno
));
471 r
= snprintf(buf
, sizeof buf
, "%s/%s", pw
->pw_dir
,
472 _PATH_SSH_USER_CONFFILE
);
473 if (r
> 0 && (size_t)r
< sizeof(buf
))
474 (void)read_config_file(buf
, pw
, host
, host_arg
,
475 &options
, SSHCONF_CHECKPERM
| SSHCONF_USERCONF
|
476 (post_canon
? SSHCONF_POSTCANON
: 0));
478 /* Read systemwide configuration file after user config. */
479 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, pw
,
480 host
, host_arg
, &options
,
481 post_canon
? SSHCONF_POSTCANON
: 0);
485 /* Rewrite the port number in an addrinfo list of addresses */
487 set_addrinfo_port(struct addrinfo
*addrs
, int port
)
489 struct addrinfo
*addr
;
491 for (addr
= addrs
; addr
!= NULL
; addr
= addr
->ai_next
) {
492 switch (addr
->ai_family
) {
494 ((struct sockaddr_in
*)addr
->ai_addr
)->
495 sin_port
= htons(port
);
498 ((struct sockaddr_in6
*)addr
->ai_addr
)->
499 sin6_port
= htons(port
);
506 * Main program for the ssh client.
509 main(int ac
, char **av
)
511 struct ssh
*ssh
= NULL
;
512 int i
, r
, opt
, exit_status
, use_syslog
, direct
, timeout_ms
;
513 int config_test
= 0, opt_terminated
= 0;
514 char *p
, *cp
, *line
, *argv0
, buf
[PATH_MAX
], *host_arg
, *logfile
;
515 char thishost
[NI_MAXHOST
], shorthost
[NI_MAXHOST
], portstr
[NI_MAXSERV
];
516 char cname
[NI_MAXHOST
], uidstr
[32], *conn_hash_hex
;
519 extern int optind
, optreset
;
522 struct addrinfo
*addrs
= NULL
;
523 struct ssh_digest_ctx
*md
;
524 u_char conn_hash
[SSH_DIGEST_MAX_LENGTH
];
526 ssh_malloc_init(); /* must be called before any mallocs */
527 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
530 __progname
= ssh_get_progname(av
[0]);
532 #ifndef HAVE_SETPROCTITLE
533 /* Prepare for later setproctitle emulation */
534 /* Save argv so it isn't clobbered by setproctitle() emulation */
535 saved_av
= xcalloc(ac
+ 1, sizeof(*saved_av
));
536 for (i
= 0; i
< ac
; i
++)
537 saved_av
[i
] = xstrdup(av
[i
]);
539 compat_init_setproctitle(ac
, av
);
544 * Discard other fds that are hanging around. These can cause problem
545 * with backgrounded ssh processes started by ControlPersist.
547 closefrom(STDERR_FILENO
+ 1);
550 * Save the original real uid. It will be needed later (uid-swapping
551 * may clobber the real uid).
553 original_real_uid
= getuid();
554 original_effective_uid
= geteuid();
557 * Use uid-swapping to give up root privileges for the duration of
558 * option processing. We will re-instantiate the rights when we are
559 * ready to create the privileged port, and will permanently drop
560 * them when the port has been created (actually, when the connection
561 * has been made, as we may need to create the port several times).
565 #ifdef HAVE_SETRLIMIT
566 /* If we are installed setuid root be careful to not drop core. */
567 if (original_real_uid
!= original_effective_uid
) {
569 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
570 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
571 fatal("setrlimit failed: %.100s", strerror(errno
));
575 pw
= getpwuid(original_real_uid
);
577 logit("No user exists for uid %lu", (u_long
)original_real_uid
);
580 /* Take a copy of the returned structure. */
584 * Set our umask to something reasonable, as some files are created
585 * with the default umask. This will make them world-readable but
586 * writable only by the owner, which is ok for all files for which we
587 * don't set the modes explicitly.
594 * Initialize option structure to indicate that no values have been
597 initialize_options(&options
);
600 * Prepare main ssh transport/connection structures
602 if ((ssh
= ssh_alloc_session_state()) == NULL
)
603 fatal("Couldn't allocate session state");
604 channel_init_channels(ssh
);
605 active_state
= ssh
; /* XXX legacy API compat */
607 /* Parse command-line arguments. */
614 while ((opt
= getopt(ac
, av
, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
615 "ACD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
618 fatal("SSH protocol v.1 is no longer supported");
624 options
.address_family
= AF_INET
;
627 options
.address_family
= AF_INET6
;
633 fork_after_authentication_flag
= 1;
637 options
.forward_x11
= 0;
640 options
.forward_x11
= 1;
652 options
.forward_x11
= 1;
653 options
.forward_x11_trusted
= 1;
656 options
.fwd_opts
.gateway_ports
= 1;
659 if (options
.stdio_forward_host
!= NULL
)
660 fatal("Cannot specify multiplexing "
662 else if (muxclient_command
!= 0)
663 fatal("Multiplexing command already specified");
664 if (strcmp(optarg
, "check") == 0)
665 muxclient_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
666 else if (strcmp(optarg
, "forward") == 0)
667 muxclient_command
= SSHMUX_COMMAND_FORWARD
;
668 else if (strcmp(optarg
, "exit") == 0)
669 muxclient_command
= SSHMUX_COMMAND_TERMINATE
;
670 else if (strcmp(optarg
, "stop") == 0)
671 muxclient_command
= SSHMUX_COMMAND_STOP
;
672 else if (strcmp(optarg
, "cancel") == 0)
673 muxclient_command
= SSHMUX_COMMAND_CANCEL_FWD
;
674 else if (strcmp(optarg
, "proxy") == 0)
675 muxclient_command
= SSHMUX_COMMAND_PROXY
;
677 fatal("Invalid multiplex command.");
679 case 'P': /* deprecated */
680 options
.use_privileged_port
= 0;
684 if (strcmp(optarg
, "cipher") == 0)
685 cp
= cipher_alg_list('\n', 0);
686 else if (strcmp(optarg
, "cipher-auth") == 0)
687 cp
= cipher_alg_list('\n', 1);
688 else if (strcmp(optarg
, "mac") == 0)
689 cp
= mac_alg_list('\n');
690 else if (strcmp(optarg
, "kex") == 0)
691 cp
= kex_alg_list('\n');
692 else if (strcmp(optarg
, "key") == 0)
693 cp
= sshkey_alg_list(0, 0, 0, '\n');
694 else if (strcmp(optarg
, "key-cert") == 0)
695 cp
= sshkey_alg_list(1, 0, 0, '\n');
696 else if (strcmp(optarg
, "key-plain") == 0)
697 cp
= sshkey_alg_list(0, 1, 0, '\n');
698 else if (strcmp(optarg
, "protocol-version") == 0) {
702 fatal("Unsupported query \"%s\"", optarg
);
708 options
.forward_agent
= 0;
711 options
.forward_agent
= 1;
714 options
.gss_deleg_creds
= 0;
717 options
.gss_authentication
= 1;
718 options
.gss_deleg_creds
= 1;
721 p
= tilde_expand_filename(optarg
, original_real_uid
);
722 if (stat(p
, &st
) < 0)
723 fprintf(stderr
, "Warning: Identity file %s "
724 "not accessible: %s.\n", p
,
727 add_identity_file(&options
, NULL
, p
, 1);
732 free(options
.pkcs11_provider
);
733 options
.pkcs11_provider
= xstrdup(optarg
);
735 fprintf(stderr
, "no support for PKCS#11.\n");
739 if (options
.jump_host
!= NULL
)
740 fatal("Only a single -J option permitted");
741 if (options
.proxy_command
!= NULL
)
742 fatal("Cannot specify -J with ProxyCommand");
743 if (parse_jump(optarg
, &options
, 1) == -1)
744 fatal("Invalid -J argument");
745 options
.proxy_command
= xstrdup("none");
748 if (options
.request_tty
== REQUEST_TTY_YES
)
749 options
.request_tty
= REQUEST_TTY_FORCE
;
751 options
.request_tty
= REQUEST_TTY_YES
;
754 if (debug_flag
== 0) {
756 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
758 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
) {
765 fprintf(stderr
, "%s, %s\n",
768 SSLeay_version(SSLEAY_VERSION
)
777 if (options
.tun_open
== -1)
778 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
779 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
780 if (options
.tun_local
== SSH_TUNID_ERR
) {
782 "Bad tun device '%s'\n", optarg
);
787 if (options
.stdio_forward_host
!= NULL
)
788 fatal("stdio forward already specified");
789 if (muxclient_command
!= 0)
790 fatal("Cannot specify stdio forward with -O");
791 if (parse_forward(&fwd
, optarg
, 1, 0)) {
792 options
.stdio_forward_host
= fwd
.listen_host
;
793 options
.stdio_forward_port
= fwd
.listen_port
;
794 free(fwd
.connect_host
);
797 "Bad stdio forwarding specification '%s'\n",
801 options
.request_tty
= REQUEST_TTY_NO
;
805 options
.log_level
= SYSLOG_LEVEL_QUIET
;
808 if (optarg
[0] == '^' && optarg
[2] == 0 &&
809 (u_char
) optarg
[1] >= 64 &&
810 (u_char
) optarg
[1] < 128)
811 options
.escape_char
= (u_char
) optarg
[1] & 31;
812 else if (strlen(optarg
) == 1)
813 options
.escape_char
= (u_char
) optarg
[0];
814 else if (strcmp(optarg
, "none") == 0)
815 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
817 fprintf(stderr
, "Bad escape character '%s'.\n",
823 if (!ciphers_valid(*optarg
== '+' ?
824 optarg
+ 1 : optarg
)) {
825 fprintf(stderr
, "Unknown cipher type '%s'\n",
829 free(options
.ciphers
);
830 options
.ciphers
= xstrdup(optarg
);
833 if (mac_valid(optarg
)) {
835 options
.macs
= xstrdup(optarg
);
837 fprintf(stderr
, "Unknown mac type '%s'\n",
843 if (options
.control_master
== SSHCTL_MASTER_YES
)
844 options
.control_master
= SSHCTL_MASTER_ASK
;
846 options
.control_master
= SSHCTL_MASTER_YES
;
849 options
.port
= a2port(optarg
);
850 if (options
.port
<= 0) {
851 fprintf(stderr
, "Bad port '%s'\n", optarg
);
856 options
.user
= optarg
;
860 if (parse_forward(&fwd
, optarg
, 0, 0))
861 add_local_forward(&options
, &fwd
);
864 "Bad local forwarding specification '%s'\n",
871 if (parse_forward(&fwd
, optarg
, 0, 1) ||
872 parse_forward(&fwd
, optarg
, 1, 1)) {
873 add_remote_forward(&options
, &fwd
);
876 "Bad remote forwarding specification "
883 if (parse_forward(&fwd
, optarg
, 1, 0)) {
884 add_local_forward(&options
, &fwd
);
887 "Bad dynamic forwarding specification "
894 options
.compression
= 1;
898 options
.request_tty
= REQUEST_TTY_NO
;
901 options
.request_tty
= REQUEST_TTY_NO
;
904 line
= xstrdup(optarg
);
905 if (process_config_line(&options
, pw
,
906 host
? host
: "", host
? host
: "", line
,
907 "command-line", 0, NULL
, SSHCONF_USERCONF
) != 0)
915 free(options
.control_path
);
916 options
.control_path
= xstrdup(optarg
);
919 options
.bind_address
= optarg
;
929 if (optind
> 1 && strcmp(av
[optind
- 1], "--") == 0)
935 if (ac
> 0 && !host
) {
936 if (strrchr(*av
, '@')) {
938 cp
= strrchr(p
, '@');
939 if (cp
== NULL
|| cp
== p
)
943 host
= xstrdup(++cp
);
946 if (ac
> 1 && !opt_terminated
) {
947 optind
= optreset
= 1;
953 /* Check that we got a host name. */
957 host_arg
= xstrdup(host
);
960 OpenSSL_add_all_algorithms();
961 ERR_load_crypto_strings();
964 /* Initialize the command to execute on remote host. */
965 buffer_init(&command
);
968 * Save the command to execute on the remote host in a buffer. There
969 * is no limit on the length of the command, except by the maximum
970 * packet size. Also sets the tty flag if there is no command.
973 /* No command specified - execute shell on a tty. */
974 if (subsystem_flag
) {
976 "You must specify a subsystem to invoke.\n");
980 /* A command has been specified. Store it into the buffer. */
981 for (i
= 0; i
< ac
; i
++) {
983 buffer_append(&command
, " ", 1);
984 buffer_append(&command
, av
[i
], strlen(av
[i
]));
989 * Initialize "log" output. Since we are the client all output
990 * goes to stderr unless otherwise specified by -y or -E.
992 if (use_syslog
&& logfile
!= NULL
)
993 fatal("Can't specify both -y and -E");
995 log_redirect_stderr_to(logfile
);
997 options
.log_level
== SYSLOG_LEVEL_NOT_SET
?
998 SYSLOG_LEVEL_INFO
: options
.log_level
,
999 options
.log_facility
== SYSLOG_FACILITY_NOT_SET
?
1000 SYSLOG_FACILITY_USER
: options
.log_facility
,
1004 logit("%s, %s", SSH_RELEASE
,
1006 SSLeay_version(SSLEAY_VERSION
)
1012 /* Parse the configuration files */
1013 process_config_files(host_arg
, pw
, 0);
1015 /* Hostname canonicalisation needs a few options filled. */
1016 fill_default_options_for_canonicalization(&options
);
1018 /* If the user has replaced the hostname then take it into use now */
1019 if (options
.hostname
!= NULL
) {
1020 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1021 cp
= percent_expand(options
.hostname
,
1022 "h", host
, (char *)NULL
);
1025 free(options
.hostname
);
1026 options
.hostname
= xstrdup(host
);
1029 /* If canonicalization requested then try to apply it */
1031 if (options
.canonicalize_hostname
!= SSH_CANONICALISE_NO
)
1032 addrs
= resolve_canonicalize(&host
, options
.port
);
1035 * If CanonicalizePermittedCNAMEs have been specified but
1036 * other canonicalization did not happen (by not being requested
1037 * or by failing with fallback) then the hostname may still be changed
1038 * as a result of CNAME following.
1040 * Try to resolve the bare hostname name using the system resolver's
1041 * usual search rules and then apply the CNAME follow rules.
1043 * Skip the lookup if a ProxyCommand is being used unless the user
1044 * has specifically requested canonicalisation for this case via
1045 * CanonicalizeHostname=always
1047 direct
= option_clear_or_none(options
.proxy_command
) &&
1048 options
.jump_host
== NULL
;
1049 if (addrs
== NULL
&& options
.num_permitted_cnames
!= 0 && (direct
||
1050 options
.canonicalize_hostname
== SSH_CANONICALISE_ALWAYS
)) {
1051 if ((addrs
= resolve_host(host
, options
.port
,
1052 option_clear_or_none(options
.proxy_command
),
1053 cname
, sizeof(cname
))) == NULL
) {
1054 /* Don't fatal proxied host names not in the DNS */
1055 if (option_clear_or_none(options
.proxy_command
))
1056 cleanup_exit(255); /* logged in resolve_host */
1058 check_follow_cname(direct
, &host
, cname
);
1062 * If canonicalisation is enabled then re-parse the configuration
1063 * files as new stanzas may match.
1065 if (options
.canonicalize_hostname
!= 0) {
1066 debug("Re-reading configuration after hostname "
1067 "canonicalisation");
1068 free(options
.hostname
);
1069 options
.hostname
= xstrdup(host
);
1070 process_config_files(host_arg
, pw
, 1);
1072 * Address resolution happens early with canonicalisation
1073 * enabled and the port number may have changed since, so
1074 * reset it in address list
1076 if (addrs
!= NULL
&& options
.port
> 0)
1077 set_addrinfo_port(addrs
, options
.port
);
1080 /* Fill configuration defaults. */
1081 fill_default_options(&options
);
1084 * If ProxyJump option specified, then construct a ProxyCommand now.
1086 if (options
.jump_host
!= NULL
) {
1089 /* Consistency check */
1090 if (options
.proxy_command
!= NULL
)
1091 fatal("inconsistent options: ProxyCommand+ProxyJump");
1092 /* Never use FD passing for ProxyJump */
1093 options
.proxy_use_fdpass
= 0;
1094 snprintf(port_s
, sizeof(port_s
), "%d", options
.jump_port
);
1095 xasprintf(&options
.proxy_command
,
1096 "ssh%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1097 /* Optional "-l user" argument if jump_user set */
1098 options
.jump_user
== NULL
? "" : " -l ",
1099 options
.jump_user
== NULL
? "" : options
.jump_user
,
1100 /* Optional "-p port" argument if jump_port set */
1101 options
.jump_port
<= 0 ? "" : " -p ",
1102 options
.jump_port
<= 0 ? "" : port_s
,
1103 /* Optional additional jump hosts ",..." */
1104 options
.jump_extra
== NULL
? "" : " -J ",
1105 options
.jump_extra
== NULL
? "" : options
.jump_extra
,
1106 /* Optional "-F" argumment if -F specified */
1107 config
== NULL
? "" : " -F ",
1108 config
== NULL
? "" : config
,
1109 /* Optional "-v" arguments if -v set */
1110 debug_flag
? " -" : "",
1112 /* Mandatory hostname */
1114 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1115 options
.proxy_command
);
1118 if (options
.port
== 0)
1119 options
.port
= default_ssh_port();
1120 channel_set_af(ssh
, options
.address_family
);
1122 /* Tidy and check options */
1123 if (options
.host_key_alias
!= NULL
)
1124 lowercase(options
.host_key_alias
);
1125 if (options
.proxy_command
!= NULL
&&
1126 strcmp(options
.proxy_command
, "-") == 0 &&
1127 options
.proxy_use_fdpass
)
1128 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1129 if (options
.control_persist
&&
1130 options
.update_hostkeys
== SSH_UPDATE_HOSTKEYS_ASK
) {
1131 debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1133 options
.update_hostkeys
= 0;
1135 if (options
.connection_attempts
<= 0)
1136 fatal("Invalid number of ConnectionAttempts");
1138 if (original_effective_uid
!= 0)
1139 options
.use_privileged_port
= 0;
1142 if (buffer_len(&command
) != 0 && options
.remote_command
!= NULL
)
1143 fatal("Cannot execute command-line and remote command.");
1145 /* Cannot fork to background if no command. */
1146 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 &&
1147 options
.remote_command
== NULL
&& !no_shell_flag
)
1148 fatal("Cannot fork into background without a command "
1152 log_init(argv0
, options
.log_level
, options
.log_facility
, !use_syslog
);
1154 if (options
.request_tty
== REQUEST_TTY_YES
||
1155 options
.request_tty
== REQUEST_TTY_FORCE
)
1158 /* Allocate a tty by default if no command specified. */
1159 if (buffer_len(&command
) == 0 && options
.remote_command
== NULL
)
1160 tty_flag
= options
.request_tty
!= REQUEST_TTY_NO
;
1163 if (options
.request_tty
== REQUEST_TTY_NO
||
1164 (muxclient_command
&& muxclient_command
!= SSHMUX_COMMAND_PROXY
))
1166 /* Do not allocate a tty if stdin is not a tty. */
1167 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) &&
1168 options
.request_tty
!= REQUEST_TTY_FORCE
) {
1170 logit("Pseudo-terminal will not be allocated because "
1171 "stdin is not a terminal.");
1177 if (options
.user
== NULL
)
1178 options
.user
= xstrdup(pw
->pw_name
);
1180 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1181 fatal("gethostname: %s", strerror(errno
));
1182 strlcpy(shorthost
, thishost
, sizeof(shorthost
));
1183 shorthost
[strcspn(thishost
, ".")] = '\0';
1184 snprintf(portstr
, sizeof(portstr
), "%d", options
.port
);
1185 snprintf(uidstr
, sizeof(uidstr
), "%d", pw
->pw_uid
);
1187 if ((md
= ssh_digest_start(SSH_DIGEST_SHA1
)) == NULL
||
1188 ssh_digest_update(md
, thishost
, strlen(thishost
)) < 0 ||
1189 ssh_digest_update(md
, host
, strlen(host
)) < 0 ||
1190 ssh_digest_update(md
, portstr
, strlen(portstr
)) < 0 ||
1191 ssh_digest_update(md
, options
.user
, strlen(options
.user
)) < 0 ||
1192 ssh_digest_final(md
, conn_hash
, sizeof(conn_hash
)) < 0)
1193 fatal("%s: mux digest failed", __func__
);
1194 ssh_digest_free(md
);
1195 conn_hash_hex
= tohex(conn_hash
, ssh_digest_bytes(SSH_DIGEST_SHA1
));
1197 if (options
.local_command
!= NULL
) {
1198 debug3("expanding LocalCommand: %s", options
.local_command
);
1199 cp
= options
.local_command
;
1200 options
.local_command
= percent_expand(cp
,
1211 debug3("expanded LocalCommand: %s", options
.local_command
);
1215 if (options
.remote_command
!= NULL
) {
1216 debug3("expanding RemoteCommand: %s", options
.remote_command
);
1217 cp
= options
.remote_command
;
1218 options
.remote_command
= percent_expand(cp
,
1229 debug3("expanded RemoteCommand: %s", options
.remote_command
);
1231 buffer_append(&command
, options
.remote_command
,
1232 strlen(options
.remote_command
));
1236 if (options
.control_path
!= NULL
) {
1237 cp
= tilde_expand_filename(options
.control_path
,
1239 free(options
.control_path
);
1240 options
.control_path
= percent_expand(cp
,
1253 free(conn_hash_hex
);
1256 dump_client_config(&options
, host
);
1260 if (muxclient_command
!= 0 && options
.control_path
== NULL
)
1261 fatal("No ControlPath specified for \"-O\" command");
1262 if (options
.control_path
!= NULL
) {
1264 if ((sock
= muxclient(options
.control_path
)) >= 0) {
1265 ssh_packet_set_connection(ssh
, sock
, sock
);
1272 * If hostname canonicalisation was not enabled, then we may not
1273 * have yet resolved the hostname. Do so now.
1275 if (addrs
== NULL
&& options
.proxy_command
== NULL
) {
1276 debug2("resolving \"%s\" port %d", host
, options
.port
);
1277 if ((addrs
= resolve_host(host
, options
.port
, 1,
1278 cname
, sizeof(cname
))) == NULL
)
1279 cleanup_exit(255); /* resolve_host logs the error */
1282 timeout_ms
= options
.connection_timeout
* 1000;
1284 /* Open a connection to the remote host. */
1285 if (ssh_connect(ssh
, host
, addrs
, &hostaddr
, options
.port
,
1286 options
.address_family
, options
.connection_attempts
,
1287 &timeout_ms
, options
.tcp_keep_alive
,
1288 options
.use_privileged_port
) != 0)
1292 freeaddrinfo(addrs
);
1294 packet_set_timeout(options
.server_alive_interval
,
1295 options
.server_alive_count_max
);
1297 ssh
= active_state
; /* XXX */
1300 debug3("timeout: %d ms remain after connect", timeout_ms
);
1303 * If we successfully made the connection, load the host private key
1304 * in case we will need it later for combined rsa-rhosts
1305 * authentication. This must be done before releasing extra
1306 * privileges, because the file is only readable by root.
1307 * If we cannot access the private keys, load the public keys
1308 * instead and try to execute the ssh-keysign helper instead.
1310 sensitive_data
.nkeys
= 0;
1311 sensitive_data
.keys
= NULL
;
1312 sensitive_data
.external_keysign
= 0;
1313 if (options
.hostbased_authentication
) {
1314 sensitive_data
.nkeys
= 9;
1315 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
1316 sizeof(struct sshkey
)); /* XXX */
1317 for (i
= 0; i
< sensitive_data
.nkeys
; i
++)
1318 sensitive_data
.keys
[i
] = NULL
;
1321 #ifdef OPENSSL_HAS_ECC
1322 sensitive_data
.keys
[1] = key_load_private_cert(KEY_ECDSA
,
1323 _PATH_HOST_ECDSA_KEY_FILE
, "", NULL
);
1325 sensitive_data
.keys
[2] = key_load_private_cert(KEY_ED25519
,
1326 _PATH_HOST_ED25519_KEY_FILE
, "", NULL
);
1327 sensitive_data
.keys
[3] = key_load_private_cert(KEY_RSA
,
1328 _PATH_HOST_RSA_KEY_FILE
, "", NULL
);
1329 sensitive_data
.keys
[4] = key_load_private_cert(KEY_DSA
,
1330 _PATH_HOST_DSA_KEY_FILE
, "", NULL
);
1331 #ifdef OPENSSL_HAS_ECC
1332 sensitive_data
.keys
[5] = key_load_private_type(KEY_ECDSA
,
1333 _PATH_HOST_ECDSA_KEY_FILE
, "", NULL
, NULL
);
1335 sensitive_data
.keys
[6] = key_load_private_type(KEY_ED25519
,
1336 _PATH_HOST_ED25519_KEY_FILE
, "", NULL
, NULL
);
1337 sensitive_data
.keys
[7] = key_load_private_type(KEY_RSA
,
1338 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
1339 sensitive_data
.keys
[8] = key_load_private_type(KEY_DSA
,
1340 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
1343 if (options
.hostbased_authentication
== 1 &&
1344 sensitive_data
.keys
[0] == NULL
&&
1345 sensitive_data
.keys
[5] == NULL
&&
1346 sensitive_data
.keys
[6] == NULL
&&
1347 sensitive_data
.keys
[7] == NULL
&&
1348 sensitive_data
.keys
[8] == NULL
) {
1349 #ifdef OPENSSL_HAS_ECC
1350 sensitive_data
.keys
[1] = key_load_cert(
1351 _PATH_HOST_ECDSA_KEY_FILE
);
1353 sensitive_data
.keys
[2] = key_load_cert(
1354 _PATH_HOST_ED25519_KEY_FILE
);
1355 sensitive_data
.keys
[3] = key_load_cert(
1356 _PATH_HOST_RSA_KEY_FILE
);
1357 sensitive_data
.keys
[4] = key_load_cert(
1358 _PATH_HOST_DSA_KEY_FILE
);
1359 #ifdef OPENSSL_HAS_ECC
1360 sensitive_data
.keys
[5] = key_load_public(
1361 _PATH_HOST_ECDSA_KEY_FILE
, NULL
);
1363 sensitive_data
.keys
[6] = key_load_public(
1364 _PATH_HOST_ED25519_KEY_FILE
, NULL
);
1365 sensitive_data
.keys
[7] = key_load_public(
1366 _PATH_HOST_RSA_KEY_FILE
, NULL
);
1367 sensitive_data
.keys
[8] = key_load_public(
1368 _PATH_HOST_DSA_KEY_FILE
, NULL
);
1369 sensitive_data
.external_keysign
= 1;
1373 * Get rid of any extra privileges that we may have. We will no
1374 * longer need them. Also, extra privileges could make it very hard
1375 * to read identity files and other non-world-readable files from the
1376 * user's home directory if it happens to be on a NFS volume where
1377 * root is mapped to nobody.
1379 if (original_effective_uid
== 0) {
1381 permanently_set_uid(pw
);
1385 * Now that we are back to our own permissions, create ~/.ssh
1386 * directory if it doesn't already exist.
1388 if (config
== NULL
) {
1389 r
= snprintf(buf
, sizeof buf
, "%s%s%s", pw
->pw_dir
,
1390 strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
1391 if (r
> 0 && (size_t)r
< sizeof(buf
) && stat(buf
, &st
) < 0) {
1393 ssh_selinux_setfscreatecon(buf
);
1395 if (mkdir(buf
, 0700) < 0)
1396 error("Could not create directory '%.200s'.",
1399 ssh_selinux_setfscreatecon(NULL
);
1403 /* load options.identity_files */
1404 load_public_identity_files();
1406 /* optionally set the SSH_AUTHSOCKET_ENV_NAME varibale */
1407 if (options
.identity_agent
&&
1408 strcmp(options
.identity_agent
, SSH_AUTHSOCKET_ENV_NAME
) != 0) {
1409 if (strcmp(options
.identity_agent
, "none") == 0) {
1410 unsetenv(SSH_AUTHSOCKET_ENV_NAME
);
1412 p
= tilde_expand_filename(options
.identity_agent
,
1414 cp
= percent_expand(p
, "d", pw
->pw_dir
,
1415 "u", pw
->pw_name
, "l", thishost
, "h", host
,
1416 "r", options
.user
, (char *)NULL
);
1417 setenv(SSH_AUTHSOCKET_ENV_NAME
, cp
, 1);
1423 /* Expand ~ in known host file names. */
1424 tilde_expand_paths(options
.system_hostfiles
,
1425 options
.num_system_hostfiles
);
1426 tilde_expand_paths(options
.user_hostfiles
, options
.num_user_hostfiles
);
1428 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
1429 signal(SIGCHLD
, main_sigchld_handler
);
1431 /* Log into the remote system. Never returns if the login fails. */
1432 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
,
1433 options
.port
, pw
, timeout_ms
);
1435 if (packet_connection_is_on_socket()) {
1436 verbose("Authenticated to %s ([%s]:%d).", host
,
1437 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
));
1439 verbose("Authenticated to %s (via proxy).", host
);
1442 /* We no longer need the private host keys. Clear them now. */
1443 if (sensitive_data
.nkeys
!= 0) {
1444 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
1445 if (sensitive_data
.keys
[i
] != NULL
) {
1446 /* Destroys contents safely */
1447 debug3("clear hostkey %d", i
);
1448 key_free(sensitive_data
.keys
[i
]);
1449 sensitive_data
.keys
[i
] = NULL
;
1452 free(sensitive_data
.keys
);
1454 for (i
= 0; i
< options
.num_identity_files
; i
++) {
1455 free(options
.identity_files
[i
]);
1456 options
.identity_files
[i
] = NULL
;
1457 if (options
.identity_keys
[i
]) {
1458 key_free(options
.identity_keys
[i
]);
1459 options
.identity_keys
[i
] = NULL
;
1462 for (i
= 0; i
< options
.num_certificate_files
; i
++) {
1463 free(options
.certificate_files
[i
]);
1464 options
.certificate_files
[i
] = NULL
;
1468 exit_status
= ssh_session2(ssh
);
1471 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
1472 unlink(options
.control_path
);
1474 /* Kill ProxyCommand if it is running. */
1475 ssh_kill_proxy_command();
1481 control_persist_detach(void)
1484 int devnull
, keep_stderr
;
1486 debug("%s: backgrounding master process", __func__
);
1489 * master (current process) into the background, and make the
1490 * foreground process a client of the backgrounded master.
1492 switch ((pid
= fork())) {
1494 fatal("%s: fork: %s", __func__
, strerror(errno
));
1496 /* Child: master process continues mainloop */
1499 /* Parent: set up mux slave to connect to backgrounded master */
1500 debug2("%s: background process is %ld", __func__
, (long)pid
);
1501 stdin_null_flag
= ostdin_null_flag
;
1502 options
.request_tty
= orequest_tty
;
1503 tty_flag
= otty_flag
;
1504 close(muxserver_sock
);
1505 muxserver_sock
= -1;
1506 options
.control_master
= SSHCTL_MASTER_NO
;
1507 muxclient(options
.control_path
);
1508 /* muxclient() doesn't return on success. */
1509 fatal("Failed to connect to new control master");
1511 if ((devnull
= open(_PATH_DEVNULL
, O_RDWR
)) == -1) {
1512 error("%s: open(\"/dev/null\"): %s", __func__
,
1515 keep_stderr
= log_is_on_stderr() && debug_flag
;
1516 if (dup2(devnull
, STDIN_FILENO
) == -1 ||
1517 dup2(devnull
, STDOUT_FILENO
) == -1 ||
1518 (!keep_stderr
&& dup2(devnull
, STDERR_FILENO
) == -1))
1519 error("%s: dup2: %s", __func__
, strerror(errno
));
1520 if (devnull
> STDERR_FILENO
)
1524 setproctitle("%s [mux]", options
.control_path
);
1527 /* Do fork() after authentication. Used by "ssh -f" */
1531 if (need_controlpersist_detach
)
1532 control_persist_detach();
1533 debug("forking to background");
1534 fork_after_authentication_flag
= 0;
1535 if (daemon(1, 1) < 0)
1536 fatal("daemon() failed: %.200s", strerror(errno
));
1539 /* Callback for remote forward global requests */
1541 ssh_confirm_remote_forward(struct ssh
*ssh
, int type
, u_int32_t seq
, void *ctxt
)
1543 struct Forward
*rfwd
= (struct Forward
*)ctxt
;
1545 /* XXX verbose() on failure? */
1546 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1547 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
1548 rfwd
->listen_path
? rfwd
->listen_path
:
1549 rfwd
->listen_host
? rfwd
->listen_host
: "",
1550 (rfwd
->listen_path
|| rfwd
->listen_host
) ? ":" : "",
1551 rfwd
->listen_port
, rfwd
->connect_path
? rfwd
->connect_path
:
1552 rfwd
->connect_host
, rfwd
->connect_port
);
1553 if (rfwd
->listen_path
== NULL
&& rfwd
->listen_port
== 0) {
1554 if (type
== SSH2_MSG_REQUEST_SUCCESS
) {
1555 rfwd
->allocated_port
= packet_get_int();
1556 logit("Allocated port %u for remote forward to %s:%d",
1557 rfwd
->allocated_port
,
1558 rfwd
->connect_host
, rfwd
->connect_port
);
1559 channel_update_permitted_opens(ssh
,
1560 rfwd
->handle
, rfwd
->allocated_port
);
1562 channel_update_permitted_opens(ssh
, rfwd
->handle
, -1);
1566 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
1567 if (options
.exit_on_forward_failure
) {
1568 if (rfwd
->listen_path
!= NULL
)
1569 fatal("Error: remote port forwarding failed "
1570 "for listen path %s", rfwd
->listen_path
);
1572 fatal("Error: remote port forwarding failed "
1573 "for listen port %d", rfwd
->listen_port
);
1575 if (rfwd
->listen_path
!= NULL
)
1576 logit("Warning: remote port forwarding failed "
1577 "for listen path %s", rfwd
->listen_path
);
1579 logit("Warning: remote port forwarding failed "
1580 "for listen port %d", rfwd
->listen_port
);
1583 if (++remote_forward_confirms_received
== options
.num_remote_forwards
) {
1584 debug("All remote forwarding requests processed");
1585 if (fork_after_authentication_flag
)
1591 client_cleanup_stdio_fwd(struct ssh
*ssh
, int id
, void *arg
)
1593 debug("stdio forwarding: done");
1598 ssh_stdio_confirm(struct ssh
*ssh
, int id
, int success
, void *arg
)
1601 fatal("stdio forwarding failed");
1605 ssh_init_stdio_forwarding(struct ssh
*ssh
)
1610 if (options
.stdio_forward_host
== NULL
)
1613 debug3("%s: %s:%d", __func__
, options
.stdio_forward_host
,
1614 options
.stdio_forward_port
);
1616 if ((in
= dup(STDIN_FILENO
)) < 0 ||
1617 (out
= dup(STDOUT_FILENO
)) < 0)
1618 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1619 if ((c
= channel_connect_stdio_fwd(ssh
, options
.stdio_forward_host
,
1620 options
.stdio_forward_port
, in
, out
)) == NULL
)
1621 fatal("%s: channel_connect_stdio_fwd failed", __func__
);
1622 channel_register_cleanup(ssh
, c
->self
, client_cleanup_stdio_fwd
, 0);
1623 channel_register_open_confirm(ssh
, c
->self
, ssh_stdio_confirm
, NULL
);
1627 ssh_init_forwarding(struct ssh
*ssh
)
1632 /* Initiate local TCP/IP port forwardings. */
1633 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
1634 debug("Local connections to %.200s:%d forwarded to remote "
1635 "address %.200s:%d",
1636 (options
.local_forwards
[i
].listen_path
!= NULL
) ?
1637 options
.local_forwards
[i
].listen_path
:
1638 (options
.local_forwards
[i
].listen_host
== NULL
) ?
1639 (options
.fwd_opts
.gateway_ports
? "*" : "LOCALHOST") :
1640 options
.local_forwards
[i
].listen_host
,
1641 options
.local_forwards
[i
].listen_port
,
1642 (options
.local_forwards
[i
].connect_path
!= NULL
) ?
1643 options
.local_forwards
[i
].connect_path
:
1644 options
.local_forwards
[i
].connect_host
,
1645 options
.local_forwards
[i
].connect_port
);
1646 success
+= channel_setup_local_fwd_listener(ssh
,
1647 &options
.local_forwards
[i
], &options
.fwd_opts
);
1649 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
1650 fatal("Could not request local forwarding.");
1651 if (i
> 0 && success
== 0)
1652 error("Could not request local forwarding.");
1654 /* Initiate remote TCP/IP port forwardings. */
1655 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
1656 debug("Remote connections from %.200s:%d forwarded to "
1657 "local address %.200s:%d",
1658 (options
.remote_forwards
[i
].listen_path
!= NULL
) ?
1659 options
.remote_forwards
[i
].listen_path
:
1660 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
1661 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
1662 options
.remote_forwards
[i
].listen_port
,
1663 (options
.remote_forwards
[i
].connect_path
!= NULL
) ?
1664 options
.remote_forwards
[i
].connect_path
:
1665 options
.remote_forwards
[i
].connect_host
,
1666 options
.remote_forwards
[i
].connect_port
);
1667 options
.remote_forwards
[i
].handle
=
1668 channel_request_remote_forwarding(ssh
,
1669 &options
.remote_forwards
[i
]);
1670 if (options
.remote_forwards
[i
].handle
< 0) {
1671 if (options
.exit_on_forward_failure
)
1672 fatal("Could not request remote forwarding.");
1674 logit("Warning: Could not request remote "
1677 client_register_global_confirm(
1678 ssh_confirm_remote_forward
,
1679 &options
.remote_forwards
[i
]);
1683 /* Initiate tunnel forwarding. */
1684 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
1685 if (client_request_tun_fwd(ssh
, options
.tun_open
,
1686 options
.tun_local
, options
.tun_remote
) == -1) {
1687 if (options
.exit_on_forward_failure
)
1688 fatal("Could not request tunnel forwarding.");
1690 error("Could not request tunnel forwarding.");
1696 check_agent_present(void)
1700 if (options
.forward_agent
) {
1701 /* Clear agent forwarding if we don't have an agent. */
1702 if ((r
= ssh_get_authentication_socket(NULL
)) != 0) {
1703 options
.forward_agent
= 0;
1704 if (r
!= SSH_ERR_AGENT_NOT_PRESENT
)
1705 debug("ssh_get_authentication_socket: %s",
1712 ssh_session2_setup(struct ssh
*ssh
, int id
, int success
, void *arg
)
1714 extern char **environ
;
1715 const char *display
;
1716 int interactive
= tty_flag
;
1717 char *proto
= NULL
, *data
= NULL
;
1720 return; /* No need for error message, channels code sens one */
1722 display
= getenv("DISPLAY");
1723 if (display
== NULL
&& options
.forward_x11
)
1724 debug("X11 forwarding requested but DISPLAY not set");
1725 if (options
.forward_x11
&& client_x11_get_proto(ssh
, display
,
1726 options
.xauth_location
, options
.forward_x11_trusted
,
1727 options
.forward_x11_timeout
, &proto
, &data
) == 0) {
1728 /* Request forwarding with authentication spoofing. */
1729 debug("Requesting X11 forwarding with authentication "
1731 x11_request_forwarding_with_spoofing(ssh
, id
, display
, proto
,
1733 client_expect_confirm(ssh
, id
, "X11 forwarding", CONFIRM_WARN
);
1734 /* XXX exit_on_forward_failure */
1738 check_agent_present();
1739 if (options
.forward_agent
) {
1740 debug("Requesting authentication agent forwarding.");
1741 channel_request_start(ssh
, id
, "auth-agent-req@openssh.com", 0);
1745 /* Tell the packet module whether this is an interactive session. */
1746 packet_set_interactive(interactive
,
1747 options
.ip_qos_interactive
, options
.ip_qos_bulk
);
1749 client_session2_setup(ssh
, id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1750 NULL
, fileno(stdin
), &command
, environ
);
1753 /* open new channel for a session */
1755 ssh_session2_open(struct ssh
*ssh
)
1758 int window
, packetmax
, in
, out
, err
;
1760 if (stdin_null_flag
) {
1761 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1763 in
= dup(STDIN_FILENO
);
1765 out
= dup(STDOUT_FILENO
);
1766 err
= dup(STDERR_FILENO
);
1768 if (in
< 0 || out
< 0 || err
< 0)
1769 fatal("dup() in/out/err failed");
1771 /* enable nonblocking unless tty */
1779 window
= CHAN_SES_WINDOW_DEFAULT
;
1780 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1785 c
= channel_new(ssh
,
1786 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1787 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1788 "client-session", /*nonblock*/0);
1790 debug3("%s: channel_new: %d", __func__
, c
->self
);
1792 channel_send_open(ssh
, c
->self
);
1794 channel_register_open_confirm(ssh
, c
->self
,
1795 ssh_session2_setup
, NULL
);
1801 ssh_session2(struct ssh
*ssh
)
1805 /* XXX should be pre-session */
1806 if (!options
.control_persist
)
1807 ssh_init_stdio_forwarding(ssh
);
1808 ssh_init_forwarding(ssh
);
1810 /* Start listening for multiplex clients */
1811 if (!packet_get_mux())
1812 muxserver_listen(ssh
);
1815 * If we are in control persist mode and have a working mux listen
1816 * socket, then prepare to background ourselves and have a foreground
1817 * client attach as a control slave.
1818 * NB. we must save copies of the flags that we override for
1819 * the backgrounding, since we defer attachment of the slave until
1820 * after the connection is fully established (in particular,
1821 * async rfwd replies have been received for ExitOnForwardFailure).
1823 if (options
.control_persist
&& muxserver_sock
!= -1) {
1824 ostdin_null_flag
= stdin_null_flag
;
1825 ono_shell_flag
= no_shell_flag
;
1826 orequest_tty
= options
.request_tty
;
1827 otty_flag
= tty_flag
;
1828 stdin_null_flag
= 1;
1831 if (!fork_after_authentication_flag
)
1832 need_controlpersist_detach
= 1;
1833 fork_after_authentication_flag
= 1;
1836 * ControlPersist mux listen socket setup failed, attempt the
1837 * stdio forward setup that we skipped earlier.
1839 if (options
.control_persist
&& muxserver_sock
== -1)
1840 ssh_init_stdio_forwarding(ssh
);
1842 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1843 id
= ssh_session2_open(ssh
);
1845 packet_set_interactive(
1846 options
.control_master
== SSHCTL_MASTER_NO
,
1847 options
.ip_qos_interactive
, options
.ip_qos_bulk
);
1850 /* If we don't expect to open a new session, then disallow it */
1851 if (options
.control_master
== SSHCTL_MASTER_NO
&&
1852 (datafellows
& SSH_NEW_OPENSSH
)) {
1853 debug("Requesting no-more-sessions@openssh.com");
1854 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
1855 packet_put_cstring("no-more-sessions@openssh.com");
1860 /* Execute a local command */
1861 if (options
.local_command
!= NULL
&&
1862 options
.permit_local_command
)
1863 ssh_local_cmd(options
.local_command
);
1866 * If requested and we are not interested in replies to remote
1867 * forwarding requests, then let ssh continue in the background.
1869 if (fork_after_authentication_flag
) {
1870 if (options
.exit_on_forward_failure
&&
1871 options
.num_remote_forwards
> 0) {
1872 debug("deferring postauth fork until remote forward "
1873 "confirmation received");
1878 return client_loop(ssh
, tty_flag
, tty_flag
?
1879 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1882 /* Loads all IdentityFile and CertificateFile keys */
1884 load_public_identity_files(void)
1886 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1887 char *pwdir
= NULL
, *pwname
= NULL
;
1888 struct sshkey
*public;
1891 u_int n_ids
, n_certs
;
1892 char *identity_files
[SSH_MAX_IDENTITY_FILES
];
1893 struct sshkey
*identity_keys
[SSH_MAX_IDENTITY_FILES
];
1894 char *certificate_files
[SSH_MAX_CERTIFICATE_FILES
];
1895 struct sshkey
*certificates
[SSH_MAX_CERTIFICATE_FILES
];
1896 #ifdef ENABLE_PKCS11
1897 struct sshkey
**keys
;
1901 n_ids
= n_certs
= 0;
1902 memset(identity_files
, 0, sizeof(identity_files
));
1903 memset(identity_keys
, 0, sizeof(identity_keys
));
1904 memset(certificate_files
, 0, sizeof(certificate_files
));
1905 memset(certificates
, 0, sizeof(certificates
));
1907 #ifdef ENABLE_PKCS11
1908 if (options
.pkcs11_provider
!= NULL
&&
1909 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1910 (pkcs11_init(!options
.batch_mode
) == 0) &&
1911 (nkeys
= pkcs11_add_provider(options
.pkcs11_provider
, NULL
,
1913 for (i
= 0; i
< nkeys
; i
++) {
1914 if (n_ids
>= SSH_MAX_IDENTITY_FILES
) {
1918 identity_keys
[n_ids
] = keys
[i
];
1919 identity_files
[n_ids
] =
1920 xstrdup(options
.pkcs11_provider
); /* XXX */
1925 #endif /* ENABLE_PKCS11 */
1926 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1927 fatal("load_public_identity_files: getpwuid failed");
1928 pwname
= xstrdup(pw
->pw_name
);
1929 pwdir
= xstrdup(pw
->pw_dir
);
1930 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1931 fatal("load_public_identity_files: gethostname: %s",
1933 for (i
= 0; i
< options
.num_identity_files
; i
++) {
1934 if (n_ids
>= SSH_MAX_IDENTITY_FILES
||
1935 strcasecmp(options
.identity_files
[i
], "none") == 0) {
1936 free(options
.identity_files
[i
]);
1937 options
.identity_files
[i
] = NULL
;
1940 cp
= tilde_expand_filename(options
.identity_files
[i
],
1942 filename
= percent_expand(cp
, "d", pwdir
,
1943 "u", pwname
, "l", thishost
, "h", host
,
1944 "r", options
.user
, (char *)NULL
);
1946 public = key_load_public(filename
, NULL
);
1947 debug("identity file %s type %d", filename
,
1948 public ? public->type
: -1);
1949 free(options
.identity_files
[i
]);
1950 identity_files
[n_ids
] = filename
;
1951 identity_keys
[n_ids
] = public;
1953 if (++n_ids
>= SSH_MAX_IDENTITY_FILES
)
1957 * If no certificates have been explicitly listed then try
1958 * to add the default certificate variant too.
1960 if (options
.num_certificate_files
!= 0)
1962 xasprintf(&cp
, "%s-cert", filename
);
1963 public = key_load_public(cp
, NULL
);
1964 debug("identity file %s type %d", cp
,
1965 public ? public->type
: -1);
1966 if (public == NULL
) {
1970 if (!key_is_cert(public)) {
1971 debug("%s: key %s type %s is not a certificate",
1972 __func__
, cp
, key_type(public));
1977 /* NB. leave filename pointing to private key */
1978 identity_files
[n_ids
] = xstrdup(filename
);
1979 identity_keys
[n_ids
] = public;
1983 if (options
.num_certificate_files
> SSH_MAX_CERTIFICATE_FILES
)
1984 fatal("%s: too many certificates", __func__
);
1985 for (i
= 0; i
< options
.num_certificate_files
; i
++) {
1986 cp
= tilde_expand_filename(options
.certificate_files
[i
],
1988 filename
= percent_expand(cp
, "d", pwdir
,
1989 "u", pwname
, "l", thishost
, "h", host
,
1990 "r", options
.user
, (char *)NULL
);
1993 public = key_load_public(filename
, NULL
);
1994 debug("certificate file %s type %d", filename
,
1995 public ? public->type
: -1);
1996 free(options
.certificate_files
[i
]);
1997 options
.certificate_files
[i
] = NULL
;
1998 if (public == NULL
) {
2002 if (!key_is_cert(public)) {
2003 debug("%s: key %s type %s is not a certificate",
2004 __func__
, filename
, key_type(public));
2009 certificate_files
[n_certs
] = filename
;
2010 certificates
[n_certs
] = public;
2014 options
.num_identity_files
= n_ids
;
2015 memcpy(options
.identity_files
, identity_files
, sizeof(identity_files
));
2016 memcpy(options
.identity_keys
, identity_keys
, sizeof(identity_keys
));
2018 options
.num_certificate_files
= n_certs
;
2019 memcpy(options
.certificate_files
,
2020 certificate_files
, sizeof(certificate_files
));
2021 memcpy(options
.certificates
, certificates
, sizeof(certificates
));
2023 explicit_bzero(pwname
, strlen(pwname
));
2025 explicit_bzero(pwdir
, strlen(pwdir
));
2030 main_sigchld_handler(int sig
)
2032 int save_errno
= errno
;
2036 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0 ||
2037 (pid
< 0 && errno
== EINTR
))
2040 signal(sig
, main_sigchld_handler
);