psecio/uri

一个安全的URI生成和验证库

0.1 2018-03-22 18:06 UTC

This package is auto-updated.

Last update: 2024-09-15 11:41:53 UTC


README

渗透测试人员和实际攻击者常用的一个常见攻击方法是捕获包含"id"值的URL(如/user/view?id=1234,其中1234是ID)并手动更改此值以尝试绕过授权检查。尽管当调用URL时,应用程序应该始终进行某种类型的身份验证检查,但还有一个步骤可以帮助防止URL更改:签名值。

此签名值是使用当前URL的内容以及应用程序独有的"秘密"值构建的。然后将此签名附加到URL,并可以直接在链接中使用。当使用URL并收到请求时,签名就会与当前URL值进行校验。如果没有匹配,校验将失败。

安装

通过 Composer 安装非常简单

composer require psecio/uri

此包只有一个依赖项,即PHPUnit,并且仅作为开发依赖项。

签名URL

<?php
require_once 'vendor/autoload.php';

use \Psecio\Uri\Builder;

// Secret is loaded from a configuration outside of the library
$secret = $_ENV['link_secret'];
$uri = new \Psecio\Uri\Builder($secret);

$data = [
    'foo' => 'this is a test'
];
$url = $uri->create('http://test.com', $data);
// http://test.com?foo=this+is+a+test&signature=90b7ac10b261213f71faaf8ce4008fdbdd037bab7192041de8d54d93a158467f
?>

在这个例子中,我们创建了一个新的带有秘密值的新Builder实例,并使用它根据提供的数据和URL创建URL。$url结果将signature值附加到URL上。此值可以直接使用。

您还可以使用相同的create方法向已存在的具有URL参数的现有URL添加签名

<?php
// Sign the URL: http://foo.com/user?test=1
$url = $uri->create('http://foo.com/user?test=1');
?>

验证URL

方程式的另一半是验证URL。库提供validate方法来帮助进行验证

<?php
$url = 'http://test.com?foo=this+is+a+test&signature=90b7ac10b261213f71faaf8ce4008fdbdd037bab7192041de8d54d93a158467f';

$valid = $uri->verify($url);
echo 'Is it valid? '.var_export($valid, true)."\n"; // boolean response

?>

过期URL

库还提供了创建将因为已过期而验证失败的URL的功能。要使用此功能,只需在create方法调用中传入第三个值。此值可以是秒数或PHP的strtotime可解析的相对字符串,表示要添加的时间量

<?php
$data = [
    'foo' => 'this is a test'
];
$expire = '+10 seconds';
$url = $uri->create('http://test.com', $data, $expire);
// http://test.com?foo=this+is+a+test&expires=1521661473&signature=009e2d70add85d79e19979434e3750e682d40a3d1403ee92458fe30aece2c826
?>

您会注意到添加了一个新的URL参数,即expires值。此值在调用validate时会自动读取,以确保URL尚未超时。如果已超时,即使其他数据正确,结果也将为false

即使攻击者试图更新expires日期以尝试延长哈希的长度,验证也会失败,因为那不是原始哈希中使用的expires值。