HTML encoding proc

Problem this snippet solves:

This proc HTML encodes an input string.

See the OWASP discussion page for details on when/how to use this approach: XSS (Cross Site Scripting) Prevention Cheat Sheet

How to use this snippet:

iRule proc Source

Define the proc named html_encode in a separate iRule named library:

Code :

rule library {
proc html_encode { str } {
  set encoded ""
  foreach char [split $str ""] {
    switch $char {
      "<" { append encoded "<" }
      ">" { append encoded "<" }
      "'" { append encoded "'" }
      {"} { append encoded """ }
      "&" { append encoded "&" }
      default { append encoded $char }
    }
  }
  return $encoded
}
}

# Call the procedure from another iRule using the name of the iRule where the proc is defined as the namespace and then the name of the procedure (library::html_encode): 

when RULE_INIT {
# iRule that calls the html_encode proc:
set raw {some xss: < script >alert(document.cookie) and sqli: ' or 1==1# "}

log local0. "HTML encoded: [call library::html_encode $raw]"

# Log output
#HTML encoded: <script<alert(document.cookie)</script< and sqli: ' or 1==1# "
}
Published Mar 18, 2015
Version 1.0

Was this article helpful?

1 Comment

  • Please explain RULE_INIT.

     

    Can I call a proc anywhere? Like:

     

    when HTTP_REQUEST { set foo [call library:some_function "some arg"] ....