snifftest.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. /* snifftest.c
  2. *
  3. * Copyright (C) 2006-2024 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #include <wolfssl/wolfcrypt/types.h>
  26. #include <wolfssl/wolfcrypt/logging.h>
  27. #include <wolfssl/wolfcrypt/error-crypt.h>
  28. #include <wolfssl/version.h>
  29. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  30. #include <wolfssl/wolfcrypt/memory.h>
  31. #endif
  32. #ifdef THREADED_SNIFFTEST
  33. #include <pthread.h>
  34. #endif
  35. /* Build Options:
  36. * THREADED_SNIFFTEST: Enable threaded version of the sniffer test
  37. */
  38. /* For windows tests force sniffer build option on */
  39. #ifdef _WIN32
  40. #define WOLFSSL_SNIFFER
  41. #endif
  42. #ifndef WOLFSSL_SNIFFER
  43. #ifndef NO_MAIN_DRIVER
  44. /* blank build */
  45. #include <stdio.h>
  46. #include <stdlib.h>
  47. int main(void)
  48. {
  49. printf("do ./configure --enable-sniffer to enable build support\n");
  50. return EXIT_SUCCESS;
  51. }
  52. #endif /* !NO_MAIN_DRIVER */
  53. #else
  54. /* do a full build */
  55. #ifdef _MSC_VER
  56. /* builds on *nix too, for scanf device and port */
  57. #define _CRT_SECURE_NO_WARNINGS
  58. #endif
  59. #include <pcap/pcap.h> /* pcap stuff */
  60. #include <stdio.h> /* printf */
  61. #include <stdlib.h> /* EXIT_SUCCESS */
  62. #include <string.h> /* strcmp */
  63. #include <signal.h> /* signal */
  64. #include <ctype.h> /* isprint */
  65. #include <wolfssl/sniffer.h>
  66. #ifndef _WIN32
  67. #include <sys/socket.h> /* AF_INET */
  68. #include <arpa/inet.h>
  69. #include <netinet/in.h>
  70. #endif
  71. typedef unsigned char byte;
  72. enum {
  73. ETHER_IF_FRAME_LEN = 14, /* ethernet interface frame length */
  74. NULL_IF_FRAME_LEN = 4, /* no link interface frame length */
  75. };
  76. /* A TLS record can be 16k and change. The chain is broken up into 2K chunks.
  77. * This covers the TLS record, plus a chunk for TCP/IP headers. */
  78. #ifndef CHAIN_INPUT_CHUNK_SIZE
  79. #define CHAIN_INPUT_CHUNK_SIZE 2048
  80. #elif (CHAIN_INPUT_CHUNK_SIZE < 256)
  81. #undef CHAIN_INPUT_CHUNK_SIZE
  82. #define CHAIN_INPUT_CHUNK_SIZE 256
  83. #elif (CHAIN_INPUT_CHUNK_SIZE > 16384)
  84. #undef CHAIN_INPUT_CHUNK_SIZE
  85. #define CHAIN_INPUT_CHUNK_SIZE 16384
  86. #endif
  87. #define CHAIN_INPUT_COUNT ((16384 / CHAIN_INPUT_CHUNK_SIZE) + 1)
  88. #ifndef STORE_DATA_BLOCK_SZ
  89. #define STORE_DATA_BLOCK_SZ 1024
  90. #endif
  91. #if defined(HAVE_ECC) && !defined(NO_ECC_SECP) && (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES))
  92. #define DEFAULT_SERVER_EPH_KEY_ECC "../../certs/statickeys/ecc-secp256r1.pem"
  93. #else
  94. #define DEFAULT_SERVER_EPH_KEY_ECC ""
  95. #endif
  96. #ifndef NO_DH
  97. #define DEFAULT_SERVER_EPH_KEY_DH "../../certs/statickeys/dh-ffdhe2048.pem"
  98. #else
  99. #define DEFAULT_SERVER_EPH_KEY_DH ""
  100. #endif
  101. #ifdef HAVE_CURVE25519
  102. #define DEFAULT_SERVER_EPH_KEY_X25519 "../../certs/statickeys/x25519.pem"
  103. #else
  104. #define DEFAULT_SERVER_EPH_KEY_X25519 ""
  105. #endif
  106. #ifndef DEFAULT_SERVER_EPH_KEY
  107. #define DEFAULT_SERVER_EPH_KEY \
  108. DEFAULT_SERVER_EPH_KEY_ECC "," \
  109. DEFAULT_SERVER_EPH_KEY_DH "," \
  110. DEFAULT_SERVER_EPH_KEY_X25519
  111. #endif
  112. #define DEFAULT_SERVER_KEY_RSA "../../certs/server-key.pem"
  113. #define DEFAULT_SERVER_KEY_ECC "../../certs/ecc-key.pem"
  114. #ifndef DEFAULT_SERVER_KEY
  115. #ifndef NO_RSA
  116. #define DEFAULT_SERVER_KEY DEFAULT_SERVER_KEY_RSA
  117. #elif defined(HAVE_ECC)
  118. #define DEFAULT_SERVER_KEY DEFAULT_SERVER_KEY_ECC
  119. #endif
  120. #endif
  121. #define DEFAULT_SERVER_IP "127.0.0.1"
  122. #define DEFAULT_SERVER_PORT (443)
  123. #ifdef WOLFSSL_SNIFFER_WATCH
  124. static const byte rsaHash[] = {
  125. 0x3d, 0x4a, 0x60, 0xfc, 0xbf, 0xe5, 0x4d, 0x3e,
  126. 0x85, 0x62, 0xf2, 0xfc, 0xdb, 0x0d, 0x51, 0xdd,
  127. 0xcd, 0xc2, 0x53, 0x81, 0x1a, 0x67, 0x31, 0xa0,
  128. 0x7f, 0xd2, 0x11, 0x74, 0xbf, 0xea, 0xc9, 0xc5
  129. };
  130. static const byte eccHash[] = {
  131. 0x9e, 0x45, 0xb6, 0xf8, 0xc6, 0x5d, 0x60, 0x90,
  132. 0x40, 0x8f, 0xd2, 0x0e, 0xb1, 0x59, 0xe7, 0xbd,
  133. 0xb0, 0x9b, 0x3c, 0x7a, 0x3a, 0xbe, 0x13, 0x52,
  134. 0x07, 0x4f, 0x1a, 0x64, 0x45, 0xe0, 0x13, 0x34
  135. };
  136. #endif
  137. static pcap_t* pcap = NULL;
  138. static pcap_if_t* alldevs = NULL;
  139. static struct bpf_program pcap_fp;
  140. static void FreeAll(void)
  141. {
  142. if (pcap) {
  143. pcap_freecode(&pcap_fp);
  144. pcap_close(pcap);
  145. }
  146. if (alldevs)
  147. pcap_freealldevs(alldevs);
  148. #ifndef _WIN32
  149. ssl_FreeSniffer();
  150. #endif
  151. }
  152. #ifdef WOLFSSL_SNIFFER_STATS
  153. static void DumpStats(void)
  154. {
  155. SSLStats sslStats;
  156. ssl_ReadStatistics(&sslStats);
  157. printf("SSL Stats (sslStandardConns):%lu\n",
  158. sslStats.sslStandardConns);
  159. printf("SSL Stats (sslClientAuthConns):%lu\n",
  160. sslStats.sslClientAuthConns);
  161. printf("SSL Stats (sslResumedConns):%lu\n",
  162. sslStats.sslResumedConns);
  163. printf("SSL Stats (sslEphemeralMisses):%lu\n",
  164. sslStats.sslEphemeralMisses);
  165. printf("SSL Stats (sslResumptionInserts):%lu\n",
  166. sslStats.sslResumptionInserts);
  167. printf("SSL Stats (sslResumeMisses):%lu\n",
  168. sslStats.sslResumeMisses);
  169. printf("SSL Stats (sslCiphersUnsupported):%lu\n",
  170. sslStats.sslCiphersUnsupported);
  171. printf("SSL Stats (sslKeysUnmatched):%lu\n",
  172. sslStats.sslKeysUnmatched);
  173. printf("SSL Stats (sslKeyFails):%lu\n",
  174. sslStats.sslKeyFails);
  175. printf("SSL Stats (sslDecodeFails):%lu\n",
  176. sslStats.sslDecodeFails);
  177. printf("SSL Stats (sslAlerts):%lu\n",
  178. sslStats.sslAlerts);
  179. printf("SSL Stats (sslDecryptedBytes):%lu\n",
  180. sslStats.sslDecryptedBytes);
  181. printf("SSL Stats (sslEncryptedBytes):%lu\n",
  182. sslStats.sslEncryptedBytes);
  183. printf("SSL Stats (sslEncryptedPackets):%lu\n",
  184. sslStats.sslEncryptedPackets);
  185. printf("SSL Stats (sslDecryptedPackets):%lu\n",
  186. sslStats.sslDecryptedPackets);
  187. printf("SSL Stats (sslKeyMatches):%lu\n",
  188. sslStats.sslKeyMatches);
  189. printf("SSL Stats (sslEncryptedConns):%lu\n",
  190. sslStats.sslEncryptedConns);
  191. }
  192. #endif /* WOLFSSL_SNIFFER_STATS */
  193. static void sig_handler(const int sig)
  194. {
  195. printf("SIGINT handled = %d.\n", sig);
  196. FreeAll();
  197. #ifdef WOLFSSL_SNIFFER_STATS
  198. DumpStats();
  199. #endif
  200. if (sig)
  201. exit(EXIT_SUCCESS);
  202. }
  203. static void err_sys(const char* msg)
  204. {
  205. fprintf(stderr, "%s\n", msg);
  206. if (msg)
  207. exit(EXIT_FAILURE);
  208. }
  209. #ifdef _WIN32
  210. #define SNPRINTF _snprintf
  211. #else
  212. #define SNPRINTF snprintf
  213. #endif
  214. static char* iptos(const struct in_addr* addr)
  215. {
  216. static char output[32];
  217. byte *p = (byte*)&addr->s_addr;
  218. snprintf(output, sizeof(output), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  219. return output;
  220. }
  221. static const char* ip6tos(const struct in6_addr* addr)
  222. {
  223. static char output[42];
  224. return inet_ntop(AF_INET6, addr, output, 42);
  225. }
  226. #if defined(WOLFSSL_SNIFFER_STORE_DATA_CB) || defined(WOLFSSL_SNIFFER_CHAIN_INPUT)
  227. static inline unsigned int min(unsigned int a, unsigned int b)
  228. {
  229. return a > b ? b : a;
  230. }
  231. #endif
  232. #ifdef WOLFSSL_SNIFFER_WATCH
  233. static int myWatchCb(void* vSniffer,
  234. const unsigned char* certHash, unsigned int certHashSz,
  235. const unsigned char* certChain, unsigned int certChainSz,
  236. void* ctx, char* error)
  237. {
  238. const char* certName = NULL;
  239. (void)certChain;
  240. (void)certChainSz;
  241. (void)ctx;
  242. if (certHashSz == sizeof(rsaHash) &&
  243. XMEMCMP(certHash, rsaHash, certHashSz) == 0) {
  244. certName = DEFAULT_SERVER_KEY_RSA;
  245. }
  246. if (certHashSz == sizeof(eccHash) &&
  247. XMEMCMP(certHash, eccHash, certHashSz) == 0) {
  248. certName = DEFAULT_SERVER_KEY_ECC;
  249. }
  250. if (certName == NULL) {
  251. /* don't return error if key is not loaded */
  252. printf("Warning: No matching key found for cert hash\n");
  253. return 0;
  254. }
  255. return ssl_SetWatchKey_file(vSniffer, certName, FILETYPE_PEM, NULL, error);
  256. }
  257. #endif /* WOLFSSL_SNIFFER_WATCH */
  258. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  259. static int myStoreDataCb(const unsigned char* decryptBuf,
  260. unsigned int decryptBufSz, unsigned int decryptBufOffset, void* ctx)
  261. {
  262. byte** data = (byte**)ctx;
  263. unsigned int qty;
  264. if (data == NULL)
  265. return -1;
  266. if (decryptBufSz < decryptBufOffset)
  267. return -1;
  268. qty = min(decryptBufSz - decryptBufOffset, STORE_DATA_BLOCK_SZ);
  269. if (*data == NULL) {
  270. byte* tmpData;
  271. tmpData = (byte*)XREALLOC(*data, decryptBufSz + 1,
  272. NULL, DYNAMIC_TYPE_TMP_BUFFER);
  273. if (tmpData == NULL) {
  274. XFREE(*data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  275. *data = NULL;
  276. return -1;
  277. }
  278. *data = tmpData;
  279. }
  280. XMEMCPY(*data + decryptBufOffset, decryptBuf + decryptBufOffset, qty);
  281. return qty;
  282. }
  283. #endif /* WOLFSSL_SNIFFER_STORE_DATA_CB */
  284. /* try and load as both static ephemeral and private key */
  285. /* only fail if no key is loaded */
  286. /* Allow comma separated list of files */
  287. static int load_key(const char* name, const char* server, int port,
  288. const char* keyFiles, const char* passwd, char* err)
  289. {
  290. int ret = -1;
  291. int loadCount = 0;
  292. char *keyFile, *ptr = NULL;
  293. keyFile = XSTRTOK((char*)keyFiles, ",", &ptr);
  294. while (keyFile != NULL) {
  295. #ifdef WOLFSSL_STATIC_EPHEMERAL
  296. #ifdef HAVE_SNI
  297. ret = ssl_SetNamedEphemeralKey(name, server, port, keyFile,
  298. FILETYPE_PEM, passwd, err);
  299. #else
  300. ret = ssl_SetEphemeralKey(server, port, keyFile,
  301. FILETYPE_PEM, passwd, err);
  302. #endif
  303. if (ret == 0)
  304. loadCount++;
  305. #endif
  306. #ifdef HAVE_SNI
  307. ret = ssl_SetNamedPrivateKey(name, server, port, keyFile,
  308. FILETYPE_PEM, passwd, err);
  309. #else
  310. ret = ssl_SetPrivateKey(server, port, keyFile,
  311. FILETYPE_PEM, passwd, err);
  312. #endif
  313. if (ret == 0)
  314. loadCount++;
  315. if (loadCount == 0) {
  316. printf("Failed loading private key %s: ret %d\n", keyFile, ret);
  317. printf("Please run directly from wolfSSL root dir\n");
  318. ret = -1;
  319. }
  320. else {
  321. ret = 0;
  322. }
  323. keyFile = XSTRTOK(NULL, ",", &ptr);
  324. }
  325. (void)name;
  326. return ret;
  327. }
  328. static void TrimNewLine(char* str)
  329. {
  330. word32 strSz = 0;
  331. if (str)
  332. strSz = (word32)XSTRLEN(str);
  333. if (strSz > 0 && (str[strSz-1] == '\n' || str[strSz-1] == '\r'))
  334. str[strSz-1] = '\0';
  335. }
  336. static void show_appinfo(void)
  337. {
  338. printf("snifftest %s\n", LIBWOLFSSL_VERSION_STRING);
  339. /* list enabled sniffer features */
  340. printf("sniffer features: "
  341. #ifdef WOLFSSL_SNIFFER_STATS
  342. "stats, "
  343. #endif
  344. #ifdef WOLFSSL_SNIFFER_WATCH
  345. "watch, "
  346. #endif
  347. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  348. "store_data_cb "
  349. #endif
  350. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  351. "chain_input "
  352. #endif
  353. #ifdef WOLFSSL_SNIFFER_KEY_CALLBACK
  354. "key_callback "
  355. #endif
  356. #ifdef DEBUG_SNIFFER
  357. "debug "
  358. #endif
  359. #ifdef WOLFSSL_TLS13
  360. "tls_v13 "
  361. #endif
  362. #ifndef WOLFSSL_NO_TLS12
  363. "tls_v12 "
  364. #endif
  365. #ifdef HAVE_SESSION_TICKET
  366. "session_ticket "
  367. #endif
  368. #ifdef WOLFSSL_STATIC_EPHEMERAL
  369. "static_ephemeral "
  370. #endif
  371. #ifdef WOLFSSL_ENCRYPTED_KEYS
  372. "encrypted_keys "
  373. #endif
  374. #ifdef HAVE_SNI
  375. "sni "
  376. #endif
  377. #ifdef HAVE_EXTENDED_MASTER
  378. "extended_master "
  379. #endif
  380. #ifdef HAVE_MAX_FRAGMENT
  381. "max fragment "
  382. #endif
  383. #ifdef WOLFSSL_ASYNC_CRYPT
  384. "async_crypt "
  385. #endif
  386. #ifndef NO_RSA
  387. "rsa "
  388. #endif
  389. #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
  390. "dh "
  391. #endif
  392. #ifdef HAVE_ECC
  393. "ecc "
  394. #endif
  395. #ifdef HAVE_CURVE448
  396. "x448 "
  397. #endif
  398. #ifdef HAVE_CURVE22519
  399. "x22519 "
  400. #endif
  401. #ifdef WOLFSSL_STATIC_RSA
  402. "rsa_static "
  403. #endif
  404. #ifdef WOLFSSL_STATIC_DH
  405. "dh_static "
  406. #endif
  407. #ifdef WOLFSSL_SNIFFER_KEYLOGFILE
  408. "ssl_keylog_file "
  409. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  410. "\n\n"
  411. );
  412. }
  413. typedef struct SnifferPacket {
  414. byte* packet;
  415. int length;
  416. int lastRet;
  417. int packetNumber;
  418. #ifdef THREADED_SNIFFTEST
  419. struct SnifferPacket* next;
  420. struct SnifferPacket* prev;
  421. int placeholder;
  422. #endif
  423. } SnifferPacket;
  424. #ifdef WOLFSSL_ASYNC_CRYPT
  425. static THREAD_LS_T SnifferPacket asyncQueue[WOLF_ASYNC_MAX_PENDING];
  426. /* returns index to queue */
  427. static int SnifferAsyncQueueAdd(int lastRet, void* chain, int chainSz,
  428. int isChain, int packetNumber)
  429. {
  430. int ret, i, length;
  431. byte* packet;
  432. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  433. if (isChain) {
  434. struct iovec* vchain = (struct iovec*)chain;
  435. length = 0;
  436. for (i = 0; i < chainSz; i++)
  437. length += vchain[i].iov_len;
  438. packet = (byte*)vchain[0].iov_base;
  439. }
  440. else
  441. #endif
  442. {
  443. packet = (byte*)chain;
  444. length = chainSz;
  445. }
  446. /* find first free idx */
  447. ret = MEMORY_E;
  448. for (i=0; i<WOLF_ASYNC_MAX_PENDING; i++) {
  449. if (asyncQueue[i].packet == NULL) {
  450. if (ret == MEMORY_E) {
  451. ret = i;
  452. break;
  453. }
  454. }
  455. }
  456. if (ret != MEMORY_E) {
  457. asyncQueue[ret].packet = (byte*)XMALLOC(length, NULL,
  458. DYNAMIC_TYPE_TMP_BUFFER);
  459. if (asyncQueue[ret].packet == NULL) {
  460. return MEMORY_E;
  461. }
  462. XMEMCPY(asyncQueue[ret].packet, packet, length);
  463. asyncQueue[ret].length = length;
  464. asyncQueue[ret].lastRet = lastRet;
  465. asyncQueue[ret].packetNumber = packetNumber;
  466. }
  467. (void)isChain;
  468. return ret;
  469. }
  470. static int SnifferAsyncPollQueue(byte** data, char* err, SSLInfo* sslInfo,
  471. int* queueSz)
  472. {
  473. int ret = 0, i;
  474. WOLF_EVENT* events[WOLF_ASYNC_MAX_PENDING];
  475. int eventCount = 0;
  476. /* try to process existing items in queue */
  477. for (i=0; i<WOLF_ASYNC_MAX_PENDING; i++) {
  478. if (asyncQueue[i].packet != NULL) {
  479. (*queueSz)++;
  480. /* do poll for events on hardware */
  481. ret = ssl_PollSniffer(events, WOLF_ASYNC_MAX_PENDING,
  482. WOLF_POLL_FLAG_CHECK_HW, &eventCount);
  483. if (ret == 0) {
  484. /* attempt to reprocess pending packet */
  485. #ifdef DEBUG_SNIFFER
  486. printf("Packet Number: %d (retry)\n", asyncQueue[i].packetNumber);
  487. #endif
  488. ret = ssl_DecodePacketAsync(asyncQueue[i].packet,
  489. asyncQueue[i].length, 0, data, err, sslInfo, NULL);
  490. asyncQueue[i].lastRet = ret;
  491. if (ret != WC_PENDING_E) {
  492. if (ret < 0) {
  493. printf("ssl_Decode ret = %d, %s on packet number %d\n",
  494. ret, err, asyncQueue[i].packetNumber);
  495. }
  496. /* done, so free and break to process below */
  497. XFREE(asyncQueue[i].packet, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  498. asyncQueue[i].packet = NULL;
  499. if (ret != 0) {
  500. /* decrypted some data or found error, so return */
  501. break;
  502. }
  503. }
  504. }
  505. }
  506. }
  507. if (ret == WC_PENDING_E) {
  508. ret = 0; /* nothing new */
  509. }
  510. return ret;
  511. }
  512. #endif /* WOLFSSL_ASYNC_CRYPT */
  513. #ifdef THREADED_SNIFFTEST
  514. typedef struct {
  515. volatile int lockCount;
  516. pthread_mutex_t mutex;
  517. pthread_cond_t cond;
  518. } wm_Sem;
  519. /* Posix style semaphore */
  520. static int wm_SemInit(wm_Sem *s)
  521. {
  522. s->lockCount = 0;
  523. pthread_mutex_init(&s->mutex, NULL);
  524. pthread_cond_init(&s->cond, NULL);
  525. return 0;
  526. }
  527. static int wm_SemFree(wm_Sem *s)
  528. {
  529. pthread_mutex_destroy(&s->mutex);
  530. pthread_cond_destroy(&s->cond);
  531. return 0;
  532. }
  533. static int wm_SemLock(wm_Sem *s)
  534. {
  535. pthread_mutex_lock(&s->mutex);
  536. while (s->lockCount > 0)
  537. pthread_cond_wait(&s->cond, &s->mutex);
  538. s->lockCount++;
  539. pthread_mutex_unlock(&s->mutex);
  540. return 0;
  541. }
  542. static int wm_SemUnlock(wm_Sem *s)
  543. {
  544. pthread_mutex_lock(&s->mutex);
  545. s->lockCount--;
  546. pthread_cond_signal(&s->cond);
  547. pthread_mutex_unlock(&s->mutex);
  548. return 0;
  549. }
  550. typedef struct SnifferWorker {
  551. SnifferPacket *head; /* head for doubly-linked list of sniffer packets */
  552. SnifferPacket *tail; /* tail for doubly-linked list of sniffer packets */
  553. wm_Sem sem;
  554. pthread_t tid;
  555. char *server;
  556. char *keyFilesSrc;
  557. char *passwd;
  558. int port;
  559. int hadBadPacket; /* track if sniffer worker saw bad packet */
  560. int unused;
  561. int id;
  562. int shutdown;
  563. } SnifferWorker;
  564. static int ssl_Init_SnifferWorker(SnifferWorker* worker, int port,
  565. const char* server, const char* keyFilesSrc, const char* passwd, int id)
  566. {
  567. wm_SemInit(&worker->sem);
  568. worker->server = (char*)server;
  569. worker->keyFilesSrc = (char*)keyFilesSrc;
  570. worker->passwd = (char*)passwd;
  571. worker->port = port;
  572. worker->unused = 0;
  573. worker->shutdown = 0;
  574. worker ->id = id;
  575. worker->head = (SnifferPacket*)XMALLOC(sizeof(SnifferPacket), NULL,
  576. DYNAMIC_TYPE_TMP_BUFFER);
  577. if (worker->head == NULL) {
  578. return MEMORY_E;
  579. }
  580. XMEMSET(worker->head, 0, sizeof(SnifferPacket));
  581. worker->tail = worker->head;
  582. worker->head->packet = NULL;
  583. worker->head->next = NULL;
  584. worker->head->prev = NULL;
  585. worker->head->placeholder = 1;
  586. return 0;
  587. }
  588. static void ssl_Free_SnifferWorker(SnifferWorker* worker)
  589. {
  590. wm_SemFree(&worker->sem);
  591. XFREE(worker->head, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  592. worker->head = NULL;
  593. }
  594. static int SnifferWorkerPacketAdd(SnifferWorker* worker, int lastRet,
  595. byte* packet, int length, int packetNumber)
  596. {
  597. SnifferPacket* newEntry;
  598. newEntry = (SnifferPacket*)XMALLOC(sizeof(SnifferPacket), NULL,
  599. DYNAMIC_TYPE_TMP_BUFFER);
  600. if (newEntry == NULL) {
  601. return MEMORY_E;
  602. }
  603. XMEMSET(newEntry, 0, sizeof(SnifferPacket));
  604. newEntry->packet = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  605. if (newEntry->packet == NULL) {
  606. XFREE(newEntry, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  607. return MEMORY_E;
  608. }
  609. /* Set newEntry fields to input values */
  610. XMEMCPY(newEntry->packet, packet, length);
  611. newEntry->length = length;
  612. newEntry->lastRet = lastRet;
  613. newEntry->packetNumber = packetNumber;
  614. newEntry->placeholder = 0;
  615. /* Create worker head if null */
  616. if (worker->head == NULL) {
  617. worker->head = (SnifferPacket*)XMALLOC(sizeof(SnifferPacket), NULL,
  618. DYNAMIC_TYPE_TMP_BUFFER);
  619. XMEMSET(worker->head, 0, sizeof(SnifferPacket));
  620. worker->tail = worker->head;
  621. worker->head->packet = NULL;
  622. worker->head->next = NULL;
  623. worker->head->prev = NULL;
  624. worker->head->placeholder = 1;
  625. }
  626. if (worker->head->placeholder) {
  627. /* First packet added to be to SnifferWorker linked list,
  628. * set head and tail to the new packet */
  629. XFREE(worker->head, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  630. newEntry->next = NULL;
  631. newEntry->prev = NULL;
  632. worker->head = newEntry;
  633. worker->tail = newEntry;
  634. }
  635. else {
  636. /* Add packet to SnifferWorker linked list and move tail */
  637. newEntry->prev = worker->tail;
  638. newEntry->next = NULL;
  639. worker->tail->next = newEntry;
  640. worker->tail = newEntry;
  641. }
  642. return 0;
  643. }
  644. #endif /* THREADED_SNIFFTEST */
  645. static int DecodePacket(byte* packet, int length, int packetNumber, char err[])
  646. {
  647. int ret, j;
  648. int hadBadPacket = 0;
  649. int isChain = 0;
  650. int chainSz;
  651. void* chain;
  652. byte* data = NULL; /* pointer to decrypted data */
  653. SSLInfo sslInfo;
  654. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  655. struct iovec chains[CHAIN_INPUT_COUNT];
  656. unsigned int remainder;
  657. j = 0;
  658. chainSz = 0;
  659. isChain = 1;
  660. remainder = length;
  661. do {
  662. unsigned int chunkSz = min(remainder, CHAIN_INPUT_CHUNK_SIZE);
  663. chains[chainSz].iov_base = (void*)(packet + j);
  664. chains[chainSz].iov_len = chunkSz;
  665. j += chunkSz;
  666. remainder -= chunkSz;
  667. chainSz++;
  668. } while (j < (int)length);
  669. chain = (void*)chains;
  670. #else
  671. chain = (void*)packet;
  672. chainSz = length;
  673. #endif
  674. #if defined(DEBUG_SNIFFER)
  675. printf("Packet Number: %d\n", packetNumber);
  676. #endif
  677. /* decode packet */
  678. #ifdef WOLFSSL_ASYNC_CRYPT
  679. /* For async call the original API again with same data,
  680. * or call with different sessions for multiple concurrent
  681. * stream processing */
  682. ret = ssl_DecodePacketAsync(chain, chainSz, isChain, &data, err,
  683. &sslInfo, NULL);
  684. /* WC_PENDING_E: Hardware is processing or stream is blocked
  685. * (waiting on WC_PENDING_E) */
  686. if (ret == WC_PENDING_E) {
  687. /* add to queue, for later processing */
  688. #ifdef DEBUG_SNIFFER
  689. printf("Steam is pending, queue packet %d\n", packetNumber);
  690. #endif
  691. ret = SnifferAsyncQueueAdd(ret, chain, chainSz, isChain,
  692. packetNumber);
  693. if (ret >= 0) {
  694. ret = 0; /* mark event just added */
  695. }
  696. }
  697. #elif defined(WOLFSSL_SNIFFER_CHAIN_INPUT) && \
  698. defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  699. ret = ssl_DecodePacketWithChainSessionInfoStoreData(chain, chainSz,
  700. &data, &sslInfo, err);
  701. #elif defined(WOLFSSL_SNIFFER_CHAIN_INPUT)
  702. (void)sslInfo;
  703. ret = ssl_DecodePacketWithChain(chain, chainSz, &data, err);
  704. #elif defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  705. ret = ssl_DecodePacketWithSessionInfoStoreData(packet,
  706. length, &data, &sslInfo, err);
  707. #else
  708. ret = ssl_DecodePacketWithSessionInfo(packet, length, &data,
  709. &sslInfo, err);
  710. #endif
  711. if (ret < 0) {
  712. printf("ssl_Decode ret = %d, %s on packet number %d\n", ret, err,
  713. packetNumber);
  714. hadBadPacket = 1;
  715. }
  716. if (data != NULL && ret > 0) {
  717. /* Convert non-printable data to periods. */
  718. for (j = 0; j < ret; j++) {
  719. if (isprint(data[j]) || isspace(data[j])) continue;
  720. data[j] = '.';
  721. }
  722. data[ret] = 0;
  723. printf("SSL App Data(%d:%d):%s\n", packetNumber, ret, data);
  724. ssl_FreeZeroDecodeBuffer(&data, ret, err);
  725. }
  726. (void)isChain;
  727. (void)chain;
  728. (void)chainSz;
  729. return hadBadPacket;
  730. }
  731. #ifdef THREADED_SNIFFTEST
  732. static void* snifferWorker(void* arg)
  733. {
  734. SnifferWorker* worker = (SnifferWorker*)arg;
  735. char err[PCAP_ERRBUF_SIZE];
  736. ssl_InitSniffer_ex2(worker->id);
  737. ssl_Trace("./tracefile.txt", err);
  738. ssl_EnableRecovery(1, -1, err);
  739. #ifdef WOLFSSL_SNIFFER_WATCH
  740. ssl_SetWatchKeyCallback(myWatchCb, err);
  741. #endif
  742. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  743. ssl_SetStoreDataCallback(myStoreDataCb);
  744. #endif
  745. load_key(NULL, worker->server, worker->port, worker->keyFilesSrc,
  746. worker->passwd, err);
  747. /* continue processing the workers packets and keep expecting them
  748. * until the shutdown flag is set */
  749. while (!worker->shutdown) {
  750. while (worker->head) {
  751. int ret = 0;
  752. byte* packet;
  753. int length;
  754. int packetNumber;
  755. #ifdef WOLFSSL_ASYNC_CRYPT
  756. SSLInfo sslInfo;
  757. byte* data;
  758. int queueSz = 0;
  759. /* poll hardware and attempt to process items in queue. If
  760. * returns > 0 then data pointer has decrypted something */
  761. SnifferAsyncPollQueue(&data, err, &sslInfo, &queueSz);
  762. if (queueSz >= WOLF_ASYNC_MAX_PENDING) {
  763. /* queue full, poll again */
  764. continue;
  765. }
  766. #endif
  767. /* Shutdown worker if it was not utilized */
  768. if (worker->unused) {
  769. XFREE(worker->head, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  770. worker->head = NULL;
  771. break;
  772. }
  773. /* get lock */
  774. wm_SemLock(&worker->sem);
  775. /* get packet for current worker head */
  776. packet = worker->head->packet;
  777. length = worker->head->length;
  778. packetNumber = worker->head->packetNumber;
  779. wm_SemUnlock(&worker->sem);
  780. if (packet == NULL) {
  781. continue;
  782. }
  783. /* Decode Packet, ret value will indicate whether a
  784. * bad packet was encountered */
  785. ret = DecodePacket(packet, length, packetNumber, err);
  786. if (ret) {
  787. worker->hadBadPacket = 1;
  788. }
  789. /* get lock */
  790. wm_SemLock(&worker->sem);
  791. XFREE(worker->head->packet, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  792. worker->head->packet = NULL;
  793. if (worker->head->next) {
  794. /* Move head and free */
  795. worker->head = worker->head->next;
  796. XFREE(worker->head->prev, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  797. worker->head->prev = NULL;
  798. }
  799. else {
  800. /* No other packets in list. Keep looping until more packets
  801. * arrive or worker is shutdown. */
  802. XFREE(worker->head, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  803. worker->head = NULL;
  804. }
  805. wm_SemUnlock(&worker->sem);
  806. } /* while (worker->head) */
  807. if (worker->unused) {
  808. break;
  809. }
  810. } /* while (worker->head) */
  811. /* Thread cleanup */
  812. ssl_FreeSniffer();
  813. #if defined(HAVE_ECC) && defined(FP_ECC)
  814. wc_ecc_fp_free();
  815. #endif
  816. return NULL;
  817. }
  818. #endif /* THREADED_SNIFFTEST */
  819. int main(int argc, char** argv)
  820. {
  821. int ret = 0;
  822. int hadBadPacket = 0;
  823. int inum = 0;
  824. int saveFile = 0;
  825. int i = 0, defDev = 0;
  826. int packetNumber = 0;
  827. int frame = ETHER_IF_FRAME_LEN;
  828. char err[PCAP_ERRBUF_SIZE];
  829. char filter[32];
  830. const char *keyFilesSrc = NULL;
  831. #ifdef WOLFSSL_SNIFFER_KEYLOGFILE
  832. const char *sslKeyLogFile = NULL;
  833. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  834. char keyFilesBuf[MAX_FILENAME_SZ];
  835. char keyFilesUser[MAX_FILENAME_SZ];
  836. const char *server = DEFAULT_SERVER_IP;
  837. int port = DEFAULT_SERVER_PORT;
  838. const char *sniName = NULL;
  839. const char *passwd = NULL;
  840. pcap_if_t *d;
  841. pcap_addr_t *a;
  842. #ifdef THREADED_SNIFFTEST
  843. int workerThreadCount;
  844. #ifdef HAVE_SESSION_TICKET
  845. /* Multiple threads on resume not yet supported */
  846. workerThreadCount = 1;
  847. #else
  848. workerThreadCount = 5;
  849. #endif
  850. #endif
  851. show_appinfo();
  852. signal(SIGINT, sig_handler);
  853. #ifndef THREADED_SNIFFTEST
  854. #ifndef _WIN32
  855. ssl_InitSniffer(); /* dll load on Windows */
  856. #endif
  857. ssl_Trace("./tracefile.txt", err);
  858. ssl_EnableRecovery(1, -1, err);
  859. #ifdef WOLFSSL_SNIFFER_WATCH
  860. ssl_SetWatchKeyCallback(myWatchCb, err);
  861. #endif
  862. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  863. ssl_SetStoreDataCallback(myStoreDataCb);
  864. #endif
  865. #endif
  866. if (argc == 1) {
  867. char cmdLineArg[128];
  868. /* normal case, user chooses device and port */
  869. if (pcap_findalldevs(&alldevs, err) == -1)
  870. err_sys("Error in pcap_findalldevs");
  871. for (d = alldevs; d; d=d->next) {
  872. printf("%d. %s", ++i, d->name);
  873. if (strcmp(d->name, "lo0") == 0) {
  874. defDev = i;
  875. }
  876. if (d->description)
  877. printf(" (%s)\n", d->description);
  878. else
  879. printf(" (No description available)\n");
  880. }
  881. if (i == 0)
  882. err_sys("No interfaces found! Make sure pcap or WinPcap is"
  883. " installed correctly and you have sufficient permissions");
  884. printf("Enter the interface number (1-%d) [default: %d]: ", i, defDev);
  885. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  886. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin))
  887. inum = XATOI(cmdLineArg);
  888. if (inum == 0)
  889. inum = defDev;
  890. else if (inum < 1 || inum > i)
  891. err_sys("Interface number out of range");
  892. /* Jump to the selected adapter */
  893. for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++);
  894. pcap = pcap_create(d->name, err);
  895. if (pcap == NULL) printf("pcap_create failed %s\n", err);
  896. /* print out addresses for selected interface */
  897. for (a = d->addresses; a; a = a->next) {
  898. if (a->addr->sa_family == AF_INET) {
  899. server =
  900. iptos(&((struct sockaddr_in *)a->addr)->sin_addr);
  901. printf("server = %s\n", server);
  902. }
  903. else if (a->addr->sa_family == AF_INET6) {
  904. server =
  905. ip6tos(&((struct sockaddr_in6 *)a->addr)->sin6_addr);
  906. printf("server = %s\n", server);
  907. }
  908. }
  909. if (server == NULL)
  910. err_sys("Unable to get device IPv4 or IPv6 address");
  911. ret = pcap_set_snaplen(pcap, 65536);
  912. if (ret != 0) printf("pcap_set_snaplen failed %s\n", pcap_geterr(pcap));
  913. ret = pcap_set_timeout(pcap, 1000);
  914. if (ret != 0) printf("pcap_set_timeout failed %s\n", pcap_geterr(pcap));
  915. ret = pcap_set_buffer_size(pcap, 1000000);
  916. if (ret != 0)
  917. printf("pcap_set_buffer_size failed %s\n", pcap_geterr(pcap));
  918. ret = pcap_set_promisc(pcap, 1);
  919. if (ret != 0) printf("pcap_set_promisc failed %s\n", pcap_geterr(pcap));
  920. ret = pcap_activate(pcap);
  921. if (ret != 0) printf("pcap_activate failed %s\n", pcap_geterr(pcap));
  922. printf("Enter the port to scan [default: 11111]: ");
  923. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  924. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  925. port = XATOI(cmdLineArg);
  926. }
  927. if (port <= 0)
  928. port = 11111;
  929. SNPRINTF(filter, sizeof(filter), "tcp and port %d", port);
  930. ret = pcap_compile(pcap, &pcap_fp, filter, 0, 0);
  931. if (ret != 0) printf("pcap_compile failed %s\n", pcap_geterr(pcap));
  932. ret = pcap_setfilter(pcap, &pcap_fp);
  933. if (ret != 0) printf("pcap_setfilter failed %s\n", pcap_geterr(pcap));
  934. /* optionally enter the private key to use */
  935. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(DEFAULT_SERVER_EPH_KEY)
  936. keyFilesSrc = DEFAULT_SERVER_EPH_KEY;
  937. #else
  938. keyFilesSrc = DEFAULT_SERVER_KEY;
  939. #endif
  940. printf("Enter the server key [default: %s]: ", keyFilesSrc);
  941. XMEMSET(keyFilesBuf, 0, sizeof(keyFilesBuf));
  942. XMEMSET(keyFilesUser, 0, sizeof(keyFilesUser));
  943. if (XFGETS(keyFilesUser, sizeof(keyFilesUser), stdin)) {
  944. TrimNewLine(keyFilesUser);
  945. if (XSTRLEN(keyFilesUser) > 0) {
  946. keyFilesSrc = keyFilesUser;
  947. }
  948. }
  949. XSTRNCPY(keyFilesBuf, keyFilesSrc, sizeof(keyFilesBuf));
  950. /* optionally enter a named key (SNI) */
  951. #if !defined(WOLFSSL_SNIFFER_WATCH) && defined(HAVE_SNI)
  952. printf("Enter alternate SNI [default: none]: ");
  953. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  954. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  955. TrimNewLine(cmdLineArg);
  956. if (XSTRLEN(cmdLineArg) > 0) {
  957. sniName = cmdLineArg;
  958. }
  959. }
  960. #endif /* !WOLFSSL_SNIFFER_WATCH && HAVE_SNI */
  961. /* get IPv4 or IPv6 addresses for selected interface */
  962. for (a = d->addresses; a; a = a->next) {
  963. server = NULL;
  964. if (a->addr->sa_family == AF_INET) {
  965. server =
  966. iptos(&((struct sockaddr_in *)a->addr)->sin_addr);
  967. }
  968. else if (a->addr->sa_family == AF_INET6) {
  969. server =
  970. ip6tos(&((struct sockaddr_in6 *)a->addr)->sin6_addr);
  971. }
  972. if (server) {
  973. XSTRNCPY(keyFilesBuf, keyFilesSrc, sizeof(keyFilesBuf));
  974. ret = load_key(sniName, server, port, keyFilesBuf, NULL, err);
  975. if (ret != 0) {
  976. exit(EXIT_FAILURE);
  977. }
  978. }
  979. }
  980. }
  981. else {
  982. char *pcapFile = NULL;
  983. for (i = 1; i < argc; i++) {
  984. if (strcmp(argv[i], "-pcap") == 0 && i + 1 < argc) {
  985. pcapFile = argv[++i];
  986. }
  987. else if (strcmp(argv[i], "-key") == 0 && i + 1 < argc) {
  988. keyFilesSrc = argv[++i];
  989. }
  990. else if (strcmp(argv[i], "-server") == 0 && i + 1 < argc) {
  991. server = argv[++i];
  992. }
  993. else if (strcmp(argv[i], "-port") == 0 && i + 1 < argc) {
  994. port = XATOI(argv[++i]);
  995. }
  996. else if (strcmp(argv[i], "-password") == 0 && i + 1 < argc) {
  997. passwd = argv[++i];
  998. }
  999. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  1000. else if (strcmp(argv[i], "-keylogfile") == 0 && i + 1 < argc) {
  1001. sslKeyLogFile = argv[++i];
  1002. }
  1003. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  1004. #if defined(THREADED_SNIFFTEST)
  1005. else if (strcmp(argv[i], "-threads") == 0 && i + 1 < argc) {
  1006. workerThreadCount = XATOI(argv[++i]);
  1007. }
  1008. #endif /* THREADED_SNIFFTEST */
  1009. else {
  1010. fprintf(stderr, "Invalid option or missing argument: %s\n", argv[i]);
  1011. fprintf(stderr, "Usage: %s -pcap pcap_arg -key key_arg"
  1012. " [-password password_arg] [-server server_arg] [-port port_arg]"
  1013. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  1014. " [-keylogfile keylogfile_arg]"
  1015. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  1016. #if defined(THREADED_SNIFFTEST)
  1017. " [-threads threads_arg]"
  1018. #endif /* THREADED_SNIFFTEST */
  1019. "\n", argv[0]);
  1020. exit(EXIT_FAILURE);
  1021. }
  1022. }
  1023. if (!pcapFile) {
  1024. fprintf(stderr, "Error: -pcap option is required.\n");
  1025. exit(EXIT_FAILURE);
  1026. }
  1027. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  1028. /* If we offer keylog support, then user must provide EITHER a pubkey
  1029. * OR a keylog file but NOT both */
  1030. if ((!keyFilesSrc && !sslKeyLogFile) || (keyFilesSrc && sslKeyLogFile)) {
  1031. fprintf(stderr, "Error: either -key OR -keylogfile option required but NOT both.\n");
  1032. exit(EXIT_FAILURE);
  1033. }
  1034. #else
  1035. if (!keyFilesSrc) {
  1036. fprintf(stderr, "Error: -key option is required.\n");
  1037. exit(EXIT_FAILURE);
  1038. }
  1039. #endif
  1040. saveFile = 1;
  1041. pcap = pcap_open_offline(pcapFile , err);
  1042. if (pcap == NULL) {
  1043. fprintf(stderr, "pcap_open_offline failed %s\n", err);
  1044. err_sys(err);
  1045. }
  1046. else {
  1047. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  1048. if (sslKeyLogFile != NULL) {
  1049. ret = ssl_LoadSecretsFromKeyLogFile(sslKeyLogFile, err);
  1050. if (ret != 0) {
  1051. fprintf(stderr, "ERROR=%d, unable to load secrets from keylog file\n",ret);
  1052. err_sys(err);
  1053. }
  1054. ret = ssl_CreateKeyLogSnifferServer(server, port, err);
  1055. if (ret != 0) {
  1056. fprintf(stderr, "ERROR=%d, unable to create keylog sniffer server\n",ret);
  1057. err_sys(err);
  1058. }
  1059. }
  1060. else
  1061. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  1062. {
  1063. ret = load_key(NULL, server, port, keyFilesSrc, passwd, err);
  1064. if (ret != 0) {
  1065. fprintf(stderr, "Failed to load key\n");
  1066. err_sys(err);
  1067. }
  1068. }
  1069. /* Only let through TCP/IP packets */
  1070. ret = pcap_compile(pcap, &pcap_fp, "(ip6 or ip) and tcp", 0, 0);
  1071. if (ret != 0) {
  1072. fprintf(stderr, "pcap_compile failed %s\n", pcap_geterr(pcap));
  1073. exit(EXIT_FAILURE);
  1074. }
  1075. ret = pcap_setfilter(pcap, &pcap_fp);
  1076. if (ret != 0) {
  1077. fprintf(stderr, "pcap_setfilter failed %s\n", pcap_geterr(pcap));
  1078. exit(EXIT_FAILURE);
  1079. }
  1080. }
  1081. }
  1082. if (ret != 0)
  1083. err_sys(err);
  1084. if (pcap_datalink(pcap) == DLT_NULL)
  1085. frame = NULL_IF_FRAME_LEN;
  1086. #ifdef THREADED_SNIFFTEST
  1087. SnifferWorker workers[workerThreadCount];
  1088. int used[workerThreadCount];
  1089. XMEMSET(used, 0, sizeof(used));
  1090. XMEMSET(&workers, 0, sizeof(workers));
  1091. for (i=0; i<workerThreadCount; i++) {
  1092. ssl_Init_SnifferWorker(&workers[i], port, server, keyFilesSrc,
  1093. passwd, i);
  1094. pthread_create(&workers[i].tid, NULL, snifferWorker, &workers[i]);
  1095. }
  1096. #endif
  1097. while (1) {
  1098. struct pcap_pkthdr header;
  1099. const unsigned char* packet = NULL;
  1100. byte* data = NULL; /* pointer to decrypted data */
  1101. #ifdef THREADED_SNIFFTEST
  1102. SnifferStreamInfo info;
  1103. uint8_t infoSum;
  1104. uint8_t* infoPtr;
  1105. int threadNum;
  1106. #endif
  1107. #if defined(WOLFSSL_ASYNC_CRYPT)
  1108. SSLInfo sslInfo;
  1109. int queueSz = 0;
  1110. XMEMSET(&sslInfo, 0, sizeof(sslInfo));
  1111. /* poll hardware and attempt to process items in queue. If returns > 0
  1112. * then data pointer has decrypted something */
  1113. SnifferAsyncPollQueue(&data, err, &sslInfo, &queueSz);
  1114. if (queueSz >= WOLF_ASYNC_MAX_PENDING) {
  1115. /* queue full, poll again */
  1116. continue;
  1117. }
  1118. #endif
  1119. ret = 0; /* reset status */
  1120. if (data == NULL) {
  1121. /* grab next pcap packet */
  1122. packetNumber++;
  1123. packet = pcap_next(pcap, &header);
  1124. }
  1125. if (packet) {
  1126. if (header.caplen > 40) { /* min ip(20) + min tcp(20) */
  1127. packet += frame;
  1128. header.caplen -= frame;
  1129. }
  1130. else {
  1131. /* packet doesn't contain minimum ip/tcp header */
  1132. continue;
  1133. }
  1134. #ifdef THREADED_SNIFFTEST
  1135. XMEMSET(&info, 0, sizeof(SnifferStreamInfo));
  1136. ret = ssl_DecodePacket_GetStream(&info, packet, header.caplen, err);
  1137. /* calculate SnifferStreamInfo checksum */
  1138. infoSum = 0;
  1139. infoPtr = (uint8_t*)&info;
  1140. for (i=0; i<(int)sizeof(SnifferStreamInfo); i++) {
  1141. infoSum += infoPtr[i];
  1142. }
  1143. /* determine thread to handle stream */
  1144. threadNum = infoSum % workerThreadCount;
  1145. used[threadNum] = 1;
  1146. #ifdef DEBUG_SNIFFER
  1147. printf("Sending packet %d to thread number %d\n", packetNumber,
  1148. threadNum);
  1149. #endif
  1150. /* get lock on thread mutex */
  1151. wm_SemLock(&workers[threadNum].sem);
  1152. /* add the packet to the worker's linked list */
  1153. if (SnifferWorkerPacketAdd(&workers[threadNum], ret, (byte*)packet,
  1154. header.caplen, packetNumber)) {
  1155. printf("Unable to add packet %d to worker", packetNumber);
  1156. break;
  1157. }
  1158. wm_SemUnlock(&workers[threadNum].sem);
  1159. #else
  1160. /* Decode Packet, ret value will indicate whether a
  1161. * bad packet was encountered */
  1162. hadBadPacket = DecodePacket((byte*)packet, header.caplen,
  1163. packetNumber,err);
  1164. #endif
  1165. }
  1166. /* check if we are done reading file */
  1167. if (packet == NULL && data == NULL && saveFile) {
  1168. #ifdef WOLFSSL_ASYNC_CRYPT
  1169. /* if items pending still then keep processing */
  1170. if (queueSz > 0)
  1171. continue;
  1172. #endif
  1173. break;
  1174. }
  1175. }
  1176. #ifdef THREADED_SNIFFTEST
  1177. for (i=0; i<workerThreadCount; i++) {
  1178. workers[i].shutdown = 1;
  1179. if (used[i] == 0)
  1180. workers[i].unused = 1;
  1181. pthread_join(workers[i].tid, NULL);
  1182. }
  1183. for (i=0; i<workerThreadCount; i++) {
  1184. if (workers[i].hadBadPacket) {
  1185. hadBadPacket = 1;
  1186. }
  1187. ssl_Free_SnifferWorker(&workers[i]);
  1188. }
  1189. #endif
  1190. FreeAll();
  1191. return hadBadPacket ? EXIT_FAILURE : EXIT_SUCCESS;
  1192. }
  1193. #endif /* full build */