-
Notifications
You must be signed in to change notification settings - Fork 970
Expand file tree
/
Copy pathsniffer.c
More file actions
7890 lines (6826 loc) · 242 KB
/
sniffer.c
File metadata and controls
7890 lines (6826 loc) · 242 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* sniffer.c
*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
#ifdef WOLFSSL_ASYNC_CRYPT
#include <wolfssl/wolfcrypt/async.h>
#endif
/* Build Options:
* WOLFSSL_SNIFFER_NO_RECOVERY: Do not track missed data count.
* SNIFFER_SINGLE_SESSION_CACHE: Do not cache more than one session.
*/
/* xctime */
#ifndef XCTIME
#define XCTIME ctime
#endif
/* only in this file, to avoid confusing future ports leave
* these defines here. Do not move to wc_port.h */
#ifdef USER_CUSTOM_SNIFFX
/* To be implemented in user_settings.h */
#elif defined(FUSION_RTOS)
#include <fcl_network.h>
#define XINET_NTOA FNS_INET_NTOA
#define XINET_ATON FNS_INET_ATON
#define XINET_PTON(a,b,c,d) FNS_INET_PTON((a),(b),(c),(d),NULL)
#define XINET_NTOP(a,b,c,d) FNS_INET_NTOP((a),(b),(c),(d),NULL)
#define XINET_ADDR FNS_INET_ADDR
#define XHTONS FNS_HTONS
#define XNTOHS FNS_NTOHS
#define XHTONL FNS_HTONL
#define XNTOHL FNS_NTOHL
#define XINADDR_NONE FNS_INADDR_NONE
#else
/* default */
#define XINET_NTOA inet_ntoa
#define XINET_ATON inet_aton
#ifdef FREESCALE_MQX
#define XINET_PTON(a,b,c,d) inet_pton((a),(b),(c),(d))
#else
#define XINET_PTON(a,b,c) inet_pton((a),(b),(c))
#endif
#define XINET_NTOP inet_ntop
#define XINET_ADDR inet_addr
#define XHTONS htons
#define XNTOHS ntohs
#define XHTONL htonl
#define XNTOHL ntohl
#ifdef FREESCALE_MQX
#define XINADDR_NONE INADDR_BROADCAST
#else
#define XINADDR_NONE INADDR_NONE
#endif
#endif
#if !defined(WOLFCRYPT_ONLY) && !defined(NO_FILESYSTEM)
#ifdef WOLFSSL_SNIFFER
#include <time.h>
#ifdef FUSION_RTOS
#include <fns_inet.h>
#ifdef TCP_PROTOCOL
#undef TCP_PROTOCOL
#endif
#elif !defined(FREESCALE_MQX)
#ifndef _WIN32
#include <arpa/inet.h>
#else
#include <ws2tcpip.h>
#endif
#endif
#ifdef _WIN32
#define SNPRINTF _snprintf
#else
#define SNPRINTF snprintf
#endif
#include <wolfssl/internal.h>
#include <wolfssl/error-ssl.h>
#include <wolfssl/sniffer.h>
#include <wolfssl/sniffer_error.h>
#ifndef NO_RSA
#include <wolfssl/wolfcrypt/rsa.h>
#endif
#ifndef NO_DH
#include <wolfssl/wolfcrypt/dh.h>
#endif
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519)
#include <wolfssl/wolfcrypt/ecc.h>
#endif
#ifdef HAVE_CURVE25519
#include <wolfssl/wolfcrypt/curve25519.h>
#endif
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
#ifdef WOLF_CRYPTO_CB
#include <wolfssl/wolfcrypt/cryptocb.h>
#ifdef HAVE_INTEL_QA_SYNC
#include <wolfssl/wolfcrypt/port/intel/quickassist_sync.h>
#endif
#ifdef HAVE_CAVIUM_OCTEON_SYNC
#include <wolfssl/wolfcrypt/port/cavium/cavium_octeon_sync.h>
#endif
#endif
#define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
#ifndef WOLFSSL_SNIFFER_TIMEOUT
#define WOLFSSL_SNIFFER_TIMEOUT 900
/* Cache unclosed Sessions for 15 minutes since last used */
#endif
/* Misc constants */
enum {
MAX_SERVER_ADDRESS = 128, /* maximum server address length */
MAX_SERVER_NAME = 128, /* maximum server name length */
MAX_ERROR_LEN = 80, /* maximum error length */
ETHER_IF_ADDR_LEN = 6, /* ethernet interface address length */
LOCAL_IF_ADDR_LEN = 4, /* localhost interface address length, !windows */
TCP_PROTO = 6, /* TCP_PROTOCOL */
IP_HDR_SZ = 20, /* IPv4 header length, min */
IP6_HDR_SZ = 40, /* IPv6 header length, min */
TCP_HDR_SZ = 20, /* TCP header length, min */
IPV4 = 4, /* IP version 4 */
IPV6 = 6, /* IP version 6 */
TCP_PROTOCOL = 6, /* TCP Protocol id */
NO_NEXT_HEADER = 59, /* IPv6 no headers follow */
TRACE_MSG_SZ = 80, /* Trace Message buffer size */
HASH_SIZE = 499, /* Session Hash Table Rows */
PSEUDO_HDR_SZ = 12, /* TCP Pseudo Header size in bytes */
STREAM_INFO_SZ = 44, /* SnifferStreamInfo size in bytes */
FATAL_ERROR_STATE = 1, /* SnifferSession fatal error state */
TICKET_HINT_LEN = 4, /* Session Ticket Hint length */
TICKET_HINT_AGE_LEN= 4, /* Session Ticket Age add length */
EXT_TYPE_SZ = 2, /* Extension type length */
MAX_INPUT_SZ = MAX_RECORD_SIZE + COMP_EXTRA + MAX_MSG_EXTRA +
MTU_EXTRA, /* Max input sz of reassembly */
/* TLS Extensions */
EXT_SERVER_NAME = 0x0000, /* a.k.a. SNI */
EXT_MAX_FRAGMENT_LENGTH = 0x0001,
EXT_TRUSTED_CA_KEYS = 0x0003,
EXT_TRUNCATED_HMAC = 0x0004,
EXT_STATUS_REQUEST = 0x0005, /* a.k.a. OCSP stapling */
EXT_SUPPORTED_GROUPS = 0x000a, /* a.k.a. Supported Curves */
EXT_EC_POINT_FORMATS = 0x000b,
EXT_SIGNATURE_ALGORITHMS = 0x000d,
EXT_APPLICATION_LAYER_PROTOCOL = 0x0010, /* a.k.a. ALPN */
EXT_STATUS_REQUEST_V2 = 0x0011, /* a.k.a. OCSP stapling v2 */
EXT_ENCRYPT_THEN_MAC = 0x0016, /* RFC 7366 */
EXT_MASTER_SECRET = 0x0017, /* Extended Master Secret Extension ID */
EXT_TICKET_ID = 0x0023, /* Session Ticket Extension ID */
EXT_PRE_SHARED_KEY = 0x0029,
EXT_EARLY_DATA = 0x002a,
EXT_SUPPORTED_VERSIONS = 0x002b,
EXT_COOKIE = 0x002c,
EXT_PSK_KEY_EXCHANGE_MODES = 0x002d,
EXT_POST_HANDSHAKE_AUTH = 0x0031,
EXT_SIGNATURE_ALGORITHMS_CERT = 0x0032,
EXT_KEY_SHARE = 0x0033,
EXT_RENEGOTIATION_INFO = 0xff01
};
#ifdef _WIN32
static HMODULE dllModule; /* for error string resources */
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
static int didInit = 0;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
if (didInit == 0) {
dllModule = hModule;
ssl_InitSniffer();
didInit = 1;
}
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
if (didInit) {
ssl_FreeSniffer();
didInit = 0;
}
break;
}
return TRUE;
}
#endif /* _WIN32 */
static WC_THREADSHARED int TraceOn = 0; /* Trace is off by default */
static WC_THREADSHARED XFILE TraceFile = 0;
/* windows uses .rc table for this */
#ifndef _WIN32
static const char* const msgTable[] =
{
/* 1 */
"Out of Memory",
"New SSL Sniffer Server Registered",
"Checking IP Header",
"SSL Sniffer Server Not Registered",
"Checking TCP Header",
/* 6 */
"SSL Sniffer Server Port Not Registered",
"RSA Private Decrypt Error",
"RSA Private Decode Error",
"Set Cipher Spec Error",
"Server Hello Input Malformed",
/* 11 */
"Couldn't Resume Session Error",
"Server Did Resumption",
"Client Hello Input Malformed",
"Client Trying to Resume",
"Handshake Input Malformed",
/* 16 */
"Got Hello Verify msg",
"Got Server Hello msg",
"Got Cert Request msg",
"Got Server Key Exchange msg",
"Got Cert msg",
/* 21 */
"Got Server Hello Done msg",
"Got Finished msg",
"Got Client Hello msg",
"Got Client Key Exchange msg",
"Got Cert Verify msg",
/* 26 */
"Got Unknown Handshake msg",
"New SSL Sniffer Session created",
"Couldn't create new SSL",
"Got a Packet to decode",
"No data present",
/* 31 */
"Session Not Found",
"Got an Old Client Hello msg",
"Old Client Hello Input Malformed",
"Old Client Hello OK",
"Bad Old Client Hello",
/* 36 */
"Bad Record Header",
"Record Header Input Malformed",
"Got a HandShake msg",
"Bad HandShake msg",
"Got a Change Cipher Spec msg",
/* 41 */
"Got Application Data msg",
"Bad Application Data",
"Got an Alert msg",
"Another msg to Process",
"Removing Session From Table",
/* 46 */
"Bad Key File",
"Wrong IP Version",
"Wrong Protocol type",
"Packet Short for header processing",
"Got Unknown Record Type",
/* 51 */
"Can't Open Trace File",
"Session in Fatal Error State",
"Partial SSL record received",
"Buffer Error, malformed input",
"Added to Partial Input",
/* 56 */
"Received a Duplicate Packet",
"Received an Out of Order Packet",
"Received an Overlap Duplicate Packet",
"Received an Overlap Reassembly Begin Duplicate Packet",
"Received an Overlap Reassembly End Duplicate Packet",
/* 61 */
"Missed the Client Hello Entirely",
"Got Hello Request msg",
"Got Session Ticket msg",
"Bad Input",
"Bad Decrypt Type",
/* 66 */
"Bad Finished Message Processing",
"Bad Compression Type",
"Bad DeriveKeys Error",
"Saw ACK for Missing Packet Error",
"Bad Decrypt Operation",
/* 71 */
"Decrypt Keys Not Set Up",
"Late Key Load Error",
"Got Certificate Status msg",
"RSA Key Missing Error",
"Secure Renegotiation Not Supported",
/* 76 */
"Get Session Stats Failure",
"Reassembly Buffer Size Exceeded",
"Dropping Lost Fragment",
"Dropping Partial Record",
"Clear ACK Fault",
/* 81 */
"Bad Decrypt Size",
"Extended Master Secret Hash Error",
"Handshake Message Split Across TLS Records",
"ECC Private Decode Error",
"ECC Public Decode Error",
/* 86 */
"Watch callback not set",
"Watch hash failed",
"Watch callback failed",
"Bad Certificate Message",
"Store data callback not set",
/* 91 */
"No data destination Error",
"Store data callback failed",
"Loading chain input",
"Got encrypted extension",
"Got Hello Retry Request",
/* 96 */
"Setting up keys",
"Unsupported TLS Version",
"Server Client Key Mismatch",
/* 99 */
"Invalid or missing keylog file",
};
/* *nix version uses table above */
static void GetError(int idx, char* str)
{
if (str == NULL ||
idx <= 0 || idx > (int)(sizeof(msgTable)/sizeof(const char* const)))
return;
XSTRNCPY(str, msgTable[idx - 1], MAX_ERROR_LEN-1);
str[MAX_ERROR_LEN-1] = '\0';
}
#else /* _WIN32 */
/* Windows version uses .rc table */
static void GetError(int idx, char* buffer)
{
if (buffer == NULL)
return;
if (!LoadStringA(dllModule, idx, buffer, MAX_ERROR_LEN))
buffer[0] = 0;
}
#endif /* _WIN32 */
/* Packet Buffer for reassembly list and ready list */
typedef struct PacketBuffer {
word32 begin; /* relative sequence begin */
word32 end; /* relative sequence end */
byte* data; /* actual data */
struct PacketBuffer* next; /* next on reassembly list or ready list */
} PacketBuffer;
#ifdef HAVE_SNI
/* NamedKey maps a SNI name to a specific private key */
typedef struct NamedKey {
char name[MAX_SERVER_NAME]; /* server DNS name */
word32 nameSz; /* size of server DNS name */
byte* key; /* DER private key */
word32 keySz; /* size of DER private key */
int isEphemeralKey;
struct NamedKey* next; /* for list */
} NamedKey;
#endif
/* Sniffer Server holds info for each server/port monitored */
typedef struct SnifferServer {
WOLFSSL_CTX* ctx; /* SSL context */
char address[MAX_SERVER_ADDRESS]; /* passed in server address */
IpAddrInfo server; /* network order address */
int port; /* server port */
#ifdef HAVE_SNI
NamedKey* namedKeys; /* mapping of names and keys */
wolfSSL_Mutex namedKeysMutex; /* mutex for namedKey list */
#endif
#if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
byte useKeyLogFile; /* True if session secrets are coming from a
keylog file */
#endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
struct SnifferServer* next; /* for list */
} SnifferServer;
/* Session Flags */
typedef struct Flags {
byte side; /* which end is current packet headed */
byte serverCipherOn; /* indicates whether cipher is active */
byte clientCipherOn; /* indicates whether cipher is active */
byte resuming; /* did this session come from resumption */
byte clientHello; /* processed client hello yet, for SSLv2 */
byte finCount; /* get both FINs before removing */
byte fatalError; /* fatal error state */
byte cliAckFault; /* client acked unseen data from server */
byte srvAckFault; /* server acked unseen data from client */
byte cliSkipPartial; /* client skips partial data to catch up */
byte srvSkipPartial; /* server skips partial data to catch up */
#ifdef HAVE_EXTENDED_MASTER
byte expectEms; /* expect extended master secret */
#endif
byte gotFinished; /* processed finished */
byte secRenegEn; /* secure renegotiation enabled */
#ifdef WOLFSSL_ASYNC_CRYPT
byte wasPolled;
#endif
#ifdef SNIFFER_SINGLE_SESSION_CACHE
byte cached; /* have we cached this session yet */
#endif
} Flags;
/* Out of Order FIN capture */
typedef struct FinCapture {
word32 cliFinSeq; /* client relative sequence FIN 0 is no */
word32 srvFinSeq; /* server relative sequence FIN, 0 is no */
byte cliCounted; /* did we count yet, detects duplicates */
byte srvCounted; /* did we count yet, detects duplicates */
} FinCapture;
typedef struct HsHashes {
#ifndef NO_OLD_TLS
#ifndef NO_SHA
wc_Sha hashSha;
#endif
#ifndef NO_MD5
wc_Md5 hashMd5;
#endif
#endif /* !NO_OLD_TLS */
#ifndef NO_SHA256
wc_Sha256 hashSha256;
#endif
#ifdef WOLFSSL_SHA384
wc_Sha384 hashSha384;
#endif
} HsHashes;
typedef struct KeyShareInfo {
word16 named_group;
int key_len;
const byte* key;
/* additional info */
int dh_key_bits;
int curve_id;
} KeyShareInfo;
/* Sniffer Session holds info for each client/server SSL/TLS session */
typedef struct SnifferSession {
SnifferServer* context; /* server context */
WOLFSSL* sslServer; /* SSL server side decode */
WOLFSSL* sslClient; /* SSL client side decode */
IpAddrInfo server; /* server address in network byte order */
IpAddrInfo client; /* client address in network byte order */
word16 srvPort; /* server port */
word16 cliPort; /* client port */
word32 cliSeqStart; /* client start sequence */
word32 srvSeqStart; /* server start sequence */
word32 cliSeqLast; /* client last sequence */
word32 srvSeqLast; /* server last sequence */
word32 cliExpected; /* client expected sequence (relative) */
word32 srvExpected; /* server expected sequence (relative) */
FinCapture finCapture; /* retain out of order FIN s */
Flags flags; /* session flags */
time_t lastUsed; /* last used ticks */
word32 keySz; /* size of the private key */
PacketBuffer* cliReassemblyList; /* client out of order packets */
PacketBuffer* srvReassemblyList; /* server out of order packets */
word32 cliReassemblyMemory; /* client packet memory used */
word32 srvReassemblyMemory; /* server packet memory used */
struct SnifferSession* next; /* for hash table list */
byte* ticketID; /* mac ID of session ticket */
#ifdef HAVE_MAX_FRAGMENT
byte* tlsFragBuf;
word32 tlsFragOffset;
word32 tlsFragSize;
#endif
#ifdef HAVE_SNI
const char* sni; /* server name indication */
#endif
#ifdef HAVE_EXTENDED_MASTER
HsHashes* hash;
#endif
#ifdef WOLFSSL_TLS13
byte* cliKeyShare;
word32 cliKeyShareSz;
KeyShareInfo srvKs;
KeyShareInfo cliKs;
#endif
#ifdef WOLFSSL_ASYNC_CRYPT
void* userCtx;
word32 pendSeq; /* when WC_PENDING_E is returned capture sequence */
#endif
int error; /* store the last set error number */
byte verboseErr; /* Last set error is helpful and should
* not be overwritten by FATAL_ERROR_STATE */
} SnifferSession;
/* Sniffer Server List and mutex */
static THREAD_LS_T SnifferServer* ServerList = NULL;
#ifndef HAVE_C___ATOMIC
static WC_THREADSHARED wolfSSL_Mutex ServerListMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(ServerListMutex);
#endif
/* Session Hash Table, mutex, and count */
static THREAD_LS_T SnifferSession* SessionTable[HASH_SIZE];
#ifndef HAVE_C___ATOMIC
static WC_THREADSHARED wolfSSL_Mutex SessionMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(SessionMutex);
#endif
static THREAD_LS_T int SessionCount = 0;
static WC_THREADSHARED int RecoveryEnabled = 0; /* global switch */
static WC_THREADSHARED int MaxRecoveryMemory = -1;
/* per session max recovery memory */
#ifndef WOLFSSL_SNIFFER_NO_RECOVERY
/* Recovery of missed data switches and stats */
static WC_THREADSHARED wolfSSL_Mutex RecoveryMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(RecoveryMutex); /* for stats */
/* # of sessions with missed data */
static WC_THREADSHARED word32 MissedDataSessions = 0;
#endif
/* Connection Info Callback */
static WC_THREADSHARED SSLConnCb ConnectionCb;
static WC_THREADSHARED void* ConnectionCbCtx = NULL;
#ifdef WOLFSSL_SNIFFER_STATS
/* Sessions Statistics */
static WC_THREADSHARED SSLStats SnifferStats;
static WC_THREADSHARED wolfSSL_Mutex StatsMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(StatsMutex);
#endif
#ifdef WOLFSSL_SNIFFER_KEY_CALLBACK
static WC_THREADSHARED SSLKeyCb KeyCb;
static WC_THREADSHARED void* KeyCbCtx = NULL;
#endif
#ifdef WOLFSSL_SNIFFER_WATCH
/* Watch Key Callback */
static WC_THREADSHARED SSLWatchCb WatchCb;
static WC_THREADSHARED void* WatchCbCtx = NULL;
#endif
#ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
/* Store Data Callback */
static WC_THREADSHARED SSLStoreDataCb StoreDataCb;
#endif
#ifndef WOLFSSL_SNIFFER_NO_RECOVERY
static void UpdateMissedDataSessions(void)
{
wc_LockMutex(&RecoveryMutex);
MissedDataSessions += 1;
wc_UnLockMutex(&RecoveryMutex);
}
#endif
#ifdef WOLFSSL_SNIFFER_STATS
#ifdef HAVE_C___ATOMIC
#define LOCK_STAT() WC_DO_NOTHING
#define UNLOCK_STAT() WC_DO_NOTHING
#define NOLOCK_ADD_TO_STAT(x,y) ({ TraceStat(#x, y); \
__atomic_fetch_add(&x, y, __ATOMIC_RELAXED); })
#else
#define LOCK_STAT() wc_LockMutex(&StatsMutex)
#define UNLOCK_STAT() wc_UnLockMutex(&StatsMutex)
#define NOLOCK_ADD_TO_STAT(x,y) ({ TraceStat(#x, y); x += y; })
#endif
#define NOLOCK_INC_STAT(x) NOLOCK_ADD_TO_STAT(x,1)
#define ADD_TO_STAT(x,y) do { LOCK_STAT(); \
NOLOCK_ADD_TO_STAT(x,y); UNLOCK_STAT(); } while (0)
#define INC_STAT(x) do { LOCK_STAT(); \
NOLOCK_INC_STAT(x); UNLOCK_STAT(); } while (0)
#endif /* WOLFSSL_SNIFFER_STATS */
#ifdef HAVE_C___ATOMIC
#define LOCK_SESSION() WC_DO_NOTHING
#define UNLOCK_SESSION() WC_DO_NOTHING
#define LOCK_SERVER_LIST() WC_DO_NOTHING
#define UNLOCK_SERVER_LIST() WC_DO_NOTHING
#else
#define LOCK_SESSION() wc_LockMutex(&SessionMutex)
#define UNLOCK_SESSION() wc_UnLockMutex(&SessionMutex)
#define LOCK_SERVER_LIST() wc_LockMutex(&ServerListMutex)
#define UNLOCK_SERVER_LIST() wc_UnLockMutex(&ServerListMutex)
#endif
#if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT)
static WC_THREADSHARED int CryptoDeviceId = INVALID_DEVID;
#endif
#if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
static int addSecretNode(unsigned char* clientRandom,
int type,
unsigned char* masterSecret,
char* error);
static void hexToBin(const char* hex, unsigned char* bin, int binLength);
static int parseKeyLogFile(const char* fileName, char* error);
static unsigned char* findSecret(unsigned char* clientRandom, int type);
static void freeSecretList(void);
static int snifferSecretCb(unsigned char* client_random,
int type,
unsigned char* output_secret);
static void setSnifferSecretCb(SnifferSession* session);
static int addKeyLogSnifferServerHelper(const char* address,
int port,
char* error);
#endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
/* Initialize overall Sniffer */
void ssl_InitSniffer_ex(int devId)
{
wolfSSL_Init();
#ifndef WOLFSSL_MUTEX_INITIALIZER
#ifndef HAVE_C___ATOMIC
wc_InitMutex(&ServerListMutex);
wc_InitMutex(&SessionMutex);
#endif
#ifndef WOLFSSL_SNIFFER_NO_RECOVERY
wc_InitMutex(&RecoveryMutex);
#endif
#ifdef WOLFSSL_SNIFFER_STATS
XMEMSET(&SnifferStats, 0, sizeof(SSLStats));
wc_InitMutex(&StatsMutex);
#endif
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
#ifdef WOLFSSL_SNIFFER_STATS
XMEMSET(&SnifferStats, 0, sizeof(SSLStats));
#endif
#if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT)
CryptoDeviceId = devId;
#endif
(void)devId;
}
static int GetDevId(void)
{
int devId = INVALID_DEVID;
#ifdef WOLF_CRYPTO_CB
#ifdef HAVE_INTEL_QA_SYNC
devId = wc_CryptoCb_InitIntelQa();
if (devId == INVALID_DEVID) {
fprintf(stderr, "Couldn't init the Intel QA\n");
}
#endif
#ifdef HAVE_CAVIUM_OCTEON_SYNC
devId = wc_CryptoCb_InitOcteon();
if (devId == INVALID_DEVID) {
fprintf(stderr, "Couldn't init the Octeon\n");
}
#endif
#endif
return devId;
}
void ssl_InitSniffer(void)
{
int devId = GetDevId();
#ifdef WOLFSSL_ASYNC_CRYPT
if (wolfAsync_DevOpen(&devId) < 0) {
fprintf(stderr, "Async device open failed\nRunning without async\n");
devId = INVALID_DEVID;
}
#endif /* WOLFSSL_ASYNC_CRYPT */
(void)devId;
ssl_InitSniffer_ex(devId);
}
void ssl_InitSniffer_ex2(int threadNum)
{
int devId = GetDevId();
#ifdef WOLFSSL_ASYNC_CRYPT
#ifndef WC_NO_ASYNC_THREADING
if (wolfAsync_DevOpenThread(&devId, &threadNum) < 0)
#else
if (wolfAsync_DevOpen(&devId) < 0)
#endif
{
fprintf(stderr, "Async device open failed\nRunning without async\n");
devId = INVALID_DEVID;
}
#endif /* WOLFSSL_ASYNC_CRYPT */
(void)devId;
(void)threadNum;
ssl_InitSniffer_ex(devId);
}
#ifdef HAVE_SNI
/* Free Named Key and the zero out the private key it holds */
static void FreeNamedKey(NamedKey* in)
{
if (in) {
if (in->key) {
ForceZero(in->key, in->keySz);
XFREE(in->key, NULL, DYNAMIC_TYPE_X509);
}
XFREE(in, NULL, DYNAMIC_TYPE_SNIFFER_NAMED_KEY);
}
}
static void FreeNamedKeyList(NamedKey* in)
{
NamedKey* next;
while (in) {
next = in->next;
FreeNamedKey(in);
in = next;
}
}
#endif
/* Free Sniffer Server's resources/self */
static void FreeSnifferServer(SnifferServer* srv)
{
if (srv) {
#ifdef HAVE_SNI
wc_LockMutex(&srv->namedKeysMutex);
FreeNamedKeyList(srv->namedKeys);
wc_UnLockMutex(&srv->namedKeysMutex);
wc_FreeMutex(&srv->namedKeysMutex);
#endif
wolfSSL_CTX_free(srv->ctx);
}
XFREE(srv, NULL, DYNAMIC_TYPE_SNIFFER_SERVER);
}
/* free PacketBuffer's resources/self */
static void FreePacketBuffer(PacketBuffer* del)
{
if (del) {
XFREE(del->data, NULL, DYNAMIC_TYPE_SNIFFER_PB_BUFFER);
XFREE(del, NULL, DYNAMIC_TYPE_SNIFFER_PB);
}
}
/* remove PacketBuffer List */
static void FreePacketList(PacketBuffer* in)
{
if (in) {
PacketBuffer* del;
PacketBuffer* packet = in;
while (packet) {
del = packet;
packet = packet->next;
FreePacketBuffer(del);
}
}
}
/* Free Sniffer Session's resources/self */
static void FreeSnifferSession(SnifferSession* session)
{
if (session) {
wolfSSL_free(session->sslClient);
wolfSSL_free(session->sslServer);
FreePacketList(session->cliReassemblyList);
FreePacketList(session->srvReassemblyList);
XFREE(session->ticketID, NULL, DYNAMIC_TYPE_SNIFFER_TICKET_ID);
#ifdef HAVE_EXTENDED_MASTER
XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES);
#endif
#ifdef WOLFSSL_TLS13
XFREE(session->cliKeyShare, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
#ifdef HAVE_MAX_FRAGMENT
XFREE(session->tlsFragBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
session->tlsFragBuf = NULL;
#endif
}
XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
}
/* Free overall Sniffer */
void ssl_FreeSniffer(void)
{
SnifferServer* srv;
SnifferServer* removeServer;
SnifferSession* session;
SnifferSession* removeSession;
int i;
LOCK_SERVER_LIST();
LOCK_SESSION();
/* Free sessions (wolfSSL objects) first */
for (i = 0; i < HASH_SIZE; i++) {
session = SessionTable[i];
while (session) {
removeSession = session;
session = session->next;
FreeSnifferSession(removeSession);
}
}
XMEMSET(SessionTable, 0, sizeof(SessionTable));
SessionCount = 0;
/* Then server (wolfSSL_CTX) */
srv = ServerList;
while (srv) {
removeServer = srv;
srv = srv->next;
FreeSnifferServer(removeServer);
}
ServerList = NULL;
UNLOCK_SESSION();
UNLOCK_SERVER_LIST();
#if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
freeSecretList();
#endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
#ifndef WOLFSSL_MUTEX_INITIALIZER
#ifndef WOLFSSL_SNIFFER_NO_RECOVERY
wc_FreeMutex(&RecoveryMutex);
#endif
#ifndef HAVE_C___ATOMIC
wc_FreeMutex(&SessionMutex);
wc_FreeMutex(&ServerListMutex);
#endif
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
#ifdef WOLF_CRYPTO_CB
#ifdef HAVE_INTEL_QA_SYNC
wc_CryptoCb_CleanupIntelQa(&CryptoDeviceId);
#endif
#ifdef HAVE_CAVIUM_OCTEON_SYNC
wc_CryptoCb_CleanupOcteon(&CryptoDeviceId);
#endif
#endif
#ifdef WOLFSSL_ASYNC_CRYPT
wolfAsync_DevClose(&CryptoDeviceId);
#endif
if (TraceFile) {
TraceOn = 0;
XFCLOSE(TraceFile);
TraceFile = NULL;
}
wolfSSL_Cleanup();
}
#ifdef HAVE_EXTENDED_MASTER
static int HashInit(HsHashes* hash)
{
int ret = 0;
XMEMSET(hash, 0, sizeof(HsHashes));
#ifndef NO_OLD_TLS
#ifndef NO_SHA
if (ret == 0)
ret = wc_InitSha(&hash->hashSha);
#endif
#ifndef NO_MD5
if (ret == 0)
ret = wc_InitMd5(&hash->hashMd5);
#endif
#endif /* !NO_OLD_TLS */
#ifndef NO_SHA256
if (ret == 0)
ret = wc_InitSha256(&hash->hashSha256);
#endif
#ifdef WOLFSSL_SHA384
if (ret == 0)
ret = wc_InitSha384(&hash->hashSha384);
#endif
return ret;
}
static int HashUpdate(HsHashes* hash, const byte* input, int sz)
{
int ret = 0;
input -= HANDSHAKE_HEADER_SZ;
sz += HANDSHAKE_HEADER_SZ;
#ifndef NO_OLD_TLS
#ifndef NO_SHA
if (ret == 0)
ret = wc_ShaUpdate(&hash->hashSha, input, sz);
#endif
#ifndef NO_MD5
if (ret == 0)
ret = wc_Md5Update(&hash->hashMd5, input, sz);
#endif
#endif /* !NO_OLD_TLS */
#ifndef NO_SHA256
if (ret == 0)
ret = wc_Sha256Update(&hash->hashSha256, input, sz);
#endif
#ifdef WOLFSSL_SHA384
if (ret == 0)
ret = wc_Sha384Update(&hash->hashSha384, input, sz);
#endif
return ret;
}
static int HashCopy(HS_Hashes* d, HsHashes* s)
{
#ifndef NO_OLD_TLS