One of the most important measures to prevent XSS attacks is to check user input before displaying them. One can do HTML-encoding with the user input to achieve this goal. However, in some situations, HTML-encoding may not be preferable because it disables all HTML tags.
Yii incorporates the work of HTMLPurifier and provides developers with a useful component called CHtmlPurifier that encapsulates HTMLPurifier. This component is capable of removing all malicious code with a thoroughly audited, secure yet permissive whitelist and making sure the filtered content is standard-compliant.
$this->beginWidget('CHtmlPurifier'); ...display user-entered content here... <?php $this->endWidget();
Cross-Site Request Forgery (CSRF) attacks occur when a
malicious web site causes a user's web browser to perform
an unwanted action on a trusted site. For example, a malicious
web site has a page that contains an image tag whose
to a banking site:
If a user who has a login cookie for the banking site happens to
visit this malicous page, the action of transferring 10000 dollars
to someone will be executed. Contrary to cross-site,
which exploits the trust a user has for a particular site,
CSRF exploits the trust that a site has for a particular user.
To prevent CSRF attacks, it is important to abide to the rule
GET requests should only be allowed to retrieve data rather
than modify any data on the server. And for
POST requests, they
should include some random value which can be recognized by the server
to ensure the form is submitted from and the result is sent back to
the same origin.
Yii implements a CSRF prevention scheme to help defeat
It is based on storing a random value in a cookie and comparing this value
with the value submitted via the
return array( 'components'=>array( 'request'=>array( 'enableCsrfValidation'=>true, ), ), );
And to display a form, call CHtml::form instead of writing the HTML form tag directly. The CHtml::form method will embed the necessary random value in a hidden field so that it can be submitted for CSRF validation.
Protecting cookies from being attacked is of extreme importance, as session IDs are commonly stored in cookies. If one gets hold of a session ID, he essentially owns all relevant session information.
There are several countermeasures to prevent cookies from being attacked.
Yii implements a cookie validation scheme that prevents cookies from being modified. In particular, it does HMAC check for the cookie values if cookie validation is enabled.
return array( 'components'=>array( 'request'=>array( 'enableCookieValidation'=>true, ), ), );
To make use of the cookie validation scheme provided by Yii, we also need to
access cookies through the cookies collection, instead
of directly through
// retrieve the cookie with the specified name $cookie=Yii::app()->request->cookies[$name]; $value=$cookie->value; ...... // send a cookie $cookie=new CHttpCookie($name,$value); Yii::app()->request->cookies[$name]=$cookie;