Security of Web Apps - uniqcle/Yii2 GitHub Wiki

Безопасность - это процесс. Актуальные на сегодня знания, завтра могут быть устаревшими.

Server

Меняем содержимого заголовков Apache Networks -> Server: Apache/2.4.29 (Ubuntu)

https://httpd.apache.org/docs/2.4/mod/core.html#servertokens

Устанавливаем ServerTokens Prod в etc/apache2/apache2.conf

Перезагружаем apache

Errors

Отключаем ошибки frontend\web\index.php

Меняем с

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
...

на

defined('YII_DEBUG') or define('YII_DEBUG', false);
defined('YII_ENV') or define('YII_ENV', 'prod');
...

DEBUG

Отключаем debug frontend\config\main-local.php

/*if (!YII_ENV_TEST) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',

    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        'allowedIPs' => ['*'],
    ];
    $config['modules']['debug']['allowedIPs'] = ['*'];
}*/

Yii2

namespace frontend\models\lib;

use Yii;

class Author extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
        return 'authors';
    }

    public function rules()
    {
        return [
            [['name'], 'string', 'max' => 11],
            [['last_name'], 'string', 'max' => 256]
        ];
    }

    public function beforeValidate(){

        $this->name = strip_tags($this->name);  //Удаляем html-теги из строки
        return parent::beforeValidate(); 
    }

...
}

CSRF

Включаем CSRF-валидацию

 'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
            'enableCsrfValidation' => true,
        ],
...

Если форма не через ActiveForm, то в каждой форме добавляем

 <input id="form-token" type="hidden" name="<?=Yii::$app->request->csrfParam?>" value="<?=Yii::$app->request->csrfToken ?>"/>

или так

<?php echo Html :: hiddenInput(\Yii::$app->getRequest()->csrfParam, \Yii::$app->getRequest()->getCsrfToken(), []); ?>

Example

use yii\helpers\Html; 
use yii\widgets\ActiveForm; 
use yii\helpers\Url; 
?>
<h1>Update Author</h1>

	<?php $form = ActiveForm::begin();  ?>

	<?php echo $form->field($author, 'name'); ?>

	<?php echo $form->field($author, 'last_name'); ?>

	<input id="form-token" type="hidden" name="<?=Yii::$app->request->csrfParam?>" value="<?=Yii::$app->request->csrfToken ?>"/>

	<?php echo Html::submitButton('Изменить', ['class' => 'btn btn-success']); ?>

<?php ActiveForm::end();  ?>

</br>
<a href = "<?php echo Url::to(['lib/author/index']); ?>">Назад</a>
⚠️ **GitHub.com Fallback** ⚠️