forked from owasp-modsecurity/ModSecurity
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmod_security2.c
executable file
·1792 lines (1528 loc) · 61.4 KB
/
mod_security2.c
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].
*/
#include <limits.h>
#include "http_core.h"
#include "http_request.h"
#include "modsecurity.h"
#include "apache2.h"
#include "http_main.h"
#include "http_connection.h"
#include "apr_optional.h"
#include "mod_log_config.h"
/*
* #ifdef APLOG_USE_MODULE
* APLOG_USE_MODULE(security2);
* #endif
*/
#include "msc_logging.h"
#include "msc_util.h"
#include "ap_mpm.h"
#include "scoreboard.h"
#include "apr_version.h"
#include "msc_remote_rules.h"
#if defined(WITH_LUA)
#include "msc_lua.h"
#endif
#include "msc_status_engine.h"
#ifdef WITH_YAJL
#include <yajl/yajl_version.h>
#endif /* WITH_YAJL */
/* ModSecurity structure */
msc_engine DSOLOCAL *modsecurity = NULL;
/* Global module variables; these are used for the Apache-specific functionality */
char DSOLOCAL *chroot_dir = NULL;
char DSOLOCAL *new_server_signature = NULL;
char DSOLOCAL *real_server_signature = NULL;
char DSOLOCAL *guardianlog_name = NULL;
apr_file_t DSOLOCAL *guardianlog_fd = NULL;
char DSOLOCAL *guardianlog_condition = NULL;
unsigned long int DSOLOCAL msc_pcre_match_limit = 0;
unsigned long int DSOLOCAL msc_pcre_match_limit_recursion = 0;
#ifdef WITH_REMOTE_RULES
msc_remote_rules_server DSOLOCAL *remote_rules_server = NULL;
#endif
int DSOLOCAL remote_rules_fail_action = REMOTE_RULES_ABORT_ON_FAIL;
char DSOLOCAL *remote_rules_fail_message = NULL;
int DSOLOCAL status_engine_state = STATUS_ENGINE_DISABLED;
int DSOLOCAL conn_limits_filter_state = MODSEC_DISABLED;
unsigned long int DSOLOCAL conn_read_state_limit = 0;
TreeRoot DSOLOCAL *conn_read_state_whitelist = 0;
TreeRoot DSOLOCAL *conn_read_state_suspicious_list = 0;
unsigned long int DSOLOCAL conn_write_state_limit = 0;
TreeRoot DSOLOCAL *conn_write_state_whitelist = 0;
TreeRoot DSOLOCAL *conn_write_state_suspicious_list = 0;
#ifdef WAF_JSON_LOGGING_ENABLE
char DSOLOCAL *msc_waf_resourceId = NULL;
char DSOLOCAL *msc_waf_instanceId = NULL;
sig_atomic_t DSOLOCAL msc_waf_log_reopen_requested = 1;
struct waf_lock DSOLOCAL *wafjsonlog_lock = NULL;
apr_file_t DSOLOCAL *msc_waf_log_fd = NULL;
char DSOLOCAL msc_waf_log_path[WAF_LOG_PATH_LENGTH] = "";
cmd_parms DSOLOCAL *msc_waf_log_cmd = NULL;
#endif
#ifndef _WIN32
char DSOLOCAL *msc_waf_lock_user;
char DSOLOCAL *msc_waf_lock_group;
#endif
#if defined(WIN32) || defined(VERSION_NGINX)
int (*modsecDropAction)(request_rec *r) = NULL;
#endif
static int server_limit, thread_limit;
/* -- Miscellaneous functions -- */
/**
* \brief Print informations from used libraries
*
* \param mp Pointer to memory pool
*/
static void version(apr_pool_t *mp) {
char *pcre_vrs = NULL;
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
"ModSecurity: APR compiled version=\"%s\"; "
"loaded version=\"%s\"", APR_VERSION_STRING, apr_version_string());
if (strstr(apr_version_string(), APR_VERSION_STRING) == NULL) {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL, "ModSecurity: Loaded APR do not match with compiled!");
}
pcre_vrs = apr_psprintf(mp,"%d.%d ", PCRE_MAJOR, PCRE_MINOR);
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
"ModSecurity: PCRE compiled version=\"%s\"; "
"loaded version=\"%s\"", pcre_vrs, pcre_version());
if (strstr(pcre_version(),pcre_vrs) == NULL) {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL, "ModSecurity: Loaded PCRE do not match with compiled!");
}
/* Lua version function was removed in current 5.1. Need to check in future versions if it's back */
#if defined(WITH_LUA)
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
"ModSecurity: LUA compiled version=\"%s\"", LUA_VERSION);
#endif /* WITH_LUA */
#ifdef WITH_YAJL
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
"ModSecurity: YAJL compiled version=\"%d.%d.%d\"", YAJL_MAJOR, YAJL_MINOR, YAJL_MICRO);
#endif /* WITH_YAJL */
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
"ModSecurity: LIBXML compiled version=\"%s\"", LIBXML_DOTTED_VERSION);
}
/**
* Intercepts transaction, using the method specified
* in the structure itself. MUST return an HTTP status code,
* which will be used to terminate the transaction.
*/
int perform_interception(modsec_rec *msr) {
msre_actionset *actionset = NULL;
const char *message = NULL;
const char *phase_text = "";
unsigned int pause = 0;
int status = DECLINED;
int log_level = 1;
/* Sanity checks first. */
if (msr->was_intercepted == 0) {
msr_log(msr, 1, "Internal Error: Asked to intercept request but was_intercepted is zero");
return DECLINED;
}
if (msr->phase > 4) {
msr_log(msr, 1, "Internal Error: Asked to intercept request in phase %d.", msr->phase);
msr->was_intercepted = 0;
return DECLINED;
}
/* OK, we're good to go. */
actionset = msr->intercept_actionset;
phase_text = apr_psprintf(msr->mp, " (phase %d)", msr->phase);
/* By default we log at level 1 but we switch to 4
* if a nolog action was used or this is not the initial request
* to hide the message.
*/
log_level = (actionset->log != 1) ? 4 : 1;
/* Pause the request first (if configured and the initial request). */
if (actionset->intercept_pause != NULL) {
if(strstr(actionset->intercept_pause,"%{") != NULL) {
msc_string *var = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string));
var->value = (char *)actionset->intercept_pause;
var->value_len = strlen(actionset->intercept_pause);
expand_macros(msr, var, NULL, msr->mp);
pause = atoi(var->value);
if ((pause == LONG_MAX)||(pause == LONG_MIN)||(pause <= 0))
pause = 0;
msr_log(msr, (log_level > 3 ? log_level : log_level + 1), "Pausing transaction for "
"%d msec.", pause);
/* apr_sleep accepts microseconds */
apr_sleep((apr_interval_time_t)(pause * 1000));
} else {
pause = atoi(actionset->intercept_pause);
if ((pause == LONG_MAX)||(pause == LONG_MIN)||(pause <= 0))
pause = 0;
msr_log(msr, (log_level > 3 ? log_level : log_level + 1), "Pausing transaction for "
"%d msec.", pause);
/* apr_sleep accepts microseconds */
apr_sleep((apr_interval_time_t)(pause * 1000));
}
}
/* Determine how to respond and prepare the log message. */
switch(actionset->intercept_action) {
case ACTION_DENY :
if (actionset->intercept_status != 0) {
status = actionset->intercept_status;
message = apr_psprintf(msr->mp, "Access denied with code %d%s.",
status, phase_text);
} else {
log_level = 1;
status = HTTP_INTERNAL_SERVER_ERROR;
message = apr_psprintf(msr->mp, "Access denied with code 500%s "
"(Internal Error: Invalid status code requested %d).",
phase_text, actionset->intercept_status);
}
break;
case ACTION_PROXY :
#if !(defined(VERSION_IIS)) && !(defined(VERSION_NGINX)) && !(defined(VERSION_STANDALONE))
if (msr->phase < 3) {
if (ap_find_linked_module("mod_proxy.c") == NULL) {
log_level = 1;
status = HTTP_INTERNAL_SERVER_ERROR;
message = apr_psprintf(msr->mp, "Access denied with code 500%s "
"(Configuration Error: Proxy action to %s requested but mod_proxy not found).",
phase_text,
log_escape_nq(msr->mp, actionset->intercept_uri));
} else {
msr->r->filename = apr_psprintf(msr->mp, "proxy:%s", actionset->intercept_uri);
msr->r->proxyreq = PROXYREQ_REVERSE;
msr->r->handler = "proxy-server";
status = OK;
message = apr_psprintf(msr->mp, "Access denied using proxy to%s %s.",
phase_text,
log_escape_nq(msr->mp, actionset->intercept_uri));
}
} else {
log_level = 1;
status = HTTP_INTERNAL_SERVER_ERROR;
message = apr_psprintf(msr->mp, "Access denied with code 500%s "
"(Configuration Error: Proxy action requested but it does not work in output phases).",
phase_text);
}
#else
log_level = 1;
status = HTTP_INTERNAL_SERVER_ERROR;
message = apr_psprintf(msr->mp, "Access denied with code 500%s "
"(Configuration Error: Proxy action to %s requested but "
"proxy is only available in Apache version).",
phase_text,
log_escape_nq(msr->mp, actionset->intercept_uri));
#endif
break;
case ACTION_DROP :
/* ENH This does not seem to work on Windows. Is there a
* better way to drop a connection anyway?
*/
#if !defined(WIN32) && !defined(VERSION_NGINX)
{
extern module core_module;
apr_socket_t *csd;
#if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER > 2 && AP_SERVER_PATCHLEVEL_NUMBER > 17
/* For mod_http2 used by HTTP/2 there is a virtual connection so must go through
* master to get the main connection or the drop request doesn't seem to do anything.
* For HTTP/1.1 master will not be defined so just go through normal connection.
* More details here: https://github.com/icing/mod_h2/issues/127
*/
if (msr->r->connection->master) {
csd = ap_get_module_config(msr->r->connection->master->conn_config, &core_module);
} else {
csd = ap_get_module_config(msr->r->connection->conn_config, &core_module);
}
#else
csd = ap_get_module_config(msr->r->connection->conn_config, &core_module);
#endif
if (csd) {
if (apr_socket_close(csd) == APR_SUCCESS) {
status = HTTP_FORBIDDEN;
message = apr_psprintf(msr->mp, "Access denied with connection close%s.",
phase_text);
} else {
log_level = 1;
status = HTTP_INTERNAL_SERVER_ERROR;
message = apr_psprintf(msr->mp, "Access denied with code 500%s "
"(Error: Connection drop requested but failed to close the "
" socket).",
phase_text);
}
} else {
log_level = 1;
status = HTTP_INTERNAL_SERVER_ERROR;
message = apr_psprintf(msr->mp, "Access denied with code 500%s "
"(Error: Connection drop requested but socket not found.",
phase_text);
}
}
#else
{
if (modsecDropAction == NULL) {
log_level = 1;
status = HTTP_INTERNAL_SERVER_ERROR;
message = apr_psprintf(msr->mp, "Access denied with code 500%s "
"(Error: Connection drop not implemented on this platform.",
phase_text);
} else if (modsecDropAction(msr->r) == 0) {
status = HTTP_FORBIDDEN;
message = apr_psprintf(msr->mp, "Access denied with connection close%s.",
phase_text);
} else {
log_level = 1;
status = HTTP_INTERNAL_SERVER_ERROR;
message = apr_psprintf(msr->mp, "Access denied with code 500%s "
"(Error: Connection drop request failed.",
phase_text);
}
}
#endif
break;
case ACTION_REDIRECT :
if(strstr(actionset->intercept_uri,"%{") != NULL) {
msc_string *var = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string));
var->value = (char *)actionset->intercept_uri;
var->value_len = strlen(actionset->intercept_uri);
expand_macros(msr, var, NULL, msr->mp);
apr_table_setn(msr->r->headers_out, "Location", var->value);
if ((actionset->intercept_status == 301)||(actionset->intercept_status == 302)
||(actionset->intercept_status == 303)||(actionset->intercept_status == 307))
{
status = actionset->intercept_status;
} else {
status = HTTP_MOVED_TEMPORARILY;
}
message = apr_psprintf(msr->mp, "Access denied with redirection to %s using "
"status %d%s.",
log_escape_nq(msr->mp, var->value), status,
phase_text);
} else {
apr_table_setn(msr->r->headers_out, "Location", actionset->intercept_uri);
if ((actionset->intercept_status == 301)||(actionset->intercept_status == 302)
||(actionset->intercept_status == 303)||(actionset->intercept_status == 307))
{
status = actionset->intercept_status;
} else {
status = HTTP_MOVED_TEMPORARILY;
}
message = apr_psprintf(msr->mp, "Access denied with redirection to %s using "
"status %d%s.",
log_escape_nq(msr->mp, actionset->intercept_uri), status,
phase_text);
}
break;
case ACTION_ALLOW :
status = DECLINED;
message = apr_psprintf(msr->mp, "Access allowed%s.", phase_text);
msr->was_intercepted = 0;
msr->allow_scope = ACTION_ALLOW;
break;
case ACTION_PAUSE :
status = DECLINED;
message = apr_psprintf(msr->mp, "Paused Access%s.", phase_text);
msr->was_intercepted = 0;
msr->allow_scope = ACTION_ALLOW;
break;
case ACTION_ALLOW_PHASE :
status = DECLINED;
message = apr_psprintf(msr->mp, "Access to phase allowed%s.", phase_text);
msr->was_intercepted = 0;
msr->allow_scope = ACTION_ALLOW_PHASE;
break;
case ACTION_ALLOW_REQUEST :
status = DECLINED;
message = apr_psprintf(msr->mp, "Access to request allowed%s.", phase_text);
msr->was_intercepted = 0;
msr->allow_scope = ACTION_ALLOW_REQUEST;
break;
default :
log_level = 1;
status = HTTP_INTERNAL_SERVER_ERROR;
message = apr_psprintf(msr->mp, "Access denied with code 500%s "
"(Internal Error: invalid interception action %d).",
phase_text, actionset->intercept_action);
break;
}
/* If the level is not high enough to add an alert message, but "auditlog"
* is enabled, then still add the message. */
if ((log_level > 3) && (actionset->auditlog != 0)) {
*(const char **)apr_array_push(msr->alerts) = msc_alert_message(msr, actionset, NULL, message);
}
/* Log the message now. */
msc_alert(msr, log_level, actionset, message, msr->intercept_message);
/* However, this will mark the txn relevant again if it is <= 3,
* which will mess up noauditlog. We need to compensate for this
* so that we do not increment twice when auditlog is enabled and
* prevent incrementing when auditlog is disabled.
*/
if ((actionset->auditlog == 0) && (log_level <= 3)) {
msr->is_relevant--;
}
return status;
}
/**
* Retrieves a previously stored transaction context by
* looking at the main request, and the previous requests.
*/
static modsec_rec *retrieve_tx_context(request_rec *r) {
modsec_rec *msr = NULL;
request_rec *rx = NULL;
/* Look in the current request first. */
msr = (modsec_rec *)apr_table_get(r->notes, NOTE_MSR);
if (msr != NULL) {
msr->r = r;
return msr;
}
/* If this is a subrequest then look in the main request. */
if (r->main != NULL) {
msr = (modsec_rec *)apr_table_get(r->main->notes, NOTE_MSR);
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 = (modsec_rec *)apr_table_get(rx->notes, NOTE_MSR);
if (msr != NULL) {
msr->r = r;
return msr;
}
rx = rx->prev;
}
return NULL;
}
/**
* Stores transaction context where it can be found in subsequent
* phases, redirections, or subrequests.
*/
static void store_tx_context(modsec_rec *msr, request_rec *r) {
apr_table_setn(r->notes, NOTE_MSR, (void *)msr);
}
/**
* Creates a new transaction context.
*/
modsec_rec *create_tx_context(request_rec *r) {
apr_allocator_t *allocator = NULL;
modsec_rec *msr = NULL;
msr = (modsec_rec *)apr_pcalloc(r->pool, sizeof(modsec_rec));
if (msr == NULL) return NULL;
apr_allocator_create(&allocator);
apr_allocator_max_free_set(allocator, 1024);
apr_pool_create_ex(&msr->mp, r->pool, NULL, allocator);
if (msr->mp == NULL) return NULL;
apr_allocator_owner_set(allocator, msr->mp);
msr->modsecurity = modsecurity;
msr->r = r;
msr->r_early = r;
msr->request_time = r->request_time;
msr->dcfg1 = (directory_config *)ap_get_module_config(r->per_dir_config,
&security2_module);
#if defined(WITH_LUA)
#ifdef CACHE_LUA
#if LUA_VERSION_NUM > 501
msr->L = luaL_newstate();
#else
msr->L = lua_open();
#endif
luaL_openlibs(msr->L);
#endif
#endif
/**
* Create a special user configuration. This is where
* explicit instructions will be stored. This will be used
* to override the default settings (and to override the
* configuration in the second phase, dcfg2, with the user
* setting executed in the first phase.
*/
msr->usercfg = create_directory_config(msr->mp, NULL);
if (msr->usercfg == NULL) return NULL;
/* Create a transaction context and populate
* it using the directory config we just
* got from Apache.
*/
msr->txcfg = create_directory_config(msr->mp, NULL);
if (msr->txcfg == NULL) return NULL;
if (msr->dcfg1 != NULL) {
msr->txcfg = merge_directory_configs(msr->mp, msr->txcfg, msr->dcfg1);
if (msr->txcfg == NULL) return NULL;
}
init_directory_config(msr->txcfg);
msr->txid = get_env_var(r, "UNIQUE_ID");
if (msr->txid == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, r->server,
"ModSecurity: ModSecurity requires mod_unique_id to be installed.");
return NULL;
}
if (msr->txcfg->debuglog_level >= 4) {
msr_log(msr, 4, "Initialising transaction (txid %s).", msr->txid);
}
/* Populate tx fields */
msr->error_messages = apr_array_make(msr->mp, 5, sizeof(error_message_t *));
msr->alerts = apr_array_make(msr->mp, 5, sizeof(char *));
msr->server_software = real_server_signature;
msr->local_addr = r->connection->local_ip;
msr->local_port = r->connection->local_addr->port;
#if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER < 3
msr->remote_addr = r->connection->remote_ip;
msr->remote_port = r->connection->remote_addr->port;
#else
msr->remote_addr = r->connection->client_ip;
msr->remote_port = r->connection->client_addr->port;
msr->useragent_ip = r->useragent_ip;
#endif
msr->request_line = r->the_request;
msr->request_uri = r->uri;
msr->request_method = r->method;
msr->query_string = r->args;
msr->request_protocol = r->protocol;
msr->request_headers = apr_table_copy(msr->mp, r->headers_in);
msr->hostname = ap_get_server_name(r);
msr->msc_full_request_buffer = NULL;
msr->msc_full_request_length = 0;
msr->msc_rule_mptmp = NULL;
/* Invoke the engine to continue with initialisation */
if (modsecurity_tx_init(msr) < 0) {
msr_log(msr, 1, "Failed to initialise transaction (txid %s).", msr->txid);
return NULL;
}
store_tx_context(msr, r);
if (msr->txcfg->debuglog_level >= 4) {
msr_log(msr, 4, "Transaction context created (dcfg %pp).", msr->dcfg1);
}
return msr;
}
/* -- Hooks -- */
/*
* Change the signature of the server if change was requested in
* configuration. We do this by locating the signature in server
* memory and writing over it.
*/
static apr_status_t change_server_signature(server_rec *s) {
char *server_version = NULL;
/* This is a very particular way to handle the server banner. It is Apache
* only. Stanalone and descendants should address that in its specifics
* implementations, e.g. Nginx module.
*/
#if !(defined(VERSION_IIS)) && !(defined(VERSION_NGINX)) && !(defined(VERSION_STANDALONE))
if (new_server_signature == NULL) return 0;
server_version = (char *)apache_get_server_version();
if (server_version == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, s,
"SecServerSignature: Apache returned null as signature.");
return -1;
}
if (strlen(server_version) >= strlen(new_server_signature)) {
strcpy(server_version, new_server_signature);
}
else {
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, s,
"SecServerSignature: original signature too short. Please set "
"ServerTokens to Full.");
return -1;
}
/* Check that it really changed. This assumes that what we got was
* not a copy and this could change in future versions of Apache.
*/
server_version = (char *)apache_get_server_version();
if ((server_version == NULL) || (strcmp(server_version, new_server_signature) != 0)) {
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, s, "SecServerSignature: Failed to change server signature to \"%s\".", new_server_signature);
return 0;
}
else {
ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, s, "SecServerSignature: Changed server signature to \"%s\".", server_version);
}
#endif
return 1;
}
/**
* Executed at the end of server lifetime to cleanup the allocated resources.
*/
static apr_status_t module_cleanup(void *data) {
modsecurity_shutdown(modsecurity);
return APR_SUCCESS;
}
/**
* Generate a single variable for use with mod_log_config.
*/
static const char *modsec_var_log_handler(request_rec *r, char *name) {
modsec_rec *msr = NULL;
if (name == NULL) return NULL;
msr = retrieve_tx_context(r);
if (msr == NULL) return NULL;
return construct_single_var(msr, name);
}
/**
* Pre-configuration initialisation hook.
*/
static int hook_pre_config(apr_pool_t *mp, apr_pool_t *mp_log, apr_pool_t *mp_temp) {
static APR_OPTIONAL_FN_TYPE(ap_register_log_handler) *log_pfn_register;
/* Initialise ModSecurity engine */
modsecurity = modsecurity_create(mp, MODSEC_ONLINE);
if (modsecurity == NULL) {
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
"ModSecurity: Failed to initialise engine.");
return HTTP_INTERNAL_SERVER_ERROR;
}
log_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_log_handler);
if (log_pfn_register) {
log_pfn_register(mp, "M", modsec_var_log_handler, 0);
}
return OK;
}
/**
* Main (post-configuration) module initialisation.
*/
static int hook_post_config(apr_pool_t *mp, apr_pool_t *mp_log, apr_pool_t *mp_temp, server_rec *s) {
void *init_flag = NULL;
int first_time = 0;
/* ENH Figure out a way to validate config before we start
* - skipafter: need to make sure we found all of our targets
*/
/* Figure out if we are here for the first time */
apr_pool_userdata_get(&init_flag, "modsecurity-init-flag", s->process->pool);
if (init_flag == NULL) {
first_time = 1;
apr_pool_userdata_set((const void *)1, "modsecurity-init-flag",
apr_pool_cleanup_null, s->process->pool);
} else {
modsecurity_init(modsecurity, mp);
}
/* Store the original server signature */
real_server_signature = apr_pstrdup(mp, apache_get_server_version());
/* Make some space in the server signature for later */
if (new_server_signature != NULL) {
ap_add_version_component(mp, new_server_signature);
change_server_signature(s);
}
/* For connection level hook */
ap_mpm_query(AP_MPMQ_HARD_LIMIT_THREADS, &thread_limit);
ap_mpm_query(AP_MPMQ_HARD_LIMIT_DAEMONS, &server_limit);
#if (!(defined(WIN32) || defined(NETWARE)))
/* Internal chroot functionality */
if (chroot_dir != NULL) {
/* ENH Is it safe to simply return with an error, instead
* of using exit()?
*/
if (first_time == 0) {
ap_log_error(APLOG_MARK, APLOG_NOTICE | APLOG_NOERRNO, 0, s,
"ModSecurity: chroot checkpoint #2 (pid=%ld ppid=%ld)", (long)getpid(), (long)getppid());
if (chdir(chroot_dir) < 0) {
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, s,
"ModSecurity: chroot failed, unable to chdir to %s, errno=%d (%s)",
chroot_dir, errno, strerror(errno));
exit(1);
}
if (chroot(chroot_dir) < 0) {
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, s,
"ModSecurity: chroot failed, path=%s, errno=%d(%s)",
chroot_dir, errno, strerror(errno));
exit(1);
}
if (chdir("/") < 0) {
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, s,
"ModSecurity: chdoot failed, unable to chdir to /, errno=%d (%s)",
errno, strerror(errno));
exit(1);
}
ap_log_error(APLOG_MARK, APLOG_NOTICE | APLOG_NOERRNO, 0, s,
"ModSecurity: chroot successful, path=%s", chroot_dir);
} else {
ap_log_error(APLOG_MARK, APLOG_NOTICE | APLOG_NOERRNO, 0, s,
"ModSecurity: chroot checkpoint #1 (pid=%ld ppid=%ld)", (long)getpid(), (long)getppid());
}
}
#endif
/* Schedule main cleanup for later, when the main pool is destroyed. */
apr_pool_cleanup_register(mp, (void *)s, module_cleanup, apr_pool_cleanup_null);
/* Log our presence to the error log. */
if (first_time) {
ap_log_error(APLOG_MARK, APLOG_NOTICE | APLOG_NOERRNO, 0, s,
"%s configured.", MODSEC_MODULE_NAME_FULL);
version(mp);
/* If we've changed the server signature make note of the original. */
if (new_server_signature != NULL) {
ap_log_error(APLOG_MARK, APLOG_NOTICE | APLOG_NOERRNO, 0, s,
"ModSecurity: Original server signature: %s",
real_server_signature);
}
#ifndef VERSION_IIS
if (status_engine_state != STATUS_ENGINE_DISABLED) {
msc_status_engine_call();
}
else {
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
"ModSecurity: Status engine is currently disabled, enable " \
"it by set SecStatusEngine to On.");
}
#endif
}
/**
* Checking if it is not the first time that we are in this very function.
* We want to show the messages below during the start and the reload.
*/
#ifndef VERSION_IIS
if (first_time != 1)
{
#ifdef WITH_REMOTE_RULES
if (remote_rules_server != NULL)
{
if (remote_rules_server->amount_of_rules == 1)
{
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
"ModSecurity: Loaded %d rule from: '%s'.",
remote_rules_server->amount_of_rules,
remote_rules_server->uri);
}
else
{
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
"ModSecurity: Loaded %d rules from: '%s'.",
remote_rules_server->amount_of_rules,
remote_rules_server->uri);
}
}
#endif
if (remote_rules_fail_message != NULL)
{
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL, "ModSecurity: " \
"Problems loading external resources: %s",
remote_rules_fail_message);
}
}
#endif
srand((unsigned int)(time(NULL) * getpid()));
return OK;
}
/**
* Initialisation performed for every new child process.
*/
static void hook_child_init(apr_pool_t *mp, server_rec *s) {
modsecurity_child_init(modsecurity);
}
#ifndef _WIN32
static void hook_set_lock_owner(const char *user, const char *group) {
modsecurity_set_lock_owner(user, group);
}
#endif
/**
* Initial request processing, executed immediatelly after
* Apache receives the request headers. This function wil create
* a transaction context.
*/
static int hook_request_early(request_rec *r) {
modsec_rec *msr = NULL;
int rc = DECLINED;
/* This function needs to run only once per transaction
* (i.e. subrequests and redirects are excluded).
*/
if ((r->main != NULL)||(r->prev != NULL)) {
return DECLINED;
}
/* Check if the transaction context
* has already been initialised.
*/
msr = retrieve_tx_context(r);
if (msr == NULL) {
/* Initialise transaction context and
* create the initial configuration.
*/
msr = create_tx_context(r);
if (msr == NULL) return DECLINED;
}
#ifdef REQUEST_EARLY
/* Are we allowed to continue? */
if (msr->txcfg->is_enabled == MODSEC_DISABLED) {
if (msr->txcfg->debuglog_level >= 4) {
msr_log(msr, 4, "Processing disabled, skipping (hook request_early).");
}
return DECLINED;
}
/* Process phase REQUEST_HEADERS */
if (modsecurity_process_phase(msr, PHASE_REQUEST_HEADERS) > 0) {
rc = perform_interception(msr);
}
if ( (msr->txcfg->is_enabled != MODSEC_DISABLED)
&& (msr->txcfg->reqbody_access == 1)
&& (rc == DECLINED))
{
/* Check request body limit (non-chunked requests only). */
if (msr->request_content_length > msr->txcfg->reqbody_limit) {
msr_log(msr, 1, "Request body (Content-Length) is larger than the "
"configured limit (%ld).", msr->txcfg->reqbody_limit);
if(msr->txcfg->is_enabled != MODSEC_DETECTION_ONLY && msr->txcfg->if_limit_action != REQUEST_BODY_LIMIT_ACTION_PARTIAL)
return HTTP_REQUEST_ENTITY_TOO_LARGE;
}
}
#endif
return rc;
}
/**
* Invoked as the first hook in the handler chain, this function
* executes the second phase of ModSecurity request processing.
*/
static int hook_request_late(request_rec *r) {
char *my_error_msg = NULL;
modsec_rec *msr = NULL;
int rc;
/* This function needs to run only once per transaction
* (i.e. subrequests and redirects are excluded).
*/
if ((r->main != NULL)||(r->prev != NULL)) {
return DECLINED;
}
/* Find the transaction context and make sure
* we are supposed to proceed.
*/
msr = retrieve_tx_context(r);
if (msr == NULL) {
/* If we can't find the context that probably means it's
* a subrequest that was not initiated from the outside.
*/
return DECLINED;
}
/* Has this phase been completed already? */
if (msr->phase_request_body_complete) {
msr_log(msr, 1, "Internal Error: Attempted to process the request body more than once.");
return DECLINED;
}
msr->phase_request_body_complete = 1;
msr->remote_user = r->user;
/* Get the second configuration context. */
msr->dcfg2 = (directory_config *)ap_get_module_config(r->per_dir_config,
&security2_module);
/* Create a transaction context. */
msr->txcfg = create_directory_config(msr->mp, NULL);
if (msr->txcfg == NULL) return DECLINED;
if (msr->dcfg2 != NULL) {
msr->txcfg = merge_directory_configs(msr->mp, msr->txcfg, msr->dcfg2);
if (msr->txcfg == NULL) return DECLINED;
}
/* Update with the explicit user settings. */
msr->txcfg = merge_directory_configs(msr->mp, msr->txcfg, msr->usercfg);
init_directory_config(msr->txcfg);
if (msr->txcfg->is_enabled == 0) {
if (msr->txcfg->debuglog_level >= 4) {
msr_log(msr, 4, "Processing disabled, skipping (hook request_late).");
}
return DECLINED;
}
#ifndef REQUEST_EARLY
/* Phase 1 */
if (msr->txcfg->debuglog_level >= 4) {
msr_log(msr, 4, "First phase starting (dcfg %pp).", msr->dcfg2);
}
/* Process phase REQUEST_HEADERS */
if (modsecurity_process_phase(msr, PHASE_REQUEST_HEADERS) > 0) {
/* There was a match; see if we need to intercept. */
rc = perform_interception(msr);
if (rc != DECLINED) {
/* Intercepted */
return rc;
}
}
#endif
/* The rule engine could have been disabled in phase 1. */
if (msr->txcfg->is_enabled == MODSEC_DISABLED) {
if (msr->txcfg->debuglog_level >= 4) {
msr_log(msr, 4, "Skipping phase 2 as the rule engine was disabled by a rule in phase 1.");
}
return DECLINED;
}