sshdump/ciscodump: use groups in config.
[metze/wireshark/wip.git] / extcap / sshdump.c
1 /* sshdump.c
2  * sshdump is extcap tool used to capture data using a remote ssh host
3  *
4  * Copyright 2015, Dario Lombardo
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * SPDX-License-Identifier: GPL-2.0-or-later
11  */
12
13 #include "config.h"
14
15 #include <extcap/extcap-base.h>
16 #include <extcap/ssh-base.h>
17 #include <wsutil/interface.h>
18 #include <wsutil/file_util.h>
19 #include <wsutil/strtoi.h>
20 #include <wsutil/filesystem.h>
21
22 #include <errno.h>
23 #include <string.h>
24 #include <fcntl.h>
25
26 #define SSHDUMP_VERSION_MAJOR "1"
27 #define SSHDUMP_VERSION_MINOR "0"
28 #define SSHDUMP_VERSION_RELEASE "0"
29
30 #define SSH_EXTCAP_INTERFACE "sshdump"
31 #define SSH_READ_BLOCK_SIZE 256
32
33 enum {
34         EXTCAP_BASE_OPTIONS_ENUM,
35         OPT_HELP,
36         OPT_VERSION,
37         OPT_REMOTE_HOST,
38         OPT_REMOTE_PORT,
39         OPT_REMOTE_USERNAME,
40         OPT_REMOTE_PASSWORD,
41         OPT_REMOTE_INTERFACE,
42         OPT_REMOTE_CAPTURE_COMMAND,
43         OPT_REMOTE_FILTER,
44         OPT_SSHKEY,
45         OPT_SSHKEY_PASSPHRASE,
46         OPT_REMOTE_COUNT,
47         OPT_REMOTE_SUDO,
48         OPT_REMOTE_NOPROM
49 };
50
51 static struct option longopts[] = {
52         EXTCAP_BASE_OPTIONS,
53         { "help", no_argument, NULL, OPT_HELP},
54         { "version", no_argument, NULL, OPT_VERSION},
55         SSH_BASE_OPTIONS,
56         { "remote-capture-command", required_argument, NULL, OPT_REMOTE_CAPTURE_COMMAND},
57         { "remote-sudo", required_argument, NULL, OPT_REMOTE_SUDO },
58         { "remote-noprom", no_argument, NULL, OPT_REMOTE_NOPROM },
59         { 0, 0, 0, 0}
60 };
61
62 static char* interfaces_list_to_filter(GSList* if_list, const unsigned int remote_port);
63
64 static int ssh_loop_read(ssh_channel channel, FILE* fp)
65 {
66         int nbytes;
67         int ret = EXIT_SUCCESS;
68         char buffer[SSH_READ_BLOCK_SIZE];
69
70         /* read from stdin until data are available */
71         while (ssh_channel_is_open(channel) && !ssh_channel_is_eof(channel)) {
72                 nbytes = ssh_channel_read(channel, buffer, SSH_READ_BLOCK_SIZE, 0);
73                 if (nbytes < 0) {
74                         g_warning("Error reading from channel");
75                         goto end;
76                 }
77                 if (nbytes == 0) {
78                         goto end;
79                 }
80                 if (fwrite(buffer, 1, nbytes, fp) != (guint)nbytes) {
81                         g_warning("Error writing to fifo");
82                         ret = EXIT_FAILURE;
83                         goto end;
84                 }
85                 fflush(fp);
86         }
87
88         /* read loop finished... maybe something wrong happened. Read from stderr */
89         while (ssh_channel_is_open(channel) && !ssh_channel_is_eof(channel)) {
90                 nbytes = ssh_channel_read(channel, buffer, SSH_READ_BLOCK_SIZE, 1);
91                 if (nbytes < 0) {
92                         g_warning("Error reading from channel");
93                         goto end;
94                 }
95                 if (fwrite(buffer, 1, nbytes, stderr) != (guint)nbytes) {
96                         g_warning("Error writing to stderr");
97                         break;
98                 }
99         }
100
101 end:
102         if (ssh_channel_send_eof(channel) != SSH_OK) {
103                 g_warning("Error sending EOF in ssh channel");
104                 ret = EXIT_FAILURE;
105         }
106         return ret;
107 }
108
109 static char* local_interfaces_to_filter(const guint16 remote_port)
110 {
111         GSList* interfaces = local_interfaces_to_list();
112         char* filter = interfaces_list_to_filter(interfaces, remote_port);
113         g_slist_free_full(interfaces, g_free);
114         return filter;
115 }
116
117 static ssh_channel run_ssh_command(ssh_session sshs, const char* capture_command, const gboolean use_sudo, gboolean noprom,
118                 const char* iface, const char* cfilter, const guint32 count)
119 {
120         gchar* cmdline;
121         ssh_channel channel;
122         char* quoted_iface = NULL;
123         char* quoted_filter = NULL;
124         char* count_str = NULL;
125         unsigned int remote_port = 22;
126
127         if (!iface)
128                 iface = "eth0";
129
130         channel = ssh_channel_new(sshs);
131         if (!channel) {
132                 g_warning("Can't create channel");
133                 return NULL;
134         }
135
136         if (ssh_channel_open_session(channel) != SSH_OK) {
137                 g_warning("Can't open session");
138                 ssh_channel_free(channel);
139                 return NULL;
140         }
141
142         ssh_options_get_port(sshs, &remote_port);
143
144         /* escape parameters to go save with the shell */
145         if (capture_command && *capture_command) {
146                 cmdline = g_strdup(capture_command);
147                 g_debug("Remote capture command has disabled other options");
148         } else {
149                 quoted_iface = g_shell_quote(iface);
150                 quoted_filter = g_shell_quote(cfilter ? cfilter : "");
151                 if (count > 0)
152                         count_str = g_strdup_printf("-c %u", count);
153
154                 cmdline = g_strdup_printf("%s tcpdump -U -i %s %s -w - %s %s",
155                         use_sudo ? "sudo" : "",
156                         quoted_iface,
157                         noprom ? "-p" : "",
158                         count_str ? count_str : "",
159                         quoted_filter);
160         }
161
162         g_debug("Running: %s", cmdline);
163         if (ssh_channel_request_exec(channel, cmdline) != SSH_OK) {
164                 g_warning("Can't request exec");
165                 ssh_channel_close(channel);
166                 ssh_channel_free(channel);
167                 channel = NULL;
168         }
169
170         g_free(quoted_iface);
171         g_free(quoted_filter);
172         g_free(cmdline);
173         g_free(count_str);
174
175         return channel;
176 }
177
178 static int ssh_open_remote_connection(const char* hostname, const unsigned int port, const char* username, const char* password,
179         const char* sshkey, const char* sshkey_passphrase, const char* iface, const char* cfilter, const char* capture_command,
180         const gboolean use_sudo, gboolean noprom, const guint32 count, const char* fifo)
181 {
182         ssh_session sshs = NULL;
183         ssh_channel channel = NULL;
184         FILE* fp = stdout;
185         int ret = EXIT_FAILURE;
186         char* err_info = NULL;
187
188         if (g_strcmp0(fifo, "-")) {
189                 /* Open or create the output file */
190                 fp = fopen(fifo, "wb");
191                 if (fp == NULL) {
192                         g_warning("Error creating output file: %s (%s)", fifo, g_strerror(errno));
193                         return EXIT_FAILURE;
194                 }
195         }
196
197         sshs = create_ssh_connection(hostname, port, username, password, sshkey, sshkey_passphrase, &err_info);
198
199         if (!sshs) {
200                 g_warning("Error creating connection: %s", err_info);
201                 goto cleanup;
202         }
203
204         channel = run_ssh_command(sshs, capture_command, use_sudo, noprom, iface, cfilter, count);
205
206         if (!channel) {
207                 g_warning("Can't run ssh command");
208                 goto cleanup;
209         }
210
211         /* read from channel and write into fp */
212         if (ssh_loop_read(channel, fp) != EXIT_SUCCESS) {
213                 g_warning("Error in read loop");
214                 ret = EXIT_FAILURE;
215                 goto cleanup;
216         }
217
218         ret = EXIT_SUCCESS;
219 cleanup:
220         if (err_info)
221                 g_warning("%s", err_info);
222         g_free(err_info);
223
224         /* clean up and exit */
225         ssh_cleanup(&sshs, &channel);
226
227         if (g_strcmp0(fifo, "-"))
228                 fclose(fp);
229         return ret;
230 }
231
232 static char* interfaces_list_to_filter(GSList* interfaces, const unsigned int remote_port)
233 {
234         GString* filter = g_string_new(NULL);
235         GSList* cur;
236
237         if (!interfaces) {
238                 g_string_append_printf(filter, "not port %u", remote_port);
239         } else {
240                 g_string_append_printf(filter, "not ((host %s", (char*)interfaces->data);
241                 cur = g_slist_next(interfaces);
242                 while (cur) {
243                         g_string_append_printf(filter, " or host %s", (char*)cur->data);
244                         cur = g_slist_next(cur);
245                 }
246                 g_string_append_printf(filter, ") and port %u)", remote_port);
247         }
248         return g_string_free(filter, FALSE);
249 }
250
251 static int list_config(char *interface, unsigned int remote_port)
252 {
253         unsigned inc = 0;
254         char* ipfilter;
255
256         if (!interface) {
257                 g_warning("ERROR: No interface specified.");
258                 return EXIT_FAILURE;
259         }
260
261         if (g_strcmp0(interface, SSH_EXTCAP_INTERFACE)) {
262                 g_warning("ERROR: interface must be %s", SSH_EXTCAP_INTERFACE);
263                 return EXIT_FAILURE;
264         }
265
266         ipfilter = local_interfaces_to_filter(remote_port);
267
268         printf("arg {number=%u}{call=--remote-host}{display=Remote SSH server address}"
269                 "{type=string}{tooltip=The remote SSH host. It can be both "
270                 "an IP address or a hostname}{required=true}{group=Server}\n", inc++);
271         printf("arg {number=%u}{call=--remote-port}{display=Remote SSH server port}"
272                 "{type=unsigned}{default=22}{tooltip=The remote SSH host port (1-65535)}"
273                 "{range=1,65535}{group=Server}\n", inc++);
274         printf("arg {number=%u}{call=--remote-username}{display=Remote SSH server username}"
275                 "{type=string}{default=%s}{tooltip=The remote SSH username. If not provided, "
276                 "the current user will be used}{group=Authentication}\n", inc++, g_get_user_name());
277         printf("arg {number=%u}{call=--remote-password}{display=Remote SSH server password}"
278                 "{type=password}{tooltip=The SSH password, used when other methods (SSH agent "
279                 "or key files) are unavailable.}{group=Authentication}\n", inc++);
280         printf("arg {number=%u}{call=--sshkey}{display=Path to SSH private key}"
281                 "{type=fileselect}{tooltip=The path on the local filesystem of the private ssh key}"
282                 "{group=Authentication}\n",inc++);
283         printf("arg {number=%u}{call=--sshkey-passphrase}{display=SSH key passphrase}"
284                 "{type=password}{tooltip=Passphrase to unlock the SSH private key}{group=Authentication}\n",
285                 inc++);
286         printf("arg {number=%u}{call=--remote-interface}{display=Remote interface}"
287                 "{type=string}{default=eth0}{tooltip=The remote network interface used for capture"
288                 "}{group=Capture}\n", inc++);
289         printf("arg {number=%u}{call=--remote-capture-command}{display=Remote capture command}"
290                 "{type=string}{tooltip=The remote command used to capture}{group=Capture}\n", inc++);
291         printf("arg {number=%u}{call=--remote-sudo}{display=Use sudo on the remote machine}"
292                 "{type=boolean}{tooltip=Prepend the capture command with sudo on the remote machine}"
293                 "{group=Capture}\n", inc++);
294         printf("arg {number=%u}{call=--remote-noprom}{display=No promiscuous mode}"
295                 "{type=boolflag}{tooltip=Don't use promiscuous mode on the remote machine}{group=Capture}"
296                 "\n", inc++);
297         printf("arg {number=%u}{call=--remote-filter}{display=Remote capture filter}{type=string}"
298                 "{tooltip=The remote capture filter}", inc++);
299         if (ipfilter)
300                 printf("{default=%s}", ipfilter);
301         printf("{group=Capture}\n");
302         printf("arg {number=%u}{call=--remote-count}{display=Packets to capture}"
303                 "{type=unsigned}{default=0}{tooltip=The number of remote packets to capture. (Default: inf)}"
304                 "{group=Capture}\n", inc++);
305
306         extcap_config_debug(&inc);
307
308         g_free(ipfilter);
309
310         return EXIT_SUCCESS;
311 }
312
313 static char* concat_filters(const char* extcap_filter, const char* remote_filter)
314 {
315         if (!extcap_filter && remote_filter)
316                 return g_strdup(remote_filter);
317
318         if (!remote_filter && extcap_filter)
319                 return g_strdup(extcap_filter);
320
321         if (!remote_filter && !extcap_filter)
322                 return NULL;
323
324         return g_strdup_printf("(%s) and (%s)", extcap_filter, remote_filter);
325 }
326
327 int main(int argc, char **argv)
328 {
329         int result;
330         int option_idx = 0;
331         char* remote_host = NULL;
332         guint16 remote_port = 22;
333         char* remote_username = NULL;
334         char* remote_password = NULL;
335         char* remote_interface = NULL;
336         char* remote_capture_command = NULL;
337         char* sshkey = NULL;
338         char* sshkey_passphrase = NULL;
339         char* remote_filter = NULL;
340         guint32 count = 0;
341         int ret = EXIT_FAILURE;
342         extcap_parameters* extcap_conf = g_new0(extcap_parameters, 1);
343         char* help_url;
344         char* help_header = NULL;
345         gboolean use_sudo = FALSE;
346         gboolean noprom = FALSE;
347
348 #ifdef _WIN32
349         WSADATA wsaData;
350
351         attach_parent_console();
352 #endif  /* _WIN32 */
353
354         help_url = data_file_url("sshdump.html");
355         extcap_base_set_util_info(extcap_conf, argv[0], SSHDUMP_VERSION_MAJOR, SSHDUMP_VERSION_MINOR,
356                 SSHDUMP_VERSION_RELEASE, help_url);
357         g_free(help_url);
358         extcap_base_register_interface(extcap_conf, SSH_EXTCAP_INTERFACE, "SSH remote capture", 147, "Remote capture dependent DLT");
359
360         help_header = g_strdup_printf(
361                 " %s --extcap-interfaces\n"
362                 " %s --extcap-interface=%s --extcap-dlts\n"
363                 " %s --extcap-interface=%s --extcap-config\n"
364                 " %s --extcap-interface=%s --remote-host myhost --remote-port 22222 "
365                 "--remote-username myuser --remote-interface eth2 --remote-capture-command 'tcpdump -U -i eth0 -w -' "
366                 "--fifo=FILENAME --capture\n", argv[0], argv[0], SSH_EXTCAP_INTERFACE, argv[0],
367                 SSH_EXTCAP_INTERFACE, argv[0], SSH_EXTCAP_INTERFACE);
368         extcap_help_add_header(extcap_conf, help_header);
369         g_free(help_header);
370         extcap_help_add_option(extcap_conf, "--help", "print this help");
371         extcap_help_add_option(extcap_conf, "--version", "print the version");
372         extcap_help_add_option(extcap_conf, "--remote-host <host>", "the remote SSH host");
373         extcap_help_add_option(extcap_conf, "--remote-port <port>", "the remote SSH port (default: 22)");
374         extcap_help_add_option(extcap_conf, "--remote-username <username>", "the remote SSH username (default: the current user)");
375         extcap_help_add_option(extcap_conf, "--remote-password <password>", "the remote SSH password. If not specified, ssh-agent and ssh-key are used");
376         extcap_help_add_option(extcap_conf, "--sshkey <public key path>", "the path of the ssh key");
377         extcap_help_add_option(extcap_conf, "--sshkey-passphrase <public key passphrase>", "the passphrase to unlock public ssh");
378         extcap_help_add_option(extcap_conf, "--remote-interface <iface>", "the remote capture interface (default: eth0)");
379         extcap_help_add_option(extcap_conf, "--remote-capture-command <capture command>", "the remote capture command");
380         extcap_help_add_option(extcap_conf, "--remote-sudo yes", "use sudo on the remote machine to capture");
381         extcap_help_add_option(extcap_conf, "--remote-noprom", "don't use promiscuous mode on the remote machine");
382         extcap_help_add_option(extcap_conf, "--remote-filter <filter>", "a filter for remote capture (default: don't "
383                 "listen on local interfaces IPs)");
384         extcap_help_add_option(extcap_conf, "--remote-count <count>", "the number of packets to capture");
385
386         opterr = 0;
387         optind = 0;
388
389         if (argc == 1) {
390                 extcap_help_print(extcap_conf);
391                 goto end;
392         }
393
394         while ((result = getopt_long(argc, argv, ":", longopts, &option_idx)) != -1) {
395
396                 switch (result) {
397
398                 case OPT_HELP:
399                         extcap_help_print(extcap_conf);
400                         ret = EXIT_SUCCESS;
401                         goto end;
402
403                 case OPT_VERSION:
404                         printf("%s\n", extcap_conf->version);
405                         ret = EXIT_SUCCESS;
406                         goto end;
407
408                 case OPT_REMOTE_HOST:
409                         g_free(remote_host);
410                         remote_host = g_strdup(optarg);
411                         break;
412
413                 case OPT_REMOTE_PORT:
414                         if (!ws_strtou16(optarg, NULL, &remote_port) || remote_port == 0) {
415                                 g_warning("Invalid port: %s", optarg);
416                                 goto end;
417                         }
418                         break;
419
420                 case OPT_REMOTE_USERNAME:
421                         g_free(remote_username);
422                         remote_username = g_strdup(optarg);
423                         break;
424
425                 case OPT_REMOTE_PASSWORD:
426                         g_free(remote_password);
427                         remote_password = g_strdup(optarg);
428                         memset(optarg, 'X', strlen(optarg));
429                         break;
430
431                 case OPT_SSHKEY:
432                         g_free(sshkey);
433                         sshkey = g_strdup(optarg);
434                         break;
435
436                 case OPT_SSHKEY_PASSPHRASE:
437                         g_free(sshkey_passphrase);
438                         sshkey_passphrase = g_strdup(optarg);
439                         memset(optarg, 'X', strlen(optarg));
440                         break;
441
442                 case OPT_REMOTE_INTERFACE:
443                         g_free(remote_interface);
444                         remote_interface = g_strdup(optarg);
445                         break;
446
447                 case OPT_REMOTE_CAPTURE_COMMAND:
448                         g_free(remote_capture_command);
449                         remote_capture_command = g_strdup(optarg);
450                         break;
451
452                 case OPT_REMOTE_SUDO:
453                         use_sudo = TRUE;
454                         break;
455
456                 case OPT_REMOTE_FILTER:
457                         g_free(remote_filter);
458                         remote_filter = g_strdup(optarg);
459                         break;
460
461                 case OPT_REMOTE_COUNT:
462                         if (!ws_strtou32(optarg, NULL, &count)) {
463                                 g_warning("Invalid value for count: %s", optarg);
464                                 goto end;
465                         }
466                         break;
467
468                 case OPT_REMOTE_NOPROM:
469                         noprom = TRUE;
470                         break;
471
472                 case ':':
473                         /* missing option argument */
474                         g_warning("Option '%s' requires an argument", argv[optind - 1]);
475                         break;
476
477                 default:
478                         if (!extcap_base_parse_options(extcap_conf, result - EXTCAP_OPT_LIST_INTERFACES, optarg)) {
479                                 g_warning("Invalid option: %s", argv[optind - 1]);
480                                 goto end;
481                         }
482                 }
483         }
484
485         extcap_cmdline_debug(argv, argc);
486
487         if (extcap_base_handle_interface(extcap_conf)) {
488                 ret = EXIT_SUCCESS;
489                 goto end;
490         }
491
492         if (extcap_conf->show_config) {
493                 ret = list_config(extcap_conf->interface, remote_port);
494                 goto end;
495         }
496
497 #ifdef _WIN32
498         result = WSAStartup(MAKEWORD(1,1), &wsaData);
499         if (result != 0) {
500                 g_warning("ERROR: WSAStartup failed with error: %d", result);
501                 goto end;
502         }
503 #endif  /* _WIN32 */
504
505         if (extcap_conf->capture) {
506                 char* filter;
507
508                 if (!remote_host) {
509                         g_warning("Missing parameter: --remote-host");
510                         goto end;
511                 }
512                 filter = concat_filters(extcap_conf->capture_filter, remote_filter);
513                 ret = ssh_open_remote_connection(remote_host, remote_port, remote_username,
514                         remote_password, sshkey, sshkey_passphrase, remote_interface,
515                         filter, remote_capture_command, use_sudo, noprom, count, extcap_conf->fifo);
516                 g_free(filter);
517         } else {
518                 g_debug("You should not come here... maybe some parameter missing?");
519                 ret = EXIT_FAILURE;
520         }
521
522 end:
523         /* clean up stuff */
524         g_free(remote_host);
525         g_free(remote_username);
526         g_free(remote_password);
527         g_free(remote_interface);
528         g_free(remote_capture_command);
529         g_free(sshkey);
530         g_free(sshkey_passphrase);
531         g_free(remote_filter);
532         extcap_base_cleanup(&extcap_conf);
533         return ret;
534 }
535
536 #ifdef _WIN32
537 int _stdcall
538 WinMain (struct HINSTANCE__ *hInstance,
539         struct HINSTANCE__ *hPrevInstance,
540         char               *lpszCmdLine,
541         int                 nCmdShow)
542 {
543         return main(__argc, __argv);
544 }
545 #endif
546
547 /*
548  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
549  *
550  * Local variables:
551  * c-basic-offset: 8
552  * tab-width: 8
553  * indent-tabs-mode: t
554  * End:
555  *
556  * vi: set shiftwidth=8 tabstop=8 noexpandtab:
557  * :indentSize=8:tabSize=8:noTabs=false:
558  */