作者:mengchen@知道創宇404實驗室
時間:2019年8月1日
英文版本:http://www.jmbmsq.com/997/

1. 前言

TYPO3是一個以PHP編寫、采用GNU通用公共許可證的自由、開源的內容管理系統。

2019年7月16日,RIPS的研究團隊公開了Typo3 CMS的一個關鍵漏洞詳情CVE編號為CVE-2019-12747,它允許后臺用戶執行任意PHP代碼。

漏洞影響范圍:Typo3 8.x-8.7.26 9.x-9.5.7

2. 測試環境簡述

Nginx/1.15.8
PHP 7.3.1 + xdebug 2.7.2
MySQL 5.7.27
Typo3 9.5.7

3. TCA

在進行分析之前,我們需要了解下Typo3TCA(Table Configuration Array),在Typo3的代碼中,它表示為$GLOBALS['TCA']

Typo3中,TCA算是對于數據庫表的定義的擴展,定義了哪些表可以在Typo3的后端可以被編輯,主要的功能有

  • 表示表與表之間的關系
  • 定義后端顯示的字段和布局
  • 驗證字段的方式

這次漏洞的兩個利用點分別出在了CoreEngineFormEngine這兩大結構中,而TCA就是這兩者之間的橋梁,告訴兩個核心結構該如何表現表、字段和關系。

TCA的第一層是表名:

$GLOBALS['TCA']['pages'] = [
    ...
];
$GLOBALS['TCA']['tt_content'] = [
    ...
];

其中pagestt_content就是數據庫中的表。

接下來一層就是一個數組,它定義了如何處理表,

$GLOBALS['TCA']['pages'] = [
    'ctrl' => [ // 通常包含表的屬性
        ....
    ],
    'interface' => [ // 后端接口屬性等
        ....
    ],
    'columns' => [
        ....
    ],
    'types' => [
        ....
    ],
    'palettes' => [
        ....
    ],
];

在這次分析過程中,只需要了解這么多,更多詳細的資料可以查詢官方手冊

4. 漏洞分析

整個漏洞的利用流程并不是特別復雜,主要需要兩個步驟,第一步變量覆蓋后導致反序列化的輸入可控,第二步構造特殊的反序列化字符串來寫shell。第二步這個就是老套路了,找個在魔術方法中能寫文件的類就行。這個漏洞好玩的地方在于變量覆蓋這一步,而且進入兩個組件漏洞點的傳入方式也有著些許不同,接下來讓我們看一看這個漏洞吧。

4.1 補丁分析

從Typo3官方的通告中我們可以知道漏洞影響了兩個組件——Backend & Core API (ext:backend, ext:core),在GitHub上我們可以找到修復記錄

很明顯,補丁分別禁用了backendDatabaseLanguageRows.phpcore中的DataHandler.php中的的反序列化操作。

4.2 Backend ext 漏洞點利用過程分析

根據補丁的位置,看下Backend組件中的漏洞點。

路徑:typo3/sysext/backend/Classes/Form/FormDataProvider/DatabaseLanguageRows.php:37

public function addData(array $result)
{
    if (!empty($result['processedTca']['ctrl']['languageField'])
        && !empty($result['processedTca']['ctrl']['transOrigPointerField'])
    ) {
        $languageField = $result['processedTca']['ctrl']['languageField'];
        $fieldWithUidOfDefaultRecord = $result['processedTca']['ctrl']['transOrigPointerField'];

        if (isset($result['databaseRow'][$languageField]) && $result['databaseRow'][$languageField] > 0
            && isset($result['databaseRow'][$fieldWithUidOfDefaultRecord]) && $result['databaseRow'][$fieldWithUidOfDefaultRecord] > 0
        ) {
            // Default language record of localized record
            $defaultLanguageRow = $this->getRecordWorkspaceOverlay(
                $result['tableName'],
                (int)$result['databaseRow'][$fieldWithUidOfDefaultRecord]
            );
            if (empty($defaultLanguageRow)) {
                throw new DatabaseDefaultLanguageException(
                    'Default language record with id ' . (int)$result['databaseRow'][$fieldWithUidOfDefaultRecord]
                    . ' not found in table ' . $result['tableName'] . ' while editing record ' . $result['databaseRow']['uid'],
                    1438249426
                );
            }
            $result['defaultLanguageRow'] = $defaultLanguageRow;

            // Unserialize the "original diff source" if given
            if (!empty($result['processedTca']['ctrl']['transOrigDiffSourceField'])
                && !empty($result['databaseRow'][$result['processedTca']['ctrl']['transOrigDiffSourceField']])
            ) {
                $defaultLanguageKey = $result['tableName'] . ':' . (int)$result['databaseRow']['uid'];
                $result['defaultLanguageDiffRow'][$defaultLanguageKey] = unserialize($result['databaseRow'][$result['processedTca']['ctrl']['transOrigDiffSourceField']]);
            }
                //省略代碼
        }
        //省略代碼
    }
    //省略代碼
}

