-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtls.c
More file actions
3797 lines (3142 loc) · 134 KB
/
Copy pathtls.c
File metadata and controls
3797 lines (3142 loc) · 134 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
/*
* tls.c - TLS/TLS/DTLS dissector
*
* Copyright (C) 2016-26 - ntop.org
*
* nDPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nDPI 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with nDPI. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ndpi_protocol_ids.h"
#define NDPI_CURRENT_PROTO NDPI_PROTOCOL_TLS
#include "ndpi_api.h"
#include "ndpi_md5.h"
#include "ndpi_sha1.h"
#include "ndpi_sha256.h"
#include "ndpi_encryption.h"
#include "ndpi_private.h"
//#define JA4R_DECIMAL 1
static void ndpi_search_tls_wrapper(struct ndpi_detection_module_struct *ndpi_struct,
struct ndpi_flow_struct *flow);
// #define DEBUG_TLS_MEMORY 1
// #define DEBUG_TLS 1
// #define DEBUG_TLS_BLOCKS 1
// #define DEBUG_CERTIFICATE_HASH
// #define DEBUG_HEURISTIC
// #define DEBUG_JA 1
/* #define DEBUG_FINGERPRINT 1 */
/* #define DEBUG_ENCRYPTED_SNI 1 */
/* **************************************** */
/*
JA3
https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967
JA4
https://github.com/FoxIO-LLC/ja4/blob/main/technical_details/JA4.md
*/
#define JA_STR_LEN 1024
union ndpi_ja_info {
ndpi_tls_client_info client;
ndpi_tls_server_info server;
};
/*
NOTE
How to view the certificate fingerprint
1. Using wireshark save the certificate on certificate.bin file as explained
in https://security.stackexchange.com/questions/123851/how-can-i-extract-the-certificate-from-this-pcap-file
2. openssl x509 -inform der -in certificate.bin -text > certificate.der
3. openssl x509 -noout -fingerprint -sha1 -inform pem -in certificate.der
SHA1 Fingerprint=15:9A:76....
$ shasum -a 1 www.grc.com.bin
159a76.....
*/
#define NDPI_MAX_TLS_REQUEST_SIZE 10000
#define TLS_THRESHOLD 34387200 /* Threshold for certificate validity */
#define TLS_LIMIT_DATE 1598918400 /* From 01/09/2020 TLS certificates lifespan is limited to 13 months */
static void ndpi_int_tls_add_connection(struct ndpi_detection_module_struct *ndpi_struct,
struct ndpi_flow_struct *flow);
/* **************************************** */
static bool str_contains_digit(char *str) {
u_int i = 0;
for(i=0; (str[i] != '.') && (str[i] != '\0'); i++) {
if(isdigit(str[i]))
return(true);
}
return(false);
}
/* **************************************** */
/* TODO: rename */
static int keep_extra_dissection_tcp(struct ndpi_detection_module_struct *ndpi_struct,
struct ndpi_flow_struct *flow) {
if(ndpi_struct->cfg.tls_max_num_blocks_to_analyze > 0)
return(1); /* Process as much TLS blocks as the max packet number */
/* Common path: found handshake on both directions */
if(
(flow->tls_quic.certificate_processed == 1 && flow->protos.tls_quic.client_hello_processed)
/* Application Data on both directions: handshake already ended (did we miss it?) */
|| (flow->l4.tcp.tls.app_data_seen[0] == 1 && flow->l4.tcp.tls.app_data_seen[1] == 1)
/* Handshake on one direction and Application Data on the other */
|| ((flow->protos.tls_quic.client_hello_processed && flow->l4.tcp.tls.app_data_seen[!flow->protos.tls_quic.ch_direction] == 1) ||
(flow->protos.tls_quic.server_hello_processed && flow->l4.tcp.tls.app_data_seen[flow->protos.tls_quic.ch_direction] == 1))
) {
return 0;
}
/* Non-warning alert */
if(flow->tls_quic.alert)
return 0;
/* Are we interested only in the (sub)-classification? */
if(/* Subclassification */
flow->detected_protocol_stack[1] != NDPI_PROTOCOL_UNKNOWN &&
/* No metadata from SH or certificate */
!ndpi_struct->cfg.tls_alpn_negotiated_enabled &&
!ndpi_struct->cfg.tls_cipher_enabled &&
!ndpi_struct->cfg.tls_sha1_fingerprint_enabled &&
!ndpi_struct->cfg.tls_cert_server_names_enabled &&
!ndpi_struct->cfg.tls_cert_validity_enabled &&
!ndpi_struct->cfg.tls_cert_issuer_enabled &&
!ndpi_struct->cfg.tls_cert_subject_enabled &&
!ndpi_struct->cfg.tls_browser_enabled &&
!ndpi_struct->cfg.tls_ja3s_fingerprint_enabled &&
/* No flow risks from SH or certificate: we should have disabled all
metadata needed for flow risks, so we should not need to explicitly
check them */
/* Ookla aggressiveness has no impact here because it is evaluated only
without sub-classification */
/* TLS heuristics */
(ndpi_struct->cfg.tls_heuristics == 0 || is_flow_addr_informative(flow))) {
return 0;
}
return 1;
}
/* **************************************** */
/* Heuristic to detect proxied/obfuscated TLS flows, based on
https://www.usenix.org/conference/usenixsecurity24/presentation/xue-fingerprinting.
Main differences between the paper and our implementation:
* only Mahalanobis Distance, no Chi-squared Test
* instead of 3-grams, we use 4-grams, always starting from the Client -> Server direction
* consecutive packets in the same direction always belong to the same burst/flight
Core idea:
* the packets/bytes distribution of a TLS handshake is quite unique
* this fingerprint is still detectable if the handshake is
encrypted/proxied/obfuscated
*/
struct tls_obfuscated_heuristic_set {
u_int8_t stage;
u_int32_t bytes[4];
u_int32_t pkts[4];
};
struct tls_obfuscated_heuristic_state {
u_int8_t num_pkts;
/* Burst/flight: consecutive packets in the same direction.
* Set: packet/bytes distribution of 4 consecutive bursts (always starting from C->S),
i.e. a 4-grams (using the paper terminology)
* We have up tp 2 sets contemporarily active.
* At the first pkt of a new C->S flight, we close the oldest set and open a new one */
struct tls_obfuscated_heuristic_set sets[2];
};
static int check_set(struct ndpi_detection_module_struct* ndpi_struct,
struct tls_obfuscated_heuristic_set *set)
{
#ifdef NDPI_ENABLE_DEBUG_MESSAGES
struct ndpi_packet_struct* packet = &ndpi_struct->packet;
#endif
/* Model: TLS 1.2; Firefox; No session resumption/0rtt */
const float i_s_tls_12[4 * 4] = { 0.000292421113167604, 4.43677617831228E-07, -5.69966093492813E-05, -2.18124698406311E-06,
4.43677617831228E-07, 5.98954952745268E-07, -3.59798436724817E-07, 5.71638172955893E-07,
-5.69966093492813E-05, -3.59798436724817E-07, 0.00076893788148309, 2.22278496185964E-05,
-2.18124698406311E-06, 5.71638172955893E-07, 2.22278496185964E-05, 5.72770077086287E-05 };
const float average_tls_12[4] = { 212.883690341977, 4514.71195039459, 107.770762871101, 307.580232995115 };
const float distance_tls_12 = 3.5;
/* Model: TLS 1.3; Firefox; No session resumption/0rtt; no PQ; ECH(-grease) enabled */
const float i_s_tls_13[4 * 4] = { 3.08030337925007E-05, 1.16179172096944E-07, 1.05356744968627E-07, 3.8862884355278E-08,
1.16179172096944E-07, 6.93179117519316E-07, 2.77413220880937E-08, -3.63723200682445E-09,
1.05356744968627E-07, 2.77413220880937E-08, 1.0260950589675E-06, -1.08769813590053E-08,
3.88628843552779E-08, -3.63723200682445E-09, -1.08769813590053E-08, 8.63307792288604E-08 };
const float average_tls_13[4] = { 640.657378447541, 4649.30338356554, 448.408302530566, 1094.2013079329};
const float distance_tls_13 = 3.0;
/* Model: TLS 1.2/1.3; Chrome; No session resumption/0rtt; PQ; ECH(-grease) enabled */
const float i_s_chrome[4 * 4] = { 6.72374390966642E-06, -2.32109583941723E-08, 6.67140014394388E-08, 1.2526322628285E-08,
-2.32109583941723E-08, 5.64668947932086E-07, 4.58963631972597E-08, 6.41254684791958E-09,
6.67140014394388E-08, 4.58963631972597E-08, 6.04057768431344E-07, -9.1507432597718E-10,
1.2526322628285E-08, 6.41254684791958E-09, -9.1507432597718E-10, 1.01184796635481E-07 };
const float average_chrome[4] = { 1850.43045387994, 4903.07735480722, 785.25280624695, 1051.22303562714 };
const float distance_chrome = 3.0;
/* TODO: * ECH/PQ are still under development/deployment -> re-evaluate these models
* Session resumptions/0rtt
* Non-web traffic */
/* This is the only logic about pkts distributions.
ClientHello shoudn't be splitted in too many fragments: usually 1; 2 with PQ */
if(set->pkts[0] > 3) {
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: too many pkts in the first burst %d\n", set->pkts[0]);
return 0;
}
if(ndpi_mahalanobis_distance(set->bytes, 4, average_chrome, i_s_chrome) < distance_chrome ||
/* To avoid false positives: we didn't find TLS 1.3 CH smaller than 517 */
(set->bytes[0] >= 517 && ndpi_mahalanobis_distance(set->bytes, 4, average_tls_13, i_s_tls_13) < distance_tls_13) ||
ndpi_mahalanobis_distance(set->bytes, 4, average_tls_12, i_s_tls_12) < distance_tls_12) {
NDPI_LOG_DBG(ndpi_struct, "TLS-Obf-Heur: md %f %f %f [%d/%d/%d/%d %d/%d/%d/%d] TCP? %d\n",
ndpi_mahalanobis_distance(set->bytes, 4, average_tls_12, i_s_tls_12),
ndpi_mahalanobis_distance(set->bytes, 4, average_tls_13, i_s_tls_13),
ndpi_mahalanobis_distance(set->bytes, 4, average_chrome, i_s_chrome),
set->pkts[0], set->pkts[1], set->pkts[2], set->pkts[3],
set->bytes[0], set->bytes[1], set->bytes[2], set->bytes[3],
!!packet->tcp);
return 1;
}
return 0;
}
/* **************************************** */
static int tls_obfuscated_heur_search(struct ndpi_detection_module_struct* ndpi_struct,
struct ndpi_flow_struct* flow) {
struct ndpi_packet_struct* packet = &ndpi_struct->packet;
struct tls_obfuscated_heuristic_state *state = flow->tls_quic.obfuscated_heur_state;
struct tls_obfuscated_heuristic_set *set;
int i, j;
int is_tls_in_tls_heur = 0;
int byte_overhead;
/* Stages:
0: Unused/Start
1: C->S : burst 1
2: S->C : burst 2
3: C->S : burst 3
4: S->C : burst 4
5: C->S : End
*/
if(!state)
return 1; /* Exclude */
if(packet->payload_packet_len == 0)
return 0; /* Continue */
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: num_pkts %d\n", state->num_pkts);
if(flow->extra_packets_func &&
(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_TLS ||
flow->detected_protocol_stack[1] == NDPI_PROTOCOL_TLS)) /* TLS-in-TLS heuristic */
is_tls_in_tls_heur = 1;
/* We try to keep into account the overhead (header/padding/mac/iv/nonce) of the
external layers (i.e. above the TLS hanshake we are trying to detect) */
if(is_tls_in_tls_heur == 1) {
/* According to https://datatracker.ietf.org/doc/html/draft-mattsson-uta-tls-overhead-01
the average packet overhead for TLS is 29 bytes.
TODO: this draft is OLD and about TLS 1.2
Looking at real traffic, we found that we can have TLS packets 24 bytes long
*/
byte_overhead = 24;
} else {
/* The paper says that the overhead is usually quite small
["typically ranging between 20 to 60 bytes"], without any citations.
From the tests, it seams that we can ignore it */
byte_overhead = 0;
}
if(packet->payload_packet_len < byte_overhead) {
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: packet too small. Stop.\n");
return 1; /* Exclude */
}
if(is_tls_in_tls_heur == 1) {
/* We usually stop processing TLS handshake (and switch to this extra dissection
data path) after the FIRST Change-Cipher message. However, for this
heuristic, we need to ignore all packets before a Change-Cipher is sent in the
same direction */
if(current_pkt_from_client_to_server(ndpi_struct, flow) &&
flow->tls_quic.change_cipher_from_client == 0) {
if(packet->payload[0] == 0x14) {
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: Change-Cipher from client\n");
flow->tls_quic.change_cipher_from_client = 1;
}
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: skip\n");
return 0; /* Continue */
}
if(current_pkt_from_server_to_client(ndpi_struct, flow) &&
flow->tls_quic.change_cipher_from_server == 0) {
if(packet->payload[0] == 0x14) {
flow->tls_quic.change_cipher_from_server = 1;
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: Change-Cipher from server\n");
}
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: skip\n");
return 0; /* Continue */
}
}
if(state->num_pkts++ > ndpi_struct->cfg.tls_heuristics_max_packets) {
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: too many pkts. Stop\n");
return 1; /* Exclude */
}
/* Update active sets */
for(i = 0; i < 2; i ++) {
set = &state->sets[i];
switch(set->stage) {
case 0:
/* This happen only at the beginning of the heuristic: after the first pkt
of the third (absolute) burst, we always have both sets used */
if(i == 0 || state->sets[0].stage == 3) {
if(current_pkt_from_client_to_server(ndpi_struct, flow)) {
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: open set %d\n", i);
set->stage = 1;
break;
} else {
/* First packet should be always from client.
This shortcut makes detection harder if, before the obfuscated TLS hanshake
there is random traffic */
return 1; /* Exclude */
}
}
continue;
case 1:
if(current_pkt_from_server_to_client(ndpi_struct, flow))
set->stage = 2;
break;
case 2:
if(current_pkt_from_client_to_server(ndpi_struct, flow))
set->stage = 3;
break;
case 3:
if(current_pkt_from_server_to_client(ndpi_struct, flow))
set->stage = 4;
break;
case 4:
if(current_pkt_from_client_to_server(ndpi_struct, flow))
set->stage = 5;
break;
/* We cant have 5 here */
}
if(set->stage != 5) {
set->bytes[set->stage - 1] += (packet->payload_packet_len - byte_overhead);
set->pkts[set->stage - 1] += 1;
}
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: set %d stage %d bytes %d/%d/%d/%d pkts %d/%d/%d/%d\n",
i, set->stage,
set->bytes[0], set->bytes[1], set->bytes[2], set->bytes[3],
set->pkts[0], set->pkts[1], set->pkts[2], set->pkts[3]);
/* Check completed set */
if(set->stage == 5) {
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: set %d completed\n", i);
if(check_set(ndpi_struct, set)) {
/* Heuristic match */
return 2; /* Found */
} else {
/* Close this set and open a new one... */
set->stage = 1;
set->bytes[0] = packet->payload_packet_len - byte_overhead;
set->pkts[0] = 1;
for(j = 1; j < 4; j++) {
set->bytes[j] = 0;
set->pkts[j] = 0;
}
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: set %d closed and reused\n", i);
}
}
}
return 0; /* Continue */
}
/* **************************************** */
static int tls_obfuscated_heur_search_again(struct ndpi_detection_module_struct* ndpi_struct,
struct ndpi_flow_struct* flow) {
int rc;
NDPI_LOG_DBG2(ndpi_struct, "TLS-Obf-Heur: extra dissection\n");
rc = tls_obfuscated_heur_search(ndpi_struct, flow);
if(rc == 0)
return 1; /* Keep working */
if(rc == 2) {
NDPI_LOG_DBG(ndpi_struct, "TLS-Obf-Heur: found!\n");
/* Right now, if an heuritic matches, we set the classification/risk.
TODO: avoid false positives!
Some ideas:
* try to identify the servers: we wait for multiple sessions to the same server,
before to start marking the flows to that address
* consider the number of burst after TLS handshake (see Fig 8 paper) */
if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) {
ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, NDPI_PROTOCOL_UNKNOWN, NDPI_CONFIDENCE_DPI_AGGRESSIVE);
ndpi_set_risk(ndpi_struct, flow, NDPI_OBFUSCATED_TRAFFIC, "Obfuscated TLS traffic");
} else {
flow->confidence = NDPI_CONFIDENCE_DPI_AGGRESSIVE; /* Update the value */
if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_TLS ||
flow->detected_protocol_stack[1] == NDPI_PROTOCOL_TLS)
ndpi_set_risk(ndpi_struct, flow, NDPI_OBFUSCATED_TRAFFIC, "Obfuscated TLS-in-TLS traffic");
else
ndpi_set_risk(ndpi_struct, flow, NDPI_OBFUSCATED_TRAFFIC, "Obfuscated TLS-in-HTTP-WebSocket traffic");
}
ndpi_master_app_protocol proto;
proto.master_protocol = ndpi_get_master_proto(ndpi_struct, flow);
proto.app_protocol = NDPI_PROTOCOL_UNKNOWN;
flow->category = get_proto_category(ndpi_struct, proto);
flow->breed = get_proto_breed(ndpi_struct, proto);
}
NDPI_EXCLUDE_DISSECTOR(ndpi_struct, flow); /* Not necessary in extra-dissection data path,
but we need it with the plain heuristic */
return 0; /* Stop */
}
/* **************************************** */
void switch_extra_dissection_to_tls_obfuscated_heur(struct ndpi_detection_module_struct* ndpi_struct,
struct ndpi_flow_struct* flow)
{
NDPI_LOG_DBG(ndpi_struct, "Switching to TLS Obfuscated heuristic\n");
if(flow->tls_quic.obfuscated_heur_state == NULL)
flow->tls_quic.obfuscated_heur_state = ndpi_calloc(1, sizeof(struct tls_obfuscated_heuristic_state));
else /* If state has been already allocated (because of NDPI_HEURISTICS_TLS_OBFUSCATED_PLAIN) reset it */
memset(flow->tls_quic.obfuscated_heur_state, '\0', sizeof(struct tls_obfuscated_heuristic_state));
/* "* 2" to take into account ACKs. The "real" check is performend against
"tls_heuristics_max_packets" in tls_obfuscated_heur_search, as expected */
flow->max_extra_packets_to_check = ndpi_struct->cfg.tls_heuristics_max_packets * 2;
flow->extra_packets_func = tls_obfuscated_heur_search_again;
}
/* **************************************** */
static int ndpi_search_tls_memory(const u_int8_t *payload,
u_int16_t payload_len,
u_int32_t seq,
message_t *message) {
u_int avail_bytes;
#ifdef DEBUG_TLS_MEMORY
printf("[TLS Mem] Handling TLS flow [payload_len: %u][buffer_len: %u]\n",
payload_len,
message->buffer_len);
#endif
if(message->buffer == NULL) {
/* Allocate buffer */
message->buffer_len = 2048, message->buffer_used = 0;
message->buffer = (u_int8_t*)ndpi_malloc(message->buffer_len);
if(message->buffer == NULL)
return -1;
#ifdef DEBUG_TLS_MEMORY
printf("[TLS Mem] Allocating %u buffer\n", message->buffer_len);
#endif
}
avail_bytes = message->buffer_len - message->buffer_used;
if(avail_bytes < payload_len) {
u_int new_len = message->buffer_len + payload_len - avail_bytes + 1;
void *newbuf = ndpi_realloc(message->buffer, new_len);
if(!newbuf) return -1;
#ifdef DEBUG_TLS_MEMORY
printf("[TLS Mem] Enlarging %u -> %u buffer\n", message->buffer_len, new_len);
#endif
message->buffer = (u_int8_t*)newbuf;
message->buffer_len = new_len;
avail_bytes = message->buffer_len - message->buffer_used;
}
if(payload_len > 0 && avail_bytes >= payload_len) {
u_int8_t ok = 0;
if(message->next_seq != 0) {
if(seq == message->next_seq)
ok = 1;
} else
ok = 1;
if(ok) {
memcpy(&message->buffer[message->buffer_used],
payload, payload_len);
message->buffer_used += payload_len;
#ifdef DEBUG_TLS_MEMORY
printf("[TLS Mem] Copied data to buffer [%u/%u bytes][tcp_seq: %u][next: %u]\n",
message->buffer_used, message->buffer_len,
seq,
seq + payload_len);
#endif
message->next_seq = seq + payload_len;
} else {
#ifdef DEBUG_TLS_MEMORY
printf("[TLS Mem] Skipping packet [%u bytes][tcp_seq: %u][expected next: %u]\n",
message->buffer_len,
seq,
message->next_seq);
#endif
}
}
return 0;
}
/* **************************************** */
static void cleanupServerName(char *buffer, u_int buffer_len) {
u_int i;
/* Now all lowecase */
for(i=0; i<buffer_len; i++)
buffer[i] = tolower(buffer[i]);
}
/* **************************************** */
/*
Return code
-1: error (buffer too short)
0: OK but buffer is not human readeable (so something went wrong)
1: OK
*/
static int extractRDNSequence(struct ndpi_packet_struct *packet,
u_int offset, char *buffer, u_int buffer_len,
char *rdnSeqBuf, u_int *rdnSeqBuf_offset,
u_int rdnSeqBuf_len,
const char *label) {
u_int8_t str_len, is_printable = 1;
char *str;
u_int len;
if(*rdnSeqBuf_offset >= rdnSeqBuf_len) {
#ifdef DEBUG_TLS
printf("[TLS] %s() [buffer capacity reached][%u]\n",
__FUNCTION__, rdnSeqBuf_len);
#endif
return -1;
}
if((offset+4) >= packet->payload_packet_len)
return(-1);
str_len = packet->payload[offset+4];
// packet is truncated... further inspection is not needed
if((offset+4+str_len) >= packet->payload_packet_len)
return(-1);
str = (char*)&packet->payload[offset+5];
len = (u_int)ndpi_min(str_len, buffer_len-1);
strncpy(buffer, str, len);
buffer[len] = '\0';
// check string is printable
is_printable = ndpi_normalize_printable_string(buffer, len);
if(is_printable) {
int rc = ndpi_snprintf(&rdnSeqBuf[*rdnSeqBuf_offset],
rdnSeqBuf_len-(*rdnSeqBuf_offset),
"%s%s=%s", (*rdnSeqBuf_offset > 0) ? ", " : "",
label, buffer);
if(rc > 0 && ((u_int)rc > rdnSeqBuf_len-(*rdnSeqBuf_offset)))
return -1; /* Truncated; not enough buffer */
if(rc > 0)
(*rdnSeqBuf_offset) += rc;
}
return(is_printable);
}
/* **************************************** */
static u_int64_t make_tls_cert_key(struct ndpi_packet_struct *packet, int is_from_client)
{
u_int64_t key;
/* Server ip/port */
if(packet->iphv6 == NULL) {
if(packet->tcp) {
if(is_from_client)
key = ((u_int64_t)packet->iph->daddr << 32) | packet->tcp->dest;
else
key = ((u_int64_t)packet->iph->saddr << 32) | packet->tcp->source;
} else {
if(is_from_client)
key = ((u_int64_t)packet->iph->daddr << 32) | packet->udp->dest;
else
key = ((u_int64_t)packet->iph->saddr << 32) | packet->udp->source;
}
} else {
if(packet->tcp) {
if(is_from_client)
key = (ndpi_quick_hash64((const char *)&packet->iphv6->ip6_dst, 16) << 16) | packet->tcp->dest;
else
key = (ndpi_quick_hash64((const char *)&packet->iphv6->ip6_src, 16) << 16) | packet->tcp->source;
} else {
if(is_from_client)
key = (ndpi_quick_hash64((const char *)&packet->iphv6->ip6_dst, 16) << 16) | packet->udp->dest;
else
key = (ndpi_quick_hash64((const char *)&packet->iphv6->ip6_src, 16) << 16) | packet->udp->source;
}
}
return key;
}
/* **************************************** */
static void checkTLSSubprotocol(struct ndpi_detection_module_struct *ndpi_struct,
struct ndpi_flow_struct *flow,
int is_from_client) {
struct ndpi_packet_struct *packet = &ndpi_struct->packet;
if(ndpi_struct->cfg.tls_subclassification_enabled &&
flow->detected_protocol_stack[1] == NDPI_PROTOCOL_UNKNOWN) {
/* Subprotocol not yet set */
if(ndpi_struct->tls_cert_cache) {
u_int16_t cached_proto;
u_int64_t key;
key = make_tls_cert_key(packet, is_from_client);
if(ndpi_lru_find_cache(ndpi_struct->tls_cert_cache, key,
&cached_proto, 0 /* Don't remove it as it can be used for other connections */,
ndpi_get_current_time(flow))) {
ndpi_master_app_protocol proto;
ndpi_set_detected_protocol(ndpi_struct, flow, cached_proto, ndpi_get_master_proto(ndpi_struct, flow), NDPI_CONFIDENCE_DPI_CACHE);
proto.master_protocol = ndpi_get_master_proto(ndpi_struct, flow);
proto.app_protocol = cached_proto;
flow->category = get_proto_category(ndpi_struct, proto);
flow->breed = get_proto_breed(ndpi_struct, proto);
ndpi_check_subprotocol_risk(ndpi_struct, flow, cached_proto);
ndpi_unset_risk(ndpi_struct, flow, NDPI_NUMERIC_IP_HOST);
}
}
}
}
/* **************************************** */
/* See https://blog.catchpoint.com/2017/05/12/dissecting-tls-using-wireshark/ */
void processCertificateElements(struct ndpi_detection_module_struct *ndpi_struct,
struct ndpi_flow_struct *flow,
u_int16_t p_offset, u_int16_t certificate_len) {
struct ndpi_packet_struct *packet = &ndpi_struct->packet;
u_int16_t num_found = 0;
int32_t i;
char buffer[64] = { '\0' }, rdnSeqBuf[2048];
u_int rdn_len = 0;
rdnSeqBuf[0] = '\0';
#ifdef DEBUG_TLS
printf("[TLS] %s() [offset: %u][certificate_len: %u]\n", __FUNCTION__, p_offset, certificate_len);
#endif
/* Check after handshake protocol header (5 bytes) and message header (4 bytes) */
for(i = p_offset; i < certificate_len - 2; i++) {
/*
See https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.sec.doc/q009860_.htm
for X.509 certificate labels
*/
if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x03)) {
/* Common Name */
int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "CN");
if(rc == -1) break;
#ifdef DEBUG_TLS
printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Common Name", buffer);
#endif
} else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x06)) {
/* Country */
int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "C");
if(rc == -1) break;
#ifdef DEBUG_TLS
printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Country", buffer);
#endif
} else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x07)) {
/* Locality */
int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "L");
if(rc == -1) break;
#ifdef DEBUG_TLS
printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Locality", buffer);
#endif
} else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x08)) {
/* State or Province */
int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "ST");
if(rc == -1) break;
#ifdef DEBUG_TLS
printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "State or Province", buffer);
#endif
} else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0a)) {
/* Organization Name */
int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "O");
if(rc == -1) break;
#ifdef DEBUG_TLS
printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Name", buffer);
#endif
} else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0b)) {
/* Organization Unit */
int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "OU");
if(rc == -1) break;
#ifdef DEBUG_TLS
printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Unit", buffer);
#endif
} else if((packet->payload[i] == 0x30) && (packet->payload[i+1] == 0x1e) && (packet->payload[i+2] == 0x17)) {
/* Certificate Validity */
u_int offset = i+4;
if(num_found == 0) {
num_found++;
#ifdef DEBUG_TLS
printf("[TLS] %s() IssuerDN [%s]\n", __FUNCTION__, rdnSeqBuf);
#endif
if(rdn_len && (flow->protos.tls_quic.issuerDN == NULL) &&
ndpi_struct->cfg.tls_cert_issuer_enabled) {
flow->protos.tls_quic.issuerDN = ndpi_strdup(rdnSeqBuf);
if(ndpi_normalize_printable_string(rdnSeqBuf, rdn_len) == 0) {
if(is_flowrisk_info_enabled(ndpi_struct, NDPI_INVALID_CHARACTERS)) {
char str[64];
snprintf(str, sizeof(str), "Invalid issuerDN %s", flow->protos.tls_quic.issuerDN);
ndpi_set_risk(ndpi_struct, flow, NDPI_INVALID_CHARACTERS, str);
} else {
ndpi_set_risk(ndpi_struct, flow, NDPI_INVALID_CHARACTERS, NULL);
}
}
}
rdn_len = 0; /* Reset buffer */
}
if(i + 3 < certificate_len &&
(offset+packet->payload[i+3]) < packet->payload_packet_len &&
ndpi_struct->cfg.tls_cert_validity_enabled) {
char utcDate[32];
u_int8_t len = packet->payload[i+3];
#ifdef DEBUG_TLS
u_int j;
printf("[CERTIFICATE] notBefore [len: %u][", len);
for(j=0; j<len; j++) printf("%c", packet->payload[i+4+j]);
printf("]\n");
#endif
if(len < (sizeof(utcDate)-1)) {
struct tm utc;
utc.tm_isdst = -1; /* Not set by strptime */
strncpy(utcDate, (const char*)&packet->payload[i+4], len);
utcDate[len] = '\0';
/* 141021000000Z */
if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) {
flow->protos.tls_quic.notBefore = timegm(&utc);
#ifdef DEBUG_TLS
printf("[CERTIFICATE] notBefore %u [%s]\n",
flow->protos.tls_quic.notBefore, utcDate);
#endif
}
}
offset += len;
if((offset+1) < packet->payload_packet_len) {
len = packet->payload[offset+1];
offset += 2;
if((offset+len) < packet->payload_packet_len) {
u_int32_t time_sec = packet->current_time_ms / 1000;
#ifdef DEBUG_TLS
u_int j;
printf("[CERTIFICATE] notAfter [len: %u][", len);
for(j=0; j<len; j++) printf("%c", packet->payload[offset+j]);
printf("]\n");
#endif
if(len < (sizeof(utcDate)-1)) {
struct tm utc;
utc.tm_isdst = -1; /* Not set by strptime */
strncpy(utcDate, (const char*)&packet->payload[offset], len);
utcDate[len] = '\0';
/* 141021000000Z */
if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) {
flow->protos.tls_quic.notAfter = timegm(&utc);
#ifdef DEBUG_TLS
printf("[CERTIFICATE] notAfter %u [%s]\n",
flow->protos.tls_quic.notAfter, utcDate);
#endif
}
}
if(flow->protos.tls_quic.notBefore > TLS_LIMIT_DATE)
if((flow->protos.tls_quic.notAfter-flow->protos.tls_quic.notBefore) > TLS_THRESHOLD) {
if(is_flowrisk_info_enabled(ndpi_struct, NDPI_TLS_CERT_VALIDITY_TOO_LONG)) {
char str[64];
snprintf(str, sizeof(str), "TLS Cert lasts %u days",
(flow->protos.tls_quic.notAfter-flow->protos.tls_quic.notBefore) / 86400);
ndpi_set_risk(ndpi_struct, flow, NDPI_TLS_CERT_VALIDITY_TOO_LONG, str); /* Certificate validity longer than 13 months */
} else {
ndpi_set_risk(ndpi_struct, flow, NDPI_TLS_CERT_VALIDITY_TOO_LONG, NULL);
}
}
if((time_sec < flow->protos.tls_quic.notBefore) || (time_sec > flow->protos.tls_quic.notAfter)) {
if(is_flowrisk_info_enabled(ndpi_struct, NDPI_TLS_CERTIFICATE_EXPIRED)) {
char str[96], b[32], e[32];
struct tm result;
time_t theTime;
theTime = flow->protos.tls_quic.notBefore;
strftime(b, sizeof(b), "%d/%b/%Y %H:%M:%S", ndpi_gmtime_r(&theTime, &result));
theTime = flow->protos.tls_quic.notAfter;
strftime(e, sizeof(e), "%d/%b/%Y %H:%M:%S", ndpi_gmtime_r(&theTime, &result));
snprintf(str, sizeof(str), "%s - %s", b, e);
ndpi_set_risk(ndpi_struct, flow, NDPI_TLS_CERTIFICATE_EXPIRED, str); /* Certificate expired */
} else {
ndpi_set_risk(ndpi_struct, flow, NDPI_TLS_CERTIFICATE_EXPIRED, NULL);
}
} else if((time_sec > flow->protos.tls_quic.notBefore)
&& (time_sec > (flow->protos.tls_quic.notAfter - (ndpi_struct->cfg.tls_certificate_expire_in_x_days * 86400)))) {
if(is_flowrisk_info_enabled(ndpi_struct, NDPI_TLS_CERTIFICATE_ABOUT_TO_EXPIRE)) {
char str[96], b[32], e[32];
struct tm result;
time_t theTime;
theTime = flow->protos.tls_quic.notBefore;
strftime(b, sizeof(b), "%d/%b/%Y %H:%M:%S", ndpi_gmtime_r(&theTime, &result));
theTime = flow->protos.tls_quic.notAfter;
strftime(e, sizeof(e), "%d/%b/%Y %H:%M:%S", ndpi_gmtime_r(&theTime, &result));
snprintf(str, sizeof(str), "%s - %s", b, e);
ndpi_set_risk(ndpi_struct, flow, NDPI_TLS_CERTIFICATE_ABOUT_TO_EXPIRE, str); /* Certificate almost expired */
} else {
ndpi_set_risk(ndpi_struct, flow, NDPI_TLS_CERTIFICATE_ABOUT_TO_EXPIRE, NULL);
}
}
}
}
}
} else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x1d) && (packet->payload[i+2] == 0x11)) {
/* Organization OID: 2.5.29.17 (subjectAltName) */
u_int8_t matched_name = 0;
/* If the client hello was not observed or the requested name was missing, there is no need to trigger an alert */
if(flow->host_server_name[0] == '\0')
matched_name = 1;
#ifdef DEBUG_TLS
printf("******* [TLS] Found subjectAltName\n");
#endif
i += 3 /* skip the initial patten 55 1D 11 */;
/* skip the first type, 0x04 == BIT STRING, and jump to it's length */
if(i < packet->payload_packet_len && packet->payload[i] == 0x04) i++; else i += 4; /* 4 bytes, with the last byte set to 04 */
if(i < packet->payload_packet_len) {
i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip BIT STRING length */
if(i < packet->payload_packet_len) {
i += 2; /* skip the second type, 0x30 == SEQUENCE, and jump to it's length */
if(i < packet->payload_packet_len) {
i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip SEQUENCE length */
i++;
while(i < packet->payload_packet_len) {
u_int8_t general_name_type = packet->payload[i];
if((general_name_type == 0x81) /* rfc822Name */
|| (general_name_type == 0x82) /* dNSName */
|| (general_name_type == 0x87) /* ipAddress */
)
{
if((i < (packet->payload_packet_len - 1))
&& ((i + packet->payload[i + 1] + 2) < packet->payload_packet_len)) {
u_int8_t len = packet->payload[i + 1];
char dNSName[256];
u_int16_t dNSName_len;
i += 2;
/* The check "len > sizeof(dNSName) - 1" will be always false. If we add it,
the compiler is smart enough to detect it and throws a warning */
if((len == 0 /* Looks something went wrong */)
|| ((i+len) > packet->payload_packet_len))
break;
if(general_name_type == 0x87) {
if(len == 4 /* IPv4 */) {
ndpi_snprintf(dNSName, sizeof(dNSName), "%u.%u.%u.%u",
packet->payload[i] & 0xFF,
packet->payload[i+1] & 0xFF,
packet->payload[i+2] & 0xFF,
packet->payload[i+3] & 0xFF);
} else if(len == 16 /* IPv6 */) {
struct in6_addr addr = *(struct in6_addr *)&packet->payload[i];
inet_ntop(AF_INET6, &addr, dNSName, sizeof(dNSName));
} else {
/* Is that possibile? Better safe than sorry */
dNSName[0] = '\0';
}
} else {
strncpy(dNSName, (const char*)&packet->payload[i], len);
dNSName[len] = '\0';
}
dNSName_len = strlen(dNSName);
cleanupServerName(dNSName, dNSName_len);
#if DEBUG_TLS
printf("[TLS] dNSName %s [%s][len: %u][leftover: %d]\n", dNSName,
flow->host_server_name, len,
packet->payload_packet_len-i-len);
#endif
/*
We cannot use ndpi_is_valid_hostname() as we can have wildcards
here that will create false positives
*/
if(ndpi_normalize_printable_string(dNSName, dNSName_len) == 0) {
ndpi_set_risk(ndpi_struct, flow, NDPI_INVALID_CHARACTERS, dNSName);
/* This looks like an attack */
ndpi_set_risk(ndpi_struct, flow, NDPI_POSSIBLE_EXPLOIT, "Invalid dNSName name");
}
if(matched_name == 0) {
#if DEBUG_TLS
printf("[TLS] Trying to match '%s' with '%s'\n",
flow->host_server_name, dNSName);
#endif
if(dNSName[0] == '*') {
char * label = strstr(flow->host_server_name, &dNSName[1]);
if(label != NULL) {
char * first_dot = strchr(flow->host_server_name, '.');
if((first_dot == NULL) || (first_dot <= label)) {
matched_name = 1;
}
}