I have read the best practices article here, and I have not found a recent post which answers these questions.
A couple things remain unclear to me.
Yii2 recommends encoding data entered by user and output to users. Do Widgets such as GridView automatically encode data output to the browser?
Best practices state that ActiveRecord uses PDO statements. Are PDO statements adequate protection from SQL injection or should more security be layered onto the data input to the database?
GridView per si doesn’t encode data. Many, if not all, GridColumns do. If you set the type to ‘raw’ then no, but otherwise yes.
Look at the source code. If the widget you are looking at has something like encode, encodeItems, encodeLabel, etc it does the Html::encode() thing in it.
Not sure about this. I think I’ve seen that one of the reasons to use ActiveRecord/PDO was SQL Injection. There may be some cases where you would encode() input.
Basic/Advanced mode doesn’t matter. It all uses the same Yii code
PDO if not used in the correct way do not save you from sql injections, the same is for Yii2
The way to avoid sql injection in PDO (and also in any generic db driver) is using prepared statement and placeholder and parameter binding.
What does it means?
Lets say you have a query like
SELECT * form people where last_name’ like “$user_input”
if $user_input is coming form user input it is a weak point for sql injection because the user can insert extra sql commands and they will be executed
prepared statement and placeholder avoid this problem since the query became something like
SELECT * form people where name like :last_name’
and then another function bind the parameter :user_input to the value you passed, during the binding the value is opportunely escaped according to the db sql dialect
How yii2 works.
inserting/updating data via models is safe since $model->last_name’=‘smith’ the value is binded
batch commands are safe for the same reason
the weak part (o better where you should code properly) is during search with user input.
Here is the relevant part in docs: http://www.yiiframew…uilding-queries , check the where section
There are 3 way to add the a where (or filter) condition:
string
hash
operator
While hash and operator are safe since they use parameter binding, string is not since the raw string is passed to the db.
String should never be used with user input, it is intend to set simple where like record’s flag which value you control directly:
good --> $query->where(‘status=1’);
BAD --> $query->where("status=$status");
Same apply when you use Expression with user input