snifftest.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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. return ret;
  456. }
  457. static int SnifferAsyncPollQueue(byte** data, char* err, SSLInfo* sslInfo,
  458. int* queueSz)
  459. {
  460. int ret = 0, i;
  461. WOLF_EVENT* events[WOLF_ASYNC_MAX_PENDING];
  462. int eventCount = 0;
  463. /* try to process existing items in queue */
  464. for (i=0; i<WOLF_ASYNC_MAX_PENDING; i++) {
  465. if (asyncQueue[i].packet != NULL) {
  466. (*queueSz)++;
  467. /* do poll for events on hardware */
  468. ret = ssl_PollSniffer(events, WOLF_ASYNC_MAX_PENDING,
  469. WOLF_POLL_FLAG_CHECK_HW, &eventCount);
  470. if (ret == 0) {
  471. /* attempt to reprocess pending packet */
  472. #ifdef DEBUG_SNIFFER
  473. printf("Retrying packet %d\n", asyncQueue[i].packetNumber);
  474. #endif
  475. ret = ssl_DecodePacketAsync(asyncQueue[i].packet,
  476. asyncQueue[i].length, 0, data, err, sslInfo, NULL);
  477. asyncQueue[i].lastRet = ret;
  478. if (ret >= 0) {
  479. /* done, so free and break to process below */
  480. XFREE(asyncQueue[i].packet, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  481. asyncQueue[i].packet = NULL;
  482. if (ret > 0) {
  483. /* decrypted some data, so return */
  484. break;
  485. }
  486. }
  487. }
  488. }
  489. }
  490. if (ret == WC_PENDING_E) {
  491. ret = 0; /* nothing new */
  492. }
  493. return ret;
  494. }
  495. #endif /* WOLFSSL_ASYNC_CRYPT */
  496. int main(int argc, char** argv)
  497. {
  498. int ret = 0;
  499. int hadBadPacket = 0;
  500. int inum = 0;
  501. int port = 0;
  502. int saveFile = 0;
  503. int i = 0, defDev = 0;
  504. int frame = ETHER_IF_FRAME_LEN;
  505. char err[PCAP_ERRBUF_SIZE];
  506. char filter[32];
  507. const char *keyFilesSrc = NULL;
  508. char keyFilesBuf[MAX_FILENAME_SZ];
  509. char keyFilesUser[MAX_FILENAME_SZ];
  510. const char *server = NULL;
  511. const char *sniName = NULL;
  512. pcap_if_t *d;
  513. pcap_addr_t *a;
  514. int isChain = 0;
  515. int j;
  516. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  517. struct iovec chains[CHAIN_INPUT_COUNT];
  518. unsigned int remainder;
  519. #endif
  520. int packetNumber = 0;
  521. show_appinfo();
  522. signal(SIGINT, sig_handler);
  523. #ifndef _WIN32
  524. ssl_InitSniffer(); /* dll load on Windows */
  525. #endif
  526. ssl_Trace("./tracefile.txt", err);
  527. ssl_EnableRecovery(1, -1, err);
  528. #ifdef WOLFSSL_SNIFFER_WATCH
  529. ssl_SetWatchKeyCallback(myWatchCb, err);
  530. #endif
  531. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  532. ssl_SetStoreDataCallback(myStoreDataCb);
  533. #endif
  534. if (argc == 1) {
  535. char cmdLineArg[128];
  536. /* normal case, user chooses device and port */
  537. if (pcap_findalldevs(&alldevs, err) == -1)
  538. err_sys("Error in pcap_findalldevs");
  539. for (d = alldevs; d; d=d->next) {
  540. printf("%d. %s", ++i, d->name);
  541. if (strcmp(d->name, "lo0") == 0) {
  542. defDev = i;
  543. }
  544. if (d->description)
  545. printf(" (%s)\n", d->description);
  546. else
  547. printf(" (No description available)\n");
  548. }
  549. if (i == 0)
  550. err_sys("No interfaces found! Make sure pcap or WinPcap is"
  551. " installed correctly and you have sufficient permissions");
  552. printf("Enter the interface number (1-%d) [default: %d]: ", i, defDev);
  553. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  554. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin))
  555. inum = XATOI(cmdLineArg);
  556. if (inum == 0)
  557. inum = defDev;
  558. else if (inum < 1 || inum > i)
  559. err_sys("Interface number out of range");
  560. /* Jump to the selected adapter */
  561. for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++);
  562. pcap = pcap_create(d->name, err);
  563. if (pcap == NULL) printf("pcap_create failed %s\n", err);
  564. /* print out addresses for selected interface */
  565. for (a = d->addresses; a; a = a->next) {
  566. if (a->addr->sa_family == AF_INET) {
  567. server =
  568. iptos(&((struct sockaddr_in *)a->addr)->sin_addr);
  569. printf("server = %s\n", server);
  570. }
  571. else if (a->addr->sa_family == AF_INET6) {
  572. server =
  573. ip6tos(&((struct sockaddr_in6 *)a->addr)->sin6_addr);
  574. printf("server = %s\n", server);
  575. }
  576. }
  577. if (server == NULL)
  578. err_sys("Unable to get device IPv4 or IPv6 address");
  579. ret = pcap_set_snaplen(pcap, 65536);
  580. if (ret != 0) printf("pcap_set_snaplen failed %s\n", pcap_geterr(pcap));
  581. ret = pcap_set_timeout(pcap, 1000);
  582. if (ret != 0) printf("pcap_set_timeout failed %s\n", pcap_geterr(pcap));
  583. ret = pcap_set_buffer_size(pcap, 1000000);
  584. if (ret != 0)
  585. printf("pcap_set_buffer_size failed %s\n", pcap_geterr(pcap));
  586. ret = pcap_set_promisc(pcap, 1);
  587. if (ret != 0) printf("pcap_set_promisc failed %s\n", pcap_geterr(pcap));
  588. ret = pcap_activate(pcap);
  589. if (ret != 0) printf("pcap_activate failed %s\n", pcap_geterr(pcap));
  590. printf("Enter the port to scan [default: 11111]: ");
  591. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  592. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  593. port = XATOI(cmdLineArg);
  594. }
  595. if (port <= 0)
  596. port = 11111;
  597. SNPRINTF(filter, sizeof(filter), "tcp and port %d", port);
  598. ret = pcap_compile(pcap, &pcap_fp, filter, 0, 0);
  599. if (ret != 0) printf("pcap_compile failed %s\n", pcap_geterr(pcap));
  600. ret = pcap_setfilter(pcap, &pcap_fp);
  601. if (ret != 0) printf("pcap_setfilter failed %s\n", pcap_geterr(pcap));
  602. /* optionally enter the private key to use */
  603. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(DEFAULT_SERVER_EPH_KEY)
  604. keyFilesSrc = DEFAULT_SERVER_EPH_KEY;
  605. #else
  606. keyFilesSrc = DEFAULT_SERVER_KEY;
  607. #endif
  608. printf("Enter the server key [default: %s]: ", keyFilesSrc);
  609. XMEMSET(keyFilesBuf, 0, sizeof(keyFilesBuf));
  610. XMEMSET(keyFilesUser, 0, sizeof(keyFilesUser));
  611. if (XFGETS(keyFilesUser, sizeof(keyFilesUser), stdin)) {
  612. TrimNewLine(keyFilesUser);
  613. if (XSTRLEN(keyFilesUser) > 0) {
  614. keyFilesSrc = keyFilesUser;
  615. }
  616. }
  617. XSTRNCPY(keyFilesBuf, keyFilesSrc, sizeof(keyFilesBuf));
  618. /* optionally enter a named key (SNI) */
  619. #if !defined(WOLFSSL_SNIFFER_WATCH) && defined(HAVE_SNI)
  620. printf("Enter alternate SNI [default: none]: ");
  621. XMEMSET(cmdLineArg, 0, sizeof(cmdLineArg));
  622. if (XFGETS(cmdLineArg, sizeof(cmdLineArg), stdin)) {
  623. TrimNewLine(cmdLineArg);
  624. if (XSTRLEN(cmdLineArg) > 0) {
  625. sniName = cmdLineArg;
  626. }
  627. }
  628. #endif /* !WOLFSSL_SNIFFER_WATCH && HAVE_SNI */
  629. /* get IPv4 or IPv6 addresses for selected interface */
  630. for (a = d->addresses; a; a = a->next) {
  631. server = NULL;
  632. if (a->addr->sa_family == AF_INET) {
  633. server =
  634. iptos(&((struct sockaddr_in *)a->addr)->sin_addr);
  635. }
  636. else if (a->addr->sa_family == AF_INET6) {
  637. server =
  638. ip6tos(&((struct sockaddr_in6 *)a->addr)->sin6_addr);
  639. }
  640. if (server) {
  641. XSTRNCPY(keyFilesBuf, keyFilesSrc, sizeof(keyFilesBuf));
  642. ret = load_key(sniName, server, port, keyFilesBuf, NULL, err);
  643. if (ret != 0) {
  644. exit(EXIT_FAILURE);
  645. }
  646. }
  647. }
  648. }
  649. else if (argc >= 3) {
  650. saveFile = 1;
  651. pcap = pcap_open_offline(argv[1], err);
  652. if (pcap == NULL) {
  653. printf("pcap_open_offline failed %s\n", err);
  654. ret = -1;
  655. }
  656. else {
  657. const char* passwd = NULL;
  658. /* defaults for server and port */
  659. port = 443;
  660. server = "127.0.0.1";
  661. keyFilesSrc = argv[2];
  662. if (argc >= 4)
  663. server = argv[3];
  664. if (argc >= 5)
  665. port = XATOI(argv[4]);
  666. if (argc >= 6)
  667. passwd = argv[5];
  668. ret = load_key(NULL, server, port, keyFilesSrc, passwd, err);
  669. if (ret != 0) {
  670. exit(EXIT_FAILURE);
  671. }
  672. /* Only let through TCP/IP packets */
  673. ret = pcap_compile(pcap, &pcap_fp, "(ip6 or ip) and tcp", 0, 0);
  674. if (ret != 0) {
  675. printf("pcap_compile failed %s\n", pcap_geterr(pcap));
  676. exit(EXIT_FAILURE);
  677. }
  678. ret = pcap_setfilter(pcap, &pcap_fp);
  679. if (ret != 0) {
  680. printf("pcap_setfilter failed %s\n", pcap_geterr(pcap));
  681. exit(EXIT_FAILURE);
  682. }
  683. }
  684. }
  685. else {
  686. show_usage();
  687. exit(EXIT_FAILURE);
  688. }
  689. if (ret != 0)
  690. err_sys(err);
  691. if (pcap_datalink(pcap) == DLT_NULL)
  692. frame = NULL_IF_FRAME_LEN;
  693. while (1) {
  694. struct pcap_pkthdr header;
  695. const unsigned char* packet = NULL;
  696. SSLInfo sslInfo;
  697. void* chain = NULL;
  698. int chainSz = 0;
  699. byte* data = NULL; /* pointer to decrypted data */
  700. #ifdef WOLFSSL_ASYNC_CRYPT
  701. int queueSz = 0;
  702. #endif
  703. #ifndef WOLFSSL_ASYNC_CRYPT
  704. ret = 0; /* reset status */
  705. #else
  706. /* poll hardware and attempt to process items in queue. If returns > 0
  707. * then data pointer has decrypted something */
  708. ret = SnifferAsyncPollQueue(&data, err, &sslInfo, &queueSz);
  709. if (queueSz >= WOLF_ASYNC_MAX_PENDING) {
  710. /* queue full, poll again */
  711. continue;
  712. }
  713. #endif
  714. if (data == NULL) {
  715. /* grab next pcap packet */
  716. packetNumber++;
  717. packet = pcap_next(pcap, &header);
  718. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(DEBUG_SNIFFER)
  719. printf("Packet Number: %d\n", packetNumber);
  720. #endif
  721. }
  722. if (packet) {
  723. if (header.caplen > 40) { /* min ip(20) + min tcp(20) */
  724. packet += frame;
  725. header.caplen -= frame;
  726. }
  727. else {
  728. /* packet doesn't contain minimum ip/tcp header */
  729. continue;
  730. }
  731. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  732. isChain = 1;
  733. j = 0;
  734. remainder = header.caplen;
  735. chainSz = 0;
  736. do {
  737. unsigned int chunkSz = min(remainder, CHAIN_INPUT_CHUNK_SIZE);
  738. chains[chainSz].iov_base = (void*)(packet + j);
  739. chains[chainSz].iov_len = chunkSz;
  740. j += chunkSz;
  741. remainder -= chunkSz;
  742. chainSz++;
  743. } while (j < (int)header.caplen);
  744. chain = (void*)chains;
  745. #else
  746. chain = (void*)packet;
  747. chainSz = header.caplen;
  748. #endif
  749. #ifdef WOLFSSL_ASYNC_CRYPT
  750. /* For async call the original API again with same data,
  751. * or call with different sessions for multiple concurrent
  752. * stream processing */
  753. ret = ssl_DecodePacketAsync(chain, chainSz, isChain, &data, err,
  754. &sslInfo, NULL);
  755. /* WC_PENDING_E: Hardware is processing or stream is blocked
  756. * (waiting on WC_PENDING_E) */
  757. if (ret == WC_PENDING_E) {
  758. /* add to queue, for later processing */
  759. #ifdef DEBUG_SNIFFER
  760. printf("Steam is pending, queue packet %d\n", packetNumber);
  761. #endif
  762. ret = SnifferAsyncQueueAdd(ret, chain, chainSz, isChain,
  763. packetNumber);
  764. if (ret >= 0) {
  765. ret = 0; /* mark event just added */
  766. }
  767. }
  768. #elif defined(WOLFSSL_SNIFFER_CHAIN_INPUT) && \
  769. defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  770. ret = ssl_DecodePacketWithChainSessionInfoStoreData(chain, chainSz,
  771. &data, &sslInfo, err);
  772. #elif defined(WOLFSSL_SNIFFER_CHAIN_INPUT)
  773. (void)sslInfo;
  774. ret = ssl_DecodePacketWithChain(chain, chainSz, &data, err);
  775. #else
  776. #if defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  777. ret = ssl_DecodePacketWithSessionInfoStoreData(packet,
  778. header.caplen, &data, &sslInfo, err);
  779. #else
  780. ret = ssl_DecodePacketWithSessionInfo(packet, header.caplen, &data,
  781. &sslInfo, err);
  782. #endif
  783. (void)chain;
  784. (void)chainSz;
  785. #endif
  786. }
  787. /* check if we are done reading file */
  788. if (packet == NULL && data == NULL && saveFile) {
  789. break;
  790. }
  791. if (ret < 0) {
  792. printf("ssl_Decode ret = %d, %s\n", ret, err);
  793. hadBadPacket = 1;
  794. }
  795. if (data != NULL && ret > 0) {
  796. /* Convert non-printable data to periods. */
  797. for (j = 0; j < ret; j++) {
  798. if (isprint(data[j]) || isspace(data[j])) continue;
  799. data[j] = '.';
  800. }
  801. data[ret] = 0;
  802. printf("SSL App Data(%d:%d):%s\n", packetNumber, ret, data);
  803. ssl_FreeZeroDecodeBuffer(&data, ret, err);
  804. }
  805. }
  806. FreeAll();
  807. (void)isChain;
  808. return hadBadPacket ? EXIT_FAILURE : EXIT_SUCCESS;
  809. }
  810. #endif /* full build */