很多類都繼承了FormDataProviderInterface接口,因此靜態分析尋找誰調用的DatabaseLanguageRowsaddData方法根本不現實,但是根據文章中的演示視頻,我們可以知道網站中修改page這個功能中進入了漏洞點。在addData方法加上斷點,然后發出一個正常的修改page的請求。

當程序斷在DatabaseLanguageRowsaddData方法后,我們就可以得到調用鏈。

DatabaseLanguageRows這個addData中,只傳入了一個$result數組,而且進行反序列化操作的目標是$result['databaseRow']中的某個值。看命名有可能是從數據庫中獲得的值,往前分析一下。

進入OrderedProviderListcompile方法。

路徑:typo3/sysext/backend/Classes/Form/FormDataGroup/OrderedProviderList.php:43

public function compile(array $result): array
{
    $orderingService = GeneralUtility::makeInstance(DependencyOrderingService::class);
    $orderedDataProvider = $orderingService->orderByDependencies($this->providerList, 'before', 'depends');

    foreach ($orderedDataProvider as $providerClassName => $providerConfig) {
        if (isset($providerConfig['disabled']) && $providerConfig['disabled'] === true) {
            // Skip this data provider if disabled by configuration
            continue;
        }

        /** @var FormDataProviderInterface $provider */
        $provider = GeneralUtility::makeInstance($providerClassName);

        if (!$provider instanceof FormDataProviderInterface) {
            throw new \UnexpectedValueException(
                'Data provider ' . $providerClassName . ' must implement FormDataProviderInterface',
                1485299408
            );
        }

        $result = $provider->addData($result);
    }
    return $result;
}

我們可以看到,在foreach這個循環中,動態實例化$this->providerList中的類,然后調用它的addData方法,并將$result作為方法的參數。

在調用DatabaseLanguageRows之前,調用了如圖所示的類的addData方法。

經過查詢手冊以及分析代碼,可以知道在DatabaseEditRow類中,通過調用addData方法,將數據庫表中數據讀取出來,存儲到了$result['databaseRow']中。

路徑:typo3/sysext/backend/Classes/Form/FormDataProvider/DatabaseEditRow.php:32

public function addData(array $result)
{
    if ($result['command'] !== 'edit' || !empty($result['databaseRow'])) {// 限制功能為`edit`
        return $result;
    }

    $databaseRow = $this->getRecordFromDatabase($result['tableName'], $result['vanillaUid']); // 獲取數據庫中的記錄
    if (!array_key_exists('pid', $databaseRow)) {
        throw new \UnexpectedValueException(
            'Parent record does not have a pid field',
            1437663061
        );
    }
    BackendUtility::fixVersioningPid($result['tableName'], $databaseRow);
    $result['databaseRow'] = $databaseRow;
    return $result;
}

再后面又調用了DatabaseRecordOverrideValues類的addData方法。

路徑:typo3/sysext/backend/Classes/Form/FormDataProvider/DatabaseRecordOverrideValues.php:31

public function addData(array $result)
{
    foreach ($result['overrideValues'] as $fieldName => $fieldValue) {
        if (isset($result['processedTca']['columns'][$fieldName])) {
            $result['databaseRow'][$fieldName] = $fieldValue;
            $result['processedTca']['columns'][$fieldName]['config'] = [
                'type' => 'hidden',
                'renderType' => 'hidden',
            ];
        }
    }
    return $result;
}

在這里,將$result['overrideValues']中的鍵值對存儲到了$result['databaseRow']中,如果$result['overrideValues']可控,那么通過這個類,我們就能控制$result['databaseRow']的值了。

再往前,看看$result的值是怎么來的。

路徑:typo3/sysext/backend/Classes/Form/FormDataCompiler.php:58

