snifftest.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. /* snifftest.c
  2. *
  3. * Copyright (C) 2006-2022 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 _WIN32
  33. #define WOLFSSL_SNIFFER
  34. #endif
  35. #ifndef WOLFSSL_SNIFFER
  36. #ifndef NO_MAIN_DRIVER
  37. /* blank build */
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. int main(void)
  41. {
  42. printf("do ./configure --enable-sniffer to enable build support\n");
  43. return EXIT_SUCCESS;
  44. }
  45. #endif /* !NO_MAIN_DRIVER */
  46. #else
  47. /* do a full build */
  48. #ifdef _MSC_VER
  49. /* builds on *nix too, for scanf device and port */
  50. #define _CRT_SECURE_NO_WARNINGS
  51. #endif
  52. #include <pcap/pcap.h> /* pcap stuff */
  53. #include <stdio.h> /* printf */
  54. #include <stdlib.h> /* EXIT_SUCCESS */
  55. #include <string.h> /* strcmp */
  56. #include <signal.h> /* signal */
  57. #include <ctype.h> /* isprint */
  58. #include <cyassl/sniffer.h>
  59. #ifndef _WIN32
  60. #include <sys/socket.h> /* AF_INET */
  61. #include <arpa/inet.h>
  62. #include <netinet/in.h>
  63. #endif
  64. typedef unsigned char byte;
  65. enum {
  66. ETHER_IF_FRAME_LEN = 14, /* ethernet interface frame length */
  67. NULL_IF_FRAME_LEN = 4, /* no link interface frame length */
  68. };
  69. /* A TLS record can be 16k and change. The chain is broken up into 2K chunks.
  70. * This covers the TLS record, plus a chunk for TCP/IP headers. */
  71. #ifndef CHAIN_INPUT_CHUNK_SIZE
  72. #define CHAIN_INPUT_CHUNK_SIZE 2048
  73. #elif (CHAIN_INPUT_CHUNK_SIZE < 256)
  74. #undef CHAIN_INPUT_CHUNK_SIZE
  75. #define CHAIN_INPUT_CHUNK_SIZE 256
  76. #elif (CHAIN_INPUT_CHUNK_SIZE > 16384)
  77. #undef CHAIN_INPUT_CHUNK_SIZE
  78. #define CHAIN_INPUT_CHUNK_SIZE 16384
  79. #endif
  80. #define CHAIN_INPUT_COUNT ((16384 / CHAIN_INPUT_CHUNK_SIZE) + 1)
  81. #ifndef STORE_DATA_BLOCK_SZ
  82. #define STORE_DATA_BLOCK_SZ 1024
  83. #endif
  84. #if defined(HAVE_ECC) && !defined(NO_ECC_SECP) && (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES))
  85. #define DEFAULT_SERVER_EPH_KEY_ECC "../../certs/statickeys/ecc-secp256r1.pem"
  86. #else
  87. #define DEFAULT_SERVER_EPH_KEY_ECC ""
  88. #endif
  89. #ifndef NO_DH
  90. #define DEFAULT_SERVER_EPH_KEY_DH "../../certs/statickeys/dh-ffdhe2048.pem"
  91. #else
  92. #define DEFAULT_SERVER_EPH_KEY_DH ""
  93. #endif
  94. #ifdef HAVE_CURVE25519
  95. #define DEFAULT_SERVER_EPH_KEY_X25519 "../../certs/statickeys/x25519.pem"
  96. #else
  97. #define DEFAULT_SERVER_EPH_KEY_X25519 ""
  98. #endif
  99. #ifndef DEFAULT_SERVER_EPH_KEY
  100. #define DEFAULT_SERVER_EPH_KEY \
  101. DEFAULT_SERVER_EPH_KEY_ECC "," \
  102. DEFAULT_SERVER_EPH_KEY_DH "," \
  103. DEFAULT_SERVER_EPH_KEY_X25519
  104. #endif
  105. #define DEFAULT_SERVER_KEY_RSA "../../certs/server-key.pem"
  106. #define DEFAULT_SERVER_KEY_ECC "../../certs/ecc-key.pem"
  107. #ifndef DEFAULT_SERVER_KEY
  108. #ifndef NO_RSA
  109. #define DEFAULT_SERVER_KEY DEFAULT_SERVER_KEY_RSA
  110. #elif defined(HAVE_ECC)
  111. #define DEFAULT_SERVER_KEY DEFAULT_SERVER_KEY_ECC
  112. #endif
  113. #endif
  114. #ifdef WOLFSSL_SNIFFER_WATCH
  115. static const byte rsaHash[] = {
  116. 0x3d, 0x4a, 0x60, 0xfc, 0xbf, 0xe5, 0x4d, 0x3e,
  117. 0x85, 0x62, 0xf2, 0xfc, 0xdb, 0x0d, 0x51, 0xdd,
  118. 0xcd, 0xc2, 0x53, 0x81, 0x1a, 0x67, 0x31, 0xa0,
  119. 0x7f, 0xd2, 0x11, 0x74, 0xbf, 0xea, 0xc9, 0xc5
  120. };
  121. static const byte eccHash[] = {
  122. 0x9e, 0x45, 0xb6, 0xf8, 0xc6, 0x5d, 0x60, 0x90,
  123. 0x40, 0x8f, 0xd2, 0x0e, 0xb1, 0x59, 0xe7, 0xbd,
  124. 0xb0, 0x9b, 0x3c, 0x7a, 0x3a, 0xbe, 0x13, 0x52,
  125. 0x07, 0x4f, 0x1a, 0x64, 0x45, 0xe0, 0x13, 0x34
  126. };
  127. #endif
  128. static pcap_t* pcap = NULL;
  129. static pcap_if_t* alldevs = NULL;
  130. static struct bpf_program pcap_fp;
  131. static void FreeAll(void)
  132. {
  133. if (pcap) {
  134. pcap_freecode(&pcap_fp);
  135. pcap_close(pcap);
  136. }
  137. if (alldevs)
  138. pcap_freealldevs(alldevs);
  139. #ifndef _WIN32
  140. ssl_FreeSniffer();
  141. #endif
  142. }
  143. #ifdef WOLFSSL_SNIFFER_STATS
  144. static void DumpStats(void)
  145. {
  146. SSLStats sslStats;
  147. ssl_ReadStatistics(&sslStats);
  148. printf("SSL Stats (sslStandardConns):%lu\n",
  149. sslStats.sslStandardConns);
  150. printf("SSL Stats (sslClientAuthConns):%lu\n",
  151. sslStats.sslClientAuthConns);
  152. printf("SSL Stats (sslResumedConns):%lu\n",
  153. sslStats.sslResumedConns);
  154. printf("SSL Stats (sslEphemeralMisses):%lu\n",
  155. sslStats.sslEphemeralMisses);
  156. printf("SSL Stats (sslResumptionInserts):%lu\n",
  157. sslStats.sslResumptionInserts);
  158. printf("SSL Stats (sslResumeMisses):%lu\n",
  159. sslStats.sslResumeMisses);
  160. printf("SSL Stats (sslCiphersUnsupported):%lu\n",
  161. sslStats.sslCiphersUnsupported);
  162. printf("SSL Stats (sslKeysUnmatched):%lu\n",
  163. sslStats.sslKeysUnmatched);
  164. printf("SSL Stats (sslKeyFails):%lu\n",
  165. sslStats.sslKeyFails);
  166. printf("SSL Stats (sslDecodeFails):%lu\n",
  167. sslStats.sslDecodeFails);
  168. printf("SSL Stats (sslAlerts):%lu\n",
  169. sslStats.sslAlerts);
  170. printf("SSL Stats (sslDecryptedBytes):%lu\n",
  171. sslStats.sslDecryptedBytes);
  172. printf("SSL Stats (sslEncryptedBytes):%lu\n",
  173. sslStats.sslEncryptedBytes);
  174. printf("SSL Stats (sslEncryptedPackets):%lu\n",
  175. sslStats.sslEncryptedPackets);
  176. printf("SSL Stats (sslDecryptedPackets):%lu\n",
  177. sslStats.sslDecryptedPackets);
  178. printf("SSL Stats (sslKeyMatches):%lu\n",
  179. sslStats.sslKeyMatches);
  180. printf("SSL Stats (sslEncryptedConns):%lu\n",
  181. sslStats.sslEncryptedConns);
  182. }
  183. #endif /* WOLFSSL_SNIFFER_STATS */
  184. static void sig_handler(const int sig)
  185. {
  186. printf("SIGINT handled = %d.\n", sig);
  187. FreeAll();
  188. #ifdef WOLFSSL_SNIFFER_STATS
  189. DumpStats();
  190. #endif
  191. if (sig)
  192. exit(EXIT_SUCCESS);
  193. }
  194. static void err_sys(const char* msg)
  195. {
  196. fprintf(stderr, "%s\n", msg);
  197. if (msg)
  198. exit(EXIT_FAILURE);
  199. }
  200. #ifdef _WIN32
  201. #define SNPRINTF _snprintf
  202. #else
  203. #define SNPRINTF snprintf
  204. #endif
  205. static char* iptos(const struct in_addr* addr)
  206. {
  207. static char output[32];
  208. byte *p = (byte*)&addr->s_addr;
  209. snprintf(output, sizeof(output), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  210. return output;
  211. }
  212. static const char* ip6tos(const struct in6_addr* addr)
  213. {
  214. static char output[42];
  215. return inet_ntop(AF_INET6, addr, output, 42);
  216. }
  217. #if defined(WOLFSSL_SNIFFER_STORE_DATA_CB) || defined(WOLFSSL_SNIFFER_CHAIN_INPUT)
  218. static inline unsigned int min(unsigned int a, unsigned int b)
  219. {
  220. return a > b ? b : a;
  221. }
  222. #endif
  223. #ifdef WOLFSSL_SNIFFER_WATCH
  224. static int myWatchCb(void* vSniffer,
  225. const unsigned char* certHash, unsigned int certHashSz,
  226. const unsigned char* certChain, unsigned int certChainSz,
  227. void* ctx, char* error)
  228. {
  229. const char* certName = NULL;
  230. (void)certChain;
  231. (void)certChainSz;
  232. (void)ctx;
  233. if (certHashSz == sizeof(rsaHash) &&
  234. XMEMCMP(certHash, rsaHash, certHashSz) == 0) {
  235. certName = DEFAULT_SERVER_KEY_RSA;
  236. }
  237. if (certHashSz == sizeof(eccHash) &&
  238. XMEMCMP(certHash, eccHash, certHashSz) == 0) {
  239. certName = DEFAULT_SERVER_KEY_ECC;
  240. }
  241. if (certName == NULL) {
  242. /* don't return error if key is not loaded */
  243. printf("Warning: No matching key found for cert hash\n");
  244. return 0;
  245. }
  246. return ssl_SetWatchKey_file(vSniffer, certName, FILETYPE_PEM, NULL, error);
  247. }
  248. #endif /* WOLFSSL_SNIFFER_WATCH */
  249. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  250. static int myStoreDataCb(const unsigned char* decryptBuf,
  251. unsigned int decryptBufSz, unsigned int decryptBufOffset, void* ctx)
  252. {
  253. byte** data = (byte**)ctx;
  254. unsigned int qty;
  255. if (data == NULL)
  256. return -1;
  257. if (decryptBufSz < decryptBufOffset)
  258. return -1;
  259. qty = min(decryptBufSz - decryptBufOffset, STORE_DATA_BLOCK_SZ);
  260. if (*data == NULL) {
  261. byte* tmpData;
  262. tmpData = (byte*)XREALLOC(*data, decryptBufSz + 1,
  263. NULL, DYNAMIC_TYPE_TMP_BUFFER);
  264. if (tmpData == NULL) {
  265. XFREE(*data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  266. *data = NULL;
  267. return -1;
  268. }
  269. *data = tmpData;
  270. }
  271. XMEMCPY(*data + decryptBufOffset, decryptBuf + decryptBufOffset, qty);
  272. return qty;
  273. }
  274. #endif /* WOLFSSL_SNIFFER_STORE_DATA_CB */
  275. /* try and load as both static ephemeral and private key */
  276. /* only fail if no key is loaded */
  277. /* Allow comma separated list of files */
  278. static int load_key(const char* name, const char* server, int port,
  279. const char* keyFiles, const char* passwd, char* err)
  280. {
  281. int ret = -1;
  282. int loadCount = 0;
  283. char *keyFile, *ptr = NULL;
  284. keyFile = XSTRTOK((char*)keyFiles, ",", &ptr);
  285. while (keyFile != NULL) {
  286. #ifdef WOLFSSL_STATIC_EPHEMERAL
  287. #ifdef HAVE_SNI
  288. ret = ssl_SetNamedEphemeralKey(name, server, port, keyFile,
  289. FILETYPE_PEM, passwd, err);
  290. #else
  291. ret = ssl_SetEphemeralKey(server, port, keyFile,
  292. FILETYPE_PEM, passwd, err);
  293. #endif
  294. if (ret == 0)
  295. loadCount++;
  296. #endif
  297. #ifdef HAVE_SNI
  298. ret = ssl_SetNamedPrivateKey(name, server, port, keyFile,
  299. FILETYPE_PEM, passwd, err);
  300. #else
  301. ret = ssl_SetPrivateKey(server, port, keyFile,
  302. FILETYPE_PEM, passwd, err);
  303. #endif
  304. if (ret == 0)
  305. loadCount++;
  306. if (loadCount == 0) {
  307. printf("Failed loading private key %s: ret %d\n", keyFile, ret);
  308. printf("Please run directly from sslSniffer/sslSnifferTest dir\n");
  309. ret = -1;
  310. }
  311. else {
  312. ret = 0;
  313. }
  314. keyFile = XSTRTOK(NULL, ",", &ptr);
  315. }
  316. (void)name;
  317. return ret;
  318. }
  319. static void TrimNewLine(char* str)
  320. {
  321. word32 strSz = 0;
  322. if (str)
  323. strSz = (word32)XSTRLEN(str);
  324. if (strSz > 0 && (str[strSz-1] == '\n' || str[strSz-1] == '\r'))
  325. str[strSz-1] = '\0';
  326. }
  327. static void show_appinfo(void)
  328. {
  329. printf("snifftest %s\n", LIBWOLFSSL_VERSION_STRING);
  330. /* list enabled sniffer features */
  331. printf("sniffer features: "
  332. #ifdef WOLFSSL_SNIFFER_STATS
  333. "stats, "
  334. #endif
  335. #ifdef WOLFSSL_SNIFFER_WATCH
  336. "watch, "
  337. #endif
  338. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  339. "store_data_cb "
  340. #endif
  341. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  342. "chain_input "
  343. #endif
  344. #ifdef WOLFSSL_SNIFFER_KEY_CALLBACK
  345. "key_callback "
  346. #endif
  347. #ifdef DEBUG_SNIFFER
  348. "debug "
  349. #endif
  350. #ifdef WOLFSSL_TLS13
  351. "tls_v13 "
  352. #endif
  353. #ifndef WOLFSSL_NO_TLS12
  354. "tls_v12 "
  355. #endif
  356. #ifdef HAVE_SESSION_TICKET
  357. "session_ticket "
  358. #endif
  359. #ifdef WOLFSSL_STATIC_EPHEMERAL
  360. "static_ephemeral "
  361. #endif
  362. #ifdef WOLFSSL_ENCRYPTED_KEYS
  363. "encrypted_keys "
  364. #endif
  365. #ifdef HAVE_SNI
  366. "sni "
  367. #endif
  368. #ifdef HAVE_EXTENDED_MASTER
  369. "extended_master "
  370. #endif
  371. #ifdef HAVE_MAX_FRAGMENT
  372. "max fragment "
  373. #endif
  374. #ifdef WOLFSSL_ASYNC_CRYPT
  375. "async_crypt "
  376. #endif
  377. #ifndef NO_RSA
  378. "rsa "
  379. #endif
  380. #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
  381. "dh "
  382. #endif
  383. #ifdef HAVE_ECC
  384. "ecc "
  385. #endif
  386. #ifdef HAVE_CURVE448
  387. "x448 "
  388. #endif
  389. #ifdef HAVE_CURVE22519
  390. "x22519 "
  391. #endif
  392. #ifdef WOLFSSL_STATIC_RSA
  393. "rsa_static "
  394. #endif
  395. #ifdef WOLFSSL_STATIC_DH
  396. "dh_static "
  397. #endif
  398. "\n\n"
  399. );
  400. }
  401. static void show_usage(void)
  402. {
  403. printf("usage:\n");
  404. printf("\t./snifftest\n");
  405. printf("\t\tprompts for options\n");
  406. printf("\t./snifftest dump pemKey [server] [port] [password]\n");
  407. }
  408. #ifdef WOLFSSL_ASYNC_CRYPT
  409. typedef struct SnifferPacket {
  410. byte* packet;
  411. int length;
  412. int lastRet;
  413. int packetNumber;
  414. } SnifferPacket;
  415. static SnifferPacket asyncQueue[WOLF_ASYNC_MAX_PENDING];
  416. /* returns index to queue */
  417. static int SnifferAsyncQueueAdd(int lastRet, void* chain, int chainSz,
  418. int isChain, int packetNumber)
  419. {
  420. int ret = MEMORY_E, i, length;
  421. byte* packet;
  422. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  423. if (isChain) {
  424. struct iovec* vchain = (struct iovec*)chain;
  425. length = 0;
  426. for (i = 0; i < chainSz; i++)
  427. length += vchain[i].iov_len;
  428. packet = (byte*)vchain[0].iov_base;
  429. }
  430. else
  431. #endif
  432. {
  433. packet = (byte*)chain;
  434. length = chainSz;
  435. }
  436. /* find first free idx */
  437. for (i=0; i<WOLF_ASYNC_MAX_PENDING; i++) {
  438. if (asyncQueue[i].packet == NULL) {
  439. if (ret == MEMORY_E) {
  440. ret = i;
  441. break;
  442. }
  443. }
  444. }
  445. if (ret != MEMORY_E) {
  446. asyncQueue[ret].packet = XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  447. if (asyncQueue[ret].packet == NULL) {
  448. return MEMORY_E;
  449. }
  450. XMEMCPY(asyncQueue[ret].packet, packet, length);
  451. asyncQueue[ret].length = length;
  452. asyncQueue[ret].lastRet = lastRet;
  453. asyncQueue[ret].packetNumber = packetNumber;
  454. }
  455. (void)isChain;
  456. return ret;
  457. }
  458. static int SnifferAsyncPollQueue(byte** data, char* err, SSLInfo* sslInfo,
  459. int* queueSz)
  460. {
  461. int ret = 0, i;
  462. WOLF_EVENT* events[WOLF_ASYNC_MAX_PENDING];
  463. int eventCount = 0;
  464. /* try to process existing items in queue */
  465. for (i=0; i<WOLF_ASYNC_MAX_PENDING; i++) {
  466. if (asyncQueue[i].packet != NULL) {
  467. (*queueSz)++;
  468. /* do poll for events on hardware */
  469. ret = ssl_PollSniffer(events, WOLF_ASYNC_MAX_PENDING,
  470. WOLF_POLL_FLAG_CHECK_HW, &eventCount);
  471. if (ret == 0) {
  472. /* attempt to reprocess pending packet */
  473. #ifdef DEBUG_SNIFFER
  474. printf("Packet Number: %d (retry)\n", asyncQueue[i].packetNumber);
  475. #endif
  476. ret = ssl_DecodePacketAsync(asyncQueue[i].packet,
  477. asyncQueue[i].length, 0, data, err, sslInfo, NULL);
  478. asyncQueue[i].lastRet = ret;
  479. if (ret >= 0) {
  480. /* done, so free and break to process below */
  481. XFREE(asyncQueue[i].packet, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  482. asyncQueue[i].packet = NULL;
  483. if (ret > 0) {
  484. /* decrypted some data, so return */
  485. break;
  486. }
  487. }
  488. }
  489. }
  490. }
  491. if (ret == WC_PENDING_E) {
  492. ret = 0; /* nothing new */
  493. }
  494. return ret;
  495. }
  496. #endif /* WOLFSSL_ASYNC_CRYPT */
  497. int main(int argc, char** argv)
  498. {
  499. int ret = 0;
  500. int hadBadPacket = 0;
  501. int inum = 0;
  502. int port = 0;
  503. int saveFile = 0;
  504. int i = 0, defDev = 0;
  505. int frame = ETHER_IF_FRAME_LEN;
  506. char err[PCAP_ERRBUF_SIZE];
  507. char filter[32];
  508. const char *keyFilesSrc = NULL;
  509. char keyFilesBuf[MAX_FILENAME_SZ];
  510. char keyFilesUser[MAX_FILENAME_SZ];
  511. const char *server = NULL;
  512. const char *sniName = NULL;
  513. pcap_if_t *d;
  514. pcap_addr_t *a;
  515. int isChain = 0;
  516. int j;
  517. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  518. struct iovec chains[CHAIN_INPUT_COUNT];
  519. unsigned int remainder;
  520. #endif
  521. int packetNumber = 0;
  522. show_appinfo();
  523. signal(SIGINT, sig_handler);
  524. #ifndef _WIN32
  525. ssl_InitSniffer(); /* dll load on Windows */
  526. #endif
  527. ssl_Trace("./tracefile.txt", err);
  528. ssl_EnableRecovery(1, -1, err);
  529. #ifdef WOLFSSL_SNIFFER_WATCH
  530. ssl_SetWatchKeyCallback(myWatchCb, err);
  531. #endif
  532. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  533. ssl_SetStoreDataCallback(myStoreDataCb);
  534. #endif
  535. if (argc == 1) {
  536. char cmdLineArg[128];
  537. /* normal case, user chooses device and port */
  538. if (pcap_findalldevs(&alldevs, err) == -1)
  539. err_sys("Error in pcap_findalldevs");
  540. for (d = alldevs; d; d=d->next) {
  541. printf("%d. %s", ++i, d->name);
  542. if (strcmp(d->name, "lo0") == 0) {
  543. defDev = i;
  544. }
  545. if (d->description)
  546. printf(" (%s)\n", d->description);
  547. else
  548. printf(" (No description available)\n");
  549. }
  550. if (i == 0)
  551. err_sys("No interfaces found! Make sure pcap or WinPcap is"
  552. " installed correctly and you have sufficient permissions");
  553. printf("Enter the interface number (1-%d) [default: %d]: ", i, defDev);
  554. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  555. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin))
  556. inum = XATOI(cmdLineArg);
  557. if (inum == 0)
  558. inum = defDev;
  559. else if (inum < 1 || inum > i)
  560. err_sys("Interface number out of range");
  561. /* Jump to the selected adapter */
  562. for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++);
  563. pcap = pcap_create(d->name, err);
  564. if (pcap == NULL) printf("pcap_create failed %s\n", err);
  565. /* print out addresses for selected interface */
  566. for (a = d->addresses; a; a = a->next) {
  567. if (a->addr->sa_family == AF_INET) {
  568. server =
  569. iptos(&((struct sockaddr_in *)a->addr)->sin_addr);
  570. printf("server = %s\n", server);
  571. }
  572. else if (a->addr->sa_family == AF_INET6) {
  573. server =
  574. ip6tos(&((struct sockaddr_in6 *)a->addr)->sin6_addr);
  575. printf("server = %s\n", server);
  576. }
  577. }
  578. if (server == NULL)
  579. err_sys("Unable to get device IPv4 or IPv6 address");
  580. ret = pcap_set_snaplen(pcap, 65536);
  581. if (ret != 0) printf("pcap_set_snaplen failed %s\n", pcap_geterr(pcap));
  582. ret = pcap_set_timeout(pcap, 1000);
  583. if (ret != 0) printf("pcap_set_timeout failed %s\n", pcap_geterr(pcap));
  584. ret = pcap_set_buffer_size(pcap, 1000000);
  585. if (ret != 0)
  586. printf("pcap_set_buffer_size failed %s\n", pcap_geterr(pcap));
  587. ret = pcap_set_promisc(pcap, 1);
  588. if (ret != 0) printf("pcap_set_promisc failed %s\n", pcap_geterr(pcap));
  589. ret = pcap_activate(pcap);
  590. if (ret != 0) printf("pcap_activate failed %s\n", pcap_geterr(pcap));
  591. printf("Enter the port to scan [default: 11111]: ");
  592. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  593. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  594. port = XATOI(cmdLineArg);
  595. }
  596. if (port <= 0)
  597. port = 11111;
  598. SNPRINTF(filter, sizeof(filter), "tcp and port %d", port);
  599. ret = pcap_compile(pcap, &pcap_fp, filter, 0, 0);
  600. if (ret != 0) printf("pcap_compile failed %s\n", pcap_geterr(pcap));
  601. ret = pcap_setfilter(pcap, &pcap_fp);
  602. if (ret != 0) printf("pcap_setfilter failed %s\n", pcap_geterr(pcap));
  603. /* optionally enter the private key to use */
  604. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(DEFAULT_SERVER_EPH_KEY)
  605. keyFilesSrc = DEFAULT_SERVER_EPH_KEY;
  606. #else
  607. keyFilesSrc = DEFAULT_SERVER_KEY;
  608. #endif
  609. printf("Enter the server key [default: %s]: ", keyFilesSrc);
  610. XMEMSET(keyFilesBuf, 0, sizeof(keyFilesBuf));
  611. XMEMSET(keyFilesUser, 0, sizeof(keyFilesUser));
  612. if (XFGETS(keyFilesUser, sizeof(keyFilesUser), stdin)) {
  613. TrimNewLine(keyFilesUser);
  614. if (XSTRLEN(keyFilesUser) > 0) {
  615. keyFilesSrc = keyFilesUser;
  616. }
  617. }
  618. XSTRNCPY(keyFilesBuf, keyFilesSrc, sizeof(keyFilesBuf));
  619. /* optionally enter a named key (SNI) */
  620. #if !defined(WOLFSSL_SNIFFER_WATCH) && defined(HAVE_SNI)
  621. printf("Enter alternate SNI [default: none]: ");
  622. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  623. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  624. TrimNewLine(cmdLineArg);
  625. if (XSTRLEN(cmdLineArg) > 0) {
  626. sniName = cmdLineArg;
  627. }
  628. }
  629. #endif /* !WOLFSSL_SNIFFER_WATCH && HAVE_SNI */
  630. /* get IPv4 or IPv6 addresses for selected interface */
  631. for (a = d->addresses; a; a = a->next) {
  632. server = NULL;
  633. if (a->addr->sa_family == AF_INET) {
  634. server =
  635. iptos(&((struct sockaddr_in *)a->addr)->sin_addr);
  636. }
  637. else if (a->addr->sa_family == AF_INET6) {
  638. server =
  639. ip6tos(&((struct sockaddr_in6 *)a->addr)->sin6_addr);
  640. }
  641. if (server) {
  642. XSTRNCPY(keyFilesBuf, keyFilesSrc, sizeof(keyFilesBuf));
  643. ret = load_key(sniName, server, port, keyFilesBuf, NULL, err);
  644. if (ret != 0) {
  645. exit(EXIT_FAILURE);
  646. }
  647. }
  648. }
  649. }
  650. else if (argc >= 3) {
  651. saveFile = 1;
  652. pcap = pcap_open_offline(argv[1], err);
  653. if (pcap == NULL) {
  654. printf("pcap_open_offline failed %s\n", err);
  655. ret = -1;
  656. }
  657. else {
  658. const char* passwd = NULL;
  659. /* defaults for server and port */
  660. port = 443;
  661. server = "127.0.0.1";
  662. keyFilesSrc = argv[2];
  663. if (argc >= 4)
  664. server = argv[3];
  665. if (argc >= 5)
  666. port = XATOI(argv[4]);
  667. if (argc >= 6)
  668. passwd = argv[5];
  669. ret = load_key(NULL, server, port, keyFilesSrc, passwd, err);
  670. if (ret != 0) {
  671. exit(EXIT_FAILURE);
  672. }
  673. /* Only let through TCP/IP packets */
  674. ret = pcap_compile(pcap, &pcap_fp, "(ip6 or ip) and tcp", 0, 0);
  675. if (ret != 0) {
  676. printf("pcap_compile failed %s\n", pcap_geterr(pcap));
  677. exit(EXIT_FAILURE);
  678. }
  679. ret = pcap_setfilter(pcap, &pcap_fp);
  680. if (ret != 0) {
  681. printf("pcap_setfilter failed %s\n", pcap_geterr(pcap));
  682. exit(EXIT_FAILURE);
  683. }
  684. }
  685. }
  686. else {
  687. show_usage();
  688. exit(EXIT_FAILURE);
  689. }
  690. if (ret != 0)
  691. err_sys(err);
  692. if (pcap_datalink(pcap) == DLT_NULL)
  693. frame = NULL_IF_FRAME_LEN;
  694. while (1) {
  695. struct pcap_pkthdr header;
  696. const unsigned char* packet = NULL;
  697. SSLInfo sslInfo;
  698. void* chain = NULL;
  699. int chainSz = 0;
  700. byte* data = NULL; /* pointer to decrypted data */
  701. #ifdef WOLFSSL_ASYNC_CRYPT
  702. int queueSz = 0;
  703. #endif
  704. #ifndef WOLFSSL_ASYNC_CRYPT
  705. ret = 0; /* reset status */
  706. #else
  707. /* poll hardware and attempt to process items in queue. If returns > 0
  708. * then data pointer has decrypted something */
  709. ret = SnifferAsyncPollQueue(&data, err, &sslInfo, &queueSz);
  710. if (queueSz >= WOLF_ASYNC_MAX_PENDING) {
  711. /* queue full, poll again */
  712. continue;
  713. }
  714. #endif
  715. if (data == NULL) {
  716. /* grab next pcap packet */
  717. packetNumber++;
  718. packet = pcap_next(pcap, &header);
  719. #ifdef DEBUG_SNIFFER
  720. printf("Packet Number: %d\n", packetNumber);
  721. #endif
  722. }
  723. if (packet) {
  724. if (header.caplen > 40) { /* min ip(20) + min tcp(20) */
  725. packet += frame;
  726. header.caplen -= frame;
  727. }
  728. else {
  729. /* packet doesn't contain minimum ip/tcp header */
  730. continue;
  731. }
  732. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  733. isChain = 1;
  734. j = 0;
  735. remainder = header.caplen;
  736. chainSz = 0;
  737. do {
  738. unsigned int chunkSz = min(remainder, CHAIN_INPUT_CHUNK_SIZE);
  739. chains[chainSz].iov_base = (void*)(packet + j);
  740. chains[chainSz].iov_len = chunkSz;
  741. j += chunkSz;
  742. remainder -= chunkSz;
  743. chainSz++;
  744. } while (j < (int)header.caplen);
  745. chain = (void*)chains;
  746. #else
  747. chain = (void*)packet;
  748. chainSz = header.caplen;
  749. #endif
  750. #ifdef WOLFSSL_ASYNC_CRYPT
  751. /* For async call the original API again with same data,
  752. * or call with different sessions for multiple concurrent
  753. * stream processing */
  754. ret = ssl_DecodePacketAsync(chain, chainSz, isChain, &data, err,
  755. &sslInfo, NULL);
  756. /* WC_PENDING_E: Hardware is processing or stream is blocked
  757. * (waiting on WC_PENDING_E) */
  758. if (ret == WC_PENDING_E) {
  759. /* add to queue, for later processing */
  760. #ifdef DEBUG_SNIFFER
  761. printf("Steam is pending, queue packet %d\n", packetNumber);
  762. #endif
  763. ret = SnifferAsyncQueueAdd(ret, chain, chainSz, isChain,
  764. packetNumber);
  765. if (ret >= 0) {
  766. ret = 0; /* mark event just added */
  767. }
  768. }
  769. #elif defined(WOLFSSL_SNIFFER_CHAIN_INPUT) && \
  770. defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  771. ret = ssl_DecodePacketWithChainSessionInfoStoreData(chain, chainSz,
  772. &data, &sslInfo, err);
  773. #elif defined(WOLFSSL_SNIFFER_CHAIN_INPUT)
  774. (void)sslInfo;
  775. ret = ssl_DecodePacketWithChain(chain, chainSz, &data, err);
  776. #else
  777. #if defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  778. ret = ssl_DecodePacketWithSessionInfoStoreData(packet,
  779. header.caplen, &data, &sslInfo, err);
  780. #else
  781. ret = ssl_DecodePacketWithSessionInfo(packet, header.caplen, &data,
  782. &sslInfo, err);
  783. #endif
  784. (void)chain;
  785. (void)chainSz;
  786. #endif
  787. }
  788. /* check if we are done reading file */
  789. if (packet == NULL && data == NULL && saveFile) {
  790. #ifdef WOLFSSL_ASYNC_CRYPT
  791. /* if items pending still then keep processing */
  792. if (queueSz > 0)
  793. continue;
  794. #endif
  795. break;
  796. }
  797. if (ret < 0) {
  798. printf("ssl_Decode ret = %d, %s\n", ret, err);
  799. hadBadPacket = 1;
  800. }
  801. if (data != NULL && ret > 0) {
  802. /* Convert non-printable data to periods. */
  803. for (j = 0; j < ret; j++) {
  804. if (isprint(data[j]) || isspace(data[j])) continue;
  805. data[j] = '.';
  806. }
  807. data[ret] = 0;
  808. printf("SSL App Data(%d:%d):%s\n", packetNumber, ret, data);
  809. ssl_FreeZeroDecodeBuffer(&data, ret, err);
  810. }
  811. }
  812. FreeAll();
  813. (void)isChain;
  814. return hadBadPacket ? EXIT_FAILURE : EXIT_SUCCESS;
  815. }
  816. #endif /* full build */