forked from owasp-modsecurity/ModSecurity
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmymodule.cpp
1351 lines (1088 loc) · 37.9 KB
/
mymodule.cpp
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
/*
* ModSecurity for Apache 2.x, http://www.modsecurity.org/
* Copyright (c) 2004-2013 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* You may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address [email protected].
*/
#define WIN32_LEAN_AND_MEAN
#undef inline
#define inline inline
// IIS7 Server API header file
#include <Windows.h>
#include <sal.h>
#include <strsafe.h>
#include "httpserv.h"
// Project header files
#include "mymodule.h"
#include "mymodulefactory.h"
#include "api.h"
#include "moduleconfig.h"
#include "winsock2.h"
class REQUEST_STORED_CONTEXT : public IHttpStoredContext
{
public:
REQUEST_STORED_CONTEXT()
{
m_pConnRec = NULL;
m_pRequestRec = NULL;
m_pHttpContext = NULL;
m_pProvider = NULL;
m_pResponseBuffer = NULL;
m_pResponseLength = 0;
m_pResponsePosition = 0;
}
~REQUEST_STORED_CONTEXT()
{
FinishRequest();
}
// virtual
VOID
CleanupStoredContext(
VOID
)
{
FinishRequest();
delete this;
}
void FinishRequest()
{
if(m_pRequestRec != NULL)
{
modsecFinishRequest(m_pRequestRec);
m_pRequestRec = NULL;
}
if(m_pConnRec != NULL)
{
modsecFinishConnection(m_pConnRec);
m_pConnRec = NULL;
}
}
conn_rec *m_pConnRec;
request_rec *m_pRequestRec;
IHttpContext *m_pHttpContext;
IHttpEventProvider *m_pProvider;
char *m_pResponseBuffer;
ULONGLONG m_pResponseLength;
ULONGLONG m_pResponsePosition;
};
//----------------------------------------------------------------------------
char *GetIpAddr(apr_pool_t *pool, PSOCKADDR pAddr)
{
const char *format = "%15[0-9.]:%5[0-9]";
char ip[16] = { 0 }; // ip4 addresses have max len 15
char port[6] = { 0 }; // port numbers are 16bit, ie 5 digits max
DWORD len = 50;
char *buf = (char *)apr_palloc(pool, len);
if(buf == NULL)
return "";
buf[0] = 0;
WSAAddressToString(pAddr, sizeof(SOCKADDR), NULL, buf, &len);
// test for IPV4 with port on the end
if (sscanf(buf, format, ip, port) == 2) {
// IPV4 but with port - remove the port
char* input = ":";
char* ipv4 = strtok(buf, input);
return ipv4;
}
return buf;
}
apr_sockaddr_t *CopySockAddr(apr_pool_t *pool, PSOCKADDR pAddr)
{
apr_sockaddr_t *addr = (apr_sockaddr_t *)apr_palloc(pool, sizeof(apr_sockaddr_t));
int adrlen = 16, iplen = 4;
if(pAddr->sa_family == AF_INET6)
{
adrlen = 46;
iplen = 16;
}
addr->addr_str_len = adrlen;
addr->family = pAddr->sa_family;
addr->hostname = "unknown";
#ifdef WIN32
addr->ipaddr_len = sizeof(IN_ADDR);
#else
addr->ipaddr_len = sizeof(struct in_addr);
#endif
addr->ipaddr_ptr = &addr->sa.sin.sin_addr;
addr->pool = pool;
addr->port = 80;
#ifdef WIN32
memcpy(&addr->sa.sin.sin_addr.S_un.S_addr, pAddr->sa_data, iplen);
#else
memcpy(&addr->sa.sin.sin_addr.s_addr, pAddr->sa_data, iplen);
#endif
addr->sa.sin.sin_family = pAddr->sa_family;
addr->sa.sin.sin_port = 80;
addr->salen = sizeof(addr->sa);
addr->servname = addr->hostname;
return addr;
}
//----------------------------------------------------------------------------
char *ZeroTerminate(const char *str, size_t len, apr_pool_t *pool)
{
char *_n = (char *)apr_palloc(pool, len + 1);
memcpy(_n, str, len);
_n[len] = 0;
return _n;
}
//----------------------------------------------------------------------------
// FUNCTION: ConvertUTF16ToUTF8
// DESC: Converts Unicode UTF-16 (Windows default) text to Unicode UTF-8.
//----------------------------------------------------------------------------
char *ConvertUTF16ToUTF8( __in const WCHAR * pszTextUTF16, size_t cchUTF16, apr_pool_t *pool )
{
//
// Special case of NULL or empty input string
//
if ( (pszTextUTF16 == NULL) || (*pszTextUTF16 == L'\0') || cchUTF16 == 0 )
{
// Return empty string
return "";
}
//
// Get size of destination UTF-8 buffer, in CHAR's (= bytes)
//
int cbUTF8 = ::WideCharToMultiByte(
CP_UTF8, // convert to UTF-8
0, // specify conversion behavior
pszTextUTF16, // source UTF-16 string
static_cast<int>( cchUTF16 ), // total source string length, in WCHAR's,
NULL, // unused - no conversion required in this step
0, // request buffer size
NULL, NULL // unused
);
if ( cbUTF8 == 0 )
{
return "";
}
//
// Allocate destination buffer for UTF-8 string
//
int cchUTF8 = cbUTF8; // sizeof(CHAR) = 1 byte
char *pszUTF8 = (char *)apr_palloc(pool, cchUTF8 + 1 );
//
// Do the conversion from UTF-16 to UTF-8
//
int result = ::WideCharToMultiByte(
CP_UTF8, // convert to UTF-8
0, // specify conversion behavior
pszTextUTF16, // source UTF-16 string
static_cast<int>( cchUTF16 ), // total source string length, in WCHAR's,
// including end-of-string \0
pszUTF8, // destination buffer
cbUTF8, // destination buffer size, in bytes
NULL, NULL // unused
);
if ( result == 0 )
{
return "";
}
pszUTF8[cchUTF8] = 0;
return pszUTF8;
}
void Log(void *obj, int level, char *str)
{
CMyHttpModule *mod = (CMyHttpModule *)obj;
WORD logcat = EVENTLOG_INFORMATION_TYPE;
level &= APLOG_LEVELMASK;
if(level <= APLOG_ERR)
logcat = EVENTLOG_ERROR_TYPE;
if(level == APLOG_WARNING || strstr(str, "Warning.") != NULL)
logcat = EVENTLOG_WARNING_TYPE;
mod->WriteEventViewerLog(str, logcat);
}
#define NOTE_IIS "iis-tx-context"
void StoreIISContext(request_rec *r, REQUEST_STORED_CONTEXT *rsc)
{
apr_table_setn(r->notes, NOTE_IIS, (const char *)rsc);
}
REQUEST_STORED_CONTEXT *RetrieveIISContext(request_rec *r)
{
REQUEST_STORED_CONTEXT *msr = NULL;
request_rec *rx = NULL;
/* Look in the current request first. */
msr = (REQUEST_STORED_CONTEXT *)apr_table_get(r->notes, NOTE_IIS);
if (msr != NULL) {
//msr->r = r;
return msr;
}
/* If this is a subrequest then look in the main request. */
if (r->main != NULL) {
msr = (REQUEST_STORED_CONTEXT *)apr_table_get(r->main->notes, NOTE_IIS);
if (msr != NULL) {
//msr->r = r;
return msr;
}
}
/* If the request was redirected then look in the previous requests. */
rx = r->prev;
while(rx != NULL) {
msr = (REQUEST_STORED_CONTEXT *)apr_table_get(rx->notes, NOTE_IIS);
if (msr != NULL) {
//msr->r = r;
return msr;
}
rx = rx->prev;
}
return NULL;
}
HRESULT CMyHttpModule::ReadFileChunk(HTTP_DATA_CHUNK *chunk, char *buf)
{
OVERLAPPED ovl;
DWORD dwDataStartOffset;
ULONGLONG bytesTotal = 0;
BYTE * pIoBuffer = NULL;
HANDLE hIoEvent = INVALID_HANDLE_VALUE;
HRESULT hr = S_OK;
pIoBuffer = (BYTE *)VirtualAlloc(NULL,
1,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (pIoBuffer == NULL)
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Done;
}
hIoEvent = CreateEvent(NULL, // security attr
FALSE, // manual reset
FALSE, // initial state
NULL); // name
if (hIoEvent == NULL)
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Done;
}
while(bytesTotal < chunk->FromFileHandle.ByteRange.Length.QuadPart)
{
DWORD bytesRead = 0;
int was_eof = 0;
ULONGLONG offset = chunk->FromFileHandle.ByteRange.StartingOffset.QuadPart + bytesTotal;
ZeroMemory(&ovl, sizeof ovl);
ovl.hEvent = hIoEvent;
ovl.Offset = (DWORD)offset;
dwDataStartOffset = ovl.Offset & (m_dwPageSize - 1);
ovl.Offset &= ~(m_dwPageSize - 1);
ovl.OffsetHigh = offset >> 32;
if (!ReadFile(chunk->FromFileHandle.FileHandle,
pIoBuffer,
m_dwPageSize,
&bytesRead,
&ovl))
{
DWORD dwErr = GetLastError();
switch (dwErr)
{
case ERROR_IO_PENDING:
//
// GetOverlappedResult can return without waiting for the
// event thus leaving it signalled and causing problems
// with future use of that event handle, so just wait ourselves
//
WaitForSingleObject(ovl.hEvent, INFINITE); // == WAIT_OBJECT_0);
if (!GetOverlappedResult(
chunk->FromFileHandle.FileHandle,
&ovl,
&bytesRead,
TRUE))
{
dwErr = GetLastError();
switch(dwErr)
{
case ERROR_HANDLE_EOF:
was_eof = 1;
break;
default:
hr = HRESULT_FROM_WIN32(dwErr);
goto Done;
}
}
break;
case ERROR_HANDLE_EOF:
was_eof = 1;
break;
default:
hr = HRESULT_FROM_WIN32(dwErr);
goto Done;
}
}
bytesRead -= dwDataStartOffset;
if (bytesRead > chunk->FromFileHandle.ByteRange.Length.QuadPart)
{
bytesRead = (DWORD)chunk->FromFileHandle.ByteRange.Length.QuadPart;
}
if ((bytesTotal + bytesRead) > chunk->FromFileHandle.ByteRange.Length.QuadPart)
{
bytesRead = chunk->FromFileHandle.ByteRange.Length.QuadPart - bytesTotal;
}
memcpy(buf, pIoBuffer + dwDataStartOffset, bytesRead);
buf += bytesRead;
bytesTotal += bytesRead;
if(was_eof != 0)
chunk->FromFileHandle.ByteRange.Length.QuadPart = bytesTotal;
}
Done:
if(NULL != pIoBuffer)
{
VirtualFree(pIoBuffer, 0, MEM_RELEASE);
}
if(INVALID_HANDLE_VALUE != hIoEvent)
{
CloseHandle(hIoEvent);
}
return hr;
}
REQUEST_NOTIFICATION_STATUS
CMyHttpModule::OnSendResponse(
IN IHttpContext * pHttpContext,
IN ISendResponseProvider * pResponseProvider
)
{
REQUEST_STORED_CONTEXT *rsc = NULL;
rsc = (REQUEST_STORED_CONTEXT *)pHttpContext->GetModuleContextContainer()->GetModuleContext(g_pModuleContext);
EnterCriticalSection(&m_csLock);
// here we must check if response body processing is enabled
//
if(rsc == NULL || rsc->m_pRequestRec == NULL || rsc->m_pResponseBuffer != NULL || !modsecIsResponseBodyAccessEnabled(rsc->m_pRequestRec))
{
goto Exit;
}
HRESULT hr = S_OK;
IHttpResponse *pHttpResponse = NULL;
HTTP_RESPONSE *pRawHttpResponse = NULL;
HTTP_BYTE_RANGE *pFileByteRange = NULL;
HTTP_DATA_CHUNK *pSourceDataChunk = NULL;
LARGE_INTEGER lFileSize;
REQUEST_NOTIFICATION_STATUS ret = RQ_NOTIFICATION_CONTINUE;
ULONGLONG ulTotalLength = 0;
DWORD c;
request_rec *r = rsc->m_pRequestRec;
pHttpResponse = pHttpContext->GetResponse();
pRawHttpResponse = pHttpResponse->GetRawHttpResponse();
// here we must add handling of chunked response
// apparently IIS 7 calls this handler once per chunk
// see: http://stackoverflow.com/questions/4385249/how-to-buffer-and-process-chunked-data-before-sending-headers-in-iis7-native-mod
if(pRawHttpResponse->EntityChunkCount == 0)
goto Exit;
// here we must transfer response headers
//
USHORT ctcch = 0;
char *ct = (char *)pHttpResponse->GetHeader(HttpHeaderContentType, &ctcch);
char *ctz = ZeroTerminate(ct, ctcch, r->pool);
// assume HTML if content type not set
// without this output filter would not buffer response and processing would hang
//
if(ctz[0] == 0)
ctz = "text/html";
r->content_type = ctz;
#define _TRANSHEADER(id,str) if(pRawHttpResponse->Headers.KnownHeaders[id].pRawValue != NULL) \
{\
apr_table_setn(r->headers_out, str, \
ZeroTerminate(pRawHttpResponse->Headers.KnownHeaders[id].pRawValue, pRawHttpResponse->Headers.KnownHeaders[id].RawValueLength, r->pool)); \
}
_TRANSHEADER(HttpHeaderCacheControl, "Cache-Control");
_TRANSHEADER(HttpHeaderConnection, "Connection");
_TRANSHEADER(HttpHeaderDate, "Date");
_TRANSHEADER(HttpHeaderKeepAlive, "Keep-Alive");
_TRANSHEADER(HttpHeaderPragma, "Pragma");
_TRANSHEADER(HttpHeaderTrailer, "Trailer");
_TRANSHEADER(HttpHeaderTransferEncoding, "Transfer-Encoding");
_TRANSHEADER(HttpHeaderUpgrade, "Upgrade");
_TRANSHEADER(HttpHeaderVia, "Via");
_TRANSHEADER(HttpHeaderWarning, "Warning");
_TRANSHEADER(HttpHeaderAllow, "Allow");
_TRANSHEADER(HttpHeaderContentLength, "Content-Length");
_TRANSHEADER(HttpHeaderContentType, "Content-Type");
_TRANSHEADER(HttpHeaderContentEncoding, "Content-Encoding");
_TRANSHEADER(HttpHeaderContentLanguage, "Content-Language");
_TRANSHEADER(HttpHeaderContentLocation, "Content-Location");
_TRANSHEADER(HttpHeaderContentMd5, "Content-Md5");
_TRANSHEADER(HttpHeaderContentRange, "Content-Range");
_TRANSHEADER(HttpHeaderExpires, "Expires");
_TRANSHEADER(HttpHeaderLastModified, "Last-Modified");
_TRANSHEADER(HttpHeaderAcceptRanges, "Accept-Ranges");
_TRANSHEADER(HttpHeaderAge, "Age");
_TRANSHEADER(HttpHeaderEtag, "Etag");
_TRANSHEADER(HttpHeaderLocation, "Location");
_TRANSHEADER(HttpHeaderProxyAuthenticate, "Proxy-Authenticate");
_TRANSHEADER(HttpHeaderRetryAfter, "Retry-After");
_TRANSHEADER(HttpHeaderServer, "Server");
_TRANSHEADER(HttpHeaderSetCookie, "Set-Cookie");
_TRANSHEADER(HttpHeaderVary, "Vary");
_TRANSHEADER(HttpHeaderWwwAuthenticate, "Www-Authenticate");
#undef _TRANSHEADER
for(int i = 0; i < pRawHttpResponse->Headers.UnknownHeaderCount; i++)
{
apr_table_setn(r->headers_out,
ZeroTerminate(pRawHttpResponse->Headers.pUnknownHeaders[i].pName, pRawHttpResponse->Headers.pUnknownHeaders[i].NameLength, r->pool),
ZeroTerminate(pRawHttpResponse->Headers.pUnknownHeaders[i].pRawValue, pRawHttpResponse->Headers.pUnknownHeaders[i].RawValueLength, r->pool));
}
r->content_encoding = apr_table_get(r->headers_out, "Content-Encoding");
//r->content_type = apr_table_get(r->headers_out, "Content-Type"); -- already set above
const char *lng = apr_table_get(r->headers_out, "Content-Languages");
if(lng != NULL)
{
r->content_languages = apr_array_make(r->pool, 1, sizeof(const char *));
*(const char **)apr_array_push(r->content_languages) = lng;
}
// Disable kernel caching for this response
// Probably we don't have to do it for ModSecurity
//pHttpContext->GetResponse()->DisableKernelCache(
// IISCacheEvents::HTTPSYS_CACHEABLE::HANDLER_HTTPSYS_UNFRIENDLY);
for(c = 0; c < pRawHttpResponse->EntityChunkCount; c++ )
{
pSourceDataChunk = &pRawHttpResponse->pEntityChunks[ c ];
switch( pSourceDataChunk->DataChunkType )
{
case HttpDataChunkFromMemory:
ulTotalLength += pSourceDataChunk->FromMemory.BufferLength;
break;
case HttpDataChunkFromFileHandle:
pFileByteRange = &pSourceDataChunk->FromFileHandle.ByteRange;
//
// File chunks may contain by ranges with unspecified length
// (HTTP_BYTE_RANGE_TO_EOF). In order to send parts of such a chunk,
// its necessary to know when the chunk is finished, and
// we need to move to the next chunk.
//
if ( pFileByteRange->Length.QuadPart == HTTP_BYTE_RANGE_TO_EOF)
{
if ( GetFileType( pSourceDataChunk->FromFileHandle.FileHandle ) ==
FILE_TYPE_DISK )
{
if ( !GetFileSizeEx( pSourceDataChunk->FromFileHandle.FileHandle,
&lFileSize ) )
{
DWORD dwError = GetLastError();
hr = HRESULT_FROM_WIN32(dwError);
goto Finished;
}
// put the resolved file length in the chunk, replacing
// HTTP_BYTE_RANGE_TO_EOF
pFileByteRange->Length.QuadPart =
lFileSize.QuadPart - pFileByteRange->StartingOffset.QuadPart;
}
else
{
hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
goto Finished;
}
}
ulTotalLength += pFileByteRange->Length.QuadPart;
break;
default:
// TBD: consider implementing HttpDataChunkFromFragmentCache,
// and HttpDataChunkFromFragmentCacheEx
hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
goto Finished;
}
}
rsc->m_pResponseBuffer = (char *)apr_palloc(rsc->m_pRequestRec->pool, ulTotalLength);
ulTotalLength = 0;
for(c = 0; c < pRawHttpResponse->EntityChunkCount; c++ )
{
pSourceDataChunk = &pRawHttpResponse->pEntityChunks[ c ];
switch( pSourceDataChunk->DataChunkType )
{
case HttpDataChunkFromMemory:
memcpy(rsc->m_pResponseBuffer + ulTotalLength, pSourceDataChunk->FromMemory.pBuffer, pSourceDataChunk->FromMemory.BufferLength);
ulTotalLength += pSourceDataChunk->FromMemory.BufferLength;
break;
case HttpDataChunkFromFileHandle:
pFileByteRange = &pSourceDataChunk->FromFileHandle.ByteRange;
if(ReadFileChunk(pSourceDataChunk, rsc->m_pResponseBuffer + ulTotalLength) != S_OK)
{
DWORD dwErr = GetLastError();
hr = HRESULT_FROM_WIN32(dwErr);
goto Finished;
}
ulTotalLength += pFileByteRange->Length.QuadPart;
break;
default:
// TBD: consider implementing HttpDataChunkFromFragmentCache,
// and HttpDataChunkFromFragmentCacheEx
hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
goto Finished;
}
}
rsc->m_pResponseLength = ulTotalLength;
//
// If there's no content-length set, we need to set it to avoid chunked transfer mode
// We can only do it if there is it's the only response to be sent.
//
DWORD dwFlags = pResponseProvider->GetFlags();
if (pResponseProvider->GetHeadersBeingSent() &&
(dwFlags & HTTP_SEND_RESPONSE_FLAG_MORE_DATA) == 0 &&
pHttpContext->GetResponse()->GetHeader(HttpHeaderContentLength) == NULL)
{
CHAR szLength[21]; //Max length for a 64 bit int is 20
ZeroMemory(szLength, sizeof(szLength));
hr = StringCchPrintfA(
szLength,
sizeof(szLength) / sizeof(CHAR) - 1, "%d",
ulTotalLength);
if(FAILED(hr))
{
goto Finished;
}
hr = pHttpContext->GetResponse()->SetHeader(
HttpHeaderContentLength,
szLength,
(USHORT)strlen(szLength),
TRUE);
if(FAILED(hr))
{
goto Finished;
}
}
Finished:
int status = modsecProcessResponse(rsc->m_pRequestRec);
// the logic here is temporary, needs clarification
//
if(status != 0 && status != -1)
{
pHttpContext->GetResponse()->Clear();
pHttpContext->GetResponse()->SetStatus(status, "ModSecurity Action");
pHttpContext->SetRequestHandled();
rsc->FinishRequest();
LeaveCriticalSection(&m_csLock);
return RQ_NOTIFICATION_FINISH_REQUEST;
}
Exit:
// temporary hack, in reality OnSendRequest theoretically could possibly come before OnEndRequest
//
if(rsc != NULL)
rsc->FinishRequest();
LeaveCriticalSection(&m_csLock);
return RQ_NOTIFICATION_CONTINUE;
}
REQUEST_NOTIFICATION_STATUS
CMyHttpModule::OnPostEndRequest(
IN IHttpContext * pHttpContext,
IN IHttpEventProvider * pProvider
)
{
REQUEST_STORED_CONTEXT *rsc = NULL;
rsc = (REQUEST_STORED_CONTEXT *)pHttpContext->GetModuleContextContainer()->GetModuleContext(g_pModuleContext);
// only finish request if OnSendResponse have been called already
//
if(rsc != NULL && rsc->m_pResponseBuffer != NULL)
{
EnterCriticalSection(&m_csLock);
rsc->FinishRequest();
LeaveCriticalSection(&m_csLock);
}
return RQ_NOTIFICATION_CONTINUE;
}
REQUEST_NOTIFICATION_STATUS
CMyHttpModule::OnBeginRequest(
IN IHttpContext * pHttpContext,
IN IHttpEventProvider * pProvider
)
{
HRESULT hr = S_OK;
IHttpRequest* pRequest = NULL;
MODSECURITY_STORED_CONTEXT* pConfig = NULL;
UNREFERENCED_PARAMETER ( pProvider );
EnterCriticalSection(&m_csLock);
if ( pHttpContext == NULL )
{
hr = E_UNEXPECTED;
goto Finished;
}
pRequest = pHttpContext->GetRequest();
if ( pRequest == NULL )
{
hr = E_UNEXPECTED;
goto Finished;
}
hr = MODSECURITY_STORED_CONTEXT::GetConfig(pHttpContext, &pConfig );
if ( FAILED( hr ) )
{
pHttpContext->GetResponse()->SetStatus(500, "WAF internal error. Unable to get config.");
pHttpContext->SetRequestHandled();
return RQ_NOTIFICATION_FINISH_REQUEST;
}
// If module is disabled, dont go any further
//
if( pConfig->GetIsEnabled() == false )
{
goto Finished;
}
auto reportConfigurationError = [pConfig, pHttpContext] {
pConfig->configLoadingFailed = true;
pHttpContext->GetResponse()->SetStatus(500, "WAF internal error. Invalid configuration.");
pHttpContext->SetRequestHandled();
return RQ_NOTIFICATION_FINISH_REQUEST;
};
// If we previously failed to load the config, don't spam the event log by trying and failing again
if (pConfig->configLoadingFailed)
{
return reportConfigurationError();
}
if(pConfig->m_Config == NULL)
{
char *path;
USHORT pathlen;
hr = pConfig->GlobalWideCharToMultiByte(pConfig->GetPath(), wcslen(pConfig->GetPath()), &path, &pathlen);
if ( FAILED( hr ) )
{
return reportConfigurationError();
}
pConfig->m_Config = modsecGetDefaultConfig();
PCWSTR servpath = pHttpContext->GetApplication()->GetApplicationPhysicalPath();
char *apppath;
USHORT apppathlen;
hr = pConfig->GlobalWideCharToMultiByte((WCHAR *)servpath, wcslen(servpath), &apppath, &apppathlen);
if ( FAILED( hr ) )
{
delete path;
return reportConfigurationError();
}
if(path[0] != 0)
{
const char * err = modsecProcessConfig((directory_config *)pConfig->m_Config, path, apppath);
if(err != NULL)
{
WriteEventViewerLog(err, EVENTLOG_ERROR_TYPE);
delete apppath;
delete path;
return reportConfigurationError();
}
modsecReportRemoteLoadedRules();
if (this->status_call_already_sent == false)
{
this->status_call_already_sent = true;
modsecStatusEngineCall();
}
}
delete apppath;
delete path;
}
conn_rec *c;
request_rec *r;
c = modsecNewConnection();
modsecProcessConnection(c);
r = modsecNewRequest(c, (directory_config *)pConfig->m_Config);
// on IIS we force input stream inspection flag, because its absence does not add any performance gain
// it's because on IIS request body must be restored each time it was read
//
modsecSetConfigForIISRequestBody(r);
REQUEST_STORED_CONTEXT *rsc = new REQUEST_STORED_CONTEXT();
rsc->m_pConnRec = c;
rsc->m_pRequestRec = r;
rsc->m_pHttpContext = pHttpContext;
rsc->m_pProvider = pProvider;
pHttpContext->GetModuleContextContainer()->SetModuleContext(rsc, g_pModuleContext);
StoreIISContext(r, rsc);
HTTP_REQUEST *req = pRequest->GetRawHttpRequest();
r->hostname = ConvertUTF16ToUTF8(req->CookedUrl.pHost, req->CookedUrl.HostLength / sizeof(WCHAR), r->pool);
r->path_info = ConvertUTF16ToUTF8(req->CookedUrl.pAbsPath, req->CookedUrl.AbsPathLength / sizeof(WCHAR), r->pool);
if(r->hostname == NULL)
{
if(req->Headers.KnownHeaders[HttpHeaderHost].pRawValue != NULL)
r->hostname = ZeroTerminate(req->Headers.KnownHeaders[HttpHeaderHost].pRawValue,
req->Headers.KnownHeaders[HttpHeaderHost].RawValueLength, r->pool);
}
int port = 0;
char *port_str = NULL;
if(r->hostname != NULL)
{
int k = 0;
char *ptr = (char *)r->hostname;
while(*ptr != 0 && *ptr != ':')
ptr++;
if(*ptr == ':')
{
*ptr = 0;
port_str = ptr + 1;
port = atoi(port_str);
}
}
if(req->CookedUrl.pQueryString != NULL && req->CookedUrl.QueryStringLength > 0)
r->args = ConvertUTF16ToUTF8(req->CookedUrl.pQueryString + 1, (req->CookedUrl.QueryStringLength / sizeof(WCHAR)) - 1, r->pool);
#define _TRANSHEADER(id,str) if(req->Headers.KnownHeaders[id].pRawValue != NULL) \
{\
apr_table_setn(r->headers_in, str, \
ZeroTerminate(req->Headers.KnownHeaders[id].pRawValue, req->Headers.KnownHeaders[id].RawValueLength, r->pool)); \
}
_TRANSHEADER(HttpHeaderCacheControl, "Cache-Control");
_TRANSHEADER(HttpHeaderConnection, "Connection");
_TRANSHEADER(HttpHeaderDate, "Date");
_TRANSHEADER(HttpHeaderKeepAlive, "Keep-Alive");
_TRANSHEADER(HttpHeaderPragma, "Pragma");
_TRANSHEADER(HttpHeaderTrailer, "Trailer");
_TRANSHEADER(HttpHeaderTransferEncoding, "Transfer-Encoding");
_TRANSHEADER(HttpHeaderUpgrade, "Upgrade");
_TRANSHEADER(HttpHeaderVia, "Via");
_TRANSHEADER(HttpHeaderWarning, "Warning");
_TRANSHEADER(HttpHeaderAllow, "Allow");
_TRANSHEADER(HttpHeaderContentLength, "Content-Length");
_TRANSHEADER(HttpHeaderContentType, "Content-Type");
_TRANSHEADER(HttpHeaderContentEncoding, "Content-Encoding");
_TRANSHEADER(HttpHeaderContentLanguage, "Content-Language");
_TRANSHEADER(HttpHeaderContentLocation, "Content-Location");
_TRANSHEADER(HttpHeaderContentMd5, "Content-Md5");
_TRANSHEADER(HttpHeaderContentRange, "Content-Range");
_TRANSHEADER(HttpHeaderExpires, "Expires");
_TRANSHEADER(HttpHeaderLastModified, "Last-Modified");
_TRANSHEADER(HttpHeaderAccept, "Accept");
_TRANSHEADER(HttpHeaderAcceptCharset, "Accept-Charset");
_TRANSHEADER(HttpHeaderAcceptEncoding, "Accept-Encoding");
_TRANSHEADER(HttpHeaderAcceptLanguage, "Accept-Language");
_TRANSHEADER(HttpHeaderAuthorization, "Authorization");
_TRANSHEADER(HttpHeaderCookie, "Cookie");
_TRANSHEADER(HttpHeaderExpect, "Expect");
_TRANSHEADER(HttpHeaderFrom, "From");
_TRANSHEADER(HttpHeaderHost, "Host");
_TRANSHEADER(HttpHeaderIfMatch, "If-Match");
_TRANSHEADER(HttpHeaderIfModifiedSince, "If-Modified-Since");
_TRANSHEADER(HttpHeaderIfNoneMatch, "If-None-Match");
_TRANSHEADER(HttpHeaderIfRange, "If-Range");
_TRANSHEADER(HttpHeaderIfUnmodifiedSince, "If-Unmodified-Since");
_TRANSHEADER(HttpHeaderMaxForwards, "Max-Forwards");
_TRANSHEADER(HttpHeaderProxyAuthorization, "Proxy-Authorization");
_TRANSHEADER(HttpHeaderReferer, "Referer");
_TRANSHEADER(HttpHeaderRange, "Range");
_TRANSHEADER(HttpHeaderTe, "TE");
_TRANSHEADER(HttpHeaderTranslate, "Translate");
_TRANSHEADER(HttpHeaderUserAgent, "User-Agent");
#undef _TRANSHEADER
for(int i = 0; i < req->Headers.UnknownHeaderCount; i++)
{
apr_table_setn(r->headers_in,
ZeroTerminate(req->Headers.pUnknownHeaders[i].pName, req->Headers.pUnknownHeaders[i].NameLength, r->pool),
ZeroTerminate(req->Headers.pUnknownHeaders[i].pRawValue, req->Headers.pUnknownHeaders[i].RawValueLength, r->pool));
}
r->content_encoding = apr_table_get(r->headers_in, "Content-Encoding");
r->content_type = apr_table_get(r->headers_in, "Content-Type");
const char *lng = apr_table_get(r->headers_in, "Content-Languages");
if(lng != NULL)
{
r->content_languages = apr_array_make(r->pool, 1, sizeof(const char *));
*(const char **)apr_array_push(r->content_languages) = lng;
}
switch(req->Verb)
{
case HttpVerbUnparsed:
case HttpVerbUnknown:
case HttpVerbInvalid:
case HttpVerbTRACK: // used by Microsoft Cluster Server for a non-logged trace
case HttpVerbSEARCH:
default:
r->method = "INVALID";
r->method_number = M_INVALID;
break;
case HttpVerbOPTIONS:
r->method = "OPTIONS";
r->method_number = M_OPTIONS;
break;
case HttpVerbGET:
case HttpVerbHEAD:
r->method = "GET";
r->method_number = M_GET;
break;
case HttpVerbPOST:
r->method = "POST";
r->method_number = M_POST;
break;
case HttpVerbPUT:
r->method = "PUT";
r->method_number = M_PUT;
break;
case HttpVerbDELETE:
r->method = "DELETE";
r->method_number = M_DELETE;
break;
case HttpVerbTRACE:
r->method = "TRACE";
r->method_number = M_TRACE;
break;
case HttpVerbCONNECT:
r->method = "CONNECT";
r->method_number = M_CONNECT;
break;
case HttpVerbMOVE:
r->method = "MOVE";
r->method_number = M_MOVE;
break;
case HttpVerbCOPY:
r->method = "COPY";
r->method_number = M_COPY;
break;
case HttpVerbPROPFIND:
r->method = "PROPFIND";
r->method_number = M_PROPFIND;
break;
case HttpVerbPROPPATCH: