本文的示例代码参考xss
目录
XSS
方法1-HTTPOnly
方法2-数据有效性
方法3-数据的过滤
XSS
关于XSS基础知识 可以参考
web攻击 之 XSS
Web安全 之 XSS攻击
本文主要讨论应对XSS的3种常见方法
HTTPOnly: 禁止页面JavaScript访问带有HttpOnly属性的Cookie
数据有效性: 对数据有效性做校验 例如: 邮箱 / 手机号/ 账号 / 密码是否合理(符合规则)等
数据的过滤: 对特殊数据进行过滤 例如: script标签等
方法1 HTTPOnly
vim httponly.php
sudo vim /etc/nginx/conf.d/httponly.conf
server {
listen 80;
server_name httponly.test;
location / {
include fastcgi_params;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_param SCRIPT_FILENAME /home/saas/httponly.php;
}
}
sudo nginx -s reload
关于Nginx的安装配置 更多参考Nginx简明教程
- 测试
sudo sh -c "echo '127.0.0.1 httponly.test' >> /etc/hosts"
浏览器打开http://httponly.test/ 查看当前cookie
此时 页面弹框只能获取到未设置HTTPOnly的Cookie
方法2 数据有效性
composer create-project laravel/laravel validation --prefer-dist "5.5.*"
# cd validation
php artisan make:controller DemoController
vim app/Http/Controllers/DemoController.php
validate($request, [
'email' => 'required|email|max:255',
]);
return 'ok';
}
}
vim routes/web.php
name('validation');
vim app/Http/Middleware/VerifyCsrfToken.php
关于Laravel框架的CSRF 更多参考Laravel框架 之 CSRF
- 测试
php artisan serve
curl -X POST -H "Content-type: application/json" -d '{"email":"[email protected]"}' http://localhost:8000/validation
校验成功 返回信息如下
ok
curl -X POST -H "Content-type: application/json" -d '{"email":"test"}' http://localhost:8000/validation
校验失败 返回信息如下
Redirecting to http://localhost:8000
Redirecting to http://localhost:8000.
- 优化
现在校验失败会重定向到一个页面 并且显示html
下面我们做一个优化 自己控制校验异常的处理
php artisan make:request ValidationRequest
vim app/Http/Requests/ValidationRequest.php
'required|email|max:255',
];
}
protected function failedValidation(Validator $validator)
{
throw new ValidationException($validator);
}
}
vim app/Http/Controllers/DemoController.php
vim app/Exceptions/Handler.php
getMessage() ?: '您没有权限操作';
$code = $exception->getCode() ?: 401;
return response()->json([ 'message' => $message ], $code);
}
return parent::render($request, $exception);
}
}
- 测试
php artisan serve
curl -X POST -H "Content-type: application/json" -d '{"email":"[email protected]"}' http://localhost:8000/validation
校验成功 返回信息如下
ok
curl -X POST -H "Content-type: application/json" -d '{"email":"test"}' http://localhost:8000/validation
校验失败 返回信息如下
{"message":"The given data was invalid."}
方法3 数据的过滤
composer create-project laravel/laravel purifier --prefer-dist "5.5.*"
# cd purifier
php artisan make:controller DemoController
vim app/Http/Controllers/DemoController.php
data;
}
}
vim routes/web.php
name('purifier');
vim app/Http/Middleware/VerifyCsrfToken.php
- 测试
php artisan serve
curl -X POST -H "Content-type: application/json" -d '{"data":"hello"}' http://localhost:8000/purifier
返回信息如下
hello
上述"}' http://localhost:8000/purifier
返回信息如下
hello
参考
web攻击 之 XSS
Web安全 之 XSS攻击
你所不知道的HostOnly Cookie
Laravel 的表单验证机制详解
Where does laravel 5 handle the ValidationException?
form validation exception not catching by Exception in laravel 5.1?
thepsion5/BaseController.php
toplan/laravel-sms
HTMLPurifier
HTMLPurifier for Laravel 5