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) printf(__VA_ARGS__); }
158 #define errmsg_print(...) { fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\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 errmsg_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)
367 ssh_session sshs = NULL;
368 ssh_channel channel = NULL;
369 int fd = STDOUT_FILENO;
370 int ret = EXIT_FAILURE;
372 if (g_strcmp0(fifo, "-")) {
373 /* Open or create the output file */
374 fd = open(fifo, O_WRONLY);
376 fd = open(fifo, O_WRONLY | O_CREAT, 0640);
378 errmsg_print("Error creating output file: %s\n", g_strerror(errno));
384 sshs = create_ssh_connection(hostname, port, username, password, sshkey, sshkey_passphrase);
389 channel = run_ssh_command(sshs, capture_bin, iface, cfilter, count);
393 /* read from channel and write into fd */
394 ssh_loop_read(channel, fd);
398 /* clean up and exit */
399 ssh_cleanup(sshs, channel);
401 if (g_strcmp0(fifo, "-"))
406 static void help(const char* binname)
410 printf(" %s --extcap-interfaces\n", binname);
411 printf(" %s --extcap-interface=INTERFACE --extcap-dlts\n", binname);
412 printf(" %s --extcap-interface=INTERFACE --extcap-config\n", binname);
413 printf(" %s --extcap-interface=INTERFACE --remote-host myhost --remote-port 22222 "
414 "--remote-username myuser --remote-interface eth2 --remote-capture-bin /bin/dumpcap "
415 "--fifo=FILENAME --capture\n", binname);
417 printf(" --help: print this help\n");
418 printf(" --version: print the version\n");
419 printf(" --verbose: print more messages\n");
420 printf(" --extcap-interfaces: list the interfaces\n");
421 printf(" --extcap-interface <iface>: specify the interface\n");
422 printf(" --extcap-dlts: list the DTLs for an interface\n");
423 printf(" --extcap-config: list the additional configuration for an interface\n");
424 printf(" --extcap-capture-filter <filter>: the capture filter\n");
425 printf(" --capture: run the capture\n");
426 printf(" --fifo <file>: dump data to file or fifo\n");
427 printf(" --remote-host <host>: the remote SSH host\n");
428 printf(" --remote-port <port>: the remote SSH port (default: 22)\n");
429 printf(" --remote-username <username>: the remote SSH username (default: the current user)\n");
430 printf(" --remote-password <password>: the remote SSH password. If not specified, ssh-agent and ssh-key are used\n");
431 printf(" --sshkey <public key path>: the path of the ssh key\n");
432 printf(" --sshkey-passphrase <public key passphrase>: the passphrase to unlock public ssh\n");
433 printf(" --remote-interface <iface>: the remote capture interface (default: eth0)\n");
434 printf(" --remote-capture-bin <capture bin>: the remote dumcap binary (default: %s)\n", DEFAULT_CAPTURE_BIN);
435 printf(" --remote-filter <filter>: a filter for remote capture (default: don't listen on local local interfaces IPs)\n");
438 static int list_interfaces(void)
440 printf("extcap {version=%u.%u.%u}\n", SSHDUMP_VERSION_MAJOR, SSHDUMP_VERSION_MINOR, SSHDUMP_VERSION_RELEASE);
441 printf("interface {value=%s}{display=SSH remote capture}\n", SSH_EXTCAP_INTERFACE);
445 static int list_dlts(const char *interface)
448 printf("ERROR: No interface specified.\n");
452 if (g_strcmp0(interface, SSH_EXTCAP_INTERFACE)) {
453 printf("ERROR: interface must be %s\n", SSH_EXTCAP_INTERFACE);
457 printf("dlt {number=147}{name=%s}{display=Remote capture dependant DLT}\n", SSH_EXTCAP_INTERFACE);
462 static char* local_interfaces_to_filter(unsigned int remote_port)
465 #ifdef USE_GETIFADDRS
466 struct ifaddrs* ifap;
470 char ip[INET6_ADDRSTRLEN];
472 if (getifaddrs(&ifap)) {
476 interfaces = g_string_new(NULL);
478 for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
479 if (ifa->ifa_addr == NULL)
482 family = ifa->ifa_addr->sa_family;
484 memset(&ip, 0x0, INET6_ADDRSTRLEN);
489 struct sockaddr_in *addr4 = (struct sockaddr_in *)ifa->ifa_addr;
490 inet_ntop(family, (char *)&addr4->sin_addr, ip, sizeof(ip));
496 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)ifa->ifa_addr;
497 inet_ntop(family, (char *)&addr6->sin6_addr, ip, sizeof(ip));
505 /* skip loopback addresses */
506 if (!g_strcmp0(ip, "127.0.0.1") || !g_strcmp0(ip, "::1"))
511 g_string_append(interfaces, " or ");
512 g_string_append_printf(interfaces, "host %s", ip);
518 filter = g_strdup_printf("not ((%s) and port %u)", interfaces->str, remote_port);
520 g_string_free(interfaces, TRUE);
524 filter = g_strdup_printf("not port %u", remote_port);
528 static int list_config(char *interface, unsigned int remote_port)
534 g_fprintf(stderr, "ERROR: No interface specified.\n");
538 if (g_strcmp0(interface, SSH_EXTCAP_INTERFACE)) {
539 errmsg_print("ERROR: interface must be %s\n", SSH_EXTCAP_INTERFACE);
543 ipfilter = local_interfaces_to_filter(remote_port);
545 printf("arg {number=%u}{call=--remote-host}{display=Remote SSH server address}"
546 "{type=string}{tooltip=The remote SSH host. It can be both "
547 "an IP address or a hostname}{required=true}\n", inc++);
548 printf("arg {number=%u}{call=--remote-port}{display=Remote SSH server port}"
549 "{type=unsigned}{default=22}{tooltip=The remote SSH host port (1-65535)}"
550 "{range=1,65535}\n", inc++);
551 printf("arg {number=%u}{call=--remote-username}{display=Remote SSH server username}"
552 "{type=string}{default=%s}{tooltip=The remote SSH username. If not provided, "
553 "the current user will be used}\n", inc++, g_get_user_name());
554 printf("arg {number=%u}{call=--remote-password}{display=Remote SSH server password}"
555 "{type=password}{tooltip=The SSH password, used when other methods (SSH agent "
556 "or key files) are unavailable.}\n", inc++);
557 printf("arg {number=%u}{call=--sshkey}{display=Path to SSH private key}"
558 "{type=fileselect}{tooltip=The path on the local filesystem of the private ssh key}\n",
560 printf("arg {number=%u}{call=--sshkey-passphrase}{display=SSH key passphrase}"
561 "{type=password}{tooltip=Passphrase to unlock the SSH private key}\n",
563 printf("arg {number=%u}{call=--remote-interface}{display=Remote interface}"
564 "{type=string}{default=eth0}{tooltip=The remote network interface used for capture"
566 printf("arg {number=%u}{call=--remote-capture-bin}{display=Remote capture binary}"
567 "{type=string}{default=%s}{tooltip=The remote dumpcap binary used "
568 "for capture.}\n", inc++, DEFAULT_CAPTURE_BIN);
569 printf("arg {number=%u}{call=--remote-filter}{display=Remote capture filter}"
570 "{type=string}{tooltip=The remote capture filter}", inc++);
572 printf("{default=%s}", ipfilter);
574 printf("arg {number=%u}{call=--remote-count}{display=Packets to capture}"
575 "{type=unsigned}{default=0}{tooltip=The number of remote packets to capture. (Default: inf)}\n",
583 static char* concat_filters(const char* extcap_filter, const char* remote_filter)
585 if (!extcap_filter && remote_filter)
586 return g_strdup(remote_filter);
588 if (!remote_filter && extcap_filter)
589 return g_strdup(extcap_filter);
591 if (!remote_filter && !extcap_filter)
594 return g_strdup_printf("(%s) and (%s)", extcap_filter, remote_filter);
598 BOOLEAN IsHandleRedirected(DWORD handle)
600 HANDLE h = GetStdHandle(handle);
602 BY_HANDLE_FILE_INFORMATION fi;
603 if (GetFileInformationByHandle(h, &fi)) {
610 static void attach_parent_console()
612 BOOL outRedirected, errRedirected;
614 outRedirected = IsHandleRedirected(STD_OUTPUT_HANDLE);
615 errRedirected = IsHandleRedirected(STD_ERROR_HANDLE);
617 if (outRedirected && errRedirected) {
618 /* Both standard output and error handles are redirected.
619 * There is no point in attaching to parent process console.
624 if (AttachConsole(ATTACH_PARENT_PROCESS) == 0) {
625 /* Console attach failed. */
629 /* Console attach succeeded */
630 if (outRedirected == FALSE) {
631 freopen("CONOUT$", "w", stdout);
634 if (errRedirected == FALSE) {
635 freopen("CONOUT$", "w", stderr);
640 int main(int argc, char **argv)
644 int do_list_interfaces = 0;
648 char* interface = NULL;
649 char* remote_host = NULL;
650 unsigned int remote_port = 22;
651 char* remote_username = NULL;
652 char* remote_password = NULL;
655 char* remote_interface = NULL;
656 char* remote_capture_bin = NULL;
657 char* extcap_filter = NULL;
659 char* sshkey_passphrase = NULL;
660 char* remote_filter = NULL;
661 unsigned long int count = 0;
666 attach_parent_console();
677 for (i = 0; i < argc; i++) {
678 verbose_print("%s ", argv[i]);
682 while ((result = getopt_long(argc, argv, ":", longopts, &option_idx)) != -1) {
695 printf("%u.%u.%u\n", SSHDUMP_VERSION_MAJOR, SSHDUMP_VERSION_MINOR, SSHDUMP_VERSION_RELEASE);
698 case OPT_LIST_INTERFACES:
699 do_list_interfaces = 1;
709 interface = g_strdup(optarg);
723 fifo = g_strdup(optarg);
726 case OPT_REMOTE_HOST:
729 remote_host = g_strdup(optarg);
732 case OPT_REMOTE_PORT:
733 remote_port = (unsigned int)strtoul(optarg, NULL, 10);
734 if (remote_port > 65535 || remote_port == 0) {
735 printf("Invalid port: %s\n", optarg);
740 case OPT_REMOTE_USERNAME:
742 g_free(remote_username);
743 remote_username = g_strdup(optarg);
746 case OPT_REMOTE_PASSWORD:
748 g_free(remote_password);
749 remote_password = g_strdup(optarg);
750 memset(optarg, 'X', strlen(optarg));
756 sshkey = g_strdup(optarg);
759 case OPT_SSHKEY_PASSPHRASE:
760 if (sshkey_passphrase)
761 g_free(sshkey_passphrase);
762 sshkey_passphrase = g_strdup(optarg);
763 memset(optarg, 'X', strlen(optarg));
766 case OPT_REMOTE_INTERFACE:
767 if (remote_interface)
768 g_free(remote_interface);
769 remote_interface = g_strdup(optarg);
772 case OPT_REMOTE_CAPTURE_BIN:
773 if (remote_capture_bin)
774 g_free(remote_capture_bin);
775 remote_capture_bin = g_strdup(optarg);
778 case OPT_EXTCAP_FILTER:
780 g_free(extcap_filter);
781 extcap_filter = g_strdup(optarg);
784 case OPT_REMOTE_FILTER:
786 g_free(remote_filter);
787 remote_filter = g_strdup(optarg);
790 case OPT_REMOTE_COUNT:
791 count = strtoul(optarg, NULL, 10);
795 /* missing option argument */
796 printf("Option '%s' requires an argument\n", argv[optind - 1]);
800 printf("Invalid option: %s\n", argv[optind - 1]);
805 if (optind != argc) {
806 printf("Unexpected extra option: %s\n", argv[optind]);
810 if (do_list_interfaces)
811 return list_interfaces();
814 return list_config(interface, remote_port);
817 return list_dlts(interface);
820 result = WSAStartup(MAKEWORD(1,1), &wsaData);
823 errmsg_print("ERROR: WSAStartup failed with error: %d\n", result);
832 errmsg_print("ERROR: No FIFO or file specified\n");
835 if (g_strcmp0(interface, SSH_EXTCAP_INTERFACE)) {
836 errmsg_print("ERROR: invalid interface\n");
840 errmsg_print("Missing parameter: --remote-host");
843 filter = concat_filters(extcap_filter, remote_filter);
844 ret = ssh_open_remote_connection(remote_host, remote_port, remote_username,
845 remote_password, sshkey, sshkey_passphrase, remote_interface,
846 filter, remote_capture_bin, count, fifo);
851 verbose_print("You should not come here... maybe some parameter missing?\n");
857 int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
858 LPSTR lpCmdLine, int nCmdShow) {
859 return main(__argc, __argv);
864 * Editor modelines - https://www.wireshark.org/tools/modelines.html
869 * indent-tabs-mode: t
872 * vi: set shiftwidth=4 tabstop=4 noexpandtab:
873 * :indentSize=4:tabSize=4:noTabs=false: