Using the OWASP PHP ESAPI – Part 3

On February 3, 2011, in Secure coding, by SecBytes

And here we are at the 3rd part of the OWASP ESAPI PHP tutorial series. If you haven’t read the first two yet, you can find Part One here and Part Two here. This week we’re going to cover encoding our output, and making our database queries safer. Let’s get right into it. This week’s files can be found here.

Encoding our output
We’ve seen the encoder in use a little bit so far – we’ve used it canonicalize our input. This week, we’re going to use it to encode user submitted output so that we can display it safely. Our blog app is extremely vulnerable to XSS attacks right now; for example, any commentor can post malicious code. By encoding our output before we display it we can significantly cut that risk.

First step, let’s examine our application and figure out where we’re outputting any user input. Of our four pieces, only one of them displays user submitted data; index.php.

Last week, we said that we would not allow the user to add actual functioning HTML or JavaScript into their comments or posts, so if there is any of that, we’re just going to encode it to display safely on the screen. So basically, anywhere in index.php that we’re displaying something a user submitted, we’re going to run it through the DefaultEncoder’s encodeForHTML function. All of that is contained in our construct_content_display function, which will now look like this:

function construct_content_display($content_arr) {
$output = '';
$encoder = ESAPI::getEncoder();
for($i=0;$i $output .= "

" . $encoder->encodeForHTML($content_arr[$i]->get_title()) . "

";
$output .= "

" . $encoder->encodeForHTML($content_arr[$i]->get_content()) . "

";
$comment_arr = get_all_comments($content_arr[$i]->get_content_id());
for($j=0;$j $output .= "

" . $encoder->encodeForHTML($comment_arr[$j]->get_comment()) . " - " . $encoder->encodeForHTML($comment_arr[$j]->get_date_created()) . "

";
}
$output .= "
get_content_id() . "\">Comment";
}
return $output;
}

And that’s all there is to it! There are lots of other useful functions in the Encoder security control and I highly encourage you to check them all out.

Making our database queries safe
The other thing we’re going to go over this week isn’t completely ESAPI PHP centric. There are several tactics we could use to protect ourselves against SQL injection attacks and generally make them more error-resistant. We could use the ESAPI PHP encoder to escape our queries, but the ESAPI PHP docs for the encodeForSQL function state it best when they say

check here to read more.

Tagged with:
 

Leave a Reply

*