#!/usr/bin/perl
#
# snort2modsec.pl
# mod_security, http://www.modsecurity.org/
# Copyright (c) 2002,2003 Ivan Ristic <ivanr@webkreator.com>
#
# $Id: snort2modsec.pl,v 1.1 2003/10/19 18:09:25 ivanr Exp $
#
# This script will convert Snort rules into the mod_security
# rule format. Supply a list of files on the command line and
# it will write mod_security rules to the standard output.
#
# See http://www.modsecurity.org/documentation/converted-snort-rules.html
# for more information

die("Usage: snort2modsec.pl <snort rule files>\n") unless(@ARGV);

foreach $file (@ARGV) {
   
	open(RULES, $file) or die( "Cannot open file: $file\n" );

LOOP:	
	while(<RULES>) {
		next if(/^\s$/);
		next if(/^\#/);

		if (/\((.*)\)/) {
			$action = $1;

			$uricontent = "";
			$content = "";
			$msg = "";
			$classtype = "";
			$reference = "";

			foreach $rule (split(/;\s+/, $action)) {

				# print "$rule\n";

				if ($rule =~ /uricontent:\s*\"(.*)\"/) {
					$uricontent = $1;
				} elsif ($rule =~ /content:\s*\"(.*)\"/) {
					$content = $1;
				} elsif ($rule =~ /msg:\s*\"(.*)\"/) {
					$msg = $1;
				} elsif ($rule =~ /classtype:\s*(.*)/) {
					$classtype = $1;
				}
			}

			# decode URL decoding
			$uricontent =~ s/%([a-fA-F0-9][a-fA-F0-9])/\\x$1/sg;
			$content =~ s/%([a-fA-F0-9][a-fA-F0-9])/\\x$1/sg;

            $uricontent =~ s/([][|()\$\^{}+?.])/\\\1/g;
            $content =~ s/([][|()\$\^{}+?.])/\\\1/g;

			# todo: decode |XX XX XX| content, for now
			# skip over the rules that are using it
			if ($content =~ /\|/) {
				next LOOP;
			}

            if ($uricontent =~ /\|/) {
                next LOOP;
            }

			print "# $msg";
			# if (!($reference eq "")) {
			# 	print ", $reference";
			# }
			print "\n";

			if (!($uricontent eq "")) {
				if (!($content eq "")) {
					print "SecFilterSelective THE_REQUEST \"$uricontent\" chain\n";
					print "SecFilter \"$content\"";
				} else {
					print "SecFilterSelective THE_REQUEST \"$uricontent\"";
					
				}
			} else {
				print "SecFilter \"$content\"";
			}

			if ($classtype eq "web-application-activity") {
				print " log,pass";
			}

			print "\n\n";
		}
   }
   close(RULES);
}
