views:

86

answers:

1

I am working on an public facing interface that makes use of a database that is effectively untrusted due to multiple applications accessing it.

I would like a clean way of encoding all my output to UTF-8 with htmlentities to prevent XSS.

Codeigniter (CI) has nothing built in. The filter that is there is meant for input and does not actually filter all XSS attacks.

I would prefer a blanket fix but don’t think there is one.

What I’m really after in this discussion is what is the best way to filter my output? And is the following the best / most concise solution? (encode function is a wrapper on htmlentities with utf8 and ent_compat)

<?php 
    echo form_input(“start_date[”.encode($id).”]”, encode($action->start_date,true), class=“input input-date dateISO required” readonly=readonly title=“must set a date.”’); 
?>

As you can see the code starts looking pretty silly sprinkling this encode function everywhere. Encoding at controller level is just not a solution as CI doesn’t use strict templating. Encoding at model level leaves other possible avenues open. Encoding at time of output seems like the safest / catch all cases way of doing things, I just want someone to confirm I’m not missing something obvious and nicer to look at / maintain

A: 

If you are only concerned with escaping HTML (as anything that goes between script tags is a different story) then I would subclass the Model class (call it base_model), create a method that you pass all output through before returning it to the controller, and subclass all of your other models off of the base_model.

// Base Model
class Base_model extends Model {

    function __construct()
    {
        parent::Model();
    }

    function escape_output($str) 
    {
        return htmlentities($str, ENT_COMPAT);
    }

}


// Whatever model is a subclass of base_model
class Whatever_model extends Base_model {

    function __construct()
    {
        parent::__construct();
    }

    function get_all($table)
    {
        return $this->db->get($table)->result_array();
    }

}

// Some controller somewhere
$data['first_name'] = $this->Whatever_model->escape_output($str);

You could even go a step further and create a helper function to use in views.

Even better you could make escape_output recursively run through the $data array escaping everything before you load your view.

Bill H
thanks for the input, I've thought this kind of idea through already and although it is a nicer idea I've had to use legacy and poorly ported to code igniter views that have some logic and even database calls in them so this solution wouldn't solve all cases. Specifically I'm after something that fits in with CI and all CI's freedom. Something I don't think is going to happen. I've since realised the XSS filter CI has + encode helper function for passing each output item through should suffice for what I'm doing anyway.
stuckinphp