kenjis / csp
内容安全策略(CSP)nonce-source实现
dev-master / 1.0.x-dev
2021-02-02 07:10 UTC
Requires
- php: >=5.4.0
- ext-openssl: *
- crossjoin/browscap: dev-master
- woothee/woothee: 1.0.*
Requires (Dev)
- codeception/aspect-mock: 0.5.*
- phpunit/phpunit: 4.3.*
This package is auto-updated.
Last update: 2024-09-19 21:09:00 UTC
README
PHP的CSP(内容安全策略)nonce-source库。
什么是CSP nonce-source?
它是CSP 2特性之一,用于防止跨站脚本攻击(XSS)。
如果您不知道,请参阅CSP for the web we have | Mozilla Security Blog。
要求
- PHP 5.4或更高版本
安装
$ git clone https://github.com/kenjis/php-csp-nonce-source.git
$ cd php-csp-nonce-source
$ composer install
用法
您只需要调用Csp::sendHeader()
和Csp::getNonce()
。
Csp::sendHeader()
发送CSP头部。
Csp::getNonce()
返回nonce值。
<?php require __DIR__ . '/bootstrap.php'; Csp::sendHeader(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sample of CSP nonce-source</title> </head> <body> <script type="text/javascript" nonce="<?= Csp::getNonce() ?>"> alert('This works!'); </script> <script type="text/javascript"> alert('This does not work!'); </script> </body> </html>
您可以使用PHP内置的web服务器进行测试。
$ php -S localhost:8000
并浏览https://:8000/。
您可以在csp-report.log
文件中看到CSP违规报告。
(可选)添加其他策略
您可以使用Csp::addPolicy()
添加其他策略。
<?php require __DIR__ . '/bootstrap.php'; Csp::addPolicy('default-src', 'self'); Csp::addPolicy('img-src', 'img.example.com'); Csp::sendHeader();
(可选)仅报告
您可以使用Csp::setReportOnly()
设置仅报告模式。
<?php require __DIR__ . '/bootstrap.php'; Csp::addPolicy('default-src', 'self'); Csp::setReportOnly(); Csp::sendHeader();
您可以在csp-report.log
文件中看到CSP违规报告。
许可
MIT许可证。请参阅LICENSE.md。
参考
- 内容安全策略第2级 http://www.w3.org/TR/2014/WD-CSP2-20140703/
- Firefox版本 31.0 https://www.mozilla.org/en-US/mobile/31.0/releasenotes/
- CSP for the web we have | Mozilla Security Blog https://blog.mozilla.org/security/2014/10/04/csp-for-the-web-we-have/