forked from OISF/suricata
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp-layer-htp.c
More file actions
5728 lines (4875 loc) · 196 KB
/
Copy pathapp-layer-htp.c
File metadata and controls
5728 lines (4875 loc) · 196 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
/* Copyright (C) 2007-2024 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \ingroup httplayer
*
* @{
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
* \author Pablo Rincon <pablo.rincon.crespo@gmail.com>
* \author Brian Rectanus <brectanu@gmail.com>
* \author Anoop Saldanha <anoopsaldanha@gmail.com>
*
* This file provides a HTTP protocol support for the engine using HTP library.
*/
#include "suricata.h"
#include "suricata-common.h"
#include "conf.h"
#include "decode.h"
#include "util-print.h"
#include "util-byte.h"
#include "stream-tcp.h"
#include "app-layer-protos.h"
#include "app-layer-parser.h"
#include "app-layer.h"
#include "app-layer-detect-proto.h"
#include "app-layer-frames.h"
#include "app-layer-htp.h"
#include "app-layer-htp-body.h"
#include "app-layer-htp-file.h"
#include "app-layer-htp-xff.h"
#include "app-layer-htp-range.h"
#include "app-layer-htp-mem.h"
#include "app-layer-events.h"
#include "util-debug.h"
#include "util-misc.h"
#include "util-unittest.h"
#include "util-unittest-helper.h"
#include "flow-util.h"
#include "detect-engine.h"
#include "detect-engine-build.h"
#include "detect-engine-state.h"
#include "detect-parse.h"
#include "util-memcmp.h"
#include "util-random.h"
#include "util-validate.h"
//#define PRINT
/** Fast lookup tree (radix) for the various HTP configurations */
static struct HTPConfigTree {
SCRadix4Tree ipv4;
SCRadix6Tree ipv6;
} cfgtree = {
.ipv4 = SC_RADIX4_TREE_INITIALIZER,
.ipv6 = SC_RADIX6_TREE_INITIALIZER,
};
SCRadix4Config htp_radix4_cfg = { NULL, NULL };
SCRadix6Config htp_radix6_cfg = { NULL, NULL };
/** List of HTP configurations. */
static HTPCfgRec cfglist;
StreamingBufferConfig htp_sbcfg = STREAMING_BUFFER_CONFIG_INITIALIZER;
/** Limit to the number of libhtp messages that can be handled */
#define HTP_MAX_MESSAGES 512
SC_ATOMIC_DECLARE(uint32_t, htp_config_flags);
#ifdef DEBUG
static SCMutex htp_state_mem_lock = SCMUTEX_INITIALIZER;
static uint64_t htp_state_memuse = 0;
static uint64_t htp_state_memcnt = 0;
#endif
SCEnumCharMap http_decoder_event_table[] = {
{ "UNKNOWN_ERROR", HTP_LOG_CODE_UNKNOWN },
{ "GZIP_DECOMPRESSION_FAILED", HTP_LOG_CODE_GZIP_DECOMPRESSION_FAILED },
{ "REQUEST_FIELD_MISSING_COLON", HTP_LOG_CODE_REQUEST_FIELD_MISSING_COLON },
{ "RESPONSE_FIELD_MISSING_COLON", HTP_LOG_CODE_RESPONSE_FIELD_MISSING_COLON },
{ "INVALID_REQUEST_CHUNK_LEN", HTP_LOG_CODE_INVALID_REQUEST_CHUNK_LEN },
{ "INVALID_RESPONSE_CHUNK_LEN", HTP_LOG_CODE_INVALID_RESPONSE_CHUNK_LEN },
{ "INVALID_TRANSFER_ENCODING_VALUE_IN_REQUEST",
HTP_LOG_CODE_INVALID_TRANSFER_ENCODING_VALUE_IN_REQUEST },
{ "INVALID_TRANSFER_ENCODING_VALUE_IN_RESPONSE",
HTP_LOG_CODE_INVALID_TRANSFER_ENCODING_VALUE_IN_RESPONSE },
{ "INVALID_CONTENT_LENGTH_FIELD_IN_REQUEST",
HTP_LOG_CODE_INVALID_CONTENT_LENGTH_FIELD_IN_REQUEST },
{ "INVALID_CONTENT_LENGTH_FIELD_IN_RESPONSE",
HTP_LOG_CODE_INVALID_CONTENT_LENGTH_FIELD_IN_RESPONSE },
{ "DUPLICATE_CONTENT_LENGTH_FIELD_IN_REQUEST",
HTP_LOG_CODE_DUPLICATE_CONTENT_LENGTH_FIELD_IN_REQUEST },
{ "DUPLICATE_CONTENT_LENGTH_FIELD_IN_RESPONSE",
HTP_LOG_CODE_DUPLICATE_CONTENT_LENGTH_FIELD_IN_RESPONSE },
{ "100_CONTINUE_ALREADY_SEEN", HTP_LOG_CODE_CONTINUE_ALREADY_SEEN },
{ "UNABLE_TO_MATCH_RESPONSE_TO_REQUEST", HTP_LOG_CODE_UNABLE_TO_MATCH_RESPONSE_TO_REQUEST },
{ "INVALID_SERVER_PORT_IN_REQUEST", HTP_LOG_CODE_INVALID_SERVER_PORT_IN_REQUEST },
{ "INVALID_AUTHORITY_PORT", HTP_LOG_CODE_INVALID_AUTHORITY_PORT },
{ "REQUEST_HEADER_INVALID", HTP_LOG_CODE_REQUEST_HEADER_INVALID },
{ "RESPONSE_HEADER_INVALID", HTP_LOG_CODE_RESPONSE_HEADER_INVALID },
{ "MISSING_HOST_HEADER", HTP_LOG_CODE_MISSING_HOST_HEADER },
{ "HOST_HEADER_AMBIGUOUS", HTP_LOG_CODE_HOST_HEADER_AMBIGUOUS },
{ "INVALID_REQUEST_FIELD_FOLDING", HTP_LOG_CODE_INVALID_REQUEST_FIELD_FOLDING },
{ "INVALID_RESPONSE_FIELD_FOLDING", HTP_LOG_CODE_INVALID_RESPONSE_FIELD_FOLDING },
{ "REQUEST_FIELD_TOO_LONG", HTP_LOG_CODE_REQUEST_FIELD_TOO_LONG },
{ "RESPONSE_FIELD_TOO_LONG", HTP_LOG_CODE_RESPONSE_FIELD_TOO_LONG },
{ "REQUEST_LINE_INVALID", HTP_LOG_CODE_REQUEST_LINE_INVALID },
{ "REQUEST_BODY_UNEXPECTED", HTP_LOG_CODE_REQUEST_BODY_UNEXPECTED },
{ "RESPONSE_BODY_UNEXPECTED", HTP_LOG_CODE_RESPONSE_BODY_UNEXPECTED },
{ "REQUEST_SERVER_PORT_TCP_PORT_MISMATCH", HTP_LOG_CODE_REQUEST_SERVER_PORT_TCP_PORT_MISMATCH },
{ "REQUEST_URI_HOST_INVALID", HTP_LOG_CODE_URI_HOST_INVALID },
{ "REQUEST_HEADER_HOST_INVALID", HTP_LOG_CODE_HEADER_HOST_INVALID },
{ "REQUEST_AUTH_UNRECOGNIZED", HTP_LOG_CODE_AUTH_UNRECOGNIZED },
{ "REQUEST_HEADER_REPETITION", HTP_LOG_CODE_REQUEST_HEADER_REPETITION },
{ "RESPONSE_HEADER_REPETITION", HTP_LOG_CODE_RESPONSE_HEADER_REPETITION },
{ "DOUBLE_ENCODED_URI", HTP_LOG_CODE_DOUBLE_ENCODED_URI },
{ "URI_DELIM_NON_COMPLIANT", HTP_LOG_CODE_URI_DELIM_NON_COMPLIANT },
{ "METHOD_DELIM_NON_COMPLIANT", HTP_LOG_CODE_METHOD_DELIM_NON_COMPLIANT },
{ "REQUEST_LINE_LEADING_WHITESPACE", HTP_LOG_CODE_REQUEST_LINE_LEADING_WHITESPACE },
{ "TOO_MANY_ENCODING_LAYERS", HTP_LOG_CODE_TOO_MANY_ENCODING_LAYERS },
{ "REQUEST_TOO_MANY_LZMA_LAYERS", HTP_LOG_CODE_REQUEST_TOO_MANY_LZMA_LAYERS },
{ "RESPONSE_TOO_MANY_LZMA_LAYERS", HTP_LOG_CODE_RESPONSE_TOO_MANY_LZMA_LAYERS },
{ "ABNORMAL_CE_HEADER", HTP_LOG_CODE_ABNORMAL_CE_HEADER },
{ "RESPONSE_MULTIPART_BYTERANGES", HTP_LOG_CODE_RESPONSE_MULTIPART_BYTERANGES },
{ "RESPONSE_ABNORMAL_TRANSFER_ENCODING", HTP_LOG_CODE_RESPONSE_ABNORMAL_TRANSFER_ENCODING },
{ "RESPONSE_CHUNKED_OLD_PROTO", HTP_LOG_CODE_RESPONSE_CHUNKED_OLD_PROTO },
{ "RESPONSE_INVALID_PROTOCOL", HTP_LOG_CODE_RESPONSE_INVALID_PROTOCOL },
{ "RESPONSE_INVALID_STATUS", HTP_LOG_CODE_RESPONSE_INVALID_STATUS },
{ "REQUEST_LINE_INCOMPLETE", HTP_LOG_CODE_REQUEST_LINE_INCOMPLETE },
{ "PROTOCOL_CONTAINS_EXTRA_DATA", HTP_LOG_CODE_PROTOCOL_CONTAINS_EXTRA_DATA },
{
"CONTENT_LENGTH_EXTRA_DATA_START",
HTP_LOG_CODE_CONTENT_LENGTH_EXTRA_DATA_START,
},
{
"CONTENT_LENGTH_EXTRA_DATA_END",
HTP_LOG_CODE_CONTENT_LENGTH_EXTRA_DATA_END,
},
{ "SWITCHING_PROTO_WITH_CONTENT_LENGTH", HTP_LOG_CODE_SWITCHING_PROTO_WITH_CONTENT_LENGTH },
{ "DEFORMED_EOL", HTP_LOG_CODE_DEFORMED_EOL },
{ "PARSER_STATE_ERROR", HTP_LOG_CODE_PARSER_STATE_ERROR },
{ "MISSING_OUTBOUND_TRANSACTION_DATA", HTP_LOG_CODE_MISSING_OUTBOUND_TRANSACTION_DATA },
{ "MISSING_INBOUND_TRANSACTION_DATA", HTP_LOG_CODE_MISSING_INBOUND_TRANSACTION_DATA },
{ "ZERO_LENGTH_DATA_CHUNKS", HTP_LOG_CODE_ZERO_LENGTH_DATA_CHUNKS },
{ "REQUEST_LINE_UNKNOWN_METHOD", HTP_LOG_CODE_REQUEST_LINE_UNKNOWN_METHOD },
{ "REQUEST_LINE_UNKNOWN_METHOD_NO_PROTOCOL",
HTP_LOG_CODE_REQUEST_LINE_UNKNOWN_METHOD_NO_PROTOCOL },
{ "REQUEST_LINE_UNKNOWN_METHOD_INVALID_PROTOCOL",
HTP_LOG_CODE_REQUEST_LINE_UNKNOWN_METHOD_INVALID_PROTOCOL },
{ "REQUEST_LINE_MISSING_PROTOCOL", HTP_LOG_CODE_REQUEST_LINE_NO_PROTOCOL },
{ "RESPONSE_LINE_INVALID_PROTOCOL", HTP_LOG_CODE_RESPONSE_LINE_INVALID_PROTOCOL },
{ "RESPONSE_LINE_INVALID_RESPONSE_STATUS", HTP_LOG_CODE_RESPONSE_LINE_INVALID_RESPONSE_STATUS },
{ "RESPONSE_BODY_INTERNAL_ERROR", HTP_LOG_CODE_RESPONSE_BODY_INTERNAL_ERROR },
{ "REQUEST_BODY_DATA_CALLBACK_ERROR", HTP_LOG_CODE_REQUEST_BODY_DATA_CALLBACK_ERROR },
{ "RESPONSE_INVALID_EMPTY_NAME", HTP_LOG_CODE_RESPONSE_INVALID_EMPTY_NAME },
{ "REQUEST_INVALID_EMPTY_NAME", HTP_LOG_CODE_REQUEST_INVALID_EMPTY_NAME },
{ "RESPONSE_INVALID_LWS_AFTER_NAME", HTP_LOG_CODE_RESPONSE_INVALID_LWS_AFTER_NAME },
{ "RESPONSE_HEADER_NAME_NOT_TOKEN", HTP_LOG_CODE_RESPONSE_HEADER_NAME_NOT_TOKEN },
{ "REQUEST_INVALID_LWS_AFTER_NAME", HTP_LOG_CODE_REQUEST_INVALID_LWS_AFTER_NAME },
{ "LZMA_DECOMPRESSION_DISABLED", HTP_LOG_CODE_LZMA_DECOMPRESSION_DISABLED },
{ "CONNECTION_ALREADY_OPEN", HTP_LOG_CODE_CONNECTION_ALREADY_OPEN },
{ "COMPRESSION_BOMB_DOUBLE_LZMA", HTP_LOG_CODE_COMPRESSION_BOMB_DOUBLE_LZMA },
{ "INVALID_CONTENT_ENCODING", HTP_LOG_CODE_INVALID_CONTENT_ENCODING },
{ "INVALID_GAP", HTP_LOG_CODE_INVALID_GAP },
{ "REQUEST_CHUNK_EXTENSION", HTP_LOG_CODE_REQUEST_CHUNK_EXTENSION },
{ "RESPONSE_CHUNK_EXTENSION", HTP_LOG_CODE_RESPONSE_CHUNK_EXTENSION },
{ "LZMA_MEMLIMIT_REACHED", HTP_LOG_CODE_LZMA_MEMLIMIT_REACHED },
{ "COMPRESSION_BOMB", HTP_LOG_CODE_COMPRESSION_BOMB },
{ "REQUEST_TOO_MANY_HEADERS", HTP_LOG_CODE_REQUEST_TOO_MANY_HEADERS },
{ "RESPONSE_TOO_MANY_HEADERS", HTP_LOG_CODE_RESPONSE_TOO_MANY_HEADERS },
/* suricata warnings/errors */
{ "MULTIPART_GENERIC_ERROR", HTTP_DECODER_EVENT_MULTIPART_GENERIC_ERROR },
{ "MULTIPART_NO_FILEDATA", HTTP_DECODER_EVENT_MULTIPART_NO_FILEDATA },
{ "MULTIPART_INVALID_HEADER", HTTP_DECODER_EVENT_MULTIPART_INVALID_HEADER },
{ "TOO_MANY_WARNINGS", HTTP_DECODER_EVENT_TOO_MANY_WARNINGS },
{ "RANGE_INVALID", HTTP_DECODER_EVENT_RANGE_INVALID },
{ "FILE_NAME_TOO_LONG", HTTP_DECODER_EVENT_FILE_NAME_TOO_LONG },
{ "FAILED_PROTOCOL_CHANGE", HTTP_DECODER_EVENT_FAILED_PROTOCOL_CHANGE },
{ NULL, -1 },
};
/* app-layer-frame-documentation tag start: HttpFrameTypes */
enum HttpFrameTypes {
HTTP_FRAME_REQUEST,
HTTP_FRAME_RESPONSE,
};
SCEnumCharMap http_frame_table[] = {
{
"request",
HTTP_FRAME_REQUEST,
},
{
"response",
HTTP_FRAME_RESPONSE,
},
{ NULL, -1 },
};
/* app-layer-frame-documentation tag end: HttpFrameTypes */
static int HTTPGetFrameIdByName(const char *frame_name)
{
int id = SCMapEnumNameToValue(frame_name, http_frame_table);
if (id < 0) {
return -1;
}
return id;
}
static const char *HTTPGetFrameNameById(const uint8_t frame_id)
{
const char *name = SCMapEnumValueToName(frame_id, http_frame_table);
return name;
}
static SCEnumCharMap http_state_client_table[] = {
{
// name this "request_started" as the tx has been created
"request_started",
HTP_REQUEST_PROGRESS_NOT_STARTED,
},
{
"request_line",
HTP_REQUEST_PROGRESS_LINE,
},
{
"request_headers",
HTP_REQUEST_PROGRESS_HEADERS,
},
{
"request_body",
HTP_REQUEST_PROGRESS_BODY,
},
{
"request_trailer",
HTP_REQUEST_PROGRESS_TRAILER,
},
{
"request_complete",
HTP_REQUEST_PROGRESS_COMPLETE,
},
{ NULL, -1 },
};
static SCEnumCharMap http_state_server_table[] = {
{
// name this "response_started" as the tx has been created
"response_started",
HTP_RESPONSE_PROGRESS_NOT_STARTED,
},
{
"response_line",
HTP_RESPONSE_PROGRESS_LINE,
},
{
"response_headers",
HTP_RESPONSE_PROGRESS_HEADERS,
},
{
"response_body",
HTP_RESPONSE_PROGRESS_BODY,
},
{
"response_trailer",
HTP_RESPONSE_PROGRESS_TRAILER,
},
{
"response_complete",
HTP_RESPONSE_PROGRESS_COMPLETE,
},
{ NULL, -1 },
};
static int HtpStateGetStateIdByName(const char *name, const uint8_t direction)
{
SCEnumCharMap *map =
direction == STREAM_TOSERVER ? http_state_client_table : http_state_server_table;
int id = SCMapEnumNameToValue(name, map);
if (id < 0) {
return -1;
}
return id;
}
static const char *HtpStateGetStateNameById(const int id, const uint8_t direction)
{
SCEnumCharMap *map =
direction == STREAM_TOSERVER ? http_state_client_table : http_state_server_table;
const char *name = SCMapEnumValueToName(id, map);
return name;
}
static void *HTPStateGetTx(void *alstate, uint64_t tx_id);
static int HTPStateGetAlstateProgress(void *tx, uint8_t direction);
static uint64_t HTPStateGetTxCnt(void *alstate);
#ifdef UNITTESTS
static void HTPParserRegisterTests(void);
#endif
static inline uint64_t HtpGetActiveRequestTxID(HtpState *s)
{
uint64_t id = HTPStateGetTxCnt(s);
DEBUG_VALIDATE_BUG_ON(id == 0);
return id - 1;
}
static inline uint64_t HtpGetActiveResponseTxID(HtpState *s)
{
return s->transaction_cnt;
}
#ifdef DEBUG
/**
* \internal
*
* \brief Lookup the HTP personality string from the numeric personality.
*
* \todo This needs to be a libhtp function.
*/
static const char *HTPLookupPersonalityString(int p)
{
#define CASE_HTP_PERSONALITY_STRING(p) \
case HTP_SERVER_PERSONALITY_##p: \
return #p
switch (p) {
CASE_HTP_PERSONALITY_STRING(MINIMAL);
CASE_HTP_PERSONALITY_STRING(GENERIC);
CASE_HTP_PERSONALITY_STRING(IDS);
CASE_HTP_PERSONALITY_STRING(IIS_4_0);
CASE_HTP_PERSONALITY_STRING(IIS_5_0);
CASE_HTP_PERSONALITY_STRING(IIS_5_1);
CASE_HTP_PERSONALITY_STRING(IIS_6_0);
CASE_HTP_PERSONALITY_STRING(IIS_7_0);
CASE_HTP_PERSONALITY_STRING(IIS_7_5);
CASE_HTP_PERSONALITY_STRING(APACHE_2);
}
return NULL;
}
#endif /* DEBUG */
/**
* \internal
*
* \brief Lookup the numeric HTP personality from a string.
*
* \todo This needs to be a libhtp function.
*/
static int HTPLookupPersonality(const char *str)
{
#define IF_HTP_PERSONALITY_NUM(p) \
if (strcasecmp(#p, str) == 0) \
return HTP_SERVER_PERSONALITY_##p
IF_HTP_PERSONALITY_NUM(MINIMAL);
IF_HTP_PERSONALITY_NUM(GENERIC);
IF_HTP_PERSONALITY_NUM(IDS);
IF_HTP_PERSONALITY_NUM(IIS_4_0);
IF_HTP_PERSONALITY_NUM(IIS_5_0);
IF_HTP_PERSONALITY_NUM(IIS_5_1);
IF_HTP_PERSONALITY_NUM(IIS_6_0);
IF_HTP_PERSONALITY_NUM(IIS_7_0);
IF_HTP_PERSONALITY_NUM(IIS_7_5);
IF_HTP_PERSONALITY_NUM(APACHE_2);
if (strcasecmp("TOMCAT_6_0", str) == 0) {
SCLogError("Personality %s no "
"longer supported by libhtp.",
str);
return -1;
} else if ((strcasecmp("APACHE", str) == 0) ||
(strcasecmp("APACHE_2_2", str) == 0))
{
SCLogWarning("Personality %s no "
"longer supported by libhtp, failing back to "
"Apache2 personality.",
str);
return HTP_SERVER_PERSONALITY_APACHE_2;
}
return -1;
}
static void HTPSetEvent(HtpState *s, HtpTxUserData *htud,
const uint8_t dir, const uint8_t e)
{
SCLogDebug("setting event %u", e);
if (htud) {
SCAppLayerDecoderEventsSetEventRaw(&htud->tx_data.events, e);
s->events++;
return;
}
const uint64_t tx_id = (dir == STREAM_TOSERVER) ?
HtpGetActiveRequestTxID(s) : HtpGetActiveResponseTxID(s);
htp_tx_t *tx = HTPStateGetTx(s, tx_id);
if (tx == NULL && tx_id > 0)
tx = HTPStateGetTx(s, tx_id - 1);
if (tx != NULL) {
htud = (HtpTxUserData *)htp_tx_get_user_data(tx);
SCAppLayerDecoderEventsSetEventRaw(&htud->tx_data.events, e);
if (dir & STREAM_TOCLIENT)
htud->tx_data.updated_tc = true;
if (dir & STREAM_TOSERVER)
htud->tx_data.updated_ts = true;
s->events++;
return;
}
SCLogDebug("couldn't set event %u", e);
}
/** \brief Function to allocates the HTTP state memory and also creates the HTTP
* connection parser to be used by the HTP library
*/
static void *HTPStateAlloc(void *orig_state, AppProto proto_orig)
{
SCEnter();
HtpState *s = HTPMalloc(sizeof(HtpState));
if (unlikely(s == NULL)) {
SCReturnPtr(NULL, "void");
}
memset(s, 0x00, sizeof(HtpState));
#ifdef DEBUG
SCMutexLock(&htp_state_mem_lock);
htp_state_memcnt++;
htp_state_memuse += sizeof(HtpState);
SCLogDebug("htp memory %"PRIu64" (%"PRIu64")", htp_state_memuse, htp_state_memcnt);
SCMutexUnlock(&htp_state_mem_lock);
#endif
SCReturnPtr((void *)s, "void");
}
static void HtpTxUserDataFree(void *txud)
{
HtpTxUserData *htud = (HtpTxUserData *)txud;
if (likely(htud)) {
HtpBodyFree(&htud->request_body);
HtpBodyFree(&htud->response_body);
if (htud->request_headers_raw)
HTPFree(htud->request_headers_raw, htud->request_headers_raw_len);
if (htud->response_headers_raw)
HTPFree(htud->response_headers_raw, htud->response_headers_raw_len);
if (htud->mime_state)
SCMimeStateFree(htud->mime_state);
SCAppLayerTxDataCleanup(&htud->tx_data);
if (htud->file_range) {
SCHTPFileCloseHandleRange(&htp_sbcfg, &htud->files_tc, 0, htud->file_range, NULL, 0);
SCHttpRangeFreeBlock(htud->file_range);
}
FileContainerRecycle(&htud->files_ts, &htp_sbcfg);
FileContainerRecycle(&htud->files_tc, &htp_sbcfg);
HTPFree(htud, sizeof(HtpTxUserData));
}
}
/** \brief Function to frees the HTTP state memory and also frees the HTTP
* connection parser memory which was used by the HTP library
*/
void HTPStateFree(void *state)
{
SCEnter();
HtpState *s = (HtpState *)state;
if (s == NULL) {
SCReturn;
}
/* free the connection parser memory used by HTP library */
if (s->connp != NULL) {
SCLogDebug("freeing HTP state");
htp_connp_destroy_all(s->connp);
}
HTPFree(s, sizeof(HtpState));
#ifdef DEBUG
SCMutexLock(&htp_state_mem_lock);
htp_state_memcnt--;
htp_state_memuse -= sizeof(HtpState);
SCLogDebug("htp memory %"PRIu64" (%"PRIu64")", htp_state_memuse, htp_state_memcnt);
SCMutexUnlock(&htp_state_mem_lock);
#endif
SCReturn;
}
/**
* \brief HTP transaction cleanup callback
*
*/
static void HTPStateTransactionFree(void *state, uint64_t id)
{
SCEnter();
HtpState *s = (HtpState *)state;
SCLogDebug("state %p, id %"PRIu64, s, id);
htp_tx_destroy(s->connp, id);
}
/**
* \brief Sets a flag that informs the HTP app layer that some module in the
* engine needs the http request body data.
* \initonly
*/
void AppLayerHtpEnableRequestBodyCallback(void)
{
SCEnter();
SC_ATOMIC_OR(htp_config_flags, HTP_REQUIRE_REQUEST_BODY);
SCReturn;
}
/**
* \brief Sets a flag that informs the HTP app layer that some module in the
* engine needs the http request body data.
* \initonly
*/
void AppLayerHtpEnableResponseBodyCallback(void)
{
SCEnter();
SC_ATOMIC_OR(htp_config_flags, HTP_REQUIRE_RESPONSE_BODY);
SCReturn;
}
/**
* \brief Sets a flag that informs the HTP app layer that some module in the
* engine needs the http request file.
*
* \initonly
*/
void AppLayerHtpNeedFileInspection(void)
{
SCEnter();
AppLayerHtpEnableRequestBodyCallback();
AppLayerHtpEnableResponseBodyCallback();
SC_ATOMIC_OR(htp_config_flags, HTP_REQUIRE_REQUEST_FILE);
SCReturn;
}
static void AppLayerHtpSetStreamDepthFlag(void *tx, const uint8_t flags)
{
HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data((htp_tx_t *)tx);
SCLogDebug("setting HTP_STREAM_DEPTH_SET, flags %02x", flags);
if (flags & STREAM_TOCLIENT) {
tx_ud->tcflags |= HTP_STREAM_DEPTH_SET;
} else {
tx_ud->tsflags |= HTP_STREAM_DEPTH_SET;
}
}
static bool AppLayerHtpCheckDepth(const HTPCfgDir *cfg, HtpBody *body, uint8_t flags)
{
SCLogDebug("cfg->body_limit %u stream_depth %u body->content_len_so_far %" PRIu64,
cfg->body_limit, FileReassemblyDepth(), body->content_len_so_far);
if (flags & HTP_STREAM_DEPTH_SET) {
uint32_t stream_depth = FileReassemblyDepth();
if (body->content_len_so_far < (uint64_t)stream_depth || stream_depth == 0) {
SCLogDebug("true");
return true;
}
} else {
if (cfg->body_limit == 0 || body->content_len_so_far < cfg->body_limit) {
return true;
}
}
SCLogDebug("false");
return false;
}
static uint32_t AppLayerHtpComputeChunkLength(uint64_t content_len_so_far, uint32_t body_limit,
uint32_t stream_depth, uint8_t flags, uint32_t data_len)
{
uint32_t chunk_len = 0;
if (!(flags & HTP_STREAM_DEPTH_SET) && body_limit > 0 &&
(content_len_so_far < (uint64_t)body_limit) &&
(content_len_so_far + (uint64_t)data_len) > body_limit)
{
chunk_len = (uint32_t)(body_limit - content_len_so_far);
} else if ((flags & HTP_STREAM_DEPTH_SET) && stream_depth > 0 &&
(content_len_so_far < (uint64_t)stream_depth) &&
(content_len_so_far + (uint64_t)data_len) > stream_depth)
{
chunk_len = (uint32_t)(stream_depth - content_len_so_far);
}
SCLogDebug("len %u", chunk_len);
return (chunk_len == 0 ? data_len : chunk_len);
}
/**
* \internal
*
* \brief Check state for errors, warnings and add any as events
*
* \param s state
* \param dir direction: STREAM_TOSERVER or STREAM_TOCLIENT
*/
static void HTPHandleError(HtpState *s, const uint8_t dir)
{
if (s == NULL || s->conn == NULL || s->htp_messages_count >= HTP_MAX_MESSAGES) {
// ignore further messages
return;
}
htp_log_t *log = htp_conn_next_log(s->conn);
while (log != NULL) {
char *msg = htp_log_message(log);
if (msg == NULL) {
htp_log_free(log);
log = htp_conn_next_log(s->conn);
continue;
}
SCLogDebug("message %s", msg);
htp_log_code_t id = htp_log_code(log);
if (id != HTP_LOG_CODE_UNKNOWN && id != HTP_LOG_CODE_ERROR) {
HTPSetEvent(s, NULL, dir, (uint8_t)id);
}
htp_free_cstring(msg);
htp_log_free(log);
s->htp_messages_count++;
if (s->htp_messages_count >= HTP_MAX_MESSAGES) {
// only once per HtpState
HTPSetEvent(s, NULL, dir, HTTP_DECODER_EVENT_TOO_MANY_WARNINGS);
// too noisy in fuzzing
// DEBUG_VALIDATE_BUG_ON("Too many libhtp messages");
break;
}
log = htp_conn_next_log(s->conn);
}
SCLogDebug("s->htp_messages_count %u", s->htp_messages_count);
}
static inline void HTPErrorCheckTxRequestFlags(HtpState *s, const htp_tx_t *tx)
{
#ifdef DEBUG
BUG_ON(s == NULL || tx == NULL);
#endif
if (htp_tx_flags(tx) & (HTP_FLAGS_REQUEST_INVALID_T_E | HTP_FLAGS_REQUEST_INVALID_C_L |
HTP_FLAGS_HOST_MISSING | HTP_FLAGS_HOST_AMBIGUOUS |
HTP_FLAGS_HOSTU_INVALID | HTP_FLAGS_HOSTH_INVALID)) {
HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx);
if (htp_tx_flags(tx) & HTP_FLAGS_REQUEST_INVALID_T_E)
HTPSetEvent(s, htud, STREAM_TOSERVER,
HTP_LOG_CODE_INVALID_TRANSFER_ENCODING_VALUE_IN_REQUEST);
if (htp_tx_flags(tx) & HTP_FLAGS_REQUEST_INVALID_C_L)
HTPSetEvent(
s, htud, STREAM_TOSERVER, HTP_LOG_CODE_INVALID_CONTENT_LENGTH_FIELD_IN_REQUEST);
if (htp_tx_flags(tx) & HTP_FLAGS_HOST_MISSING)
HTPSetEvent(s, htud, STREAM_TOSERVER, HTP_LOG_CODE_MISSING_HOST_HEADER);
if (htp_tx_flags(tx) & HTP_FLAGS_HOST_AMBIGUOUS)
HTPSetEvent(s, htud, STREAM_TOSERVER, HTP_LOG_CODE_HOST_HEADER_AMBIGUOUS);
if (htp_tx_flags(tx) & HTP_FLAGS_HOSTU_INVALID)
HTPSetEvent(s, htud, STREAM_TOSERVER, HTP_LOG_CODE_URI_HOST_INVALID);
if (htp_tx_flags(tx) & HTP_FLAGS_HOSTH_INVALID)
HTPSetEvent(s, htud, STREAM_TOSERVER, HTP_LOG_CODE_HEADER_HOST_INVALID);
}
if (htp_tx_request_auth_type(tx) == HTP_AUTH_TYPE_UNRECOGNIZED) {
HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx);
HTPSetEvent(s, htud, STREAM_TOSERVER, HTP_LOG_CODE_AUTH_UNRECOGNIZED);
}
if (htp_tx_is_protocol_0_9(tx) && htp_tx_request_method_number(tx) == HTP_METHOD_UNKNOWN &&
(htp_tx_request_protocol_number(tx) == HTP_PROTOCOL_INVALID ||
htp_tx_request_protocol_number(tx) == HTP_PROTOCOL_UNKNOWN)) {
HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx);
HTPSetEvent(s, htud, STREAM_TOSERVER, HTP_LOG_CODE_REQUEST_LINE_INVALID);
}
}
static int Setup(Flow *f, HtpState *hstate)
{
/* store flow ref in state so callbacks can access it */
hstate->f = f;
HTPCfgRec *htp_cfg_rec = &cfglist;
htp_cfg_t *htp = cfglist.cfg; /* Default to the global HTP config */
void *user_data = NULL;
if (FLOW_IS_IPV4(f)) {
SCLogDebug("Looking up HTP config for ipv4 %08x", *GET_IPV4_DST_ADDR_PTR(f));
(void)SCRadix4TreeFindBestMatch(
&cfgtree.ipv4, (uint8_t *)GET_IPV4_DST_ADDR_PTR(f), &user_data);
}
else if (FLOW_IS_IPV6(f)) {
SCLogDebug("Looking up HTP config for ipv6");
(void)SCRadix6TreeFindBestMatch(&cfgtree.ipv6, (uint8_t *)GET_IPV6_DST_ADDR(f), &user_data);
}
else {
SCLogError("unknown address family, bug!");
goto error;
}
if (user_data != NULL) {
htp_cfg_rec = user_data;
htp = htp_cfg_rec->cfg;
SCLogDebug("LIBHTP using config: %p", htp);
} else {
SCLogDebug("Using default HTP config: %p", htp);
}
if (NULL == htp) {
#ifdef DEBUG_VALIDATION
BUG_ON(1);
#endif
/* should never happen if HTPConfigure is properly invoked */
goto error;
}
hstate->connp = htp_connp_create(htp);
if (hstate->connp == NULL) {
goto error;
}
hstate->conn = (htp_conn_t *)htp_connp_connection(hstate->connp);
htp_connp_set_user_data(hstate->connp, (void *)hstate);
hstate->cfg = htp_cfg_rec;
SCLogDebug("New hstate->connp %p", hstate->connp);
struct timeval tv = { SCTIME_SECS(f->startts), SCTIME_USECS(f->startts) };
htp_connp_open(hstate->connp, NULL, f->sp, NULL, f->dp, &tv);
StreamTcpReassemblySetMinInspectDepth(f->protoctx, STREAM_TOSERVER,
htp_cfg_rec->request.inspect_min_size);
StreamTcpReassemblySetMinInspectDepth(f->protoctx, STREAM_TOCLIENT,
htp_cfg_rec->response.inspect_min_size);
return 0;
error:
return -1;
}
/**
* \brief Function to handle the reassembled data from client and feed it to
* the HTP library to process it.
*
* \param flow Pointer to the flow the data belong to
* \param htp_state Pointer the state in which the parsed value to be stored
* \param pstate Application layer parser state for this session
*
* \retval On success returns 1 or on failure returns -1.
*/
static AppLayerResult HTPHandleRequestData(Flow *f, void *htp_state, AppLayerParserState *pstate,
StreamSlice stream_slice, void *local_data)
{
SCEnter();
int ret = 0;
HtpState *hstate = (HtpState *)htp_state;
/* On the first invocation, create the connection parser structure to
* be used by HTP library. This is looked up via IP in the radix
* tree. Failing that, the default HTP config is used.
*/
if (NULL == hstate->conn) {
if (Setup(f, hstate) != 0) {
SCReturnStruct(APP_LAYER_ERROR);
}
}
DEBUG_VALIDATE_BUG_ON(hstate->connp == NULL);
hstate->slice = &stream_slice;
const uint8_t *input = StreamSliceGetData(&stream_slice);
uint32_t input_len = StreamSliceGetDataLen(&stream_slice);
struct timeval ts = { SCTIME_SECS(f->startts), SCTIME_USECS(f->startts) };
/* pass the new data to the htp parser */
if (input_len > 0) {
const int r = htp_connp_request_data(hstate->connp, &ts, input, input_len);
switch (r) {
case HTP_STREAM_STATE_ERROR:
ret = -1;
break;
default:
break;
}
HTPHandleError(hstate, STREAM_TOSERVER);
}
/* if the TCP connection is closed, then close the HTTP connection */
if (SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS) &&
!(hstate->flags & HTP_FLAG_STATE_CLOSED_TS)) {
htp_connp_request_close(hstate->connp, &ts);
hstate->flags |= HTP_FLAG_STATE_CLOSED_TS;
SCLogDebug("stream eof encountered, closing htp handle for ts");
}
SCLogDebug("hstate->connp %p", hstate->connp);
hstate->slice = NULL;
if (ret < 0) {
SCReturnStruct(APP_LAYER_ERROR);
}
SCReturnStruct(APP_LAYER_OK);
}
/**
* \brief Function to handle the reassembled data from server and feed it to
* the HTP library to process it.
*
* \param flow Pointer to the flow the data belong to
* \param htp_state Pointer the state in which the parsed value to be stored
* \param pstate Application layer parser state for this session
* \param input Pointer the received HTTP server data
* \param input_len Length in bytes of the received data
* \param output Pointer to the output (not used in this function)
*
* \retval On success returns 1 or on failure returns -1
*/
static AppLayerResult HTPHandleResponseData(Flow *f, void *htp_state, AppLayerParserState *pstate,
StreamSlice stream_slice, void *local_data)
{
SCEnter();
int ret = 0;
HtpState *hstate = (HtpState *)htp_state;
const uint8_t *input = StreamSliceGetData(&stream_slice);
uint32_t input_len = StreamSliceGetDataLen(&stream_slice);
/* On the first invocation, create the connection parser structure to
* be used by HTP library. This is looked up via IP in the radix
* tree. Failing that, the default HTP config is used.
*/
if (NULL == hstate->conn) {
if (Setup(f, hstate) != 0) {
SCReturnStruct(APP_LAYER_ERROR);
}
}
DEBUG_VALIDATE_BUG_ON(hstate->connp == NULL);
hstate->slice = &stream_slice;
struct timeval ts = { SCTIME_SECS(f->startts), SCTIME_USECS(f->startts) };
const htp_tx_t *tx = NULL;
uint32_t consumed = 0;
if (input_len > 0) {
const int r = htp_connp_response_data(hstate->connp, &ts, input, input_len);
switch (r) {
case HTP_STREAM_STATE_ERROR:
ret = -1;
break;
case HTP_STREAM_STATE_TUNNEL:
tx = htp_connp_get_response_tx(hstate->connp);
if (tx != NULL && htp_tx_response_status_number(tx) == 101) {
const htp_header_t *h = htp_tx_response_header(tx, "Upgrade");
if (h == NULL) {
break;
}
uint16_t dp = 0;
if (htp_tx_request_port_number(tx) != -1) {
dp = (uint16_t)htp_tx_request_port_number(tx);
}
consumed = (uint32_t)htp_connp_response_data_consumed(hstate->connp);
if (bstr_cmp_c(htp_header_value(h), "h2c") == 0) {
if (AppLayerProtoDetectGetProtoName(ALPROTO_HTTP2) == NULL) {
// if HTTP2 is disabled, keep the HTP_STREAM_STATE_TUNNEL mode
break;
}
hstate->slice = NULL;
if (!AppLayerRequestProtocolChange(hstate->f, dp, ALPROTO_HTTP2)) {
HTPSetEvent(hstate, NULL, STREAM_TOCLIENT,
HTTP_DECODER_EVENT_FAILED_PROTOCOL_CHANGE);
}
// During HTTP2 upgrade, we may consume the HTTP1 part of the data
// and we need to parser the remaining part with HTTP2
if (consumed > 0 && consumed < input_len) {
SCReturnStruct(APP_LAYER_INCOMPLETE(consumed, input_len - consumed));
}
SCReturnStruct(APP_LAYER_OK);
} else if (bstr_cmp_c_nocase(htp_header_value(h), "WebSocket")) {
if (AppLayerProtoDetectGetProtoName(ALPROTO_WEBSOCKET) == NULL) {
// if WS is disabled, keep the HTP_STREAM_STATE_TUNNEL mode
break;
}
hstate->slice = NULL;
if (!AppLayerRequestProtocolChange(hstate->f, dp, ALPROTO_WEBSOCKET)) {
HTPSetEvent(hstate, NULL, STREAM_TOCLIENT,
HTTP_DECODER_EVENT_FAILED_PROTOCOL_CHANGE);
}
// During WS upgrade, we may consume the HTTP1 part of the data
// and we need to parser the remaining part with WS
if (consumed > 0 && consumed < input_len) {
SCReturnStruct(APP_LAYER_INCOMPLETE(consumed, input_len - consumed));
}
SCReturnStruct(APP_LAYER_OK);
}
}
break;
default:
break;
}
HTPHandleError(hstate, STREAM_TOCLIENT);
}
/* if we the TCP connection is closed, then close the HTTP connection */
if (SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TC) &&
!(hstate->flags & HTP_FLAG_STATE_CLOSED_TC)) {
htp_connp_close(hstate->connp, &ts);
hstate->flags |= HTP_FLAG_STATE_CLOSED_TC;
}
SCLogDebug("hstate->connp %p", hstate->connp);
hstate->slice = NULL;
if (ret < 0) {
SCReturnStruct(APP_LAYER_ERROR);
}
SCReturnStruct(APP_LAYER_OK);
}
/**
* \param name /Lowercase/ version of the variable name
*/
static int HTTPParseContentDispositionHeader(const uint8_t *name, size_t name_len,
const uint8_t *data, size_t len, uint8_t const **retptr, size_t *retlen)
{
#ifdef PRINT
printf("DATA START: \n");
PrintRawDataFp(stdout, data, len);
printf("DATA END: \n");
#endif
size_t x;
int quote = 0;
for (x = 0; x < len; x++) {
if (!(isspace(data[x])))
break;
}
if (x >= len)
return 0;
const uint8_t *line = data + x;
size_t line_len = len-x;
size_t offset = 0;
#ifdef PRINT
printf("LINE START: \n");
PrintRawDataFp(stdout, line, line_len);
printf("LINE END: \n");
#endif
for (x = 0 ; x < line_len; x++) {
if (x > 0) {
if (line[x - 1] != '\\' && line[x] == '\"') {
quote++;
}
if (((line[x - 1] != '\\' && line[x] == ';') || ((x + 1) == line_len)) && (quote == 0 || quote % 2 == 0)) {
const uint8_t *token = line + offset;
size_t token_len = x - offset;
if ((x + 1) == line_len) {
token_len++;
}
offset = x + 1;
while (offset < line_len && isspace(line[offset])) {
x++;