Validate String Characters In Cookie Rule

Problem this snippet solves:

This rule demonstrates how to efficiently validate whether a given string contains any illegal characters. The rule uses the scan function to perform the validation. This is more efficient than other string commands and significantly more efficient than regex commands.

The example checks a configured cookie to see if its value contains any characters not defined in the configured legal list of characters. The rule doesn't actually do anything but log entries to /var/log/ltm.

Code :

when RULE_INIT {

   # Set the name of the cookie to validate
   set ::cookie_to_validate "my_cookie"

   # Log debug messages to /var/log/ltm?  1=yes, 0=no.
   set ::cookie_validation_debug 1

   # Character set validation:
   # The format is {%[CHARS]}, where CHARS can be a character ranges or single characters.  
   # For details on configuring the characters, refer to the TCL man page for 'scan'
   # The literal hyphern character '-' needs to be listed first or last in the character set
   set ::allowed_chars_cookie_value {%[-a-zA-Z0-9_]}
}

when HTTP_REQUEST {

   # Check if the cookie is present in a request and has a length
   if {[HTTP::cookie value $::cookie_to_validate] ne ""}{

      # Check if the cookie value contains any illegal characters
      if {[HTTP::cookie value $::cookie_to_validate] eq [scan [HTTP::cookie value $::cookie_to_validate] $::allowed_chars_cookie_value]}{

         # Cookie contains only valid characters

         # Log a message if debug is enabled
         if {$::cookie_validation_debug}{log local0. "[IP::client_addr]:[TCP::client_port]: Request with legal cookie value: [HTTP::cookie value $::cookie_to_validate]"}

      } else {

         # Cookie contained invalid characters

         # Log a message if debug is enabled
         if {$::cookie_validation_debug}{

 set len [string length [scan [HTTP::cookie value $::cookie_to_validate] $::allowed_chars_cookie_value]]

 log local0. "[IP::client_addr]:[TCP::client_port]: Request with illegal cookie value: [HTTP::cookie value $::cookie_to_validate], \
            char: [string range [HTTP::cookie value $::cookie_to_validate] $len $len]"}
      }
   }
}
Published Mar 18, 2015
Version 1.0
No CommentsBe the first to comment