snifftest.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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 (11111)
  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 const char *traceFile = "./tracefile.txt";
  141. static void FreeAll(void)
  142. {
  143. if (pcap) {
  144. pcap_freecode(&pcap_fp);
  145. pcap_close(pcap);
  146. }
  147. if (alldevs)
  148. pcap_freealldevs(alldevs);
  149. #ifndef _WIN32
  150. ssl_FreeSniffer();
  151. #endif
  152. }
  153. #ifdef WOLFSSL_SNIFFER_STATS
  154. static void DumpStats(void)
  155. {
  156. SSLStats sslStats;
  157. ssl_ReadStatistics(&sslStats);
  158. printf("SSL Stats (sslStandardConns):%lu\n",
  159. sslStats.sslStandardConns);
  160. printf("SSL Stats (sslClientAuthConns):%lu\n",
  161. sslStats.sslClientAuthConns);
  162. printf("SSL Stats (sslResumedConns):%lu\n",
  163. sslStats.sslResumedConns);
  164. printf("SSL Stats (sslEphemeralMisses):%lu\n",
  165. sslStats.sslEphemeralMisses);
  166. printf("SSL Stats (sslResumptionInserts):%lu\n",
  167. sslStats.sslResumptionInserts);
  168. printf("SSL Stats (sslResumeMisses):%lu\n",
  169. sslStats.sslResumeMisses);
  170. printf("SSL Stats (sslCiphersUnsupported):%lu\n",
  171. sslStats.sslCiphersUnsupported);
  172. printf("SSL Stats (sslKeysUnmatched):%lu\n",
  173. sslStats.sslKeysUnmatched);
  174. printf("SSL Stats (sslKeyFails):%lu\n",
  175. sslStats.sslKeyFails);
  176. printf("SSL Stats (sslDecodeFails):%lu\n",
  177. sslStats.sslDecodeFails);
  178. printf("SSL Stats (sslAlerts):%lu\n",
  179. sslStats.sslAlerts);
  180. printf("SSL Stats (sslDecryptedBytes):%lu\n",
  181. sslStats.sslDecryptedBytes);
  182. printf("SSL Stats (sslEncryptedBytes):%lu\n",
  183. sslStats.sslEncryptedBytes);
  184. printf("SSL Stats (sslEncryptedPackets):%lu\n",
  185. sslStats.sslEncryptedPackets);
  186. printf("SSL Stats (sslDecryptedPackets):%lu\n",
  187. sslStats.sslDecryptedPackets);
  188. printf("SSL Stats (sslKeyMatches):%lu\n",
  189. sslStats.sslKeyMatches);
  190. printf("SSL Stats (sslEncryptedConns):%lu\n",
  191. sslStats.sslEncryptedConns);
  192. }
  193. #endif /* WOLFSSL_SNIFFER_STATS */
  194. static void sig_handler(const int sig)
  195. {
  196. printf("SIGINT handled = %d.\n", sig);
  197. FreeAll();
  198. #ifdef WOLFSSL_SNIFFER_STATS
  199. DumpStats();
  200. #endif
  201. if (sig)
  202. exit(EXIT_SUCCESS);
  203. }
  204. static void err_sys(const char* msg)
  205. {
  206. fprintf(stderr, "%s\n", msg);
  207. if (msg)
  208. exit(EXIT_FAILURE);
  209. }
  210. #ifdef _WIN32
  211. #define SNPRINTF _snprintf
  212. #else
  213. #define SNPRINTF snprintf
  214. #endif
  215. static char* iptos(const struct in_addr* addr)
  216. {
  217. static char output[32];
  218. byte *p = (byte*)&addr->s_addr;
  219. snprintf(output, sizeof(output), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  220. return output;
  221. }
  222. static const char* ip6tos(const struct in6_addr* addr)
  223. {
  224. static char output[42];
  225. return inet_ntop(AF_INET6, addr, output, 42);
  226. }
  227. #if defined(WOLFSSL_SNIFFER_STORE_DATA_CB) || defined(WOLFSSL_SNIFFER_CHAIN_INPUT)
  228. static inline unsigned int min(unsigned int a, unsigned int b)
  229. {
  230. return a > b ? b : a;
  231. }
  232. #endif
  233. #ifdef WOLFSSL_SNIFFER_WATCH
  234. static int myWatchCb(void* vSniffer,
  235. const unsigned char* certHash, unsigned int certHashSz,
  236. const unsigned char* certChain, unsigned int certChainSz,
  237. void* ctx, char* error)
  238. {
  239. const char* certName = NULL;
  240. (void)certChain;
  241. (void)certChainSz;
  242. (void)ctx;
  243. if (certHashSz == sizeof(rsaHash) &&
  244. XMEMCMP(certHash, rsaHash, certHashSz) == 0) {
  245. certName = DEFAULT_SERVER_KEY_RSA;
  246. }
  247. if (certHashSz == sizeof(eccHash) &&
  248. XMEMCMP(certHash, eccHash, certHashSz) == 0) {
  249. certName = DEFAULT_SERVER_KEY_ECC;
  250. }
  251. if (certName == NULL) {
  252. /* don't return error if key is not loaded */
  253. printf("Warning: No matching key found for cert hash\n");
  254. return 0;
  255. }
  256. return ssl_SetWatchKey_file(vSniffer, certName, FILETYPE_PEM, NULL, error);
  257. }
  258. #endif /* WOLFSSL_SNIFFER_WATCH */
  259. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  260. static int myStoreDataCb(const unsigned char* decryptBuf,
  261. unsigned int decryptBufSz, unsigned int decryptBufOffset, void* ctx)
  262. {
  263. byte** data = (byte**)ctx;
  264. unsigned int qty;
  265. if (data == NULL)
  266. return -1;
  267. if (decryptBufSz < decryptBufOffset)
  268. return -1;
  269. qty = min(decryptBufSz - decryptBufOffset, STORE_DATA_BLOCK_SZ);
  270. if (*data == NULL) {
  271. byte* tmpData;
  272. tmpData = (byte*)XREALLOC(*data, decryptBufSz + 1,
  273. NULL, DYNAMIC_TYPE_TMP_BUFFER);
  274. if (tmpData == NULL) {
  275. XFREE(*data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  276. *data = NULL;
  277. return -1;
  278. }
  279. *data = tmpData;
  280. }
  281. XMEMCPY(*data + decryptBufOffset, decryptBuf + decryptBufOffset, qty);
  282. return qty;
  283. }
  284. #endif /* WOLFSSL_SNIFFER_STORE_DATA_CB */
  285. /* try and load as both static ephemeral and private key */
  286. /* only fail if no key is loaded */
  287. /* Allow comma separated list of files */
  288. static int load_key(const char* name, const char* server, int port,
  289. const char* keyFiles, const char* passwd, char* err)
  290. {
  291. int ret = -1;
  292. int loadCount = 0;
  293. char *keyFile, *ptr = NULL;
  294. keyFile = XSTRTOK((char*)keyFiles, ",", &ptr);
  295. while (keyFile != NULL) {
  296. #ifdef WOLFSSL_STATIC_EPHEMERAL
  297. #ifdef HAVE_SNI
  298. ret = ssl_SetNamedEphemeralKey(name, server, port, keyFile,
  299. FILETYPE_PEM, passwd, err);
  300. #else
  301. ret = ssl_SetEphemeralKey(server, port, keyFile,
  302. FILETYPE_PEM, passwd, err);
  303. #endif
  304. if (ret == 0)
  305. loadCount++;
  306. #endif
  307. #ifdef HAVE_SNI
  308. ret = ssl_SetNamedPrivateKey(name, server, port, keyFile,
  309. FILETYPE_PEM, passwd, err);
  310. #else
  311. ret = ssl_SetPrivateKey(server, port, keyFile,
  312. FILETYPE_PEM, passwd, err);
  313. #endif
  314. if (ret == 0)
  315. loadCount++;
  316. if (loadCount == 0) {
  317. printf("Failed loading private key %s: ret %d\n", keyFile, ret);
  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, 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 cmdLineArg[128];
  829. char *pcapFile = NULL;
  830. char *deviceName = NULL;
  831. char err[PCAP_ERRBUF_SIZE];
  832. char filter[128];
  833. const char *keyFilesSrc = NULL;
  834. #ifdef WOLFSSL_SNIFFER_KEYLOGFILE
  835. const char *sslKeyLogFile = NULL;
  836. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  837. char keyFilesBuf[MAX_FILENAME_SZ];
  838. char keyFilesUser[MAX_FILENAME_SZ];
  839. const char *server = NULL;
  840. int port = -1;
  841. const char *sniName = NULL;
  842. const char *passwd = NULL;
  843. pcap_if_t *d;
  844. pcap_addr_t *a;
  845. #ifdef THREADED_SNIFFTEST
  846. int workerThreadCount;
  847. #endif
  848. #ifdef DEBUG_WOLFSSL
  849. wolfSSL_Debugging_ON();
  850. #endif
  851. show_appinfo();
  852. signal(SIGINT, sig_handler);
  853. for (i = 1; i < argc; i++) {
  854. if (strcmp(argv[i], "-pcap") == 0 && i + 1 < argc) {
  855. pcapFile = argv[++i];
  856. }
  857. else if (strcmp(argv[i], "-deviceName") == 0 && i + 1 < argc) {
  858. deviceName = argv[++i];
  859. }
  860. else if (strcmp(argv[i], "-key") == 0 && i + 1 < argc) {
  861. keyFilesSrc = argv[++i];
  862. }
  863. else if (strcmp(argv[i], "-server") == 0 && i + 1 < argc) {
  864. server = argv[++i];
  865. }
  866. else if (strcmp(argv[i], "-port") == 0 && i + 1 < argc) {
  867. port = XATOI(argv[++i]);
  868. }
  869. else if (strcmp(argv[i], "-password") == 0 && i + 1 < argc) {
  870. passwd = argv[++i];
  871. }
  872. else if (strcmp(argv[i], "-tracefile") == 0 && i + 1 < argc) {
  873. traceFile = argv[++i];
  874. }
  875. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  876. else if (strcmp(argv[i], "-keylogfile") == 0 && i + 1 < argc) {
  877. sslKeyLogFile = argv[++i];
  878. }
  879. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  880. #if defined(THREADED_SNIFFTEST)
  881. else if (strcmp(argv[i], "-threads") == 0 && i + 1 < argc) {
  882. workerThreadCount = XATOI(argv[++i]);
  883. }
  884. #endif /* THREADED_SNIFFTEST */
  885. else {
  886. fprintf(stderr, "Error parsing: %s\n", argv[i]);
  887. fprintf(stderr, "Usage: %s -pcap pcap_arg -key key_arg"
  888. " [-deviceName deviceName_arg]"
  889. " [-password password_arg] [-server server_arg]"
  890. " [-port port_arg]"
  891. " [-tracefile tracefile_arg]"
  892. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  893. " [-keylogfile keylogfile_arg]"
  894. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  895. #if defined(THREADED_SNIFFTEST)
  896. " [-threads threads_arg]"
  897. #endif /* THREADED_SNIFFTEST */
  898. "\n", argv[0]);
  899. exit(EXIT_FAILURE);
  900. }
  901. }
  902. #ifndef THREADED_SNIFFTEST
  903. #ifndef _WIN32
  904. ssl_InitSniffer(); /* dll load on Windows */
  905. #endif
  906. ssl_Trace(traceFile, err);
  907. ssl_EnableRecovery(1, -1, err);
  908. #ifdef WOLFSSL_SNIFFER_WATCH
  909. ssl_SetWatchKeyCallback(myWatchCb, err);
  910. #endif
  911. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  912. ssl_SetStoreDataCallback(myStoreDataCb);
  913. #endif
  914. #else
  915. #ifdef HAVE_SESSION_TICKET
  916. /* Multiple threads on resume not yet supported */
  917. workerThreadCount = 1;
  918. #else
  919. workerThreadCount = 5;
  920. #endif
  921. #endif
  922. SNPRINTF(filter, sizeof(filter), "(ip6 or ip) and tcp");
  923. if (pcapFile == NULL) {
  924. /* normal case, user chooses device and port */
  925. if (pcap_findalldevs(&alldevs, err) == -1)
  926. err_sys("Error in pcap_findalldevs");
  927. if (deviceName == NULL) {
  928. for (d = alldevs, i = 0; d; d=d->next) {
  929. printf("%d. %s", ++i, d->name);
  930. if (strcmp(d->name, "lo0") == 0) {
  931. defDev = i;
  932. }
  933. if (d->description)
  934. printf(" (%s)\n", d->description);
  935. else
  936. printf(" (No description available)\n");
  937. }
  938. if (i == 0)
  939. err_sys("No interfaces found! Make sure pcap or WinPcap is"
  940. " installed correctly and you have sufficient permissions");
  941. printf("Enter the interface number (1-%d) [default: %d]: ", i, defDev);
  942. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  943. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin))
  944. inum = XATOI(cmdLineArg);
  945. if (inum == 0)
  946. inum = defDev;
  947. else if (inum < 1 || inum > i)
  948. err_sys("Interface number out of range");
  949. /* Jump to the selected adapter */
  950. for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++);
  951. } else {
  952. int deviceNameSz = (int)XSTRLEN(deviceName);
  953. for (d = alldevs; d; d = d->next) {
  954. if (XSTRNCMP(d->name,deviceName,deviceNameSz) == 0) {
  955. fprintf(stderr, "%s == %s\n", d->name, deviceName);
  956. break;
  957. }
  958. }
  959. if (d == NULL) {
  960. err_sys("Can't find the device you're looking for");
  961. }
  962. }
  963. printf("Selected %s\n", d->name);
  964. pcap = pcap_create(d->name, err);
  965. if (pcap == NULL) fprintf(stderr, "pcap_create failed %s\n", err);
  966. if (server == NULL) {
  967. /* print out addresses for selected interface */
  968. for (a = d->addresses; a; a = a->next) {
  969. if (a->addr->sa_family == AF_INET) {
  970. server =
  971. iptos(&((struct sockaddr_in *)a->addr)->sin_addr);
  972. printf("server = %s\n", server);
  973. }
  974. else if (a->addr->sa_family == AF_INET6) {
  975. server =
  976. ip6tos(&((struct sockaddr_in6 *)a->addr)->sin6_addr);
  977. printf("server = %s\n", server);
  978. }
  979. }
  980. }
  981. ret = pcap_set_snaplen(pcap, 65536);
  982. if (ret != 0)
  983. fprintf(stderr, "pcap_set_snaplen failed %s\n", pcap_geterr(pcap));
  984. ret = pcap_set_timeout(pcap, 1000);
  985. if (ret != 0)
  986. fprintf(stderr, "pcap_set_timeout failed %s\n", pcap_geterr(pcap));
  987. ret = pcap_set_buffer_size(pcap, 1000000);
  988. if (ret != 0)
  989. fprintf(stderr, "pcap_set_buffer_size failed %s\n",
  990. pcap_geterr(pcap));
  991. ret = pcap_set_promisc(pcap, 1);
  992. if (ret != 0)
  993. fprintf(stderr,"pcap_set_promisc failed %s\n", pcap_geterr(pcap));
  994. ret = pcap_activate(pcap);
  995. if (ret != 0)
  996. fprintf(stderr, "pcap_activate failed %s\n", pcap_geterr(pcap));
  997. }
  998. else {
  999. saveFile = 1;
  1000. pcap = pcap_open_offline(pcapFile , err);
  1001. if (pcap == NULL) {
  1002. fprintf(stderr, "pcap_open_offline failed %s\n", err);
  1003. err_sys(err);
  1004. }
  1005. }
  1006. if (server == NULL) {
  1007. server = DEFAULT_SERVER_IP;
  1008. }
  1009. if (port < 0) {
  1010. printf("Enter the port to scan [default: %d, '0' for all]: ",
  1011. DEFAULT_SERVER_PORT);
  1012. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  1013. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  1014. port = XATOI(cmdLineArg);
  1015. }
  1016. if ((port < 0) || (cmdLineArg[0] == '\n'))
  1017. port = DEFAULT_SERVER_PORT;
  1018. }
  1019. if (port > 0) {
  1020. SNPRINTF(cmdLineArg, sizeof(filter), " and port %d", port);
  1021. XSTRLCAT(filter, cmdLineArg, sizeof(filter));
  1022. }
  1023. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  1024. /* If we offer keylog support, then user must provide EITHER a pubkey
  1025. * OR a keylog file but NOT both */
  1026. if (keyFilesSrc && sslKeyLogFile) {
  1027. fprintf(stderr,
  1028. "Error: either -key OR -keylogfile option but NOT both.\n");
  1029. exit(EXIT_FAILURE);
  1030. }
  1031. if (sslKeyLogFile != NULL) {
  1032. ret = ssl_LoadSecretsFromKeyLogFile(sslKeyLogFile, err);
  1033. if (ret != 0) {
  1034. fprintf(stderr,
  1035. "ERROR=%d, unable to load secrets from keylog file\n",ret);
  1036. err_sys(err);
  1037. }
  1038. ret = ssl_CreateKeyLogSnifferServer(server, port, err);
  1039. if (ret != 0) {
  1040. fprintf(stderr,
  1041. "ERROR=%d, unable to create keylog sniffer server\n",ret);
  1042. err_sys(err);
  1043. }
  1044. }
  1045. else
  1046. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  1047. if (keyFilesSrc) {
  1048. ret = load_key(NULL, server, port, keyFilesSrc, passwd, err);
  1049. if (ret != 0) {
  1050. fprintf(stderr, "Failed to load key\n");
  1051. err_sys(err);
  1052. }
  1053. }
  1054. else {
  1055. /* optionally enter the private key to use */
  1056. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(DEFAULT_SERVER_EPH_KEY)
  1057. keyFilesSrc = DEFAULT_SERVER_EPH_KEY;
  1058. #else
  1059. keyFilesSrc = DEFAULT_SERVER_KEY;
  1060. #endif
  1061. printf("Enter the server key [default: %s]: ", keyFilesSrc);
  1062. XMEMSET(keyFilesBuf, 0, sizeof(keyFilesBuf));
  1063. XMEMSET(keyFilesUser, 0, sizeof(keyFilesUser));
  1064. if (XFGETS(keyFilesUser, sizeof(keyFilesUser), stdin)) {
  1065. TrimNewLine(keyFilesUser);
  1066. if (XSTRLEN(keyFilesUser) > 0) {
  1067. keyFilesSrc = keyFilesUser;
  1068. }
  1069. }
  1070. XSTRNCPY(keyFilesBuf, keyFilesSrc, sizeof(keyFilesBuf));
  1071. /* optionally enter a named key (SNI) */
  1072. #if !defined(WOLFSSL_SNIFFER_WATCH) && defined(HAVE_SNI)
  1073. printf("Enter alternate SNI [default: none]: ");
  1074. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  1075. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  1076. TrimNewLine(cmdLineArg);
  1077. if (XSTRLEN(cmdLineArg) > 0) {
  1078. sniName = cmdLineArg;
  1079. }
  1080. }
  1081. #endif /* !WOLFSSL_SNIFFER_WATCH && HAVE_SNI */
  1082. ret = load_key(sniName, server, port, keyFilesBuf, NULL, err);
  1083. if (ret != 0) {
  1084. exit(EXIT_FAILURE);
  1085. }
  1086. }
  1087. /* Only let through TCP/IP packets */
  1088. printf("Using packet filter: %s\n", filter);
  1089. ret = pcap_compile(pcap, &pcap_fp, filter, 0, 0);
  1090. if (ret != 0) {
  1091. fprintf(stderr, "pcap_compile failed %s\n", pcap_geterr(pcap));
  1092. exit(EXIT_FAILURE);
  1093. }
  1094. ret = pcap_setfilter(pcap, &pcap_fp);
  1095. if (ret != 0) {
  1096. fprintf(stderr, "pcap_setfilter failed %s\n", pcap_geterr(pcap));
  1097. exit(EXIT_FAILURE);
  1098. }
  1099. if (ret != 0)
  1100. err_sys(err);
  1101. if (pcap_datalink(pcap) == DLT_NULL)
  1102. frame = NULL_IF_FRAME_LEN;
  1103. #ifdef THREADED_SNIFFTEST
  1104. SnifferWorker workers[workerThreadCount];
  1105. int used[workerThreadCount];
  1106. XMEMSET(used, 0, sizeof(used));
  1107. XMEMSET(&workers, 0, sizeof(workers));
  1108. for (i=0; i<workerThreadCount; i++) {
  1109. ssl_Init_SnifferWorker(&workers[i], port, server, keyFilesSrc,
  1110. passwd, i);
  1111. pthread_create(&workers[i].tid, NULL, snifferWorker, &workers[i]);
  1112. }
  1113. #endif
  1114. while (1) {
  1115. struct pcap_pkthdr *header;
  1116. const unsigned char* packet = NULL;
  1117. byte* data = NULL; /* pointer to decrypted data */
  1118. #ifdef THREADED_SNIFFTEST
  1119. SnifferStreamInfo info;
  1120. uint8_t infoSum;
  1121. uint8_t* infoPtr;
  1122. int threadNum;
  1123. #endif
  1124. #if defined(WOLFSSL_ASYNC_CRYPT)
  1125. SSLInfo sslInfo;
  1126. int queueSz = 0;
  1127. XMEMSET(&sslInfo, 0, sizeof(sslInfo));
  1128. /* poll hardware and attempt to process items in queue. If returns > 0
  1129. * then data pointer has decrypted something */
  1130. SnifferAsyncPollQueue(&data, err, &sslInfo, &queueSz);
  1131. if (queueSz >= WOLF_ASYNC_MAX_PENDING) {
  1132. /* queue full, poll again */
  1133. continue;
  1134. }
  1135. #endif
  1136. ret = 0; /* reset status */
  1137. if (data == NULL) {
  1138. /* grab next pcap packet */
  1139. packetNumber++;
  1140. if(pcap_next_ex(pcap, &header, &packet) < 0) {
  1141. break;
  1142. }
  1143. }
  1144. if (packet) {
  1145. if (header->caplen > 40) { /* min ip(20) + min tcp(20) */
  1146. packet += frame;
  1147. header->caplen -= frame;
  1148. }
  1149. else {
  1150. /* packet doesn't contain minimum ip/tcp header */
  1151. continue;
  1152. }
  1153. if (pcap_datalink(pcap) == DLT_LINUX_SLL) {
  1154. packet += 2;
  1155. header->caplen -= 2;
  1156. }
  1157. #ifdef THREADED_SNIFFTEST
  1158. XMEMSET(&info, 0, sizeof(SnifferStreamInfo));
  1159. ret = ssl_DecodePacket_GetStream(&info, packet, header->caplen, err);
  1160. /* calculate SnifferStreamInfo checksum */
  1161. infoSum = 0;
  1162. infoPtr = (uint8_t*)&info;
  1163. for (i=0; i<(int)sizeof(SnifferStreamInfo); i++) {
  1164. infoSum += infoPtr[i];
  1165. }
  1166. /* determine thread to handle stream */
  1167. threadNum = infoSum % workerThreadCount;
  1168. used[threadNum] = 1;
  1169. #ifdef DEBUG_SNIFFER
  1170. printf("Sending packet %d to thread number %d\n", packetNumber,
  1171. threadNum);
  1172. #endif
  1173. /* get lock on thread mutex */
  1174. wm_SemLock(&workers[threadNum].sem);
  1175. /* add the packet to the worker's linked list */
  1176. if (SnifferWorkerPacketAdd(&workers[threadNum], ret, (byte*)packet,
  1177. header->caplen, packetNumber)) {
  1178. printf("Unable to add packet %d to worker", packetNumber);
  1179. break;
  1180. }
  1181. wm_SemUnlock(&workers[threadNum].sem);
  1182. #else
  1183. /* Decode Packet, ret value will indicate whether a
  1184. * bad packet was encountered */
  1185. hadBadPacket = DecodePacket((byte*)packet, header->caplen,
  1186. packetNumber,err);
  1187. #endif
  1188. }
  1189. /* check if we are done reading file */
  1190. if (packet == NULL && data == NULL && saveFile) {
  1191. #ifdef WOLFSSL_ASYNC_CRYPT
  1192. /* if items pending still then keep processing */
  1193. if (queueSz > 0)
  1194. continue;
  1195. #endif
  1196. break;
  1197. }
  1198. }
  1199. #ifdef THREADED_SNIFFTEST
  1200. for (i=0; i<workerThreadCount; i++) {
  1201. workers[i].shutdown = 1;
  1202. if (used[i] == 0)
  1203. workers[i].unused = 1;
  1204. pthread_join(workers[i].tid, NULL);
  1205. }
  1206. for (i=0; i<workerThreadCount; i++) {
  1207. if (workers[i].hadBadPacket) {
  1208. hadBadPacket = 1;
  1209. }
  1210. ssl_Free_SnifferWorker(&workers[i]);
  1211. }
  1212. #endif
  1213. FreeAll();
  1214. return hadBadPacket ? EXIT_FAILURE : EXIT_SUCCESS;
  1215. }
  1216. #endif /* full build */