Search code examples
phpsecuritymodel-view-controllerxsssanitization

Is it safe to echo formatted DateTime in php in terms of XSS attack?


I have quite a complex web application. I need to sanitize all variables that are sent to view (MVC architecture) with the htmlspecialchars() function to prevent XSS attack. Since it isn't just primitive data types I send to a view, I am implementing a function which goes through an array of variables and sanitizes each of them in a different way, according to their type (I'm using gettype() to distinguish it).

  • Strings, integers, booleans and doubles are sanitized simply with htmlspecialchars()
  • null stays null
  • arrays are sanitized item by item by a recursive procedure
  • objects of my custom classes have their own method, which takes care of the sanitization specifically for each class
  • DateTime - ???

My question is if I need to sanitize DateTime objects somehow when I echo their content by their format() method. Can DateTime objects be misused for XSS attacks somehow, or are their considered safe?

I guess that I should pass only primitive data types to my views, but I kinda need to pass objects too.

This is the function I use:

private function sanitize(array $data)
{
    foreach ($data as $propertyName => $propertyValue)
    {
        if (gettype($propertyValue) === 'array')
        {
            //Sanitize each element of the array by recursion
            $data[$propertyName] = $this->sanitize($data[$propertyName]);
        }
        else if (gettype($propertyValue) === 'NULL')
        {
            //NULL can stay NULL
            continue;
        }
        else if ($propertyValue instanceof DatabaseItem)
        {
            //Sanitize instances of my custom class DatabaseItem
            $propertyValue->sanitizeSelf();
        }
        else if ($propertyValue instanceof DateTime)
        {
            //TODO - is DateTime safe?
        }
        else
        {
            //boolean, integer, double, string
            $data[$propertyName] = htmlspecialchars($propertyValue, ENT_QUOTES);
        }
    }
    return $data;
}

Solution

  • Short: Yes. If your value wouldn't be a date, it would just cause an error:

    <?php
    $d=new DateTime (" <script> malicious </script>");
    #test
    echo $d->format("y");
    /*will cause something like 
    Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string ( <script> malicious </script>)*/