1
0

snifftest.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. /* snifftest.c
  2. *
  3. * Copyright (C) 2006-2023 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. if (worker->head) {
  592. XFREE(worker->head, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  593. worker->head = NULL;
  594. }
  595. }
  596. static int SnifferWorkerPacketAdd(SnifferWorker* worker, int lastRet,
  597. byte* packet, int length, int packetNumber)
  598. {
  599. SnifferPacket* newEntry;
  600. newEntry = (SnifferPacket*)XMALLOC(sizeof(SnifferPacket), NULL,
  601. DYNAMIC_TYPE_TMP_BUFFER);
  602. if (newEntry == NULL) {
  603. return MEMORY_E;
  604. }
  605. XMEMSET(newEntry, 0, sizeof(SnifferPacket));
  606. newEntry->packet = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  607. if (newEntry->packet == NULL) {
  608. XFREE(newEntry, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  609. return MEMORY_E;
  610. }
  611. /* Set newEntry fields to input values */
  612. XMEMCPY(newEntry->packet, packet, length);
  613. newEntry->length = length;
  614. newEntry->lastRet = lastRet;
  615. newEntry->packetNumber = packetNumber;
  616. newEntry->placeholder = 0;
  617. /* Create worker head if null */
  618. if (worker->head == NULL) {
  619. worker->head = (SnifferPacket*)XMALLOC(sizeof(SnifferPacket), NULL,
  620. DYNAMIC_TYPE_TMP_BUFFER);
  621. XMEMSET(worker->head, 0, sizeof(SnifferPacket));
  622. worker->tail = worker->head;
  623. worker->head->packet = NULL;
  624. worker->head->next = NULL;
  625. worker->head->prev = NULL;
  626. worker->head->placeholder = 1;
  627. }
  628. if (worker->head->placeholder) {
  629. /* First packet added to be to SnifferWorker linked list,
  630. * set head and tail to the new packet */
  631. XFREE(worker->head, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  632. newEntry->next = NULL;
  633. newEntry->prev = NULL;
  634. worker->head = newEntry;
  635. worker->tail = newEntry;
  636. }
  637. else {
  638. /* Add packet to SnifferWorker linked list and move tail */
  639. newEntry->prev = worker->tail;
  640. newEntry->next = NULL;
  641. worker->tail->next = newEntry;
  642. worker->tail = newEntry;
  643. }
  644. return 0;
  645. }
  646. #endif /* THREADED_SNIFFTEST */
  647. static int DecodePacket(byte* packet, int length, int packetNumber, char err[])
  648. {
  649. int ret, j;
  650. int hadBadPacket = 0;
  651. int isChain = 0;
  652. int chainSz;
  653. void* chain;
  654. byte* data = NULL; /* pointer to decrypted data */
  655. SSLInfo sslInfo;
  656. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  657. struct iovec chains[CHAIN_INPUT_COUNT];
  658. unsigned int remainder;
  659. j = 0;
  660. chainSz = 0;
  661. isChain = 1;
  662. remainder = length;
  663. do {
  664. unsigned int chunkSz = min(remainder, CHAIN_INPUT_CHUNK_SIZE);
  665. chains[chainSz].iov_base = (void*)(packet + j);
  666. chains[chainSz].iov_len = chunkSz;
  667. j += chunkSz;
  668. remainder -= chunkSz;
  669. chainSz++;
  670. } while (j < (int)length);
  671. chain = (void*)chains;
  672. #else
  673. chain = (void*)packet;
  674. chainSz = length;
  675. #endif
  676. #if defined(DEBUG_SNIFFER)
  677. printf("Packet Number: %d\n", packetNumber);
  678. #endif
  679. /* decode packet */
  680. #ifdef WOLFSSL_ASYNC_CRYPT
  681. /* For async call the original API again with same data,
  682. * or call with different sessions for multiple concurrent
  683. * stream processing */
  684. ret = ssl_DecodePacketAsync(chain, chainSz, isChain, &data, err,
  685. &sslInfo, NULL);
  686. /* WC_PENDING_E: Hardware is processing or stream is blocked
  687. * (waiting on WC_PENDING_E) */
  688. if (ret == WC_PENDING_E) {
  689. /* add to queue, for later processing */
  690. #ifdef DEBUG_SNIFFER
  691. printf("Steam is pending, queue packet %d\n", packetNumber);
  692. #endif
  693. ret = SnifferAsyncQueueAdd(ret, chain, chainSz, isChain,
  694. packetNumber);
  695. if (ret >= 0) {
  696. ret = 0; /* mark event just added */
  697. }
  698. }
  699. #elif defined(WOLFSSL_SNIFFER_CHAIN_INPUT) && \
  700. defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  701. ret = ssl_DecodePacketWithChainSessionInfoStoreData(chain, chainSz,
  702. &data, &sslInfo, err);
  703. #elif defined(WOLFSSL_SNIFFER_CHAIN_INPUT)
  704. (void)sslInfo;
  705. ret = ssl_DecodePacketWithChain(chain, chainSz, &data, err);
  706. #elif defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  707. ret = ssl_DecodePacketWithSessionInfoStoreData(packet,
  708. length, &data, &sslInfo, err);
  709. #else
  710. ret = ssl_DecodePacketWithSessionInfo(packet, length, &data,
  711. &sslInfo, err);
  712. #endif
  713. if (ret < 0) {
  714. printf("ssl_Decode ret = %d, %s on packet number %d\n", ret, err,
  715. packetNumber);
  716. hadBadPacket = 1;
  717. }
  718. if (data != NULL && ret > 0) {
  719. /* Convert non-printable data to periods. */
  720. for (j = 0; j < ret; j++) {
  721. if (isprint(data[j]) || isspace(data[j])) continue;
  722. data[j] = '.';
  723. }
  724. data[ret] = 0;
  725. printf("SSL App Data(%d:%d):%s\n", packetNumber, ret, data);
  726. ssl_FreeZeroDecodeBuffer(&data, ret, err);
  727. }
  728. (void)isChain;
  729. (void)chain;
  730. (void)chainSz;
  731. return hadBadPacket;
  732. }
  733. #ifdef THREADED_SNIFFTEST
  734. static void* snifferWorker(void* arg)
  735. {
  736. SnifferWorker* worker = (SnifferWorker*)arg;
  737. char err[PCAP_ERRBUF_SIZE];
  738. ssl_InitSniffer_ex2(worker->id);
  739. ssl_Trace("./tracefile.txt", err);
  740. ssl_EnableRecovery(1, -1, err);
  741. #ifdef WOLFSSL_SNIFFER_WATCH
  742. ssl_SetWatchKeyCallback(myWatchCb, err);
  743. #endif
  744. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  745. ssl_SetStoreDataCallback(myStoreDataCb);
  746. #endif
  747. load_key(NULL, worker->server, worker->port, worker->keyFilesSrc,
  748. worker->passwd, err);
  749. /* continue processing the workers packets and keep expecting them
  750. * until the shutdown flag is set */
  751. while (!worker->shutdown) {
  752. while (worker->head) {
  753. int ret = 0;
  754. byte* packet;
  755. int length;
  756. int packetNumber;
  757. #ifdef WOLFSSL_ASYNC_CRYPT
  758. SSLInfo sslInfo;
  759. byte* data;
  760. int queueSz = 0;
  761. /* poll hardware and attempt to process items in queue. If
  762. * returns > 0 then data pointer has decrypted something */
  763. SnifferAsyncPollQueue(&data, err, &sslInfo, &queueSz);
  764. if (queueSz >= WOLF_ASYNC_MAX_PENDING) {
  765. /* queue full, poll again */
  766. continue;
  767. }
  768. #endif
  769. /* Shutdown worker if it was not utilized */
  770. if (worker->unused) {
  771. XFREE(worker->head, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  772. worker->head = NULL;
  773. break;
  774. }
  775. /* get lock */
  776. wm_SemLock(&worker->sem);
  777. /* get packet for current worker head */
  778. packet = worker->head->packet;
  779. length = worker->head->length;
  780. packetNumber = worker->head->packetNumber;
  781. wm_SemUnlock(&worker->sem);
  782. if (packet == NULL) {
  783. continue;
  784. }
  785. /* Decode Packet, ret value will indicate whether a
  786. * bad packet was encountered */
  787. ret = DecodePacket(packet, length, packetNumber, err);
  788. if (ret) {
  789. worker->hadBadPacket = 1;
  790. }
  791. /* get lock */
  792. wm_SemLock(&worker->sem);
  793. XFREE(worker->head->packet, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  794. worker->head->packet = NULL;
  795. if (worker->head->next) {
  796. /* Move head and free */
  797. worker->head = worker->head->next;
  798. XFREE(worker->head->prev, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  799. worker->head->prev = NULL;
  800. }
  801. else {
  802. /* No other packets in list. Keep looping until more packets
  803. * arrive or worker is shutdown. */
  804. XFREE(worker->head, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  805. worker->head = NULL;
  806. }
  807. wm_SemUnlock(&worker->sem);
  808. } /* while (worker->head) */
  809. if (worker->unused) {
  810. break;
  811. }
  812. } /* while (worker->head) */
  813. /* Thread cleanup */
  814. ssl_FreeSniffer();
  815. #if defined(HAVE_ECC) && defined(FP_ECC)
  816. wc_ecc_fp_free();
  817. #endif
  818. return NULL;
  819. }
  820. #endif /* THREADED_SNIFFTEST */
  821. int main(int argc, char** argv)
  822. {
  823. int ret = 0;
  824. int hadBadPacket = 0;
  825. int inum = 0;
  826. int saveFile = 0;
  827. int i = 0, defDev = 0;
  828. int packetNumber = 0;
  829. int frame = ETHER_IF_FRAME_LEN;
  830. char err[PCAP_ERRBUF_SIZE];
  831. char filter[32];
  832. const char *keyFilesSrc = NULL;
  833. #ifdef WOLFSSL_SNIFFER_KEYLOGFILE
  834. const char *sslKeyLogFile = NULL;
  835. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  836. char keyFilesBuf[MAX_FILENAME_SZ];
  837. char keyFilesUser[MAX_FILENAME_SZ];
  838. const char *server = DEFAULT_SERVER_IP;
  839. int port = DEFAULT_SERVER_PORT;
  840. const char *sniName = NULL;
  841. const char *passwd = NULL;
  842. pcap_if_t *d;
  843. pcap_addr_t *a;
  844. #ifdef THREADED_SNIFFTEST
  845. int workerThreadCount;
  846. #ifdef HAVE_SESSION_TICKET
  847. /* Multiple threads on resume not yet supported */
  848. workerThreadCount = 1;
  849. #else
  850. workerThreadCount = 5;
  851. #endif
  852. #endif
  853. show_appinfo();
  854. signal(SIGINT, sig_handler);
  855. #ifndef THREADED_SNIFFTEST
  856. #ifndef _WIN32
  857. ssl_InitSniffer(); /* dll load on Windows */
  858. #endif
  859. ssl_Trace("./tracefile.txt", err);
  860. ssl_EnableRecovery(1, -1, err);
  861. #ifdef WOLFSSL_SNIFFER_WATCH
  862. ssl_SetWatchKeyCallback(myWatchCb, err);
  863. #endif
  864. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  865. ssl_SetStoreDataCallback(myStoreDataCb);
  866. #endif
  867. #endif
  868. if (argc == 1) {
  869. char cmdLineArg[128];
  870. /* normal case, user chooses device and port */
  871. if (pcap_findalldevs(&alldevs, err) == -1)
  872. err_sys("Error in pcap_findalldevs");
  873. for (d = alldevs; d; d=d->next) {
  874. printf("%d. %s", ++i, d->name);
  875. if (strcmp(d->name, "lo0") == 0) {
  876. defDev = i;
  877. }
  878. if (d->description)
  879. printf(" (%s)\n", d->description);
  880. else
  881. printf(" (No description available)\n");
  882. }
  883. if (i == 0)
  884. err_sys("No interfaces found! Make sure pcap or WinPcap is"
  885. " installed correctly and you have sufficient permissions");
  886. printf("Enter the interface number (1-%d) [default: %d]: ", i, defDev);
  887. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  888. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin))
  889. inum = XATOI(cmdLineArg);
  890. if (inum == 0)
  891. inum = defDev;
  892. else if (inum < 1 || inum > i)
  893. err_sys("Interface number out of range");
  894. /* Jump to the selected adapter */
  895. for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++);
  896. pcap = pcap_create(d->name, err);
  897. if (pcap == NULL) printf("pcap_create failed %s\n", err);
  898. /* print out addresses for selected interface */
  899. for (a = d->addresses; a; a = a->next) {
  900. if (a->addr->sa_family == AF_INET) {
  901. server =
  902. iptos(&((struct sockaddr_in *)a->addr)->sin_addr);
  903. printf("server = %s\n", server);
  904. }
  905. else if (a->addr->sa_family == AF_INET6) {
  906. server =
  907. ip6tos(&((struct sockaddr_in6 *)a->addr)->sin6_addr);
  908. printf("server = %s\n", server);
  909. }
  910. }
  911. if (server == NULL)
  912. err_sys("Unable to get device IPv4 or IPv6 address");
  913. ret = pcap_set_snaplen(pcap, 65536);
  914. if (ret != 0) printf("pcap_set_snaplen failed %s\n", pcap_geterr(pcap));
  915. ret = pcap_set_timeout(pcap, 1000);
  916. if (ret != 0) printf("pcap_set_timeout failed %s\n", pcap_geterr(pcap));
  917. ret = pcap_set_buffer_size(pcap, 1000000);
  918. if (ret != 0)
  919. printf("pcap_set_buffer_size failed %s\n", pcap_geterr(pcap));
  920. ret = pcap_set_promisc(pcap, 1);
  921. if (ret != 0) printf("pcap_set_promisc failed %s\n", pcap_geterr(pcap));
  922. ret = pcap_activate(pcap);
  923. if (ret != 0) printf("pcap_activate failed %s\n", pcap_geterr(pcap));
  924. printf("Enter the port to scan [default: 11111]: ");
  925. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  926. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  927. port = XATOI(cmdLineArg);
  928. }
  929. if (port <= 0)
  930. port = 11111;
  931. SNPRINTF(filter, sizeof(filter), "tcp and port %d", port);
  932. ret = pcap_compile(pcap, &pcap_fp, filter, 0, 0);
  933. if (ret != 0) printf("pcap_compile failed %s\n", pcap_geterr(pcap));
  934. ret = pcap_setfilter(pcap, &pcap_fp);
  935. if (ret != 0) printf("pcap_setfilter failed %s\n", pcap_geterr(pcap));
  936. /* optionally enter the private key to use */
  937. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(DEFAULT_SERVER_EPH_KEY)
  938. keyFilesSrc = DEFAULT_SERVER_EPH_KEY;
  939. #else
  940. keyFilesSrc = DEFAULT_SERVER_KEY;
  941. #endif
  942. printf("Enter the server key [default: %s]: ", keyFilesSrc);
  943. XMEMSET(keyFilesBuf, 0, sizeof(keyFilesBuf));
  944. XMEMSET(keyFilesUser, 0, sizeof(keyFilesUser));
  945. if (XFGETS(keyFilesUser, sizeof(keyFilesUser), stdin)) {
  946. TrimNewLine(keyFilesUser);
  947. if (XSTRLEN(keyFilesUser) > 0) {
  948. keyFilesSrc = keyFilesUser;
  949. }
  950. }
  951. XSTRNCPY(keyFilesBuf, keyFilesSrc, sizeof(keyFilesBuf));
  952. /* optionally enter a named key (SNI) */
  953. #if !defined(WOLFSSL_SNIFFER_WATCH) && defined(HAVE_SNI)
  954. printf("Enter alternate SNI [default: none]: ");
  955. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  956. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  957. TrimNewLine(cmdLineArg);
  958. if (XSTRLEN(cmdLineArg) > 0) {
  959. sniName = cmdLineArg;
  960. }
  961. }
  962. #endif /* !WOLFSSL_SNIFFER_WATCH && HAVE_SNI */
  963. /* get IPv4 or IPv6 addresses for selected interface */
  964. for (a = d->addresses; a; a = a->next) {
  965. server = NULL;
  966. if (a->addr->sa_family == AF_INET) {
  967. server =
  968. iptos(&((struct sockaddr_in *)a->addr)->sin_addr);
  969. }
  970. else if (a->addr->sa_family == AF_INET6) {
  971. server =
  972. ip6tos(&((struct sockaddr_in6 *)a->addr)->sin6_addr);
  973. }
  974. if (server) {
  975. XSTRNCPY(keyFilesBuf, keyFilesSrc, sizeof(keyFilesBuf));
  976. ret = load_key(sniName, server, port, keyFilesBuf, NULL, err);
  977. if (ret != 0) {
  978. exit(EXIT_FAILURE);
  979. }
  980. }
  981. }
  982. }
  983. else {
  984. char *pcapFile = NULL;
  985. for (i = 1; i < argc; i++) {
  986. if (strcmp(argv[i], "-pcap") == 0 && i + 1 < argc) {
  987. pcapFile = argv[++i];
  988. }
  989. else if (strcmp(argv[i], "-key") == 0 && i + 1 < argc) {
  990. keyFilesSrc = argv[++i];
  991. }
  992. else if (strcmp(argv[i], "-server") == 0 && i + 1 < argc) {
  993. server = argv[++i];
  994. }
  995. else if (strcmp(argv[i], "-port") == 0 && i + 1 < argc) {
  996. port = XATOI(argv[++i]);
  997. }
  998. else if (strcmp(argv[i], "-password") == 0 && i + 1 < argc) {
  999. passwd = argv[++i];
  1000. }
  1001. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  1002. else if (strcmp(argv[i], "-keylogfile") == 0 && i + 1 < argc) {
  1003. sslKeyLogFile = argv[++i];
  1004. }
  1005. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  1006. #if defined(THREADED_SNIFFTEST)
  1007. else if (strcmp(argv[i], "-threads") == 0 && i + 1 < argc) {
  1008. workerThreadCount = XATOI(argv[++i]);
  1009. }
  1010. #endif /* THREADED_SNIFFTEST */
  1011. else {
  1012. fprintf(stderr, "Invalid option or missing argument: %s\n", argv[i]);
  1013. fprintf(stderr, "Usage: %s -pcap pcap_arg -key key_arg"
  1014. " [-password password_arg] [-server server_arg] [-port port_arg]"
  1015. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  1016. " [-keylogfile keylogfile_arg]"
  1017. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  1018. #if defined(THREADED_SNIFFTEST)
  1019. " [-threads threads_arg]"
  1020. #endif /* THREADED_SNIFFTEST */
  1021. "\n", argv[0]);
  1022. exit(EXIT_FAILURE);
  1023. }
  1024. }
  1025. if (!pcapFile) {
  1026. fprintf(stderr, "Error: -pcap option is required.\n");
  1027. exit(EXIT_FAILURE);
  1028. }
  1029. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  1030. /* If we offer keylog support, then user must provide EITHER a pubkey
  1031. * OR a keylog file but NOT both */
  1032. if ((!keyFilesSrc && !sslKeyLogFile) || (keyFilesSrc && sslKeyLogFile)) {
  1033. fprintf(stderr, "Error: either -key OR -keylogfile option required but NOT both.\n");
  1034. exit(EXIT_FAILURE);
  1035. }
  1036. #else
  1037. if (!keyFilesSrc) {
  1038. fprintf(stderr, "Error: -key option is required.\n");
  1039. exit(EXIT_FAILURE);
  1040. }
  1041. #endif
  1042. saveFile = 1;
  1043. pcap = pcap_open_offline(pcapFile , err);
  1044. if (pcap == NULL) {
  1045. fprintf(stderr, "pcap_open_offline failed %s\n", err);
  1046. err_sys(err);
  1047. }
  1048. else {
  1049. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  1050. if (sslKeyLogFile != NULL) {
  1051. ret = ssl_LoadSecretsFromKeyLogFile(sslKeyLogFile, err);
  1052. if (ret != 0) {
  1053. fprintf(stderr, "ERROR=%d, unable to load secrets from keylog file\n",ret);
  1054. err_sys(err);
  1055. }
  1056. ret = ssl_CreateKeyLogSnifferServer(server, port, err);
  1057. if (ret != 0) {
  1058. fprintf(stderr, "ERROR=%d, unable to create keylog sniffer server\n",ret);
  1059. err_sys(err);
  1060. }
  1061. }
  1062. else
  1063. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  1064. {
  1065. ret = load_key(NULL, server, port, keyFilesSrc, passwd, err);
  1066. if (ret != 0) {
  1067. fprintf(stderr, "Failed to load key\n");
  1068. err_sys(err);
  1069. }
  1070. }
  1071. /* Only let through TCP/IP packets */
  1072. ret = pcap_compile(pcap, &pcap_fp, "(ip6 or ip) and tcp", 0, 0);
  1073. if (ret != 0) {
  1074. fprintf(stderr, "pcap_compile failed %s\n", pcap_geterr(pcap));
  1075. exit(EXIT_FAILURE);
  1076. }
  1077. ret = pcap_setfilter(pcap, &pcap_fp);
  1078. if (ret != 0) {
  1079. fprintf(stderr, "pcap_setfilter failed %s\n", pcap_geterr(pcap));
  1080. exit(EXIT_FAILURE);
  1081. }
  1082. }
  1083. }
  1084. if (ret != 0)
  1085. err_sys(err);
  1086. if (pcap_datalink(pcap) == DLT_NULL)
  1087. frame = NULL_IF_FRAME_LEN;
  1088. #ifdef THREADED_SNIFFTEST
  1089. SnifferWorker workers[workerThreadCount];
  1090. int used[workerThreadCount];
  1091. XMEMSET(used, 0, sizeof(used));
  1092. XMEMSET(&workers, 0, sizeof(workers));
  1093. for (i=0; i<workerThreadCount; i++) {
  1094. ssl_Init_SnifferWorker(&workers[i], port, server, keyFilesSrc,
  1095. passwd, i);
  1096. pthread_create(&workers[i].tid, NULL, snifferWorker, &workers[i]);
  1097. }
  1098. #endif
  1099. while (1) {
  1100. struct pcap_pkthdr header;
  1101. const unsigned char* packet = NULL;
  1102. byte* data = NULL; /* pointer to decrypted data */
  1103. #ifdef THREADED_SNIFFTEST
  1104. SnifferStreamInfo info;
  1105. uint8_t infoSum;
  1106. uint8_t* infoPtr;
  1107. int threadNum;
  1108. #endif
  1109. #if defined(WOLFSSL_ASYNC_CRYPT)
  1110. SSLInfo sslInfo;
  1111. int queueSz = 0;
  1112. XMEMSET(&sslInfo, 0, sizeof(sslInfo));
  1113. /* poll hardware and attempt to process items in queue. If returns > 0
  1114. * then data pointer has decrypted something */
  1115. SnifferAsyncPollQueue(&data, err, &sslInfo, &queueSz);
  1116. if (queueSz >= WOLF_ASYNC_MAX_PENDING) {
  1117. /* queue full, poll again */
  1118. continue;
  1119. }
  1120. #endif
  1121. ret = 0; /* reset status */
  1122. if (data == NULL) {
  1123. /* grab next pcap packet */
  1124. packetNumber++;
  1125. packet = pcap_next(pcap, &header);
  1126. }
  1127. if (packet) {
  1128. if (header.caplen > 40) { /* min ip(20) + min tcp(20) */
  1129. packet += frame;
  1130. header.caplen -= frame;
  1131. }
  1132. else {
  1133. /* packet doesn't contain minimum ip/tcp header */
  1134. continue;
  1135. }
  1136. #ifdef THREADED_SNIFFTEST
  1137. XMEMSET(&info, 0, sizeof(SnifferStreamInfo));
  1138. ret = ssl_DecodePacket_GetStream(&info, packet, header.caplen, err);
  1139. /* calculate SnifferStreamInfo checksum */
  1140. infoSum = 0;
  1141. infoPtr = (uint8_t*)&info;
  1142. for (i=0; i<(int)sizeof(SnifferStreamInfo); i++) {
  1143. infoSum += infoPtr[i];
  1144. }
  1145. /* determine thread to handle stream */
  1146. threadNum = infoSum % workerThreadCount;
  1147. used[threadNum] = 1;
  1148. #ifdef DEBUG_SNIFFER
  1149. printf("Sending packet %d to thread number %d\n", packetNumber,
  1150. threadNum);
  1151. #endif
  1152. /* get lock on thread mutex */
  1153. wm_SemLock(&workers[threadNum].sem);
  1154. /* add the packet to the worker's linked list */
  1155. if (SnifferWorkerPacketAdd(&workers[threadNum], ret, (byte*)packet,
  1156. header.caplen, packetNumber)) {
  1157. printf("Unable to add packet %d to worker", packetNumber);
  1158. break;
  1159. }
  1160. wm_SemUnlock(&workers[threadNum].sem);
  1161. #else
  1162. /* Decode Packet, ret value will indicate whether a
  1163. * bad packet was encountered */
  1164. hadBadPacket = DecodePacket((byte*)packet, header.caplen,
  1165. packetNumber,err);
  1166. #endif
  1167. }
  1168. /* check if we are done reading file */
  1169. if (packet == NULL && data == NULL && saveFile) {
  1170. #ifdef WOLFSSL_ASYNC_CRYPT
  1171. /* if items pending still then keep processing */
  1172. if (queueSz > 0)
  1173. continue;
  1174. #endif
  1175. break;
  1176. }
  1177. }
  1178. #ifdef THREADED_SNIFFTEST
  1179. for (i=0; i<workerThreadCount; i++) {
  1180. workers[i].shutdown = 1;
  1181. if (used[i] == 0)
  1182. workers[i].unused = 1;
  1183. pthread_join(workers[i].tid, NULL);
  1184. }
  1185. for (i=0; i<workerThreadCount; i++) {
  1186. if (workers[i].hadBadPacket) {
  1187. hadBadPacket = 1;
  1188. }
  1189. ssl_Free_SnifferWorker(&workers[i]);
  1190. }
  1191. #endif
  1192. FreeAll();
  1193. return hadBadPacket ? EXIT_FAILURE : EXIT_SUCCESS;
  1194. }
  1195. #endif /* full build */