2 * sshdump is extcap tool used to capture data using a remote ssh host
4 * Copyright 2015, Dario Lombardo
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 #include <glib/gprintf.h>
29 #include <glib/gstdio.h>
38 #include <sys/types.h>
41 #include <libssh/libssh.h>
43 #ifdef HAVE_ARPA_INET_H
44 #include <arpa/inet.h>
57 #ifndef HAVE_GETOPT_LONG
58 #include "wsutil/wsgetopt.h"
61 #if defined(_WIN32) && !defined(__CYGWIN__)
68 #ifdef HAVE_WINSOCK2_H
74 #define socket_handle_t SOCKET
77 * UN*X, or Windows pretending to be UN*X with the aid of Cygwin.
79 #define closesocket(socket) close(socket)
80 #define socket_handle_t int
81 #define INVALID_SOCKET (-1)
82 #define SOCKET_ERROR (-1)
85 #if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__) || defined(__linux__)
86 #define USE_GETIFADDRS 1
91 #define STDERR_FILENO 2
95 #define STDOUT_FILENO 1
98 #define SSHDUMP_VERSION_MAJOR 1U
99 #define SSHDUMP_VERSION_MINOR 0U
100 #define SSHDUMP_VERSION_RELEASE 0U
102 #define SSH_EXTCAP_INTERFACE "ssh"
103 #define SSH_READ_BLOCK_SIZE 256
105 #define DEFAULT_CAPTURE_BIN "dumpcap"
107 static gboolean verbose = FALSE;
124 OPT_REMOTE_INTERFACE,
125 OPT_REMOTE_CAPTURE_BIN,
128 OPT_SSHKEY_PASSPHRASE,
132 static struct option longopts[] = {
133 /* Generic application options */
134 { "help", no_argument, NULL, OPT_HELP},
135 { "version", no_argument, NULL, OPT_VERSION},
136 { "verbose", optional_argument, NULL, OPT_VERBOSE},
137 { "extcap-interfaces", no_argument, NULL, OPT_LIST_INTERFACES},
138 { "extcap-dlts", no_argument, NULL, OPT_LIST_DLTS},
139 { "extcap-interface", required_argument, NULL, OPT_INTERFACE},
140 { "extcap-config", no_argument, NULL, OPT_CONFIG},
141 { "extcap-capture-filter", required_argument, NULL, OPT_EXTCAP_FILTER},
142 { "capture", no_argument, NULL, OPT_CAPTURE},
143 { "fifo", required_argument, NULL, OPT_FIFO},
144 { "remote-host", required_argument, NULL, OPT_REMOTE_HOST},
145 { "remote-port", required_argument, NULL, OPT_REMOTE_PORT},
146 { "remote-username", required_argument, NULL, OPT_REMOTE_USERNAME},
147 { "remote-password", required_argument, NULL, OPT_REMOTE_PASSWORD},
148 { "remote-interface", required_argument, NULL, OPT_REMOTE_INTERFACE},
149 { "remote-capture-bin", required_argument, NULL, OPT_REMOTE_CAPTURE_BIN},
150 { "remote-filter", required_argument, NULL, OPT_REMOTE_FILTER},
151 { "remote-count", required_argument, NULL, OPT_REMOTE_COUNT},
152 { "sshkey", required_argument, NULL, OPT_SSHKEY},
153 { "sshkey-passphrase", required_argument, NULL, OPT_SSHKEY_PASSPHRASE},
157 #define verbose_print(...) { if (verbose) g_print(__VA_ARGS__); }
158 #define errmsg_print(...) { g_print(__VA_ARGS__); g_print("\n"); }
160 static char* local_interfaces_to_filter(unsigned int remote_port);
162 static void ssh_cleanup(ssh_session sshs, ssh_channel channel)
165 ssh_channel_send_eof(channel);
166 ssh_channel_close(channel);
167 ssh_channel_free(channel);
171 ssh_disconnect(sshs);
176 static ssh_session create_ssh_connection(const char* hostname, const unsigned int port, const char* username,
177 const char* password, const char* sshkey_path, const char* sshkey_passphrase)
181 /* Open session and set options */
184 errmsg_print("Can't create ssh session");
191 if (ssh_options_set(sshs, SSH_OPTIONS_HOST, hostname)) {
192 errmsg_print("Can't set the hostname: %s\n", hostname);
197 if (ssh_options_set(sshs, SSH_OPTIONS_PORT, &port)) {
198 errmsg_print("Can't set the port: %d\n", port);
204 username = g_get_user_name();
206 if (ssh_options_set(sshs, SSH_OPTIONS_USER, username)) {
207 errmsg_print("Can't set the username: %s\n", username);
211 verbose_print("Opening ssh connection to %s@%s:%u\n", username, hostname, port);
213 /* Connect to server */
214 if (ssh_connect(sshs) != SSH_OK) {
215 errmsg_print("Error connecting to %s@%s:%u (%s)\n", username, hostname, port,
216 ssh_get_error(sshs));
220 #ifdef HAVE_LIBSSH_USERAUTH_AGENT
221 verbose_print("Connecting using ssh-agent...");
222 /* Try to authenticate using ssh agent */
223 if (ssh_userauth_agent(sshs, NULL) == SSH_AUTH_SUCCESS) {
224 verbose_print("done\n");
227 verbose_print("failed\n");
230 /* If a public key path has been provided, try to authenticate using it */
232 ssh_key pkey = ssh_key_new();
235 verbose_print("Connecting using public key in %s...", sshkey_path);
236 ret = ssh_pki_import_privkey_file(sshkey_path, sshkey_passphrase, NULL, NULL, &pkey);
239 if (ssh_userauth_publickey(sshs, NULL, pkey) == SSH_AUTH_SUCCESS) {
240 verbose_print("done\n");
246 verbose_print("failed (%s)\n", ssh_get_error(sshs));
249 /* Try to authenticate using standard public key */
250 verbose_print("Connecting using standard public key...");
251 if (ssh_userauth_publickey_auto(sshs, NULL, NULL) == SSH_AUTH_SUCCESS) {
252 verbose_print("done\n");
255 verbose_print("failed\n");
257 /* If a password has been provided and all previous attempts failed, try to use it */
259 verbose_print("Connecting using password...");
260 if (ssh_userauth_password(sshs, username, password) == SSH_AUTH_SUCCESS) {
261 verbose_print("done\n");
264 verbose_print("failed\n");
267 verbose_print("Can't find a valid authentication. Disconnecting.\n");
269 /* All authentication failed. Disconnect and return */
270 ssh_disconnect(sshs);
277 static void ssh_loop_read(ssh_channel channel, int fd)
280 char buffer[SSH_READ_BLOCK_SIZE];
282 /* read from stdin until data are available */
284 nbytes = ssh_channel_read(channel, buffer, SSH_READ_BLOCK_SIZE, 0);
285 if (write(fd, buffer, nbytes) != nbytes) {
286 errmsg_print("ERROR reading: %s\n", g_strerror(errno));
291 /* read loop finished... maybe something wrong happened. Read from stderr */
293 nbytes = ssh_channel_read(channel, buffer, SSH_READ_BLOCK_SIZE, 1);
294 if (write(STDERR_FILENO, buffer, nbytes) != nbytes) {
299 if (ssh_channel_send_eof(channel) != SSH_OK)
303 static ssh_channel run_ssh_command(ssh_session sshs, const char* capture_bin, const char* iface, const char* cfilter,
304 unsigned long int count)
310 char* default_filter;
312 char* count_str = NULL;
313 unsigned int remote_port = 22;
316 capture_bin = DEFAULT_CAPTURE_BIN;
321 channel = ssh_channel_new(sshs);
325 if (ssh_channel_open_session(channel) != SSH_OK) {
326 ssh_channel_free(channel);
330 ssh_options_get_port(sshs, &remote_port);
332 /* escape parameters to go save with the shell */
333 quoted_bin = g_shell_quote(capture_bin);
334 quoted_iface = g_shell_quote(iface);
335 default_filter = local_interfaces_to_filter(remote_port);
337 cfilter = default_filter;
338 quoted_filter = g_shell_quote(cfilter);
340 count_str = g_strdup_printf("-c %lu", count);
342 cmdline = g_strdup_printf("%s -i %s -P -w - -f %s %s", quoted_bin, quoted_iface, quoted_filter,
343 count_str ? count_str : "");
345 verbose_print("Running: %s\n", cmdline);
346 if (ssh_channel_request_exec(channel, cmdline) != SSH_OK) {
347 ssh_channel_close(channel);
348 ssh_channel_free(channel);
353 g_free(quoted_iface);
354 g_free(default_filter);
355 g_free(quoted_filter);
363 static int ssh_open_remote_connection(const char* hostname, const unsigned int port, const char* username, const char* password,
364 const char* sshkey, const char* sshkey_passphrase, const char* iface, const char* cfilter, const char* capture_bin,
365 const unsigned long int count, const char* fifo)
371 if (!g_strcmp0(fifo, "-")) {
375 /* Open or create the output file */
376 fd = open(fifo, O_WRONLY);
378 fd = open(fifo, O_WRONLY | O_CREAT, 0640);
380 errmsg_print("Error creating output file: %s\n", g_strerror(errno));
386 sshs = create_ssh_connection(hostname, port, username, password, sshkey, sshkey_passphrase);
391 channel = run_ssh_command(sshs, capture_bin, iface, cfilter, count);
395 /* read from channel and write into fd */
396 ssh_loop_read(channel, fd);
398 /* clean up and exit */
399 ssh_cleanup(sshs, channel);
404 static void help(const char* binname)
407 g_print(" Usage:\n");
408 g_print(" %s --extcap-interfaces\n", binname);
409 g_print(" %s --extcap-interface=INTERFACE --extcap-dlts\n", binname);
410 g_print(" %s --extcap-interface=INTERFACE --extcap-config\n", binname);
411 g_print(" %s --extcap-interface=INTERFACE --remote-host myhost --remote-port 22222 "
412 "--remote-username myuser --remote-interface eth2 --remote-capture-bin /bin/dumpcap "
413 "--fifo=FILENAME --capture\n", binname);
415 g_print(" --help: print this help\n");
416 g_print(" --version: print the version\n");
417 g_print(" --verbose: print more messages\n");
418 g_print(" --extcap-interfaces: list the interfaces\n");
419 g_print(" --extcap-interface <iface>: specify the interface\n");
420 g_print(" --extcap-dlts: list the DTLs for an interface\n");
421 g_print(" --extcap-config: list the additional configuration for an interface\n");
422 g_print(" --extcap-capture-filter <filter>: the capture filter\n");
423 g_print(" --capture: run the capture\n");
424 g_print(" --fifo <file>: dump data to file or fifo\n");
425 g_print(" --remote-host <host>: the remote SSH host\n");
426 g_print(" --remote-port <port>: the remote SSH port (default: 22)\n");
427 g_print(" --remote-username <username>: the remote SSH username (default: the current user)\n");
428 g_print(" --remote-password <password>: the remote SSH password. If not specified, ssh-agent and ssh-key are used\n");
429 g_print(" --sshkey <public key path>: the path of the ssh key\n");
430 g_print(" --sshkey-passphrase <public key passphrase>: the passphrase to unlock public ssh\n");
431 g_print(" --remote-interface <iface>: the remote capture interface (default: eth0)\n");
432 g_print(" --remote-capture-bin <capture bin>: the remote dumcap binary (default: %s)\n", DEFAULT_CAPTURE_BIN);
433 g_print(" --remote-filter <filter>: a filter for remote capture (default: don't listen on local local interfaces IPs)\n");
436 static int list_interfaces(void)
438 g_print("interface {value=%s}{display=SSH remote capture}\n", SSH_EXTCAP_INTERFACE);
442 static int list_dlts(const char *interface)
445 g_print("ERROR: No interface specified.\n");
449 if (g_strcmp0(interface, SSH_EXTCAP_INTERFACE)) {
450 g_print("ERROR: interface must be %s\n", SSH_EXTCAP_INTERFACE);
454 g_print("dlt {number=147}{name=%s}{display=Remote capture dependant DLT}\n", SSH_EXTCAP_INTERFACE);
459 static char* local_interfaces_to_filter(unsigned int remote_port)
462 #ifdef USE_GETIFADDRS
463 struct ifaddrs* ifap;
467 char ip[INET6_ADDRSTRLEN];
469 if (getifaddrs(&ifap)) {
473 interfaces = g_string_new(NULL);
475 for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
476 if (ifa->ifa_addr == NULL)
479 family = ifa->ifa_addr->sa_family;
481 memset(&ip, 0x0, INET6_ADDRSTRLEN);
486 struct sockaddr_in *addr4 = (struct sockaddr_in *)ifa->ifa_addr;
487 inet_ntop(family, (char *)&addr4->sin_addr, ip, sizeof(ip));
493 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)ifa->ifa_addr;
494 inet_ntop(family, (char *)&addr6->sin6_addr, ip, sizeof(ip));
502 /* skip loopback addresses */
503 if (!g_strcmp0(ip, "127.0.0.1") || !g_strcmp0(ip, "::1"))
508 g_string_append(interfaces, " or ");
509 g_string_append_printf(interfaces, "host %s", ip);
515 filter = g_strdup_printf("not ((%s) and port %u)", interfaces->str, remote_port);
517 g_string_free(interfaces, TRUE);
521 filter = g_strdup_printf("not port %u", remote_port);
525 static int list_config(char *interface, unsigned int remote_port)
531 g_fprintf(stderr, "ERROR: No interface specified.\n");
535 if (g_strcmp0(interface, SSH_EXTCAP_INTERFACE)) {
536 errmsg_print("ERROR: interface must be %s\n", SSH_EXTCAP_INTERFACE);
540 ipfilter = local_interfaces_to_filter(remote_port);
542 g_print("arg {number=%u}{call=--remote-host}{display=Remote SSH server address}"
543 "{type=string}{tooltip=The remote SSH host. It can be both "
544 "an IP address or a hostname}\n", inc++);
545 g_print("arg {number=%u}{call=--remote-port}{display=Remote SSH server port}"
546 "{type=unsigned}{default=22}{tooltip=The remote SSH host port (1-65535)}"
547 "{range=1,65535}\n", inc++);
548 g_print("arg {number=%u}{call=--remote-username}{display=Remote SSH server username}"
549 "{type=string}{default=%s}{tooltip=The remote SSH username. If not provided, "
550 "the current user will be used}\n", inc++, g_get_user_name());
551 g_print("arg {number=%u}{call=--remote-password}{display=Remote SSH server password}"
552 "{type=string}{tooltip=The SSH password, used when other methods (SSH agent "
553 "or key files) are unavailable.}\n", inc++);
554 g_print("arg {number=%u}{call=--sshkey}{display=Path to SSH private key}"
555 "{type=fileselect}{tooltip=The path on the local filesystem of the private ssh key}\n",
557 g_print("arg {number=%u}{call--sshkey-passphrase}{display=SSH key passphrase}\n"
558 "{type=string}{tooltip=Passphrase to unlock the SSH private key}\n",
560 g_print("arg {number=%u}{call=--remote-interface}{display=Remote interface}"
561 "{type=string}{default=eth0}{tooltip=The remote network interface used for capture"
563 g_print("arg {number=%u}{call=--remote-capture-bin}{display=Remote capture binary}"
564 "{type=string}{default=%s}{tooltip=The remote dumpcap binary used "
565 "for capture.}\n", inc++, DEFAULT_CAPTURE_BIN);
566 g_print("arg {number=%u}{call=--remote-filter}{display=Remote capture filter}"
567 "{type=string}{default=%s}{tooltip=The remote capture filter}\n", inc++, ipfilter);
568 g_print("arg {number=%u}{call=--remote-count}{display=Packets to capture}"
569 "{type=unsigned}{default=0}{tooltip=The number of remote packets to capture. (Default: inf)}\n",
577 static char* concat_filters(const char* extcap_filter, const char* remote_filter)
579 if (!extcap_filter && remote_filter)
580 return g_strdup(remote_filter);
582 if (!remote_filter && extcap_filter)
583 return g_strdup(extcap_filter);
585 if (!remote_filter && !extcap_filter)
588 return g_strdup_printf("(%s) and (%s)", extcap_filter, remote_filter);
592 BOOLEAN IsHandleRedirected(DWORD handle)
594 HANDLE h = GetStdHandle(handle);
596 BY_HANDLE_FILE_INFORMATION fi;
597 if (GetFileInformationByHandle(h, &fi)) {
604 static void attach_parent_console()
606 BOOL outRedirected, errRedirected;
608 outRedirected = IsHandleRedirected(STD_OUTPUT_HANDLE);
609 errRedirected = IsHandleRedirected(STD_ERROR_HANDLE);
611 if (outRedirected && errRedirected) {
612 /* Both standard output and error handles are redirected.
613 * There is no point in attaching to parent process console.
618 if (AttachConsole(ATTACH_PARENT_PROCESS) == 0) {
619 /* Console attach failed. */
623 /* Console attach succeeded */
624 if (outRedirected == FALSE) {
625 freopen("CONOUT$", "w", stdout);
628 if (errRedirected == FALSE) {
629 freopen("CONOUT$", "w", stderr);
634 int main(int argc, char **argv)
638 int do_list_interfaces = 0;
642 char* interface = NULL;
643 char* remote_host = NULL;
644 unsigned int remote_port = 22;
645 char* remote_username = NULL;
646 char* remote_password = NULL;
649 char* remote_interface = NULL;
650 char* remote_capture_bin = NULL;
651 char* extcap_filter = NULL;
653 char* sshkey_passphrase = NULL;
654 char* remote_filter = NULL;
655 unsigned long int count = 0;
660 attach_parent_console();
671 for (i = 0; i < argc; i++) {
672 verbose_print("%s ", argv[i]);
676 while ((result = getopt_long(argc, argv, ":", longopts, &option_idx)) != -1) {
689 g_print("%u.%u.%u\n", SSHDUMP_VERSION_MAJOR, SSHDUMP_VERSION_MINOR, SSHDUMP_VERSION_RELEASE);
692 case OPT_LIST_INTERFACES:
693 do_list_interfaces = 1;
703 interface = g_strdup(optarg);
717 fifo = g_strdup(optarg);
720 case OPT_REMOTE_HOST:
723 remote_host = g_strdup(optarg);
726 case OPT_REMOTE_PORT:
727 remote_port = (unsigned int)strtoul(optarg, NULL, 10);
728 if (remote_port > 65535 || remote_port == 0) {
729 g_print("Invalid port: %s\n", optarg);
734 case OPT_REMOTE_USERNAME:
736 g_free(remote_username);
737 remote_username = g_strdup(optarg);
740 case OPT_REMOTE_PASSWORD:
742 g_free(remote_password);
743 remote_password = g_strdup(optarg);
744 memset(optarg, 'X', strlen(optarg));
750 sshkey = g_strdup(optarg);
753 case OPT_SSHKEY_PASSPHRASE:
754 if (sshkey_passphrase)
755 g_free(sshkey_passphrase);
756 sshkey_passphrase = g_strdup(optarg);
757 memset(optarg, 'X', strlen(optarg));
760 case OPT_REMOTE_INTERFACE:
761 if (remote_interface)
762 g_free(remote_interface);
763 remote_interface = g_strdup(optarg);
766 case OPT_REMOTE_CAPTURE_BIN:
767 if (remote_capture_bin)
768 g_free(remote_capture_bin);
769 remote_capture_bin = g_strdup(optarg);
772 case OPT_EXTCAP_FILTER:
774 g_free(extcap_filter);
775 extcap_filter = g_strdup(optarg);
778 case OPT_REMOTE_FILTER:
780 g_free(remote_filter);
781 remote_filter = g_strdup(optarg);
784 case OPT_REMOTE_COUNT:
785 count = strtoul(optarg, NULL, 10);
789 /* missing option argument */
790 g_print("Option '%s' requires an argument\n", argv[optind - 1]);
794 g_print("Invalid option: %s\n", argv[optind - 1]);
799 if (optind != argc) {
800 g_print("Unexpected extra option: %s\n", argv[optind]);
804 if (do_list_interfaces)
805 return list_interfaces();
808 return list_config(interface, remote_port);
811 return list_dlts(interface);
814 result = WSAStartup(MAKEWORD(1,1), &wsaData);
817 errmsg_print("ERROR: WSAStartup failed with error: %d\n", result);
826 errmsg_print("ERROR: No FIFO or file specified\n");
829 if (g_strcmp0(interface, SSH_EXTCAP_INTERFACE)) {
830 errmsg_print("ERROR: invalid interface\n");
834 errmsg_print("Missing parameter: --remote-host");
837 filter = concat_filters(extcap_filter, remote_filter);
838 ret = ssh_open_remote_connection(remote_host, remote_port, remote_username,
839 remote_password, sshkey, sshkey_passphrase, remote_interface,
840 filter, remote_capture_bin, count, fifo);
845 verbose_print("You should not come here... maybe some parameter missing?\n");
851 int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
852 LPSTR lpCmdLine, int nCmdShow) {
853 return main(__argc, __argv);
858 * Editor modelines - https://www.wireshark.org/tools/modelines.html
863 * indent-tabs-mode: t
866 * vi: set shiftwidth=4 tabstop=4 noexpandtab:
867 * :indentSize=4:tabSize=4:noTabs=false: