Securing Dynamically Generated HTML
Implementing code that simply displays a user’s IP address as part of an HTML page may be considered easy. Without security considerations, it can be implemented in PHP simply with the following:
echo "IP: " . $_SERVER['REMOTE_ADDR'];
2011 CWE/SANS Top 25: Monster Mitigations recommends establishing and maintaining “control over all your inputs” and “control over all of your outputs.” Since the IP address is output as part of an HTML page, the code is more securely implemented as follows:
$ipAddrRemote = $_SERVER['REMOTE_ADDR']; if(my_is_ipaddr_valid($ipAddrRemote)) { $ipAddrEncoded = my_htmlencode($ipAddrRemote); "IP: ${ipAddrEncoded}"; }
The remote IP address is retrieved from the global $_SERVER variable for validation then use. The validated address is encoded before it is used in the output HTML.
The difficulty of selecting appropriate validation and encoding functions is conveniently abstracted away here by user-defined functions: my_is_ipaddr_valid() and my_htmlencode(). The two code samples above demonstrate differences in effort between naive and secure implementations.