public function compile(array $initialData)
{
    $result = $this->initializeResultArray();
    //省略代碼
    foreach ($initialData as $dataKey => $dataValue) {
        // 省略代碼...
        $result[$dataKey] = $dataValue;
    }
    $resultKeysBeforeFormDataGroup = array_keys($result);

    $result = $this->formDataGroup->compile($result);

    // 省略代碼...
}

很明顯,通過調用FormDataCompilercompile方法,將$initialData中的數據存儲到了$result中。

再往前走,來到了EditDocumentController類中的makeEditForm方法中。

在這里,$formDataCompilerInput['overrideValues']獲取了$this->overrideVals[$table]中的數據。

$this->overrideVals的值是在方法preInit中設定的,獲取的是通過POST傳入的表單中的鍵值對。

這樣一來,在這個請求過程中,進行反序列化的字符串我們就可以控制了。

在表單中提交任意符合數組格式的輸入,在后端代碼中都會被解析,然后后端根據TCA來進行判斷并處理。 比如我們在提交表單中新增一個名為a[b][c][d],值為233的表單項。

在編輯表單的控制器EditDocumentController.php中下一個斷點,提交之后。

可以看到我們傳入的鍵值對在經過getParsedBody方法解析后,變成了嵌套的數組,并且沒有任何限制。

我們只需要在表單中傳入overrideVals這一個數組即可。這個數組中的具體的鍵值對,則需要看進行反序列化時取的$result['databaseRow']中的哪一個鍵值。

if (isset($result['databaseRow'][$languageField]) && $result['databaseRow'][$languageField] > 0 && isset($result['databaseRow'][$fieldWithUidOfDefaultRecord]) && $result['databaseRow'][$fieldWithUidOfDefaultRecord] > 0) {
    // 省略代碼
    if (!empty($result['processedTca']['ctrl']['transOrigDiffSourceField']) && !empty($result['databaseRow'][$result['processedTca']['ctrl']['transOrigDiffSourceField']])) {
        $defaultLanguageKey = $result['tableName'] . ':' . (int) $result['databaseRow']['uid'];
        $result['defaultLanguageDiffRow'][$defaultLanguageKey] = unserialize($result['databaseRow'][$result['processedTca']['ctrl']['transOrigDiffSourceField']]);
    }
    //省略代碼
}

要想進入反序列化的點,還需要滿足上面的if條件,動態調一下就可以知道,在if語句中調用的是

$result['databaseRow']['sys_language_uid']
$result['databaseRow']['l10n_parent']

后面反序列化中調用的是

$result['databaseRow']['l10n_diffsource']

因此,我們只需要在傳入的表單中增加三個參數即可。

overrideVals[pages][sys_language_uid] ==> 4
overrideVals[pages][l10n_parent] ==> 4
overrideVals[pages][l10n_diffsource] ==> serialized_shell_data

可以看到,我們的輸入成功的到達了反序列化的點。

4.3 Core ext 漏洞點利用過程分析

看下Core中的那個漏洞點。

路徑:typo3/sysext/core/Classes/DataHandling/DataHandler.php:1453

public function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID)
{
    // Initialize:
    $originalLanguageRecord = null;
    $originalLanguage_diffStorage = null;
    $diffStorageFlag = false;
    // Setting 'currentRecord' and 'checkValueRecord':
    if (strpos($id, 'NEW') !== false) {
        // Must have the 'current' array - not the values after processing below...
        $checkValueRecord = $fieldArray;
        if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
            ArrayUtility::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
        }
        $currentRecord = $checkValueRecord;
    } else {
        // We must use the current values as basis for this!
        $currentRecord = ($checkValueRecord = $this->recordInfo($table, $id, '*'));
        // This is done to make the pid positive for offline versions; Necessary to have diff-view for page translations in workspaces.
        BackendUtility::fixVersioningPid($table, $currentRecord);
    }

    // Get original language record if available:
    if (is_array($currentRecord)
        && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']
        && $GLOBALS['TCA'][$table]['ctrl']['languageField']
        && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0
        && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
        && (int)$currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0
       ) {
        $originalLanguageRecord = $this->recordInfo($table, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
        BackendUtility::workspaceOL($table, $originalLanguageRecord);
        $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
    }
    ......//省略代碼

看代碼,如果我們要進入反序列化的點,需要滿足前面的if條件

if (is_array($currentRecord)
        && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']
        && $GLOBALS['TCA'][$table]['ctrl']['languageField']
        && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0
        && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
        && (int)$currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0
    ) 

也就是說要滿足以下條件

  • $currentRecord是個數組
  • TCA$table的表屬性中存在transOrigDiffSourceFieldlanguageFieldtransOrigPointerField字段。
  • $table的屬性languageFieldtransOrigPointerField$currentRecord中對應的值要大于0

查一下TCA表,滿足第二條條件的表有

sys_file_reference
sys_file_metadata
sys_file_collection
sys_collection
sys_category
pages

但是所有sys_*的字段的adminOnly屬性的值都是1,只有管理員權限才可以更改。因此我們可以用的表只有pages

它的屬性值是

[languageField] => sys_language_uid
[transOrigPointerField] => l10n_parent
[transOrigDiffSourceField] => l10n_diffsource

再往上,有一個對傳入的參數進行處理的if-else語句。

從注釋中,我們可以知道傳入的各個參數的功能:

  • 數組 $fieldArray 是默認值,這種一般都是我們無法控制的
  • 數組 $incomingFieldArray 是你想要設置的字段值,如果可以,它會合并到$fieldArray中。

而且如果滿足if (strpos($id, 'NEW') !== false)條件的話,也就是$id是一個字符串且其中存在NEW字符串,會進入下面的合并操作。

$checkValueRecord = $fieldArray;
......
if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
    ArrayUtility::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
}
$currentRecord = $checkValueRecord;

