使用 HTMLPurifier (Munge.php) 对提交的链接进行内部重定向

Making internal redirect on submitted links with HTMLPurifier (Munge.php)

我正在尝试借助 HTMLPurifier 库设置内部重定向。大多数 documentation is pretty straight forward and the class for this purpose URI.Munge already exists, but there is no examples (all over internet) on how to make this work. Although, I'm not a highly skilled programmer, but documentation doesn't make sense to me on how to set it up, and even additional examples Here. Especially where to set %s, %r, %t etc.. and URI.MungeSecretKey

提交包含外部链接的文本由 TinyMCE 完成。 在 PHP 代码中,我在配置中允许了 href 并添加了 URI.Munge class:

$uri = $config->getURIDefinition(true);
$uri->addFilter(new HTMLPurifier_URIFilter_Munge(), $config);

我想这里应该是一些额外的代码......

提交的代码:

<a href="http://example.com">Link</a>

我得到输出:

<a href="">Link</a>

预期输出:

<a href="/redirect?s=http%3A%2F%2Fexample.com&amp;t=c15354f3953dfec262c55b1403067e0d045a3059&amp;r=&amp;n=a&amp;m=href&amp;p=">Link</a>

有人可以告诉我如何实现这一点吗?或者至少一些示例代码。

页面http://htmlpurifier.org/live/configdoc/plain.html提到的配置一般是这样使用的:

require_once '/path/to/HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();
$config->set('URI.Munge', ...);
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

URI 过滤器页面适用于您想要编写自己的自定义过滤器的情况 - 不适用于您想要使用内置过滤器的情况! :)

你可能想要的是:

require_once '/path/to/HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();
$config->set('URI.Munge', '/redirect?s=%s');
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

URI.MungeSecretKey 通过部分防止将您的重定向端点滥用为任意重定向器来提供帮助(这很糟糕,因为例如恶意的人会将 link 像 https://good.example.com/redirect?s=https://evil.example.com 嵌入到电子邮件,所以表面上看起来他们正在 linking 到 https://good.example.com 并且他们的 link 得到了信任提升 - 是的,这种情况发生了,是的,它在某种程度上起作用(不幸的是, "some degree" 就是这样的计划对某人有利可图))。

如果您提供例如:

require_once '/path/to/HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();
$config->set('URI.Munge', '/redirect?s=%s&t=%t');
$config->set('URI.MungeSecretKey', 'foobar');
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

然后 URL https://friendly.example.com 将变成(为了便于阅读,我在 URL 上省略了 urlencode()):

/redirect?s=https://friendly.example.com&t=41934069b21c4a3892b61194b90fc537970106ebc9fe79961930a0888b22245f

41934069b21c4a3892b61194b90fc537970106ebc9fe79961930a0888b22245fhash_hmac("sha256", "https://friendly.example.com", "foobar") 的结果。您的重定向端点可以通过计算 hash_hmac("sha256", $_GET['s'], "foobar") 并对照 $_GET['t'] 检查此值。如果这两个匹配,则重定向是由 HTML Purifier 生成的。

就其本身而言,这并不是防止重定向器滥用的完美保护,但它有所帮助。

不足之处在 URI.MungeSecretKey 的文档中进行了描述:

Please note that it would still be possible for an attacker to procure secure hashes en-mass by abusing your website's Preview feature or the like, but this service affords an additional level of protection that should be combined with website blacklisting.

有帮助吗?