1 /* $OpenBSD: ssh.c,v 1.445 2016/07/17 04:20:16 djm 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"
96 #include "pathnames.h"
98 #include "clientloop.h"
101 #include "readconf.h"
102 #include "sshconnect.h"
111 #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 [-1246AaCfGgKkMNnqsTtVvXxYy] [-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_session(void);
212 static int ssh_session2(void);
213 static void load_public_identity_files(void);
214 static void main_sigchld_handler(int);
216 /* from muxclient.c */
217 void muxclient(const char *);
218 void muxserver_listen(void);
220 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
222 tilde_expand_paths(char **paths
, u_int num_paths
)
227 for (i
= 0; i
< num_paths
; i
++) {
228 cp
= tilde_expand_filename(paths
[i
], original_real_uid
);
235 * Attempt to resolve a host name / port to a set of addresses and
236 * optionally return any CNAMEs encountered along the way.
237 * Returns NULL on failure.
238 * NB. this function must operate with a options having undefined members.
240 static struct addrinfo
*
241 resolve_host(const char *name
, int port
, int logerr
, char *cname
, size_t clen
)
243 char strport
[NI_MAXSERV
];
244 struct addrinfo hints
, *res
;
245 int gaierr
, loglevel
= SYSLOG_LEVEL_DEBUG1
;
248 port
= default_ssh_port();
250 snprintf(strport
, sizeof strport
, "%d", port
);
251 memset(&hints
, 0, sizeof(hints
));
252 hints
.ai_family
= options
.address_family
== -1 ?
253 AF_UNSPEC
: options
.address_family
;
254 hints
.ai_socktype
= SOCK_STREAM
;
256 hints
.ai_flags
= AI_CANONNAME
;
257 if ((gaierr
= getaddrinfo(name
, strport
, &hints
, &res
)) != 0) {
258 if (logerr
|| (gaierr
!= EAI_NONAME
&& gaierr
!= EAI_NODATA
))
259 loglevel
= SYSLOG_LEVEL_ERROR
;
260 do_log2(loglevel
, "%s: Could not resolve hostname %.100s: %s",
261 __progname
, name
, ssh_gai_strerror(gaierr
));
264 if (cname
!= NULL
&& res
->ai_canonname
!= NULL
) {
265 if (strlcpy(cname
, res
->ai_canonname
, clen
) >= clen
) {
266 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
267 __func__
, name
, res
->ai_canonname
, (u_long
)clen
);
276 * Attempt to resolve a numeric host address / port to a single address.
277 * Returns a canonical address string.
278 * Returns NULL on failure.
279 * NB. this function must operate with a options having undefined members.
281 static struct addrinfo
*
282 resolve_addr(const char *name
, int port
, char *caddr
, size_t clen
)
284 char addr
[NI_MAXHOST
], strport
[NI_MAXSERV
];
285 struct addrinfo hints
, *res
;
289 port
= default_ssh_port();
290 snprintf(strport
, sizeof strport
, "%u", port
);
291 memset(&hints
, 0, sizeof(hints
));
292 hints
.ai_family
= options
.address_family
== -1 ?
293 AF_UNSPEC
: options
.address_family
;
294 hints
.ai_socktype
= SOCK_STREAM
;
295 hints
.ai_flags
= AI_NUMERICHOST
|AI_NUMERICSERV
;
296 if ((gaierr
= getaddrinfo(name
, strport
, &hints
, &res
)) != 0) {
297 debug2("%s: could not resolve name %.100s as address: %s",
298 __func__
, name
, ssh_gai_strerror(gaierr
));
302 debug("%s: getaddrinfo %.100s returned no addresses",
306 if (res
->ai_next
!= NULL
) {
307 debug("%s: getaddrinfo %.100s returned multiple addresses",
311 if ((gaierr
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
312 addr
, sizeof(addr
), NULL
, 0, NI_NUMERICHOST
)) != 0) {
313 debug("%s: Could not format address for name %.100s: %s",
314 __func__
, name
, ssh_gai_strerror(gaierr
));
317 if (strlcpy(caddr
, addr
, clen
) >= clen
) {
318 error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
319 __func__
, name
, addr
, (u_long
)clen
);
330 * Check whether the cname is a permitted replacement for the hostname
331 * and perform the replacement if it is.
332 * NB. this function must operate with a options having undefined members.
335 check_follow_cname(int direct
, char **namep
, const char *cname
)
338 struct allowed_cname
*rule
;
340 if (*cname
== '\0' || options
.num_permitted_cnames
== 0 ||
341 strcmp(*namep
, cname
) == 0)
343 if (options
.canonicalize_hostname
== SSH_CANONICALISE_NO
)
346 * Don't attempt to canonicalize names that will be interpreted by
347 * a proxy or jump host unless the user specifically requests so.
350 options
.canonicalize_hostname
!= SSH_CANONICALISE_ALWAYS
)
352 debug3("%s: check \"%s\" CNAME \"%s\"", __func__
, *namep
, cname
);
353 for (i
= 0; i
< options
.num_permitted_cnames
; i
++) {
354 rule
= options
.permitted_cnames
+ i
;
355 if (match_pattern_list(*namep
, rule
->source_list
, 1) != 1 ||
356 match_pattern_list(cname
, rule
->target_list
, 1) != 1)
358 verbose("Canonicalized DNS aliased hostname "
359 "\"%s\" => \"%s\"", *namep
, cname
);
361 *namep
= xstrdup(cname
);
368 * Attempt to resolve the supplied hostname after applying the user's
369 * canonicalization rules. Returns the address list for the host or NULL
370 * if no name was found after canonicalization.
371 * NB. this function must operate with a options having undefined members.
373 static struct addrinfo
*
374 resolve_canonicalize(char **hostp
, int port
)
376 int i
, direct
, ndots
;
377 char *cp
, *fullhost
, newname
[NI_MAXHOST
];
378 struct addrinfo
*addrs
;
380 if (options
.canonicalize_hostname
== SSH_CANONICALISE_NO
)
384 * Don't attempt to canonicalize names that will be interpreted by
385 * a proxy unless the user specifically requests so.
387 direct
= option_clear_or_none(options
.proxy_command
) &&
388 options
.jump_host
== NULL
;
390 options
.canonicalize_hostname
!= SSH_CANONICALISE_ALWAYS
)
393 /* Try numeric hostnames first */
394 if ((addrs
= resolve_addr(*hostp
, port
,
395 newname
, sizeof(newname
))) != NULL
) {
396 debug2("%s: hostname %.100s is address", __func__
, *hostp
);
397 if (strcasecmp(*hostp
, newname
) != 0) {
398 debug2("%s: canonicalised address \"%s\" => \"%s\"",
399 __func__
, *hostp
, newname
);
401 *hostp
= xstrdup(newname
);
406 /* If domain name is anchored, then resolve it now */
407 if ((*hostp
)[strlen(*hostp
) - 1] == '.') {
408 debug3("%s: name is fully qualified", __func__
);
409 fullhost
= xstrdup(*hostp
);
410 if ((addrs
= resolve_host(fullhost
, port
, 0,
411 newname
, sizeof(newname
))) != NULL
)
417 /* Don't apply canonicalization to sufficiently-qualified hostnames */
419 for (cp
= *hostp
; *cp
!= '\0'; cp
++) {
423 if (ndots
> options
.canonicalize_max_dots
) {
424 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
425 __func__
, *hostp
, options
.canonicalize_max_dots
);
428 /* Attempt each supplied suffix */
429 for (i
= 0; i
< options
.num_canonical_domains
; i
++) {
431 xasprintf(&fullhost
, "%s.%s.", *hostp
,
432 options
.canonical_domains
[i
]);
433 debug3("%s: attempting \"%s\" => \"%s\"", __func__
,
435 if ((addrs
= resolve_host(fullhost
, port
, 0,
436 newname
, sizeof(newname
))) == NULL
) {
441 /* Remove trailing '.' */
442 fullhost
[strlen(fullhost
) - 1] = '\0';
443 /* Follow CNAME if requested */
444 if (!check_follow_cname(direct
, &fullhost
, newname
)) {
445 debug("Canonicalized hostname \"%s\" => \"%s\"",
453 if (!options
.canonicalize_fallback_local
)
454 fatal("%s: Could not resolve host \"%s\"", __progname
, *hostp
);
455 debug2("%s: host %s not found in any suffix", __func__
, *hostp
);
460 * Read per-user configuration file. Ignore the system wide config
461 * file if the user specifies a config file on the command line.
464 process_config_files(const char *host_arg
, struct passwd
*pw
, int post_canon
)
469 if (config
!= NULL
) {
470 if (strcasecmp(config
, "none") != 0 &&
471 !read_config_file(config
, pw
, host
, host_arg
, &options
,
472 SSHCONF_USERCONF
| (post_canon
? SSHCONF_POSTCANON
: 0)))
473 fatal("Can't open user config file %.100s: "
474 "%.100s", config
, strerror(errno
));
476 r
= snprintf(buf
, sizeof buf
, "%s/%s", pw
->pw_dir
,
477 _PATH_SSH_USER_CONFFILE
);
478 if (r
> 0 && (size_t)r
< sizeof(buf
))
479 (void)read_config_file(buf
, pw
, host
, host_arg
,
480 &options
, SSHCONF_CHECKPERM
| SSHCONF_USERCONF
|
481 (post_canon
? SSHCONF_POSTCANON
: 0));
483 /* Read systemwide configuration file after user config. */
484 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, pw
,
485 host
, host_arg
, &options
,
486 post_canon
? SSHCONF_POSTCANON
: 0);
490 /* Rewrite the port number in an addrinfo list of addresses */
492 set_addrinfo_port(struct addrinfo
*addrs
, int port
)
494 struct addrinfo
*addr
;
496 for (addr
= addrs
; addr
!= NULL
; addr
= addr
->ai_next
) {
497 switch (addr
->ai_family
) {
499 ((struct sockaddr_in
*)addr
->ai_addr
)->
500 sin_port
= htons(port
);
503 ((struct sockaddr_in6
*)addr
->ai_addr
)->
504 sin6_port
= htons(port
);
511 * Main program for the ssh client.
514 main(int ac
, char **av
)
516 struct ssh
*ssh
= NULL
;
517 int i
, r
, opt
, exit_status
, use_syslog
, direct
, config_test
= 0;
518 char *p
, *cp
, *line
, *argv0
, buf
[PATH_MAX
], *host_arg
, *logfile
;
519 char thishost
[NI_MAXHOST
], shorthost
[NI_MAXHOST
], portstr
[NI_MAXSERV
];
520 char cname
[NI_MAXHOST
], uidstr
[32], *conn_hash_hex
;
524 extern int optind
, optreset
;
527 struct addrinfo
*addrs
= NULL
;
528 struct ssh_digest_ctx
*md
;
529 u_char conn_hash
[SSH_DIGEST_MAX_LENGTH
];
531 ssh_malloc_init(); /* must be called before any mallocs */
532 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
535 __progname
= ssh_get_progname(av
[0]);
537 #ifndef HAVE_SETPROCTITLE
538 /* Prepare for later setproctitle emulation */
539 /* Save argv so it isn't clobbered by setproctitle() emulation */
540 saved_av
= xcalloc(ac
+ 1, sizeof(*saved_av
));
541 for (i
= 0; i
< ac
; i
++)
542 saved_av
[i
] = xstrdup(av
[i
]);
544 compat_init_setproctitle(ac
, av
);
549 * Discard other fds that are hanging around. These can cause problem
550 * with backgrounded ssh processes started by ControlPersist.
552 closefrom(STDERR_FILENO
+ 1);
555 * Save the original real uid. It will be needed later (uid-swapping
556 * may clobber the real uid).
558 original_real_uid
= getuid();
559 original_effective_uid
= geteuid();
562 * Use uid-swapping to give up root privileges for the duration of
563 * option processing. We will re-instantiate the rights when we are
564 * ready to create the privileged port, and will permanently drop
565 * them when the port has been created (actually, when the connection
566 * has been made, as we may need to create the port several times).
570 #ifdef HAVE_SETRLIMIT
571 /* If we are installed setuid root be careful to not drop core. */
572 if (original_real_uid
!= original_effective_uid
) {
574 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
575 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
576 fatal("setrlimit failed: %.100s", strerror(errno
));
580 pw
= getpwuid(original_real_uid
);
582 logit("No user exists for uid %lu", (u_long
)original_real_uid
);
585 /* Take a copy of the returned structure. */
589 * Set our umask to something reasonable, as some files are created
590 * with the default umask. This will make them world-readable but
591 * writable only by the owner, which is ok for all files for which we
592 * don't set the modes explicitly.
596 setlocale(LC_CTYPE
, "");
599 * Initialize option structure to indicate that no values have been
602 initialize_options(&options
);
604 /* Parse command-line arguments. */
611 while ((opt
= getopt(ac
, av
, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
612 "ACD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
615 options
.protocol
= SSH_PROTO_1
;
618 options
.protocol
= SSH_PROTO_2
;
621 options
.address_family
= AF_INET
;
624 options
.address_family
= AF_INET6
;
630 fork_after_authentication_flag
= 1;
634 options
.forward_x11
= 0;
637 options
.forward_x11
= 1;
649 options
.forward_x11
= 1;
650 options
.forward_x11_trusted
= 1;
653 options
.fwd_opts
.gateway_ports
= 1;
656 if (options
.stdio_forward_host
!= NULL
)
657 fatal("Cannot specify multiplexing "
659 else if (muxclient_command
!= 0)
660 fatal("Multiplexing command already specified");
661 if (strcmp(optarg
, "check") == 0)
662 muxclient_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
663 else if (strcmp(optarg
, "forward") == 0)
664 muxclient_command
= SSHMUX_COMMAND_FORWARD
;
665 else if (strcmp(optarg
, "exit") == 0)
666 muxclient_command
= SSHMUX_COMMAND_TERMINATE
;
667 else if (strcmp(optarg
, "stop") == 0)
668 muxclient_command
= SSHMUX_COMMAND_STOP
;
669 else if (strcmp(optarg
, "cancel") == 0)
670 muxclient_command
= SSHMUX_COMMAND_CANCEL_FWD
;
672 fatal("Invalid multiplex command.");
674 case 'P': /* deprecated */
675 options
.use_privileged_port
= 0;
679 if (strcmp(optarg
, "cipher") == 0)
680 cp
= cipher_alg_list('\n', 0);
681 else if (strcmp(optarg
, "cipher-auth") == 0)
682 cp
= cipher_alg_list('\n', 1);
683 else if (strcmp(optarg
, "mac") == 0)
684 cp
= mac_alg_list('\n');
685 else if (strcmp(optarg
, "kex") == 0)
686 cp
= kex_alg_list('\n');
687 else if (strcmp(optarg
, "key") == 0)
688 cp
= key_alg_list(0, 0);
689 else if (strcmp(optarg
, "key-cert") == 0)
690 cp
= key_alg_list(1, 0);
691 else if (strcmp(optarg
, "key-plain") == 0)
692 cp
= key_alg_list(0, 1);
693 else if (strcmp(optarg
, "protocol-version") == 0) {
695 cp
= xstrdup("1\n2");
701 fatal("Unsupported query \"%s\"", optarg
);
707 options
.forward_agent
= 0;
710 options
.forward_agent
= 1;
713 options
.gss_deleg_creds
= 0;
716 options
.gss_authentication
= 1;
717 options
.gss_deleg_creds
= 1;
720 p
= tilde_expand_filename(optarg
, original_real_uid
);
721 if (stat(p
, &st
) < 0)
722 fprintf(stderr
, "Warning: Identity file %s "
723 "not accessible: %s.\n", p
,
726 add_identity_file(&options
, NULL
, p
, 1);
731 free(options
.pkcs11_provider
);
732 options
.pkcs11_provider
= xstrdup(optarg
);
734 fprintf(stderr
, "no support for PKCS#11.\n");
738 if (options
.jump_host
!= NULL
)
739 fatal("Only a single -J option permitted");
740 if (options
.proxy_command
!= NULL
)
741 fatal("Cannot specify -J with ProxyCommand");
742 if (parse_jump(optarg
, &options
, 1) == -1)
743 fatal("Invalid -J argument");
744 options
.proxy_command
= xstrdup("none");
747 if (options
.request_tty
== REQUEST_TTY_YES
)
748 options
.request_tty
= REQUEST_TTY_FORCE
;
750 options
.request_tty
= REQUEST_TTY_YES
;
753 if (debug_flag
== 0) {
755 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
757 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
) {
764 fprintf(stderr
, "%s, %s\n",
767 SSLeay_version(SSLEAY_VERSION
)
776 if (options
.tun_open
== -1)
777 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
778 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
779 if (options
.tun_local
== SSH_TUNID_ERR
) {
781 "Bad tun device '%s'\n", optarg
);
786 if (options
.stdio_forward_host
!= NULL
)
787 fatal("stdio forward already specified");
788 if (muxclient_command
!= 0)
789 fatal("Cannot specify stdio forward with -O");
790 if (parse_forward(&fwd
, optarg
, 1, 0)) {
791 options
.stdio_forward_host
= fwd
.listen_host
;
792 options
.stdio_forward_port
= fwd
.listen_port
;
793 free(fwd
.connect_host
);
796 "Bad stdio forwarding specification '%s'\n",
800 options
.request_tty
= REQUEST_TTY_NO
;
804 options
.log_level
= SYSLOG_LEVEL_QUIET
;
807 if (optarg
[0] == '^' && optarg
[2] == 0 &&
808 (u_char
) optarg
[1] >= 64 &&
809 (u_char
) optarg
[1] < 128)
810 options
.escape_char
= (u_char
) optarg
[1] & 31;
811 else if (strlen(optarg
) == 1)
812 options
.escape_char
= (u_char
) optarg
[0];
813 else if (strcmp(optarg
, "none") == 0)
814 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
816 fprintf(stderr
, "Bad escape character '%s'.\n",
822 if (ciphers_valid(*optarg
== '+' ?
823 optarg
+ 1 : optarg
)) {
825 free(options
.ciphers
);
826 options
.ciphers
= xstrdup(optarg
);
827 options
.cipher
= SSH_CIPHER_INVALID
;
831 options
.cipher
= cipher_number(optarg
);
832 if (options
.cipher
== -1) {
833 fprintf(stderr
, "Unknown cipher type '%s'\n",
837 if (options
.cipher
== SSH_CIPHER_3DES
)
838 options
.ciphers
= xstrdup("3des-cbc");
839 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
840 options
.ciphers
= xstrdup("blowfish-cbc");
842 options
.ciphers
= xstrdup(KEX_CLIENT_ENCRYPT
);
845 if (mac_valid(optarg
)) {
847 options
.macs
= xstrdup(optarg
);
849 fprintf(stderr
, "Unknown mac type '%s'\n",
855 if (options
.control_master
== SSHCTL_MASTER_YES
)
856 options
.control_master
= SSHCTL_MASTER_ASK
;
858 options
.control_master
= SSHCTL_MASTER_YES
;
861 options
.port
= a2port(optarg
);
862 if (options
.port
<= 0) {
863 fprintf(stderr
, "Bad port '%s'\n", optarg
);
868 options
.user
= optarg
;
872 if (parse_forward(&fwd
, optarg
, 0, 0))
873 add_local_forward(&options
, &fwd
);
876 "Bad local forwarding specification '%s'\n",
883 if (parse_forward(&fwd
, optarg
, 0, 1)) {
884 add_remote_forward(&options
, &fwd
);
887 "Bad remote forwarding specification "
894 if (parse_forward(&fwd
, optarg
, 1, 0)) {
895 add_local_forward(&options
, &fwd
);
898 "Bad dynamic forwarding specification "
905 options
.compression
= 1;
909 options
.request_tty
= REQUEST_TTY_NO
;
912 options
.request_tty
= REQUEST_TTY_NO
;
915 line
= xstrdup(optarg
);
916 if (process_config_line(&options
, pw
,
917 host
? host
: "", host
? host
: "", line
,
918 "command-line", 0, NULL
, SSHCONF_USERCONF
) != 0)
926 free(options
.control_path
);
927 options
.control_path
= xstrdup(optarg
);
930 options
.bind_address
= optarg
;
943 if (ac
> 0 && !host
) {
944 if (strrchr(*av
, '@')) {
946 cp
= strrchr(p
, '@');
947 if (cp
== NULL
|| cp
== p
)
951 host
= xstrdup(++cp
);
955 optind
= optreset
= 1;
961 /* Check that we got a host name. */
965 host_arg
= xstrdup(host
);
968 OpenSSL_add_all_algorithms();
969 ERR_load_crypto_strings();
972 /* Initialize the command to execute on remote host. */
973 buffer_init(&command
);
976 * Save the command to execute on the remote host in a buffer. There
977 * is no limit on the length of the command, except by the maximum
978 * packet size. Also sets the tty flag if there is no command.
981 /* No command specified - execute shell on a tty. */
982 if (subsystem_flag
) {
984 "You must specify a subsystem to invoke.\n");
988 /* A command has been specified. Store it into the buffer. */
989 for (i
= 0; i
< ac
; i
++) {
991 buffer_append(&command
, " ", 1);
992 buffer_append(&command
, av
[i
], strlen(av
[i
]));
996 /* Cannot fork to background if no command. */
997 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 &&
999 fatal("Cannot fork into background without a command "
1003 * Initialize "log" output. Since we are the client all output
1004 * goes to stderr unless otherwise specified by -y or -E.
1006 if (use_syslog
&& logfile
!= NULL
)
1007 fatal("Can't specify both -y and -E");
1008 if (logfile
!= NULL
)
1009 log_redirect_stderr_to(logfile
);
1011 options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
1012 SYSLOG_FACILITY_USER
, !use_syslog
);
1015 logit("%s, %s", SSH_RELEASE
,
1017 SSLeay_version(SSLEAY_VERSION
)
1023 /* Parse the configuration files */
1024 process_config_files(host_arg
, pw
, 0);
1026 /* Hostname canonicalisation needs a few options filled. */
1027 fill_default_options_for_canonicalization(&options
);
1029 /* If the user has replaced the hostname then take it into use now */
1030 if (options
.hostname
!= NULL
) {
1031 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1032 cp
= percent_expand(options
.hostname
,
1033 "h", host
, (char *)NULL
);
1036 free(options
.hostname
);
1037 options
.hostname
= xstrdup(host
);
1040 /* If canonicalization requested then try to apply it */
1042 if (options
.canonicalize_hostname
!= SSH_CANONICALISE_NO
)
1043 addrs
= resolve_canonicalize(&host
, options
.port
);
1046 * If CanonicalizePermittedCNAMEs have been specified but
1047 * other canonicalization did not happen (by not being requested
1048 * or by failing with fallback) then the hostname may still be changed
1049 * as a result of CNAME following.
1051 * Try to resolve the bare hostname name using the system resolver's
1052 * usual search rules and then apply the CNAME follow rules.
1054 * Skip the lookup if a ProxyCommand is being used unless the user
1055 * has specifically requested canonicalisation for this case via
1056 * CanonicalizeHostname=always
1058 direct
= option_clear_or_none(options
.proxy_command
) &&
1059 options
.jump_host
== NULL
;
1060 if (addrs
== NULL
&& options
.num_permitted_cnames
!= 0 && (direct
||
1061 options
.canonicalize_hostname
== SSH_CANONICALISE_ALWAYS
)) {
1062 if ((addrs
= resolve_host(host
, options
.port
,
1063 option_clear_or_none(options
.proxy_command
),
1064 cname
, sizeof(cname
))) == NULL
) {
1065 /* Don't fatal proxied host names not in the DNS */
1066 if (option_clear_or_none(options
.proxy_command
))
1067 cleanup_exit(255); /* logged in resolve_host */
1069 check_follow_cname(direct
, &host
, cname
);
1073 * If canonicalisation is enabled then re-parse the configuration
1074 * files as new stanzas may match.
1076 if (options
.canonicalize_hostname
!= 0) {
1077 debug("Re-reading configuration after hostname "
1078 "canonicalisation");
1079 free(options
.hostname
);
1080 options
.hostname
= xstrdup(host
);
1081 process_config_files(host_arg
, pw
, 1);
1083 * Address resolution happens early with canonicalisation
1084 * enabled and the port number may have changed since, so
1085 * reset it in address list
1087 if (addrs
!= NULL
&& options
.port
> 0)
1088 set_addrinfo_port(addrs
, options
.port
);
1091 /* Fill configuration defaults. */
1092 fill_default_options(&options
);
1095 * If ProxyJump option specified, then construct a ProxyCommand now.
1097 if (options
.jump_host
!= NULL
) {
1100 /* Consistency check */
1101 if (options
.proxy_command
!= NULL
)
1102 fatal("inconsistent options: ProxyCommand+ProxyJump");
1103 /* Never use FD passing for ProxyJump */
1104 options
.proxy_use_fdpass
= 0;
1105 snprintf(port_s
, sizeof(port_s
), "%d", options
.jump_port
);
1106 xasprintf(&options
.proxy_command
,
1107 "ssh%s%s%s%s%s%s%s%s%s%.*s -W %%h:%%p %s",
1108 /* Optional "-l user" argument if jump_user set */
1109 options
.jump_user
== NULL
? "" : " -l ",
1110 options
.jump_user
== NULL
? "" : options
.jump_user
,
1111 /* Optional "-p port" argument if jump_port set */
1112 options
.jump_port
<= 0 ? "" : " -p ",
1113 options
.jump_port
<= 0 ? "" : port_s
,
1114 /* Optional additional jump hosts ",..." */
1115 options
.jump_extra
== NULL
? "" : " -J ",
1116 options
.jump_extra
== NULL
? "" : options
.jump_extra
,
1117 /* Optional "-F" argumment if -F specified */
1118 config
== NULL
? "" : " -F ",
1119 config
== NULL
? "" : config
,
1120 /* Optional "-v" arguments if -v set */
1121 debug_flag
? " -" : "",
1123 /* Mandatory hostname */
1125 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1126 options
.proxy_command
);
1129 if (options
.port
== 0)
1130 options
.port
= default_ssh_port();
1131 channel_set_af(options
.address_family
);
1133 /* Tidy and check options */
1134 if (options
.host_key_alias
!= NULL
)
1135 lowercase(options
.host_key_alias
);
1136 if (options
.proxy_command
!= NULL
&&
1137 strcmp(options
.proxy_command
, "-") == 0 &&
1138 options
.proxy_use_fdpass
)
1139 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1140 if (options
.control_persist
&&
1141 options
.update_hostkeys
== SSH_UPDATE_HOSTKEYS_ASK
) {
1142 debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1144 options
.update_hostkeys
= 0;
1146 if (options
.connection_attempts
<= 0)
1147 fatal("Invalid number of ConnectionAttempts");
1149 if (original_effective_uid
!= 0)
1150 options
.use_privileged_port
= 0;
1154 log_init(argv0
, options
.log_level
, SYSLOG_FACILITY_USER
, !use_syslog
);
1156 if (options
.request_tty
== REQUEST_TTY_YES
||
1157 options
.request_tty
== REQUEST_TTY_FORCE
)
1160 /* Allocate a tty by default if no command specified. */
1161 if (buffer_len(&command
) == 0)
1162 tty_flag
= options
.request_tty
!= REQUEST_TTY_NO
;
1165 if (options
.request_tty
== REQUEST_TTY_NO
|| muxclient_command
!= 0)
1167 /* Do not allocate a tty if stdin is not a tty. */
1168 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) &&
1169 options
.request_tty
!= REQUEST_TTY_FORCE
) {
1171 logit("Pseudo-terminal will not be allocated because "
1172 "stdin is not a terminal.");
1178 if (options
.user
== NULL
)
1179 options
.user
= xstrdup(pw
->pw_name
);
1181 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1182 fatal("gethostname: %s", strerror(errno
));
1183 strlcpy(shorthost
, thishost
, sizeof(shorthost
));
1184 shorthost
[strcspn(thishost
, ".")] = '\0';
1185 snprintf(portstr
, sizeof(portstr
), "%d", options
.port
);
1186 snprintf(uidstr
, sizeof(uidstr
), "%d", pw
->pw_uid
);
1188 if ((md
= ssh_digest_start(SSH_DIGEST_SHA1
)) == NULL
||
1189 ssh_digest_update(md
, thishost
, strlen(thishost
)) < 0 ||
1190 ssh_digest_update(md
, host
, strlen(host
)) < 0 ||
1191 ssh_digest_update(md
, portstr
, strlen(portstr
)) < 0 ||
1192 ssh_digest_update(md
, options
.user
, strlen(options
.user
)) < 0 ||
1193 ssh_digest_final(md
, conn_hash
, sizeof(conn_hash
)) < 0)
1194 fatal("%s: mux digest failed", __func__
);
1195 ssh_digest_free(md
);
1196 conn_hash_hex
= tohex(conn_hash
, ssh_digest_bytes(SSH_DIGEST_SHA1
));
1198 if (options
.local_command
!= NULL
) {
1199 debug3("expanding LocalCommand: %s", options
.local_command
);
1200 cp
= options
.local_command
;
1201 options
.local_command
= percent_expand(cp
,
1212 debug3("expanded LocalCommand: %s", options
.local_command
);
1216 if (options
.control_path
!= NULL
) {
1217 cp
= tilde_expand_filename(options
.control_path
,
1219 free(options
.control_path
);
1220 options
.control_path
= percent_expand(cp
,
1233 free(conn_hash_hex
);
1236 dump_client_config(&options
, host
);
1240 if (muxclient_command
!= 0 && options
.control_path
== NULL
)
1241 fatal("No ControlPath specified for \"-O\" command");
1242 if (options
.control_path
!= NULL
)
1243 muxclient(options
.control_path
);
1246 * If hostname canonicalisation was not enabled, then we may not
1247 * have yet resolved the hostname. Do so now.
1249 if (addrs
== NULL
&& options
.proxy_command
== NULL
) {
1250 debug2("resolving \"%s\" port %d", host
, options
.port
);
1251 if ((addrs
= resolve_host(host
, options
.port
, 1,
1252 cname
, sizeof(cname
))) == NULL
)
1253 cleanup_exit(255); /* resolve_host logs the error */
1256 timeout_ms
= options
.connection_timeout
* 1000;
1258 /* Open a connection to the remote host. */
1259 if (ssh_connect(host
, addrs
, &hostaddr
, options
.port
,
1260 options
.address_family
, options
.connection_attempts
,
1261 &timeout_ms
, options
.tcp_keep_alive
,
1262 options
.use_privileged_port
) != 0)
1266 freeaddrinfo(addrs
);
1268 packet_set_timeout(options
.server_alive_interval
,
1269 options
.server_alive_count_max
);
1271 ssh
= active_state
; /* XXX */
1274 debug3("timeout: %d ms remain after connect", timeout_ms
);
1277 * If we successfully made the connection, load the host private key
1278 * in case we will need it later for combined rsa-rhosts
1279 * authentication. This must be done before releasing extra
1280 * privileges, because the file is only readable by root.
1281 * If we cannot access the private keys, load the public keys
1282 * instead and try to execute the ssh-keysign helper instead.
1284 sensitive_data
.nkeys
= 0;
1285 sensitive_data
.keys
= NULL
;
1286 sensitive_data
.external_keysign
= 0;
1287 if (options
.rhosts_rsa_authentication
||
1288 options
.hostbased_authentication
) {
1289 sensitive_data
.nkeys
= 9;
1290 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
1292 for (i
= 0; i
< sensitive_data
.nkeys
; i
++)
1293 sensitive_data
.keys
[i
] = NULL
;
1297 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
1298 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
1300 #ifdef OPENSSL_HAS_ECC
1301 sensitive_data
.keys
[1] = key_load_private_cert(KEY_ECDSA
,
1302 _PATH_HOST_ECDSA_KEY_FILE
, "", NULL
);
1304 sensitive_data
.keys
[2] = key_load_private_cert(KEY_ED25519
,
1305 _PATH_HOST_ED25519_KEY_FILE
, "", NULL
);
1306 sensitive_data
.keys
[3] = key_load_private_cert(KEY_RSA
,
1307 _PATH_HOST_RSA_KEY_FILE
, "", NULL
);
1308 sensitive_data
.keys
[4] = key_load_private_cert(KEY_DSA
,
1309 _PATH_HOST_DSA_KEY_FILE
, "", NULL
);
1310 #ifdef OPENSSL_HAS_ECC
1311 sensitive_data
.keys
[5] = key_load_private_type(KEY_ECDSA
,
1312 _PATH_HOST_ECDSA_KEY_FILE
, "", NULL
, NULL
);
1314 sensitive_data
.keys
[6] = key_load_private_type(KEY_ED25519
,
1315 _PATH_HOST_ED25519_KEY_FILE
, "", NULL
, NULL
);
1316 sensitive_data
.keys
[7] = key_load_private_type(KEY_RSA
,
1317 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
1318 sensitive_data
.keys
[8] = key_load_private_type(KEY_DSA
,
1319 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
1322 if (options
.hostbased_authentication
== 1 &&
1323 sensitive_data
.keys
[0] == NULL
&&
1324 sensitive_data
.keys
[5] == NULL
&&
1325 sensitive_data
.keys
[6] == NULL
&&
1326 sensitive_data
.keys
[7] == NULL
&&
1327 sensitive_data
.keys
[8] == NULL
) {
1328 #ifdef OPENSSL_HAS_ECC
1329 sensitive_data
.keys
[1] = key_load_cert(
1330 _PATH_HOST_ECDSA_KEY_FILE
);
1332 sensitive_data
.keys
[2] = key_load_cert(
1333 _PATH_HOST_ED25519_KEY_FILE
);
1334 sensitive_data
.keys
[3] = key_load_cert(
1335 _PATH_HOST_RSA_KEY_FILE
);
1336 sensitive_data
.keys
[4] = key_load_cert(
1337 _PATH_HOST_DSA_KEY_FILE
);
1338 #ifdef OPENSSL_HAS_ECC
1339 sensitive_data
.keys
[5] = key_load_public(
1340 _PATH_HOST_ECDSA_KEY_FILE
, NULL
);
1342 sensitive_data
.keys
[6] = key_load_public(
1343 _PATH_HOST_ED25519_KEY_FILE
, NULL
);
1344 sensitive_data
.keys
[7] = key_load_public(
1345 _PATH_HOST_RSA_KEY_FILE
, NULL
);
1346 sensitive_data
.keys
[8] = key_load_public(
1347 _PATH_HOST_DSA_KEY_FILE
, NULL
);
1348 sensitive_data
.external_keysign
= 1;
1352 * Get rid of any extra privileges that we may have. We will no
1353 * longer need them. Also, extra privileges could make it very hard
1354 * to read identity files and other non-world-readable files from the
1355 * user's home directory if it happens to be on a NFS volume where
1356 * root is mapped to nobody.
1358 if (original_effective_uid
== 0) {
1360 permanently_set_uid(pw
);
1364 * Now that we are back to our own permissions, create ~/.ssh
1365 * directory if it doesn't already exist.
1367 if (config
== NULL
) {
1368 r
= snprintf(buf
, sizeof buf
, "%s%s%s", pw
->pw_dir
,
1369 strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
1370 if (r
> 0 && (size_t)r
< sizeof(buf
) && stat(buf
, &st
) < 0) {
1372 ssh_selinux_setfscreatecon(buf
);
1374 if (mkdir(buf
, 0700) < 0)
1375 error("Could not create directory '%.200s'.",
1378 ssh_selinux_setfscreatecon(NULL
);
1382 /* load options.identity_files */
1383 load_public_identity_files();
1385 /* optionally set the SSH_AUTHSOCKET_ENV_NAME varibale */
1386 if (options
.identity_agent
&&
1387 strcmp(options
.identity_agent
, SSH_AUTHSOCKET_ENV_NAME
) != 0) {
1388 if (strcmp(options
.identity_agent
, "none") == 0) {
1389 unsetenv(SSH_AUTHSOCKET_ENV_NAME
);
1391 p
= tilde_expand_filename(options
.identity_agent
,
1393 cp
= percent_expand(p
, "d", pw
->pw_dir
,
1394 "u", pw
->pw_name
, "l", thishost
, "h", host
,
1395 "r", options
.user
, (char *)NULL
);
1396 setenv(SSH_AUTHSOCKET_ENV_NAME
, cp
, 1);
1402 /* Expand ~ in known host file names. */
1403 tilde_expand_paths(options
.system_hostfiles
,
1404 options
.num_system_hostfiles
);
1405 tilde_expand_paths(options
.user_hostfiles
, options
.num_user_hostfiles
);
1407 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
1408 signal(SIGCHLD
, main_sigchld_handler
);
1410 /* Log into the remote system. Never returns if the login fails. */
1411 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
,
1412 options
.port
, pw
, timeout_ms
);
1414 if (packet_connection_is_on_socket()) {
1415 verbose("Authenticated to %s ([%s]:%d).", host
,
1416 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
));
1418 verbose("Authenticated to %s (via proxy).", host
);
1421 /* We no longer need the private host keys. Clear them now. */
1422 if (sensitive_data
.nkeys
!= 0) {
1423 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
1424 if (sensitive_data
.keys
[i
] != NULL
) {
1425 /* Destroys contents safely */
1426 debug3("clear hostkey %d", i
);
1427 key_free(sensitive_data
.keys
[i
]);
1428 sensitive_data
.keys
[i
] = NULL
;
1431 free(sensitive_data
.keys
);
1433 for (i
= 0; i
< options
.num_identity_files
; i
++) {
1434 free(options
.identity_files
[i
]);
1435 options
.identity_files
[i
] = NULL
;
1436 if (options
.identity_keys
[i
]) {
1437 key_free(options
.identity_keys
[i
]);
1438 options
.identity_keys
[i
] = NULL
;
1441 for (i
= 0; i
< options
.num_certificate_files
; i
++) {
1442 free(options
.certificate_files
[i
]);
1443 options
.certificate_files
[i
] = NULL
;
1446 exit_status
= compat20
? ssh_session2() : ssh_session();
1449 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
1450 unlink(options
.control_path
);
1452 /* Kill ProxyCommand if it is running. */
1453 ssh_kill_proxy_command();
1459 control_persist_detach(void)
1462 int devnull
, keep_stderr
;
1464 debug("%s: backgrounding master process", __func__
);
1467 * master (current process) into the background, and make the
1468 * foreground process a client of the backgrounded master.
1470 switch ((pid
= fork())) {
1472 fatal("%s: fork: %s", __func__
, strerror(errno
));
1474 /* Child: master process continues mainloop */
1477 /* Parent: set up mux slave to connect to backgrounded master */
1478 debug2("%s: background process is %ld", __func__
, (long)pid
);
1479 stdin_null_flag
= ostdin_null_flag
;
1480 options
.request_tty
= orequest_tty
;
1481 tty_flag
= otty_flag
;
1482 close(muxserver_sock
);
1483 muxserver_sock
= -1;
1484 options
.control_master
= SSHCTL_MASTER_NO
;
1485 muxclient(options
.control_path
);
1486 /* muxclient() doesn't return on success. */
1487 fatal("Failed to connect to new control master");
1489 if ((devnull
= open(_PATH_DEVNULL
, O_RDWR
)) == -1) {
1490 error("%s: open(\"/dev/null\"): %s", __func__
,
1493 keep_stderr
= log_is_on_stderr() && debug_flag
;
1494 if (dup2(devnull
, STDIN_FILENO
) == -1 ||
1495 dup2(devnull
, STDOUT_FILENO
) == -1 ||
1496 (!keep_stderr
&& dup2(devnull
, STDERR_FILENO
) == -1))
1497 error("%s: dup2: %s", __func__
, strerror(errno
));
1498 if (devnull
> STDERR_FILENO
)
1502 setproctitle("%s [mux]", options
.control_path
);
1505 /* Do fork() after authentication. Used by "ssh -f" */
1509 if (need_controlpersist_detach
)
1510 control_persist_detach();
1511 debug("forking to background");
1512 fork_after_authentication_flag
= 0;
1513 if (daemon(1, 1) < 0)
1514 fatal("daemon() failed: %.200s", strerror(errno
));
1517 /* Callback for remote forward global requests */
1519 ssh_confirm_remote_forward(int type
, u_int32_t seq
, void *ctxt
)
1521 struct Forward
*rfwd
= (struct Forward
*)ctxt
;
1523 /* XXX verbose() on failure? */
1524 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1525 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
1526 rfwd
->listen_path
? rfwd
->listen_path
:
1527 rfwd
->listen_host
? rfwd
->listen_host
: "",
1528 (rfwd
->listen_path
|| rfwd
->listen_host
) ? ":" : "",
1529 rfwd
->listen_port
, rfwd
->connect_path
? rfwd
->connect_path
:
1530 rfwd
->connect_host
, rfwd
->connect_port
);
1531 if (rfwd
->listen_path
== NULL
&& rfwd
->listen_port
== 0) {
1532 if (type
== SSH2_MSG_REQUEST_SUCCESS
) {
1533 rfwd
->allocated_port
= packet_get_int();
1534 logit("Allocated port %u for remote forward to %s:%d",
1535 rfwd
->allocated_port
,
1536 rfwd
->connect_host
, rfwd
->connect_port
);
1537 channel_update_permitted_opens(rfwd
->handle
,
1538 rfwd
->allocated_port
);
1540 channel_update_permitted_opens(rfwd
->handle
, -1);
1544 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
1545 if (options
.exit_on_forward_failure
) {
1546 if (rfwd
->listen_path
!= NULL
)
1547 fatal("Error: remote port forwarding failed "
1548 "for listen path %s", rfwd
->listen_path
);
1550 fatal("Error: remote port forwarding failed "
1551 "for listen port %d", rfwd
->listen_port
);
1553 if (rfwd
->listen_path
!= NULL
)
1554 logit("Warning: remote port forwarding failed "
1555 "for listen path %s", rfwd
->listen_path
);
1557 logit("Warning: remote port forwarding failed "
1558 "for listen port %d", rfwd
->listen_port
);
1561 if (++remote_forward_confirms_received
== options
.num_remote_forwards
) {
1562 debug("All remote forwarding requests processed");
1563 if (fork_after_authentication_flag
)
1569 client_cleanup_stdio_fwd(int id
, void *arg
)
1571 debug("stdio forwarding: done");
1576 ssh_stdio_confirm(int id
, int success
, void *arg
)
1579 fatal("stdio forwarding failed");
1583 ssh_init_stdio_forwarding(void)
1588 if (options
.stdio_forward_host
== NULL
)
1591 fatal("stdio forwarding require Protocol 2");
1593 debug3("%s: %s:%d", __func__
, options
.stdio_forward_host
,
1594 options
.stdio_forward_port
);
1596 if ((in
= dup(STDIN_FILENO
)) < 0 ||
1597 (out
= dup(STDOUT_FILENO
)) < 0)
1598 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1599 if ((c
= channel_connect_stdio_fwd(options
.stdio_forward_host
,
1600 options
.stdio_forward_port
, in
, out
)) == NULL
)
1601 fatal("%s: channel_connect_stdio_fwd failed", __func__
);
1602 channel_register_cleanup(c
->self
, client_cleanup_stdio_fwd
, 0);
1603 channel_register_open_confirm(c
->self
, ssh_stdio_confirm
, NULL
);
1607 ssh_init_forwarding(void)
1612 /* Initiate local TCP/IP port forwardings. */
1613 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
1614 debug("Local connections to %.200s:%d forwarded to remote "
1615 "address %.200s:%d",
1616 (options
.local_forwards
[i
].listen_path
!= NULL
) ?
1617 options
.local_forwards
[i
].listen_path
:
1618 (options
.local_forwards
[i
].listen_host
== NULL
) ?
1619 (options
.fwd_opts
.gateway_ports
? "*" : "LOCALHOST") :
1620 options
.local_forwards
[i
].listen_host
,
1621 options
.local_forwards
[i
].listen_port
,
1622 (options
.local_forwards
[i
].connect_path
!= NULL
) ?
1623 options
.local_forwards
[i
].connect_path
:
1624 options
.local_forwards
[i
].connect_host
,
1625 options
.local_forwards
[i
].connect_port
);
1626 success
+= channel_setup_local_fwd_listener(
1627 &options
.local_forwards
[i
], &options
.fwd_opts
);
1629 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
1630 fatal("Could not request local forwarding.");
1631 if (i
> 0 && success
== 0)
1632 error("Could not request local forwarding.");
1634 /* Initiate remote TCP/IP port forwardings. */
1635 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
1636 debug("Remote connections from %.200s:%d forwarded to "
1637 "local address %.200s:%d",
1638 (options
.remote_forwards
[i
].listen_path
!= NULL
) ?
1639 options
.remote_forwards
[i
].listen_path
:
1640 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
1641 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
1642 options
.remote_forwards
[i
].listen_port
,
1643 (options
.remote_forwards
[i
].connect_path
!= NULL
) ?
1644 options
.remote_forwards
[i
].connect_path
:
1645 options
.remote_forwards
[i
].connect_host
,
1646 options
.remote_forwards
[i
].connect_port
);
1647 options
.remote_forwards
[i
].handle
=
1648 channel_request_remote_forwarding(
1649 &options
.remote_forwards
[i
]);
1650 if (options
.remote_forwards
[i
].handle
< 0) {
1651 if (options
.exit_on_forward_failure
)
1652 fatal("Could not request remote forwarding.");
1654 logit("Warning: Could not request remote "
1657 client_register_global_confirm(ssh_confirm_remote_forward
,
1658 &options
.remote_forwards
[i
]);
1662 /* Initiate tunnel forwarding. */
1663 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
1664 if (client_request_tun_fwd(options
.tun_open
,
1665 options
.tun_local
, options
.tun_remote
) == -1) {
1666 if (options
.exit_on_forward_failure
)
1667 fatal("Could not request tunnel forwarding.");
1669 error("Could not request tunnel forwarding.");
1675 check_agent_present(void)
1679 if (options
.forward_agent
) {
1680 /* Clear agent forwarding if we don't have an agent. */
1681 if ((r
= ssh_get_authentication_socket(NULL
)) != 0) {
1682 options
.forward_agent
= 0;
1683 if (r
!= SSH_ERR_AGENT_NOT_PRESENT
)
1684 debug("ssh_get_authentication_socket: %s",
1694 int interactive
= 0;
1698 const char *display
;
1699 char *proto
= NULL
, *data
= NULL
;
1701 /* Enable compression if requested. */
1702 if (options
.compression
) {
1703 debug("Requesting compression at level %d.",
1704 options
.compression_level
);
1706 if (options
.compression_level
< 1 ||
1707 options
.compression_level
> 9)
1708 fatal("Compression level must be from 1 (fast) to "
1711 /* Send the request. */
1712 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
1713 packet_put_int(options
.compression_level
);
1715 packet_write_wait();
1716 type
= packet_read();
1717 if (type
== SSH_SMSG_SUCCESS
)
1718 packet_start_compression(options
.compression_level
);
1719 else if (type
== SSH_SMSG_FAILURE
)
1720 logit("Warning: Remote host refused compression.");
1722 packet_disconnect("Protocol error waiting for "
1723 "compression response.");
1725 /* Allocate a pseudo tty if appropriate. */
1727 debug("Requesting pty.");
1729 /* Start the packet. */
1730 packet_start(SSH_CMSG_REQUEST_PTY
);
1732 /* Store TERM in the packet. There is no limit on the
1733 length of the string. */
1734 cp
= getenv("TERM");
1737 packet_put_cstring(cp
);
1739 /* Store window size in the packet. */
1740 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
1741 memset(&ws
, 0, sizeof(ws
));
1742 packet_put_int((u_int
)ws
.ws_row
);
1743 packet_put_int((u_int
)ws
.ws_col
);
1744 packet_put_int((u_int
)ws
.ws_xpixel
);
1745 packet_put_int((u_int
)ws
.ws_ypixel
);
1747 /* Store tty modes in the packet. */
1748 tty_make_modes(fileno(stdin
), NULL
);
1750 /* Send the packet, and wait for it to leave. */
1752 packet_write_wait();
1754 /* Read response from the server. */
1755 type
= packet_read();
1756 if (type
== SSH_SMSG_SUCCESS
) {
1759 } else if (type
== SSH_SMSG_FAILURE
)
1760 logit("Warning: Remote host failed or refused to "
1761 "allocate a pseudo tty.");
1763 packet_disconnect("Protocol error waiting for pty "
1764 "request response.");
1766 /* Request X11 forwarding if enabled and DISPLAY is set. */
1767 display
= getenv("DISPLAY");
1768 if (display
== NULL
&& options
.forward_x11
)
1769 debug("X11 forwarding requested but DISPLAY not set");
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) {
1773 /* Request forwarding with authentication spoofing. */
1774 debug("Requesting X11 forwarding with authentication "
1776 x11_request_forwarding_with_spoofing(0, display
, proto
,
1778 /* Read response from the server. */
1779 type
= packet_read();
1780 if (type
== SSH_SMSG_SUCCESS
) {
1782 } else if (type
== SSH_SMSG_FAILURE
) {
1783 logit("Warning: Remote host denied X11 forwarding.");
1785 packet_disconnect("Protocol error waiting for X11 "
1789 /* Tell the packet module whether this is an interactive session. */
1790 packet_set_interactive(interactive
,
1791 options
.ip_qos_interactive
, options
.ip_qos_bulk
);
1793 /* Request authentication agent forwarding if appropriate. */
1794 check_agent_present();
1796 if (options
.forward_agent
) {
1797 debug("Requesting authentication agent forwarding.");
1798 auth_request_forwarding();
1800 /* Read response from the server. */
1801 type
= packet_read();
1803 if (type
!= SSH_SMSG_SUCCESS
)
1804 logit("Warning: Remote host denied authentication agent forwarding.");
1807 /* Initiate port forwardings. */
1808 ssh_init_stdio_forwarding();
1809 ssh_init_forwarding();
1811 /* Execute a local command */
1812 if (options
.local_command
!= NULL
&&
1813 options
.permit_local_command
)
1814 ssh_local_cmd(options
.local_command
);
1817 * If requested and we are not interested in replies to remote
1818 * forwarding requests, then let ssh continue in the background.
1820 if (fork_after_authentication_flag
) {
1821 if (options
.exit_on_forward_failure
&&
1822 options
.num_remote_forwards
> 0) {
1823 debug("deferring postauth fork until remote forward "
1824 "confirmation received");
1830 * If a command was specified on the command line, execute the
1831 * command now. Otherwise request the server to start a shell.
1833 if (buffer_len(&command
) > 0) {
1834 int len
= buffer_len(&command
);
1837 debug("Sending command: %.*s", len
,
1838 (u_char
*)buffer_ptr(&command
));
1839 packet_start(SSH_CMSG_EXEC_CMD
);
1840 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
1842 packet_write_wait();
1844 debug("Requesting shell.");
1845 packet_start(SSH_CMSG_EXEC_SHELL
);
1847 packet_write_wait();
1850 /* Enter the interactive session. */
1851 return client_loop(have_tty
, tty_flag
?
1852 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1855 /* request pty/x11/agent/tcpfwd/shell for channel */
1857 ssh_session2_setup(int id
, int success
, void *arg
)
1859 extern char **environ
;
1860 const char *display
;
1861 int interactive
= tty_flag
;
1862 char *proto
= NULL
, *data
= NULL
;
1865 return; /* No need for error message, channels code sens one */
1867 display
= getenv("DISPLAY");
1868 if (display
== NULL
&& options
.forward_x11
)
1869 debug("X11 forwarding requested but DISPLAY not set");
1870 if (options
.forward_x11
&& client_x11_get_proto(display
,
1871 options
.xauth_location
, options
.forward_x11_trusted
,
1872 options
.forward_x11_timeout
, &proto
, &data
) == 0) {
1873 /* Request forwarding with authentication spoofing. */
1874 debug("Requesting X11 forwarding with authentication "
1876 x11_request_forwarding_with_spoofing(id
, display
, proto
,
1878 client_expect_confirm(id
, "X11 forwarding", CONFIRM_WARN
);
1879 /* XXX exit_on_forward_failure */
1883 check_agent_present();
1884 if (options
.forward_agent
) {
1885 debug("Requesting authentication agent forwarding.");
1886 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1890 /* Tell the packet module whether this is an interactive session. */
1891 packet_set_interactive(interactive
,
1892 options
.ip_qos_interactive
, options
.ip_qos_bulk
);
1894 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1895 NULL
, fileno(stdin
), &command
, environ
);
1898 /* open new channel for a session */
1900 ssh_session2_open(void)
1903 int window
, packetmax
, in
, out
, err
;
1905 if (stdin_null_flag
) {
1906 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1908 in
= dup(STDIN_FILENO
);
1910 out
= dup(STDOUT_FILENO
);
1911 err
= dup(STDERR_FILENO
);
1913 if (in
< 0 || out
< 0 || err
< 0)
1914 fatal("dup() in/out/err failed");
1916 /* enable nonblocking unless tty */
1924 window
= CHAN_SES_WINDOW_DEFAULT
;
1925 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1931 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1932 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1933 "client-session", /*nonblock*/0);
1935 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1937 channel_send_open(c
->self
);
1939 channel_register_open_confirm(c
->self
,
1940 ssh_session2_setup
, NULL
);
1950 /* XXX should be pre-session */
1951 if (!options
.control_persist
)
1952 ssh_init_stdio_forwarding();
1953 ssh_init_forwarding();
1955 /* Start listening for multiplex clients */
1959 * If we are in control persist mode and have a working mux listen
1960 * socket, then prepare to background ourselves and have a foreground
1961 * client attach as a control slave.
1962 * NB. we must save copies of the flags that we override for
1963 * the backgrounding, since we defer attachment of the slave until
1964 * after the connection is fully established (in particular,
1965 * async rfwd replies have been received for ExitOnForwardFailure).
1967 if (options
.control_persist
&& muxserver_sock
!= -1) {
1968 ostdin_null_flag
= stdin_null_flag
;
1969 ono_shell_flag
= no_shell_flag
;
1970 orequest_tty
= options
.request_tty
;
1971 otty_flag
= tty_flag
;
1972 stdin_null_flag
= 1;
1975 if (!fork_after_authentication_flag
)
1976 need_controlpersist_detach
= 1;
1977 fork_after_authentication_flag
= 1;
1980 * ControlPersist mux listen socket setup failed, attempt the
1981 * stdio forward setup that we skipped earlier.
1983 if (options
.control_persist
&& muxserver_sock
== -1)
1984 ssh_init_stdio_forwarding();
1986 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1987 id
= ssh_session2_open();
1989 packet_set_interactive(
1990 options
.control_master
== SSHCTL_MASTER_NO
,
1991 options
.ip_qos_interactive
, options
.ip_qos_bulk
);
1994 /* If we don't expect to open a new session, then disallow it */
1995 if (options
.control_master
== SSHCTL_MASTER_NO
&&
1996 (datafellows
& SSH_NEW_OPENSSH
)) {
1997 debug("Requesting no-more-sessions@openssh.com");
1998 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
1999 packet_put_cstring("no-more-sessions@openssh.com");
2004 /* Execute a local command */
2005 if (options
.local_command
!= NULL
&&
2006 options
.permit_local_command
)
2007 ssh_local_cmd(options
.local_command
);
2010 * If requested and we are not interested in replies to remote
2011 * forwarding requests, then let ssh continue in the background.
2013 if (fork_after_authentication_flag
) {
2014 if (options
.exit_on_forward_failure
&&
2015 options
.num_remote_forwards
> 0) {
2016 debug("deferring postauth fork until remote forward "
2017 "confirmation received");
2022 return client_loop(tty_flag
, tty_flag
?
2023 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
2026 /* Loads all IdentityFile and CertificateFile keys */
2028 load_public_identity_files(void)
2030 char *filename
, *cp
, thishost
[NI_MAXHOST
];
2031 char *pwdir
= NULL
, *pwname
= NULL
;
2035 u_int n_ids
, n_certs
;
2036 char *identity_files
[SSH_MAX_IDENTITY_FILES
];
2037 Key
*identity_keys
[SSH_MAX_IDENTITY_FILES
];
2038 char *certificate_files
[SSH_MAX_CERTIFICATE_FILES
];
2039 struct sshkey
*certificates
[SSH_MAX_CERTIFICATE_FILES
];
2040 #ifdef ENABLE_PKCS11
2045 n_ids
= n_certs
= 0;
2046 memset(identity_files
, 0, sizeof(identity_files
));
2047 memset(identity_keys
, 0, sizeof(identity_keys
));
2048 memset(certificate_files
, 0, sizeof(certificate_files
));
2049 memset(certificates
, 0, sizeof(certificates
));
2051 #ifdef ENABLE_PKCS11
2052 if (options
.pkcs11_provider
!= NULL
&&
2053 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
2054 (pkcs11_init(!options
.batch_mode
) == 0) &&
2055 (nkeys
= pkcs11_add_provider(options
.pkcs11_provider
, NULL
,
2057 for (i
= 0; i
< nkeys
; i
++) {
2058 if (n_ids
>= SSH_MAX_IDENTITY_FILES
) {
2062 identity_keys
[n_ids
] = keys
[i
];
2063 identity_files
[n_ids
] =
2064 xstrdup(options
.pkcs11_provider
); /* XXX */
2069 #endif /* ENABLE_PKCS11 */
2070 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
2071 fatal("load_public_identity_files: getpwuid failed");
2072 pwname
= xstrdup(pw
->pw_name
);
2073 pwdir
= xstrdup(pw
->pw_dir
);
2074 if (gethostname(thishost
, sizeof(thishost
)) == -1)
2075 fatal("load_public_identity_files: gethostname: %s",
2077 for (i
= 0; i
< options
.num_identity_files
; i
++) {
2078 if (n_ids
>= SSH_MAX_IDENTITY_FILES
||
2079 strcasecmp(options
.identity_files
[i
], "none") == 0) {
2080 free(options
.identity_files
[i
]);
2081 options
.identity_files
[i
] = NULL
;
2084 cp
= tilde_expand_filename(options
.identity_files
[i
],
2086 filename
= percent_expand(cp
, "d", pwdir
,
2087 "u", pwname
, "l", thishost
, "h", host
,
2088 "r", options
.user
, (char *)NULL
);
2090 public = key_load_public(filename
, NULL
);
2091 debug("identity file %s type %d", filename
,
2092 public ? public->type
: -1);
2093 free(options
.identity_files
[i
]);
2094 identity_files
[n_ids
] = filename
;
2095 identity_keys
[n_ids
] = public;
2097 if (++n_ids
>= SSH_MAX_IDENTITY_FILES
)
2101 * If no certificates have been explicitly listed then try
2102 * to add the default certificate variant too.
2104 if (options
.num_certificate_files
!= 0)
2106 xasprintf(&cp
, "%s-cert", filename
);
2107 public = key_load_public(cp
, NULL
);
2108 debug("identity file %s type %d", cp
,
2109 public ? public->type
: -1);
2110 if (public == NULL
) {
2114 if (!key_is_cert(public)) {
2115 debug("%s: key %s type %s is not a certificate",
2116 __func__
, cp
, key_type(public));
2121 identity_keys
[n_ids
] = public;
2122 identity_files
[n_ids
] = cp
;
2126 if (options
.num_certificate_files
> SSH_MAX_CERTIFICATE_FILES
)
2127 fatal("%s: too many certificates", __func__
);
2128 for (i
= 0; i
< options
.num_certificate_files
; i
++) {
2129 cp
= tilde_expand_filename(options
.certificate_files
[i
],
2131 filename
= percent_expand(cp
, "d", pwdir
,
2132 "u", pwname
, "l", thishost
, "h", host
,
2133 "r", options
.user
, (char *)NULL
);
2136 public = key_load_public(filename
, NULL
);
2137 debug("certificate file %s type %d", filename
,
2138 public ? public->type
: -1);
2139 free(options
.certificate_files
[i
]);
2140 options
.certificate_files
[i
] = NULL
;
2141 if (public == NULL
) {
2145 if (!key_is_cert(public)) {
2146 debug("%s: key %s type %s is not a certificate",
2147 __func__
, filename
, key_type(public));
2152 certificate_files
[n_certs
] = filename
;
2153 certificates
[n_certs
] = public;
2157 options
.num_identity_files
= n_ids
;
2158 memcpy(options
.identity_files
, identity_files
, sizeof(identity_files
));
2159 memcpy(options
.identity_keys
, identity_keys
, sizeof(identity_keys
));
2161 options
.num_certificate_files
= n_certs
;
2162 memcpy(options
.certificate_files
,
2163 certificate_files
, sizeof(certificate_files
));
2164 memcpy(options
.certificates
, certificates
, sizeof(certificates
));
2166 explicit_bzero(pwname
, strlen(pwname
));
2168 explicit_bzero(pwdir
, strlen(pwdir
));
2173 main_sigchld_handler(int sig
)
2175 int save_errno
= errno
;
2179 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0 ||
2180 (pid
< 0 && errno
== EINTR
))
2183 signal(sig
, main_sigchld_handler
);