如果不滿足上面的if條件,$currentRecord的值就會通過recordInfo方法從數據庫中直接獲取。這樣后面我們就無法利用了。

簡單總結一下,我們需要

  • $tablepages
  • $id是個字符串,而且存在NEW字符串
  • $incomingFieldArray中要存在payload

接下來我們看在哪里對該函數進行了調用。

全局搜索一下,只找到一處,在typo3/sysext/core/Classes/DataHandling/DataHandler.php:954處的process_datamap方法中進行了調用。

整個項目中,對process_datamap調用的地方就太多了,嘗試使用xdebug動態調試來找一下調用鏈。從RIPS團隊的那一篇分析文章結合上面的對表名的分析,我們可以知道,漏洞點在創建page的功能處。

接下來就是找從EditDocumentController.phpmainAction方法到前面我們分析的fillInFieldArray方法的調用鏈。

嘗試在網站中新建一個page,然后在調用fillInFieldArray的位置下一個斷點,發送請求后,我們就拿到了調用鏈。

看一下mainAction的代碼。

public function mainAction(ServerRequestInterface $request): ResponseInterface
{
    // Unlock all locked records
    BackendUtility::lockRecords();
    if ($response = $this->preInit($request)) {
        return $response;
    }

    // Process incoming data via DataHandler?
    $parsedBody = $request->getParsedBody();
    if ($this->doSave
        || isset($parsedBody['_savedok'])
        || isset($parsedBody['_saveandclosedok'])
        || isset($parsedBody['_savedokview'])
        || isset($parsedBody['_savedoknew'])
        || isset($parsedBody['_duplicatedoc'])
    ) {
        if ($response = $this->processData($request)) {
            return $response;
        }
    }
    ....//省略代碼
}

當滿足if條件是進入目標$response = $this->processData($request)

if ($this->doSave
        || isset($parsedBody['_savedok'])
        || isset($parsedBody['_saveandclosedok'])
        || isset($parsedBody['_savedokview'])
        || isset($parsedBody['_savedoknew'])
        || isset($parsedBody['_duplicatedoc'])
    ) 

這個在新建一個page時,正常的表單中就攜帶doSave == 1,而doSave的值就是在方法preInit中獲取的。

這樣條件默認就是成立的,然后將$request傳入了processData方法。

