How does Yii handle data sanitization?

Hi,

Thanks for reading! I’m trying to figure out a way to gracefully and safely process forms (post variables).

In Codeigniter there’s a vibe where you can say:

$username = $this->input->post(‘username’);

…and that will fetch the posted variable which happens to have a key of ‘username’. However, you can also add the word ‘true’, like this:

$username = $this->input->post(‘username’, true);

By simply adding the word ‘true’, you send the username variable through an impressive and extensive chunk of code, all dedicated to making sure the variable is safe.

I was just wondering, does Yii2 have a similar feature?

I’ve had a look around the web and I can’t find anything similar for Yii2. This page from the userguide doesn’t seem to discuss it and - as a matter of fact - I found a thread HERE in which a very important person says that Yii doesn’t provide a sanitization feature. However, that was an old post and perhaps things have changed.

Can anyone shed any light on this? My only goal is to process basic forms - taking in post variables - as safely as possible.

Thanks!

Use PHP filter_var

http://php.net/manual/en/function.filter-var.php

In your model you can define something like this:


 public function rules()

    {

        return [

           .

           .

           .

            [['attribute_1', 'attribute_2', 'attribute_3'], 'filter', 'filter' => function ($value) {

                return filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_NO_ENCODE_QUOTES);

            }],

        ];

          .

          .

          .

Safe for what? Different contexts require different sanitization/filtering/escaping strategies and that’s why any automatic input sanitization gives you only a false sense of security and should be avoided.

See also: magic quotes

CodeIgniter sanitization isn’t as good as it’s advertized. In fact, it gives you false sense of safety which is quite bad. As phtamas mentioned, it’s all about context. There’s no way to sanitize data for all possible use cases.

1 Like

Thanks for the responses.

It’s been a long time since I’ve gone into the bowels of Codeigniter to figure out precisely how the inbuilt security features work. However, from memory, it’s a couple of hundred lines of code and it appears to be pretty solid (nobody out there is talking about Codeigniter getting hacked).

An example of the kind of thing that I’d want to protect against would be somebody adding javascript (for example) to a post in a forum - just like this one.

Now, I realise that (with Yii2) you can use things like Html::encode or even HtmlPurifier::process($html) to make sure the information being presented to the user is safe, however, I think some web owners wouldn’t want unsafe data going into the database in the first place. HTML encode and HTML purifier might do a good job of making the data safe upon presentation to the end user, but - as far as I can tell - they do nothing to stop people from adding dangerous scripts into your database.

I’m very grateful for the suggestion of using filter_var. It’s a good suggestion which seems to have the endorsement of some very good Yii developers. However, personally speaking, I think the syntax for using that is horrible. Don’t you? I’d like to think frameworks can help us to write syntax which looks nice.

Perhaps the best way forward would just be to use something like addslahes(trim(strip_tags($info))) . It’s a bit old school but at least it’s easy to read and it gets the job done.

Any thoughts?

I’m not exactly sure if LOC is an applicable measure when we talk about security but HTMLPurifier.standalone.php has more than 17000 lines.

Depends on usage. HTMLPurifier can be used to filter data before saving it to database. E.g. in the beforeSave hook of your models.

Old school and almost totally useless. The key point is that you cannot simply apply the same filter blindly to all input. You have to know how and in what context the data will be used and setup your filters/sanitization accordingly.

Will it be displayed as HTML? (Are users allowed to use some HTML tags? Are some authorized users allowed to use even "dangerous" tags, e.g. in a CMS admin backend?) - HTMLPurifier is the tool for the job.

Will it be saved to an SQL database? - Use prepared statements.

Will it be sent as an email? - Use some mailer library with built-in protection against header injections.

And so on…

And it is also possible to use it with "filter" validator.

http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#filter

I’m quite comfortable with the “validation” schema that is implemented in Yii’s Model layer. It makes it possible for us to write context-aware validators (including filters) in a very simple fashion. The combination of Model and ActiveForm is quite powerful and helps to make controllers and views very simple.

As opposed to that, in CodeIgniter the concept of "form validation" is implemented as a helper that is to be used in the Controller layer.

https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

It tends to make Controller fat and messy. I didn’t like it.

It never occurred to me that you could use HTMLpurifier before doing a db insert. Such an obvious thing, but I missed it!

I’ve also just discovered that SQL injection attacks are possible with addslashes.

Okay, so that’s all taken on board. Thanks.

Having script in a database is OK if you’re always escaping output properly. Users typically edit what they’ve entered and it’s quite bad experience to modify user entered source text.

Alright.

So, what would be your preferred method of preventing SQL injection attacks?

Check the Security best practices section in the Yii 2 guide, especially Avoiding SQL injections part.

You can validate user input for Active Record model to make sure the data is more secured.

1 Like

Using solid accepted code is almost always better than roll your own.

TBH, I don’t believe any framework (unless it’s a pure security framework) should provide point solutions for general security items. It’s hard enough writing secure code without also having to write the code for security.

PS: Seems I can’t include URLS so look up OWASP and OWASP PHP for great reading.

methods, Yii is OK about it. We take security seriously and we know a thing or two about it. Both 1.1 and 2.0 were checked by people who are really into security.

OWASP is good about vulnerability trends, descriptions and checklist but sometimes they have ugly solutions in their wiki so it should be read with caution.

1 Like