Recipe 15-1: JavaScript Cookie Testing
This recipe shows you how to validate browser clients by issuing a JavaScript cookie test.
Ingredients
- ModSecurity
- SecContentInjection directive
- SecStreamOutBodyInspection directive
- STREAM_OUTPUT_BODY variable
- @rsub operator
When your web application is under a severe attack, it is helpful to be able to identify real clients using web browsers from automated client programs. One method of doing this is to issue a JavaScript cookie test. You simply send some JavaScript to the client that creates a new cookie value. If the client is using a real web browser, it will most likely automatically create the cookie value and submit it back with subsequent requests. If the client is an automated attack program or script, however, it does not execute the JavaScript code. If the client does not execute JavaScript, the cookie is not created, and we can easily identify the client as nonhuman.
The first step is to use ModSecurity to dynamically add JavaScript calls in the HTML header tag to include our new browser validation cookie code. These rules add the code to the main page URL by using the
@rsub operator to inject our code after the HTML
<head> tag:
SecContentInjection On
SecStreamOutBodyInspection On
SecRule REQUEST_FILENAME "@streq /" "chain,phase:4,t:none,nolog
,pass"
SecRule &IP:NOT_BOT_SENT "!@eq 0" "chain"
SecRule STREAM_OUTPUT_BODY "@rsub s/<head>/<head>
<script>document.cookie = \
"not_bot=10e82e54fad29fad98a5a67eb90c5a02c4b6942f\; ...