public function processData(ServerRequestInterface $request = null): ?ResponseInterface
{
// @deprecated Variable can be removed in TYPO3 v10.0
    $deprecatedCaller = false;

    ......//省略代碼
    $parsedBody = $request->getParsedBody(); // 獲取Post請求參數
    $queryParams = $request->getQueryParams(); // 獲取Get請求參數

    $beUser = $this->getBackendUser(); // 獲取用戶數據

    // Processing related GET / POST vars
    $this->data = $parsedBody['data'] ?? $queryParams['data'] ?? [];
    $this->cmd = $parsedBody['cmd'] ?? $queryParams['cmd'] ?? [];
    $this->mirror = $parsedBody['mirror'] ?? $queryParams['mirror'] ?? [];
    // @deprecated property cacheCmd is unused and can be removed in TYPO3 v10.0
    $this->cacheCmd = $parsedBody['cacheCmd'] ?? $queryParams['cacheCmd'] ?? null;
    // @deprecated property redirect is unused and can be removed in TYPO3 v10.0
    $this->redirect = $parsedBody['redirect'] ?? $queryParams['redirect'] ?? null;
    $this->returnNewPageId = (bool)($parsedBody['returnNewPageId'] ?? $queryParams['returnNewPageId'] ?? false);

    // Only options related to $this->data submission are included here
    $tce = GeneralUtility::makeInstance(DataHandler::class);

    $tce->setControl($parsedBody['control'] ?? $queryParams['control'] ?? []);

    // Set internal vars
    if (isset($beUser->uc['neverHideAtCopy']) && $beUser->uc['neverHideAtCopy']) {
        $tce->neverHideAtCopy = 1;
    }
    // Load DataHandler with data
    $tce->start($this->data, $this->cmd);
    if (is_array($this->mirror)) {
        $tce->setMirror($this->mirror);
    }

    // Perform the saving operation with DataHandler:
    if ($this->doSave === true) {
        $tce->process_uploads($_FILES);
        $tce->process_datamap();
        $tce->process_cmdmap();
    }
    ......//省略代碼
}

代碼很容易懂,從$request中解析出來的數據,首先存儲在$this->data$this->cmd中,然后實例化一個名為$tce,調用$tce->start方法將傳入的數據存儲在其自身的成員datamapcmdmap中。

typo3/sysext/core/Classes/DataHandling/DataHandler.php:735
public function start($data, $cmd, $altUserObject = null)
{
   ......//省略代碼
    // Setting the data and cmd arrays
    if (is_array($data)) {
        reset($data);
        $this->datamap = $data;
    }
    if (is_array($cmd)) {
        reset($cmd);
        $this->cmdmap = $cmd;
    }
}

而且if ($this->doSave === true)這個條件也是成立的,進入process_datamap方法。

代碼有注釋還是容易閱讀的,在第985行,獲取了datamap中所有的鍵名,然后存儲在$orderOfTables,然后進入foreach循環,而這個$table,在后面傳入fillInFieldArray方法中,因此,我們只需要分析$table == pages時的循環即可。

$fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);

大致瀏覽下代碼,再結合前面的分析,我們需要滿足以下條件:

  • $recordAccess的值要為true
  • $incomingFieldArray中的payload不會被刪除
  • $table的值為pages
  • $id中存在NEW字符串

既然正常請求可以直接斷在調用fillInFieldArray處,正常請求中,第一條、第三條和第四條都是成立的。

根據前面對fillInFieldArray方法的分析,構造payload,向提交的表單中添加三個鍵值對。

data[pages][NEW5d3fa40cb5ac4065255421][l10n_diffsource] ==> serialized_shell_data
data[pages][NEW5d3fa40cb5ac4065255421][sys_language_uid] ==> 4
data[pages][NEW5d3fa40cb5ac4065255421][l10n_parent] ==> 4

其中NEW*字符串要根據表單生成的值進行對應的修改。

發送請求后,依舊能夠進入fillInFieldArray,而在傳入的$incomingFieldArray參數中,可以看到我們添加的三個鍵值對。

進入fillInFieldArray之后,其中l10n_diffsource將會進行反序列化操作。此時我們在請求中將其l10n_diffsource改為構造好的序列化字符串,重新發送請求即可成功getshell

5. 寫在最后

其實單看這個漏洞的利用條件,還是有點雞肋的,需要你獲取到typo3的一個有效的后臺賬戶,并且擁有編輯page的權限。

而且這次分析Typo3給我的感覺與其他網站完全不同,我在分析創建&修改page這個功能的參數過程中,并沒有發現什么過濾操作,在后臺的所有參數都是根據TCA的定義來進行相應的操作,只有傳入不符合TCA定義的才會拋出異常。而TCA的驗證又不嚴格導致了變量覆蓋這個問題。

官方的修補方式也是不太懂,直接禁止了反序列化操作,但是個人認為這次漏洞的重點還是在于前面變量覆蓋的問題上,尤其是Backend的利用過程中,可以直接覆蓋從數據庫中取出的數據,這樣只能算是治標不治本,后面還是有可能產生新的問題。

當然了,以上只是個人拙見,如有錯誤,還請諸位斧正。

6. 參考鏈接


Paper 本文由 Seebug Paper 發布,如需轉載請注明來源。本文地址:http://www.jmbmsq.com/996/