zmap.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. /*
  2. * ZMap Copyright 2013 Regents of the University of Michigan
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy
  6. * of the License at http://www.apache.org/licenses/LICENSE-2.0
  7. */
  8. #define _GNU_SOURCE
  9. #include <stdlib.h>
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <assert.h>
  14. #include <sched.h>
  15. #include <errno.h>
  16. #include <pwd.h>
  17. #include <time.h>
  18. #include <pcap/pcap.h>
  19. #ifdef JSON
  20. #include <json.h>
  21. #endif
  22. #include <pthread.h>
  23. #include "../lib/includes.h"
  24. #include "../lib/blacklist.h"
  25. #include "../lib/logger.h"
  26. #include "../lib/random.h"
  27. #include "../lib/util.h"
  28. #include "../lib/xalloc.h"
  29. #include "aesrand.h"
  30. #include "zopt.h"
  31. #include "send.h"
  32. #include "recv.h"
  33. #include "state.h"
  34. #include "monitor.h"
  35. #include "get_gateway.h"
  36. #include "filter.h"
  37. #include "summary.h"
  38. #include "output_modules/output_modules.h"
  39. #include "probe_modules/probe_modules.h"
  40. #ifdef PFRING
  41. #include <pfring_zc.h>
  42. static int32_t distrib_func(pfring_zc_pkt_buff *pkt, void *arg) {
  43. (void) pkt;
  44. (void) arg;
  45. return 0;
  46. }
  47. #endif
  48. pthread_mutex_t recv_ready_mutex = PTHREAD_MUTEX_INITIALIZER;
  49. typedef struct send_arg {
  50. uint32_t cpu;
  51. sock_t sock;
  52. shard_t *shard;
  53. } send_arg_t;
  54. typedef struct recv_arg {
  55. uint32_t cpu;
  56. } recv_arg_t;
  57. typedef struct mon_start_arg {
  58. uint32_t cpu;
  59. iterator_t *it;
  60. pthread_mutex_t *recv_ready_mutex;
  61. } mon_start_arg_t;
  62. const char *default_help_text = "By default, ZMap prints out unique, successful"
  63. "IP addresses (e.g., SYN-ACK from a TCP SYN scan) "
  64. "in ASCII form (e.g., 192.168.1.5) to stdout or the specified output "
  65. "file. Internally this is handled by the \"csv\" output module and is "
  66. "equivalent to running zmap --output-module=csv --output-fields=saddr "
  67. "--output-filter=\"success = 1 && repeat = 0\".";
  68. static void enforce_range(const char *name, int v, int min, int max)
  69. {
  70. if (check_range(v, min, max) == EXIT_FAILURE) {
  71. log_fatal("zmap", "argument `%s' must be between %d and %d\n",
  72. name, min, max);
  73. }
  74. }
  75. static void* start_send(void *arg)
  76. {
  77. send_arg_t *s = (send_arg_t *) arg;
  78. log_trace("zmap", "Pinning a send thread to core %u", s->cpu);
  79. set_cpu(s->cpu);
  80. send_run(s->sock, s->shard);
  81. free(s);
  82. return NULL;
  83. }
  84. static void* start_recv(void *arg)
  85. {
  86. recv_arg_t *r = (recv_arg_t *) arg;
  87. log_trace("zmap", "Pinning receive thread to core %u", r->cpu);
  88. set_cpu(r->cpu);
  89. recv_run(&recv_ready_mutex);
  90. return NULL;
  91. }
  92. static void *start_mon(void *arg)
  93. {
  94. mon_start_arg_t *mon_arg = (mon_start_arg_t *) arg;
  95. log_trace("zmap", "Pinning monitor thread to core %u", mon_arg->cpu);
  96. set_cpu(mon_arg->cpu);
  97. if (zconf.disable_monitor == 0)
  98. monitor_run(mon_arg->it, mon_arg->recv_ready_mutex);
  99. free(mon_arg);
  100. return NULL;
  101. }
  102. static void start_zmap(void)
  103. {
  104. if (zconf.iface == NULL) {
  105. zconf.iface = get_default_iface();
  106. assert(zconf.iface);
  107. log_debug("zmap", "no interface provided. will use default"
  108. " interface (%s).", zconf.iface);
  109. }
  110. if (zconf.source_ip_first == NULL) {
  111. struct in_addr default_ip;
  112. zconf.source_ip_first = xmalloc(INET_ADDRSTRLEN);
  113. zconf.source_ip_last = zconf.source_ip_first;
  114. if (get_iface_ip(zconf.iface, &default_ip) < 0) {
  115. log_fatal("zmap", "could not detect default IP address for %s."
  116. " Try specifying a source address (-S).", zconf.iface);
  117. }
  118. inet_ntop(AF_INET, &default_ip, zconf.source_ip_first, INET_ADDRSTRLEN);
  119. log_debug("zmap", "no source IP address given. will use default address: %s.",
  120. zconf.source_ip_first);
  121. }
  122. if (!zconf.gw_mac_set) {
  123. struct in_addr gw_ip;
  124. memset(&gw_ip, 0, sizeof(struct in_addr));
  125. if (get_default_gw(&gw_ip, zconf.iface) < 0) {
  126. log_fatal("zmap", "could not detect default gateway address for %s."
  127. " Try setting default gateway mac address (-G).",
  128. zconf.iface);
  129. }
  130. log_debug("zmap", "found gateway IP %s on %s", inet_ntoa(gw_ip), zconf.iface);
  131. zconf.gw_ip = gw_ip.s_addr;
  132. memset(&zconf.gw_mac, 0, MAC_ADDR_LEN);
  133. if (get_hw_addr(&gw_ip, zconf.iface, zconf.gw_mac)) {
  134. log_fatal("zmap", "could not detect GW MAC address for %s on %s."
  135. " Try setting default gateway mac address (-G), or run"
  136. " \"arp <gateway_ip>\" in terminal.",
  137. inet_ntoa(gw_ip), zconf.iface);
  138. }
  139. zconf.gw_mac_set = 1;
  140. }
  141. log_debug("send", "gateway MAC address %02x:%02x:%02x:%02x:%02x:%02x",
  142. zconf.gw_mac[0], zconf.gw_mac[1], zconf.gw_mac[2],
  143. zconf.gw_mac[3], zconf.gw_mac[4], zconf.gw_mac[5]);
  144. // Initialization
  145. log_info("zmap", "output module: %s", zconf.output_module->name);
  146. if (zconf.output_module && zconf.output_module->init) {
  147. zconf.output_module->init(&zconf, zconf.output_fields,
  148. zconf.output_fields_len);
  149. }
  150. iterator_t *it = send_init();
  151. if (!it) {
  152. log_fatal("zmap", "unable to initialize sending component");
  153. }
  154. if (zconf.output_module && zconf.output_module->start) {
  155. zconf.output_module->start(&zconf, &zsend, &zrecv);
  156. }
  157. // start threads
  158. uint32_t cpu = 0;
  159. pthread_t *tsend, trecv, tmon;
  160. recv_arg_t *recv_arg = xmalloc(sizeof(recv_arg_t));
  161. recv_arg->cpu = zconf.pin_cores[cpu % zconf.pin_cores_len];
  162. cpu += 1;
  163. int r = pthread_create(&trecv, NULL, start_recv, recv_arg);
  164. if (r != 0) {
  165. log_fatal("zmap", "unable to create recv thread");
  166. }
  167. for (;;) {
  168. pthread_mutex_lock(&recv_ready_mutex);
  169. if (zconf.recv_ready) {
  170. pthread_mutex_unlock(&recv_ready_mutex);
  171. break;
  172. }
  173. pthread_mutex_unlock(&recv_ready_mutex);
  174. }
  175. #ifdef PFRING
  176. pfring_zc_worker *zw = pfring_zc_run_balancer(zconf.pf.queues,
  177. &zconf.pf.send,
  178. zconf.senders,
  179. 1,
  180. zconf.pf.prefetches,
  181. round_robin_bursts_policy,
  182. NULL,
  183. distrib_func,
  184. NULL,
  185. 0,
  186. zconf.pin_cores[cpu & zconf.pin_cores_len]);
  187. cpu += 1;
  188. #endif
  189. tsend = xmalloc(zconf.senders * sizeof(pthread_t));
  190. for (uint8_t i = 0; i < zconf.senders; i++) {
  191. sock_t sock;
  192. if (zconf.dryrun) {
  193. sock = get_dryrun_socket();
  194. } else {
  195. sock = get_socket(i);
  196. }
  197. send_arg_t *arg = xmalloc(sizeof(send_arg_t));
  198. arg->sock = sock;
  199. arg->shard = get_shard(it, i);
  200. arg->cpu = zconf.pin_cores[cpu % zconf.pin_cores_len];
  201. cpu += 1;
  202. int r = pthread_create(&tsend[i], NULL, start_send, arg);
  203. if (r != 0) {
  204. log_fatal("zmap", "unable to create send thread");
  205. exit(EXIT_FAILURE);
  206. }
  207. }
  208. log_debug("zmap", "%d sender threads spawned", zconf.senders);
  209. mon_start_arg_t *mon_arg = xmalloc(sizeof(mon_start_arg_t));
  210. mon_arg->it = it;
  211. mon_arg->recv_ready_mutex = &recv_ready_mutex;
  212. mon_arg->cpu = zconf.pin_cores[cpu % zconf.pin_cores_len];
  213. {
  214. int r = pthread_create(&tmon, NULL, start_mon, mon_arg);
  215. if (r != 0) {
  216. log_fatal("zmap", "unable to create monitor thread");
  217. exit(EXIT_FAILURE);
  218. }
  219. }
  220. #ifndef PFRING
  221. drop_privs();
  222. #endif
  223. // wait for completion
  224. for (uint8_t i = 0; i < zconf.senders; i++) {
  225. int r = pthread_join(tsend[i], NULL);
  226. if (r != 0) {
  227. log_fatal("zmap", "unable to join send thread");
  228. exit(EXIT_FAILURE);
  229. }
  230. }
  231. log_debug("zmap", "senders finished");
  232. #ifdef PFRING
  233. pfring_zc_kill_worker(zw);
  234. pfring_zc_sync_queue(zconf.pf.send, tx_only);
  235. log_debug("zmap", "send queue flushed");
  236. #endif
  237. r = pthread_join(trecv, NULL);
  238. if (r != 0) {
  239. log_fatal("zmap", "unable to join recv thread");
  240. exit(EXIT_FAILURE);
  241. }
  242. if (!zconf.quiet || zconf.status_updates_file) {
  243. pthread_join(tmon, NULL);
  244. if (r != 0) {
  245. log_fatal("zmap", "unable to join monitor thread");
  246. exit(EXIT_FAILURE);
  247. }
  248. }
  249. // finished
  250. #ifdef JSON
  251. if (zconf.metadata_filename) {
  252. json_metadata(zconf.metadata_file);
  253. }
  254. #endif
  255. if (zconf.output_module && zconf.output_module->close) {
  256. zconf.output_module->close(&zconf, &zsend, &zrecv);
  257. }
  258. if (zconf.probe_module && zconf.probe_module->close) {
  259. zconf.probe_module->close(&zconf, &zsend, &zrecv);
  260. }
  261. #ifdef PFRING
  262. pfring_zc_destroy_cluster(zconf.pf.cluster);
  263. #endif
  264. log_info("zmap", "completed");
  265. }
  266. #define SET_IF_GIVEN(DST,ARG) \
  267. { if (args.ARG##_given) { (DST) = args.ARG##_arg; }; }
  268. #define SET_BOOL(DST,ARG) \
  269. { if (args.ARG##_given) { (DST) = 1; }; }
  270. int main(int argc, char *argv[])
  271. {
  272. struct gengetopt_args_info args;
  273. struct cmdline_parser_params *params;
  274. params = cmdline_parser_params_create();
  275. params->initialize = 1;
  276. params->override = 0;
  277. params->check_required = 0;
  278. int config_loaded = 0;
  279. if (cmdline_parser_ext(argc, argv, &args, params) != 0) {
  280. exit(EXIT_SUCCESS);
  281. }
  282. if (args.config_given || file_exists(args.config_arg)) {
  283. params->initialize = 0;
  284. params->override = 0;
  285. if (cmdline_parser_config_file(args.config_arg, &args, params)
  286. != 0) {
  287. exit(EXIT_FAILURE);
  288. }
  289. config_loaded = 1;
  290. }
  291. // initialize logging. if no log file or log directory are specified
  292. // default to using stderr.
  293. zconf.log_level = args.verbosity_arg;
  294. zconf.log_file = args.log_file_arg;
  295. zconf.log_directory = args.log_directory_arg;
  296. if (args.disable_syslog_given) {
  297. zconf.syslog = 0;
  298. }
  299. if (zconf.log_file && zconf.log_directory) {
  300. log_init(stderr, zconf.log_level, zconf.syslog, "zmap");
  301. log_fatal("zmap", "log-file and log-directory cannot "
  302. "specified simultaneously.");
  303. }
  304. FILE *log_location = NULL;
  305. if (zconf.log_file) {
  306. log_location = fopen(zconf.log_file, "w");
  307. } else if (zconf.log_directory) {
  308. time_t now;
  309. time(&now);
  310. struct tm *local = localtime(&now);
  311. char path[100];
  312. strftime(path, 100, "zmap-%Y-%m-%dT%H%M%S%z.log", local);
  313. char *fullpath = xmalloc(strlen(zconf.log_directory) + strlen(path) + 2);
  314. sprintf(fullpath, "%s/%s", zconf.log_directory, path);
  315. log_location = fopen(fullpath, "w");
  316. free(fullpath);
  317. } else {
  318. log_location = stderr;
  319. }
  320. if (!log_location) {
  321. log_init(stderr, zconf.log_level, zconf.syslog, "zmap");
  322. log_fatal("zmap", "unable to open specified log file: %s",
  323. strerror(errno));
  324. }
  325. log_init(log_location, zconf.log_level, zconf.syslog, "zmap");
  326. log_trace("zmap", "zmap main thread started");
  327. if (config_loaded) {
  328. log_debug("zmap", "Loaded configuration file %s",
  329. args.config_arg);
  330. }
  331. if (zconf.syslog) {
  332. log_debug("zmap", "syslog support enabled");
  333. } else {
  334. log_info("zmap", "syslog support disabled");
  335. }
  336. // parse the provided probe and output module s.t. that we can support
  337. // other command-line helpers (e.g. probe help)
  338. log_trace("zmap", "requested ouput-module: %s", args.output_module_arg);
  339. // zmap's default behavior is to provide a simple file of the unique IP
  340. // addresses that responded successfully.
  341. if (!strcmp(args.output_module_arg, "default")) {
  342. log_debug("zmap", "no output module provided. will use csv.");
  343. zconf.output_module = get_output_module_by_name("csv");
  344. zconf.raw_output_fields = (char*) "saddr";
  345. zconf.filter_duplicates = 1;
  346. zconf.filter_unsuccessful = 1;
  347. } else {
  348. zconf.output_module = get_output_module_by_name(args.output_module_arg);
  349. if (!zconf.output_module) {
  350. log_fatal("zmap", "specified output module (%s) does not exist\n",
  351. args.output_module_arg);
  352. }
  353. }
  354. zconf.probe_module = get_probe_module_by_name(args.probe_module_arg);
  355. if (!zconf.probe_module) {
  356. log_fatal("zmap", "specified probe module (%s) does not exist\n",
  357. args.probe_module_arg);
  358. exit(EXIT_FAILURE);
  359. }
  360. if (args.help_given) {
  361. cmdline_parser_print_help();
  362. printf("\nProbe-module (%s) Help:\n", zconf.probe_module->name);
  363. if (zconf.probe_module->helptext) {
  364. fprintw(stdout, (char*) zconf.probe_module->helptext, 80);
  365. } else {
  366. printf("no help text available\n");
  367. }
  368. printf("\nOutput-module (%s) Help:\n", zconf.output_module->name);
  369. if (!strcmp(args.output_module_arg, "default")) {
  370. fprintw(stdout, (char*) default_help_text, 80);
  371. } else if (zconf.output_module->helptext) {
  372. fprintw(stdout, (char*) zconf.output_module->helptext, 80);
  373. } else {
  374. printf("no help text available\n");
  375. }
  376. exit(EXIT_SUCCESS);
  377. }
  378. if (args.version_given) {
  379. cmdline_parser_print_version();
  380. exit(EXIT_SUCCESS);
  381. }
  382. if (args.list_output_modules_given) {
  383. print_output_modules();
  384. exit(EXIT_SUCCESS);
  385. }
  386. if (args.list_probe_modules_given) {
  387. print_probe_modules();
  388. exit(EXIT_SUCCESS);
  389. }
  390. if (args.vpn_given) {
  391. zconf.send_ip_pkts = 1;
  392. zconf.gw_mac_set = 1;
  393. memset(zconf.gw_mac, 0, MAC_ADDR_LEN);
  394. }
  395. if (cmdline_parser_required(&args, CMDLINE_PARSER_PACKAGE) != 0) {
  396. exit(EXIT_FAILURE);
  397. }
  398. if (! args.probe_module_given && (args.marker_encoding_given || args.markervalue_given)) {
  399. log_fatal("zmap", "maker and/or marker value defined but mo probe modul! The marker probe module needs to be defined");
  400. }
  401. if (args.marker_encoding_given)
  402. zconf.marker_encoding = args.marker_encoding_arg;
  403. if (args.markervalue_given)
  404. zconf.markervalue = strtoul(args.markervalue_arg, NULL, 10);
  405. if (args.use_markervalue_given)
  406. zconf.use_markervalue = args.use_markervalue_arg;
  407. if (args.markerbits_value_given)
  408. zconf.markerbits_value = args.markerbits_value_arg;
  409. if (args.markerbits_checksum_given)
  410. zconf.markerbits_checksum = args.markerbits_checksum_arg;
  411. if (args.markerbits_dst_small_given)
  412. zconf.marker_encoding_dst_small = args.markerbits_dst_small_arg;
  413. if (args.disable_monitor_given)
  414. zconf.disable_monitor = args.disable_monitor_arg;
  415. if (!strcmp(args.probe_module_arg, "tcp_synscan_pra")) {
  416. log_info("zmap", "Encoder values: marker type/marker value/bits value/bits checksum/markerbits small/disable monitor = %d/%u/%d/%d/%d/%d",
  417. zconf.marker_encoding,
  418. zconf.markervalue,
  419. zconf.markerbits_value,
  420. zconf.markerbits_checksum,
  421. zconf.marker_encoding_dst_small,
  422. zconf.disable_monitor);
  423. }
  424. // now that we know the probe module, let's find what it supports
  425. memset(&zconf.fsconf, 0, sizeof(struct fieldset_conf));
  426. // the set of fields made available to a user is constructed
  427. // of IP header fields + probe module fields + system fields
  428. fielddefset_t *fds = &(zconf.fsconf.defs);
  429. gen_fielddef_set(fds, (fielddef_t*) &(ip_fields), ip_fields_len);
  430. gen_fielddef_set(fds, zconf.probe_module->fields,
  431. zconf.probe_module->numfields);
  432. gen_fielddef_set(fds, (fielddef_t*) &(sys_fields), sys_fields_len);
  433. if (args.list_output_fields_given) {
  434. for (int i = 0; i < fds->len; i++) {
  435. printf("%-15s %6s: %s\n", fds->fielddefs[i].name,
  436. fds->fielddefs[i].type,
  437. fds->fielddefs[i].desc);
  438. }
  439. exit(EXIT_SUCCESS);
  440. }
  441. // find the fields we need for the framework
  442. zconf.fsconf.success_index =
  443. fds_get_index_by_name(fds, (char*) "success");
  444. if (zconf.fsconf.success_index < 0) {
  445. log_fatal("fieldset", "probe module does not supply "
  446. "required success field.");
  447. }
  448. zconf.fsconf.app_success_index =
  449. fds_get_index_by_name(fds, (char*) "app_success");
  450. if (zconf.fsconf.app_success_index < 0) {
  451. log_trace("fieldset", "probe module does not supply "
  452. "application success field.");
  453. } else {
  454. log_trace("fieldset", "probe module supplies app_success"
  455. " output field. It will be included in monitor output");
  456. }
  457. zconf.fsconf.classification_index =
  458. fds_get_index_by_name(fds, (char*) "classification");
  459. if (zconf.fsconf.classification_index < 0) {
  460. log_fatal("fieldset", "probe module does not supply "
  461. "required packet classification field.");
  462. }
  463. // process the list of requested output fields.
  464. if (args.output_fields_given) {
  465. zconf.raw_output_fields = args.output_fields_arg;
  466. } else if (!zconf.raw_output_fields) {
  467. zconf.raw_output_fields = (char*) "saddr";
  468. }
  469. if (!strcmp(zconf.raw_output_fields, "*")) {
  470. zconf.output_fields_len = zconf.fsconf.defs.len;
  471. zconf.output_fields = xcalloc(zconf.fsconf.defs.len, sizeof(char*));
  472. for (int i=0; i < zconf.fsconf.defs.len; i++) {
  473. zconf.output_fields[i] = (char*) zconf.fsconf.defs.fielddefs[i].name;
  474. }
  475. fs_generate_full_fieldset_translation(&zconf.fsconf.translation,
  476. &zconf.fsconf.defs);
  477. } else {
  478. split_string(zconf.raw_output_fields, &(zconf.output_fields_len),
  479. &(zconf.output_fields));
  480. for (int i=0; i < zconf.output_fields_len; i++) {
  481. log_debug("zmap", "requested output field (%i): %s", i,
  482. zconf.output_fields[i]);
  483. }
  484. // generate a translation that can be used to convert output
  485. // from a probe module to the input for an output module
  486. fs_generate_fieldset_translation(&zconf.fsconf.translation,
  487. &zconf.fsconf.defs, zconf.output_fields,
  488. zconf.output_fields_len);
  489. }
  490. // Parse and validate the output filter, if any
  491. if (args.output_filter_arg) {
  492. // Run it through yyparse to build the expression tree
  493. if (!parse_filter_string(args.output_filter_arg)) {
  494. log_fatal("zmap", "Unable to parse filter expression");
  495. }
  496. // Check the fields used against the fieldset in use
  497. if (!validate_filter(zconf.filter.expression, &zconf.fsconf.defs)) {
  498. log_fatal("zmap", "Invalid filter");
  499. }
  500. zconf.output_filter_str = args.output_filter_arg;
  501. }
  502. SET_BOOL(zconf.dryrun, dryrun);
  503. SET_BOOL(zconf.quiet, quiet);
  504. SET_BOOL(zconf.ignore_invalid_hosts, ignore_invalid_hosts);
  505. zconf.cooldown_secs = args.cooldown_time_arg;
  506. SET_IF_GIVEN(zconf.output_filename, output_file);
  507. SET_IF_GIVEN(zconf.blacklist_filename, blacklist_file);
  508. SET_IF_GIVEN(zconf.probe_args, probe_args);
  509. SET_IF_GIVEN(zconf.output_args, output_args);
  510. SET_IF_GIVEN(zconf.iface, interface);
  511. SET_IF_GIVEN(zconf.max_runtime, max_runtime);
  512. SET_IF_GIVEN(zconf.max_results, max_results);
  513. SET_IF_GIVEN(zconf.rate, rate);
  514. SET_IF_GIVEN(zconf.packet_streams, probes);
  515. SET_IF_GIVEN(zconf.status_updates_file, status_updates_file);
  516. SET_IF_GIVEN(zconf.num_retries, retries);
  517. SET_IF_GIVEN(zconf.max_sendto_failures, max_sendto_failures);
  518. SET_IF_GIVEN(zconf.min_hitrate, min_hitrate);
  519. if (zconf.num_retries < 0) {
  520. log_fatal("zmap", "Invalid retry count");
  521. }
  522. if (zconf.max_sendto_failures >= 0) {
  523. log_debug("zmap", "scan will abort if more than %i "
  524. "sendto failures occur", zconf.max_sendto_failures);
  525. }
  526. if (zconf.min_hitrate > 0.0) {
  527. log_debug("zmap", "scan will abort if hitrate falls below %f",
  528. zconf.min_hitrate);
  529. }
  530. if (args.metadata_file_arg) {
  531. #ifdef JSON
  532. zconf.metadata_filename = args.metadata_file_arg;
  533. if (!strcmp(zconf.metadata_filename, "-")) {
  534. zconf.metadata_file = stdout;
  535. } else {
  536. zconf.metadata_file = fopen(zconf.metadata_filename, "w");
  537. }
  538. if (!zconf.metadata_file) {
  539. log_fatal("metadata", "unable to open metadata file");
  540. }
  541. log_trace("metadata", "metdata will be saved to %s",
  542. zconf.metadata_filename);
  543. #else
  544. log_fatal("zmap", "JSON support not compiled into ZMap. "
  545. "Metadata output not supported.");
  546. #endif
  547. }
  548. if (args.user_metadata_given) {
  549. #ifdef JSON
  550. zconf.custom_metadata_str = args.user_metadata_arg;
  551. if (!json_tokener_parse(zconf.custom_metadata_str)) {
  552. log_fatal("metadata", "unable to parse custom user metadata");
  553. } else {
  554. log_debug("metadata", "user metadata validated successfully");
  555. }
  556. #else
  557. log_fatal("zmap", "JSON support not compiled into ZMap. "
  558. "Metadata output not supported.");
  559. #endif
  560. }
  561. if (args.notes_given) {
  562. #ifdef JSON
  563. zconf.notes = args.notes_arg;
  564. #else
  565. log_fatal("zmap", "JSON support not compiled into ZMap. "
  566. "Metadata output and note injection are not supported.");
  567. #endif
  568. }
  569. // find if zmap wants any specific cidrs scanned instead
  570. // of the entire Internet
  571. zconf.destination_cidrs = args.inputs;
  572. zconf.destination_cidrs_len = args.inputs_num;
  573. if (zconf.destination_cidrs && zconf.blacklist_filename
  574. && !strcmp(zconf.blacklist_filename, "/etc/zmap/blacklist.conf")) {
  575. log_warn("blacklist", "ZMap is currently using the default blacklist located "
  576. "at /etc/zmap/blacklist.conf. By default, this blacklist excludes locally "
  577. "scoped networks (e.g. 10.0.0.0/8, 127.0.0.1/8, and 192.168.0.0/16). If you are"
  578. " trying to scan local networks, you can change the default blacklist by "
  579. "editing the default ZMap configuration at /etc/zmap/zmap.conf.");
  580. }
  581. SET_IF_GIVEN(zconf.whitelist_filename, whitelist_file);
  582. if (zconf.probe_module->port_args) {
  583. if (args.source_port_given) {
  584. char *dash = strchr(args.source_port_arg, '-');
  585. if (dash) { // range
  586. *dash = '\0';
  587. zconf.source_port_first = atoi(args.source_port_arg);
  588. enforce_range("starting source-port", zconf.source_port_first, 0, 0xFFFF);
  589. zconf.source_port_last = atoi(dash+1);
  590. enforce_range("ending source-port", zconf.source_port_last, 0, 0xFFFF);
  591. if (zconf.source_port_first > zconf.source_port_last) {
  592. fprintf(stderr, "%s: invalid source port range: "
  593. "last port is less than first port\n",
  594. CMDLINE_PARSER_PACKAGE);
  595. exit(EXIT_FAILURE);
  596. }
  597. } else { // single port
  598. int port = atoi(args.source_port_arg);
  599. enforce_range("source-port", port, 0, 0xFFFF);
  600. zconf.source_port_first = port;
  601. zconf.source_port_last = port;
  602. }
  603. }
  604. if (!args.target_port_given) {
  605. log_fatal("zmap", "target port (-p) is required for this type of probe");
  606. }
  607. enforce_range("target-port", args.target_port_arg, 0, 0xFFFF);
  608. zconf.target_port = args.target_port_arg;
  609. }
  610. if (args.source_ip_given) {
  611. char *dash = strchr(args.source_ip_arg, '-');
  612. if (dash) { // range
  613. *dash = '\0';
  614. zconf.source_ip_first = args.source_ip_arg;
  615. zconf.source_ip_last = dash+1;
  616. } else { // single address
  617. zconf.source_ip_first = args.source_ip_arg;
  618. zconf.source_ip_last = args.source_ip_arg;
  619. }
  620. }
  621. if (args.gateway_mac_given) {
  622. if (!parse_mac(zconf.gw_mac, args.gateway_mac_arg)) {
  623. fprintf(stderr, "%s: invalid MAC address `%s'\n",
  624. CMDLINE_PARSER_PACKAGE, args.gateway_mac_arg);
  625. exit(EXIT_FAILURE);
  626. }
  627. zconf.gw_mac_set = 1;
  628. }
  629. if (args.source_mac_given) {
  630. if (!parse_mac(zconf.hw_mac, args.source_mac_arg)) {
  631. fprintf(stderr, "%s: invalid MAC address `%s'\n",
  632. CMDLINE_PARSER_PACKAGE, args.gateway_mac_arg);
  633. exit(EXIT_FAILURE);
  634. }
  635. log_debug("send", "source MAC address specified on CLI: "
  636. "%02x:%02x:%02x:%02x:%02x:%02x",
  637. zconf.hw_mac[0], zconf.hw_mac[1], zconf.hw_mac[2],
  638. zconf.hw_mac[3], zconf.hw_mac[4], zconf.hw_mac[5]);
  639. zconf.hw_mac_set = 1;
  640. }
  641. // Check for a random seed
  642. if (args.seed_given) {
  643. zconf.seed = args.seed_arg;
  644. zconf.use_seed = 1;
  645. }
  646. // Seed the RNG
  647. if (zconf.use_seed) {
  648. zconf.aes = aesrand_init_from_seed(zconf.seed);
  649. } else {
  650. zconf.aes = aesrand_init_from_random();
  651. }
  652. // Set up sharding
  653. zconf.shard_num = 0;
  654. zconf.total_shards = 1;
  655. if ((args.shard_given || args.shards_given) && !args.seed_given) {
  656. log_fatal("zmap", "Need to specify seed if sharding a scan");
  657. }
  658. if (args.shard_given ^ args.shards_given) {
  659. log_fatal("zmap",
  660. "Need to specify both shard number and total number of shards");
  661. }
  662. if (args.shard_given) {
  663. enforce_range("shard", args.shard_arg, 0, 254);
  664. }
  665. if (args.shards_given) {
  666. enforce_range("shards", args.shards_arg, 1, 254);
  667. }
  668. SET_IF_GIVEN(zconf.shard_num, shard);
  669. SET_IF_GIVEN(zconf.total_shards, shards);
  670. if (zconf.shard_num >= zconf.total_shards) {
  671. log_fatal("zmap", "With %hhu total shards, shard number (%hhu)"
  672. " must be in range [0, %hhu)", zconf.total_shards,
  673. zconf.shard_num, zconf.total_shards);
  674. }
  675. if (args.bandwidth_given) {
  676. // Supported: G,g=*1000000000; M,m=*1000000 K,k=*1000 bits per second
  677. zconf.bandwidth = atoi(args.bandwidth_arg);
  678. char *suffix = args.bandwidth_arg;
  679. while (*suffix >= '0' && *suffix <= '9') {
  680. suffix++;
  681. }
  682. if (*suffix) {
  683. switch (*suffix) {
  684. case 'G': case 'g':
  685. zconf.bandwidth *= 1000000000;
  686. break;
  687. case 'M': case 'm':
  688. zconf.bandwidth *= 1000000;
  689. break;
  690. case 'K': case 'k':
  691. zconf.bandwidth *= 1000;
  692. break;
  693. default:
  694. fprintf(stderr, "%s: unknown bandwidth suffix '%s' "
  695. "(supported suffixes are G, M and K)\n",
  696. CMDLINE_PARSER_PACKAGE, suffix);
  697. exit(EXIT_FAILURE);
  698. }
  699. }
  700. }
  701. if (args.max_targets_given) {
  702. errno = 0;
  703. char *end;
  704. double v = strtod(args.max_targets_arg, &end);
  705. if (end == args.max_targets_arg || errno != 0) {
  706. fprintf(stderr, "%s: can't convert max-targets to a number\n",
  707. CMDLINE_PARSER_PACKAGE);
  708. exit(EXIT_FAILURE);
  709. }
  710. if (end[0] == '%' && end[1] == '\0') {
  711. // treat as percentage
  712. v = v * ((unsigned long long int)1 << 32) / 100.;
  713. } else if (end[0] != '\0') {
  714. fprintf(stderr, "%s: extra characters after max-targets\n",
  715. CMDLINE_PARSER_PACKAGE);
  716. exit(EXIT_FAILURE);
  717. }
  718. if (v <= 0) {
  719. zconf.max_targets = 0;
  720. }
  721. else if (v >= ((unsigned long long int)1 << 32)) {
  722. zconf.max_targets = 0xFFFFFFFF;
  723. } else {
  724. zconf.max_targets = v;
  725. }
  726. }
  727. // blacklist
  728. if (blacklist_init(zconf.whitelist_filename, zconf.blacklist_filename,
  729. zconf.destination_cidrs, zconf.destination_cidrs_len,
  730. NULL, 0,
  731. zconf.ignore_invalid_hosts)) {
  732. log_fatal("zmap", "unable to initialize blacklist / whitelist");
  733. }
  734. // compute number of targets
  735. uint64_t allowed = blacklist_count_allowed();
  736. zconf.total_allowed = allowed;
  737. zconf.total_disallowed = blacklist_count_not_allowed();
  738. assert(allowed <= (1LL << 32));
  739. if (allowed == (1LL << 32)) {
  740. zsend.targets = 0xFFFFFFFF;
  741. } else {
  742. zsend.targets = allowed;
  743. }
  744. if (zsend.targets > zconf.max_targets) {
  745. zsend.targets = zconf.max_targets;
  746. }
  747. if (zsend.targets == 0) {
  748. log_fatal("zmap", "zero eligible addresses to scan");
  749. }
  750. #ifndef PFRING
  751. // Set the correct number of threads, default to num_cores - 1
  752. if (args.sender_threads_given) {
  753. zconf.senders = args.sender_threads_arg;
  754. } else {
  755. int num_cores = sysconf(_SC_NPROCESSORS_ONLN);
  756. zconf.senders = max_int(num_cores - 1, 1);
  757. if (!zconf.quiet || zconf.status_updates_file) {
  758. // If monitoring, save a core for the monitor thread
  759. zconf.senders = max_int(zconf.senders - 1, 1);
  760. }
  761. }
  762. if (2*zconf.senders >= zsend.targets) {
  763. log_warn("zmap", "too few targets relative to senders, dropping to one sender");
  764. zconf.senders = 1;
  765. }
  766. #else
  767. zconf.senders = args.sender_threads_arg;
  768. #endif
  769. // Figure out what cores to bind to
  770. if (args.cores_given) {
  771. char **core_list = NULL;
  772. int len = 0;
  773. split_string(args.cores_arg, &len, &core_list);
  774. zconf.pin_cores_len = (uint32_t) len;
  775. zconf.pin_cores = xcalloc(zconf.pin_cores_len,
  776. sizeof(uint32_t));
  777. for (uint32_t i = 0; i < zconf.pin_cores_len; ++i) {
  778. zconf.pin_cores[i] = atoi(core_list[i]);
  779. }
  780. } else {
  781. int num_cores = sysconf(_SC_NPROCESSORS_ONLN);
  782. zconf.pin_cores_len = (uint32_t) num_cores;
  783. zconf.pin_cores = xcalloc(zconf.pin_cores_len,
  784. sizeof(uint32_t));
  785. for (uint32_t i = 0; i < zconf.pin_cores_len; ++i) {
  786. zconf.pin_cores[i] = i;
  787. }
  788. }
  789. // PFRING
  790. #ifdef PFRING
  791. #define MAX_CARD_SLOTS 32768
  792. #define QUEUE_LEN 8192
  793. #define ZMAP_PF_BUFFER_SIZE 1536
  794. #define ZMAP_PF_ZC_CLUSTER_ID 9627
  795. uint32_t user_buffers = zconf.senders*256;
  796. uint32_t queue_buffers = zconf.senders*QUEUE_LEN;
  797. uint32_t card_buffers = 2*MAX_CARD_SLOTS;
  798. uint32_t total_buffers = user_buffers + queue_buffers + card_buffers + 2;
  799. uint32_t metadata_len = 0;
  800. uint32_t numa_node = 0; // TODO
  801. zconf.pf.cluster = pfring_zc_create_cluster(
  802. ZMAP_PF_ZC_CLUSTER_ID,
  803. ZMAP_PF_BUFFER_SIZE,
  804. metadata_len,
  805. total_buffers,
  806. numa_node,
  807. NULL);
  808. if (zconf.pf.cluster == NULL) {
  809. log_fatal("zmap", "Could not create zc cluster: %s", strerror(errno));
  810. }
  811. zconf.pf.buffers = xcalloc(user_buffers, sizeof(pfring_zc_pkt_buff *));
  812. for (uint32_t i = 0; i < user_buffers; ++i) {
  813. zconf.pf.buffers[i] = pfring_zc_get_packet_handle(zconf.pf.cluster);
  814. if (zconf.pf.buffers[i] == NULL) {
  815. log_fatal("zmap", "Could not get ZC packet handle");
  816. }
  817. }
  818. zconf.pf.send = pfring_zc_open_device(zconf.pf.cluster, zconf.iface,
  819. tx_only, 0);
  820. if (zconf.pf.send == NULL) {
  821. log_fatal("zmap", "Could not open device %s for TX. [%s]",
  822. zconf.iface, strerror(errno));
  823. }
  824. zconf.pf.recv = pfring_zc_open_device(zconf.pf.cluster, zconf.iface,
  825. rx_only, 0);
  826. if (zconf.pf.recv == NULL) {
  827. log_fatal("zmap", "Could not open device %s for RX. [%s]",
  828. zconf.iface, strerror(errno));
  829. }
  830. zconf.pf.queues = xcalloc(zconf.senders, sizeof(pfring_zc_queue *));
  831. for (uint32_t i = 0; i < zconf.senders; ++i) {
  832. zconf.pf.queues[i] = pfring_zc_create_queue(zconf.pf.cluster,
  833. QUEUE_LEN);
  834. if (zconf.pf.queues[i] == NULL) {
  835. log_fatal("zmap", "Could not create queue: %s",
  836. strerror(errno));
  837. }
  838. }
  839. zconf.pf.prefetches = pfring_zc_create_buffer_pool(zconf.pf.cluster, 8);
  840. if (zconf.pf.prefetches == NULL) {
  841. log_fatal("zmap", "Could not open prefetch pool: %s",
  842. strerror(errno));
  843. }
  844. #endif
  845. start_zmap();
  846. fclose(log_location);
  847. cmdline_parser_free(&args);
  848. free(params);
  849. return EXIT_SUCCESS;
  850. }