1
0

snifftest.c 40 KB

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