Product SiteDocumentation Site

10.3.2. Writing Your Own mod_security Rules

In this section, we'll create a rule chain which blocks the request if certain "spammy" words are entered in a HTML form. First, we'll create a PHP script which gets the input from a textbox and displays it back to the user.
  1. Download form.php script.
    $ wget http://zeus.fei.tuke.sk/bps3r/form.php.txt
    $ cp form.php.txt /var/www/html/form.php
    $ \rm /etc/httpd/modsecurity.d/*.conf
    <html>
        <body>
            <?php
                if(isset($_POST['data']))
                    echo $_POST['data'];
                else
                {
            ?>
                    <form method="post" action="">
                            Enter something here:<textarea name="data"></textarea>
                            <input type="submit"/>
                    </form>
            <?php
                }
            ?>
        </body>
    </html>
  2. Custom rules can be added to any of the configuration files or placed in modsecurity directories. We'll place our rules in a separate new file.
    $ mcedit /etc/httpd/modsecurity.d/rules.conf
    Enter:
    SecRule REQUEST_FILENAME "form.php" "id:'400001',chain,deny,log,msg:'Spam detected'"
    SecRule REQUEST_METHOD "POST" chain
    SecRule REQUEST_BODY "@rx (?i:(pills|insurance|rolex))"
  3. Save the file and reload Apache.
    $ service httpd restart
  4. Open http://192.168.56.XYZ/form.php in the browser and enter text containing any of these words: pills, insurance, rolex. You'll either see a 403 page and a log entry or only a log entry based on SecRuleEngine setting.