Threat Level: green Handler on Duty: Brad Duncan

SANS ISC: The bane of XSS SANS ISC InfoSec Forums

Watch ISC TV. Great for NOCs, SOCs and Living Rooms:

Sign Up for Free!   Forgot Password?
Log In or Sign Up for Free!
The bane of XSS

I would like to thank Andrew for pointing out a XSS vulnerability in one of our tools. The tool pretty simply echoed back user input without proper output encoding.

XSS is in particular difficult to avoid as it may happen anywhere you send data back to the user. The proper encoding depends on the context the data is used in, and sometimes, a simple "replace < and > with &lt; and &gt;" doesn't cut it [1]. However, in my experience, many cross site scripting errors happen because the coder (in this case me), just didn't bother to properly escape at all.

A while back, I started using a "safe_out" function. This function will do the simple HTML entity replacement before printing the data. By using "safe_out" instead of "echo" or "print", I got a simple check ("grep print") to make sure I didn't miss a spot. The function is only good if you return data in the HTML body of a page, but this is what I am doing 99% of the time. 

function safe_out($sText){

The function is however a pain to use if you are mixing HTML and user data. Lets say you are trying to replace a print statement like:

print "<tr><td>$col1</td><td>$col2</td><td>$col3</td></tr>";

this would become:

print "<tr><td>";
print "</td><td>";

To overcome this, I modified the safe_out function somewhat, to make it easier to use in these case:

function safe_out($sText,$aVars=''){
  if ( $aVars=='' ) {
  } else {
    if ( is_array($aVars) ) {
      foreach ( $aVars as $key=>$value ) {
      echo $sText;
Now, it almost starts to look like  a prepared statement:


Of course Java users, may want to consider the OWASP ESAPI framework. It includes appropriate output encoders. But for php coders like me, the above snippet may be of help.


Johannes B. Ullrich, Ph.D.
SANS Technology Institute

I will be teaching next: Defending Web Applications Security Essentials - SANS Cyber Defense Initiative 2021


4306 Posts
ISC Handler
Jun 12th 2012

Sign Up for Free or Log In to start participating in the conversation!