Automate reconnaissance bash script
Create a bash script that run reconnaissance scan from another machine over a VPN.
Introduction
Reconnaissance is one of the most important parts of cybersecurity. No matter whether we are analyzing cyber attack incidents, or preparing to perform a pentest on our client. Reconnaissance typically involves issuing multiple commands to gather information about the target, which may result in frequent human typing errors. But luckily, most of the commands are repeated, which means we can automate the process
This project aims to reduce human error and increase efficiency. This project will include some of the most commonly used in reconnaissance. Some of the commands included connecting to a safe gateway, connecting to the private remote server, whois, nmap, etc.
At the end of the project, we will analyze one of the insecure protocols used in this project and provide an alternative secure version.
Methodology
Predefined variable
Before the script executes any command, we define some variables on top of the script. This will help us easily manage the script and modify the value as needed.
In the meantime, we also create a help menu to let users input their preferences when executing this script.
We can feed our preferences when we try to execute the script.
Install required package
Before we were able to run a command, we needed to install those packages related to the command. Most of them are not installed by default on the machine. Hence, we need to check if the required package is installed and install it if not.
First, we create a function to run the install package command, because most installation commands are the same.
But there are some of the packages have different installation processes. In the next step, we define a switch case to cater to different package installation processes. We will install Nipe in this project which is a package that has different installation processes compared with others.
Git clone is the command we used to download the Nipe project from GitHub. The Nipe package is a GitHub project, we need to download it from GitHub in order to install it. The first if statement is to check if the Nipe project exists on a specified path.
- -d: check if the directory exists and is a directory.
- !: A not statement, turn false to true or true to false
- >/dev/null: Redirect the output to /dev/null.
- 2>&1: Redirects stderr to stdout, so errors (if any) also go to /dev/null
It will download the project from GitHub if the Nipe project is not found.
Next, when the Nipe project is downloaded, install the dependency for the Nipe package. The second if statement shown in the picture is to verify Nipe package can run correctly, If not, then download and install all the dependencies packages for the Nipe project.
Lastly, the switch case needs to cater to most of the packages that can be installed with a single command.
Before we install the package, we need to check if the package is installed by running dpkg-query \-W \-f='${Status}' $1 2\>/dev/null
- $1: This is the package name we trying to install.
- -W: List the package with a specific pattern, the default pattern shows the name and its version.
- -f: Specific the output format. In our case, we just want to show the status of the package.
- >/dev/null 2>&1: Hide the progress output.
Dpkg-query will output “install ok installed” if the package is installed, we will use grep "install ok installed" to determine if the package is installed.
The full command will be dpkg-query \-W \-f='${Status}' $1 2\>/dev/null | grep "install ok installed"
It means the package is not yet installed if the above command generates empty output. In this case, we will perform installation processes.
The command to install a package is sudo apt-get install \-y $1 \>/dev/null 2\>&1
- -y: Agree on everything when installing the package.
- $1: This is the package name we trying to install.
- >/dev/null 2>&1: Hide the progress output.
There will be a lot of output when we install a package. The above command will hide all the output during the installation, making the script output clean.
Now we have created the function, we can feed the package name into the function to run the installation processes.
We define an APP_TO_INSTALL variable that includes all the necessary packages and loop it to installRequiredPackage function. But before we loop into the function, we need to update the package repo to get the latest version of the package information.
Connect to a safer network gateway
The Nipe project allows us to route our traffic to multiple different networks and makes us anonymous. Hence, we need to start Nipe before we start our script.
The Nipe network might failed to connect, so we set several retries to reconnect the Nipe network. We will use sudo perl nipe.pl status 2\>/dev/null to verify do we successfully connected to the Nipe network by checking the output containing the wording “Status: true”. If the output does not contain “Status: true”, it means failed to connect Nipe network, it will try to reconnect it after 1 second. We pause for 1 second using the command sleep before retrying the connection.
If the script excess the number of retries and it still not able to connect to Nipe network, the script will output it failed to connect Nipe network and stop the script.
The script will determine if it successfully connected to Nipe network by checking the output containing the wording “Status: true”. If it is successfully connected, the script will output the Nipe network Ip address and the connected country.
Ask for the domain or IP to scan
We will get the domain or IP address to scan from the user input.
- -p: Prompt to the user before requesting input from the user.
Example of the output:
Execute command to the private remote server
To get the maximum security for our environment, it is best practice to execute some commands on a remote server that we control. This script will run some scanning to the domain or IP address we retrieve from the user.
For the script to run a command on the remote server automated, we will be using sshpass to pass the command. We create a function that will accept any command and pass the command to the remote server.
- -p: The user password to log into the private remote server
- -o StrictHostKeyChecking=no: Force to connect unknown host
- $*: Special parameter that treats all the parameters passed to this function as a string.
- 2>/dev/null: Ignore all error.
In order to execute commands in the remote server, we need to register the remote server as a known host, else it will ignore the commands that we try to execute. By adding the \-o StrictHostKeyChecking=no in the ssh option, we are able to force our host to register as a known host.
In normal cases, \-o StrictHostKeyChecking=no will expose us to MITM vulnerability, but our script needs this option to connect to the private network from a clean machine. To eliminate this vulnerability, we can remove this option and connect to the private server once to register the remote server as a known host before we execute this script.
After we create the function, we can pass in the command we wish to run on the remote server.
We pass the uptime command to the function, which will pass the command to the remote server to verify if it is running. The script will prompt an error message and exit if it is not running.
If the remote server is running as expected, the script will output its IP address and the country. The script also creates a directory named the target domain or IP address to store all the scanning results performed on the remote server.
Scanning target from the remote server
The script will be using the function executeCommandOnRemote to scan the target from the remote server.
The script defines the output file name and stores it in the output_name variable, saving the output result into the file.
After completing the scan, the script will download all the scanning results through FTP using the wget command.
- -P: Specific the directory name for downloaded contents.
- >/dev/null 2>&1: Hide the download progress output.
Script auditing
As the user will use this script to scan multiple domains or IP addresses, a log file might be needed to keep track of what domain or IP address runs with this script.
Let’s create a function that will accept any input and append it to a log file. With this function, it will include the date and time of the moment it appends the message to the log file.
- date: Command that will output the system’s current date & time
- +’%a %d-%b-%Y %r %z’: Customize the date output format.
- $*: Special parameter that treats all the parameters passed to this function as a string.
- tee: Used to write the content to $LOG_FILE
- -a: Append content to file
With this function, we will have consistent log information every time we call this function.
Network Research and Monitoring
As we run the script, we notice that the script downloads the output through an insecure protocol which is FTP.
FTP stands for file transfer protocol, which is used to transfer files between machines over the Telnet protocol. FTP allows 2 individuals or organizations to share electronic files without having to be in the same place, but both parties need to have an internet connection.
FTP has 2 types of channels: Control channel and Data channel. Control channel for sending information like user identity, password, and control command (upload, download, move file, etc). This channel was initiated on port 21. Data channel for sending actual files. This channel was initiated on port 20.
In order to establish an FTP connection, one end needs to act as an FTP server, and the other act as an FTP client. First, a user from FTP can log in to the FTP server via a control channel, depending on the FTP server configuration, it allows the user to log in without a password. It is known as anonymous FTP. Second, the FTP client sends action requests to the server, like download, upload, move and etc. Third, the FTP server manages the file based on the client’s request.
FTP sessions work in 2 modes: active and passive. For active mode, the client sends a connection request to the server via the control channel, and the server creates a data connection back to the client and starts data transfer. For passive mode, the server uses a control channel to send the client the information it needs to open a data channel and start the data transfer. Due to the session initial by the client, high possibility the client’s firewall won’t block it.
FTP accepts 4 data types: ASCII, EBCDIC, image, and local.
- ASCII: Describes an ASCII text file in which each line is indicated by an end-of-line marker.
- EBCDIC: For files that use IBM’s EBCDIC character set, this type is conceptually identical to ASCII.
- Image: The file has no formal internal structure and is transferred one byte at a time without any processing.
- Local: Files containing data in logical bytes with a bit count other than eight can be handled by this data type.
After the FTP client tries to connect FTP server, the server will reply different code depending on the connection status.
- 200: Command okay.
- 530: Not logged in.
- 331: User name okay, need a password.
- 221: Service closing control connection.
- 551: Requested action aborted: page type unknown.
- 502: Command not implemented.
- 503: Bad sequence of commands.
- 504: Command not implemented for that parameter.
Moreover, let’s compare some of the pros and cons of FTP:
| FTP Pros | FTP Cons |
|---|---|
| Faster transfers | Do not encrypt data during the transfer |
| Transfer files to multiple directories at a time | Vulnerable to attack |
| Difficult to monitor |
From the table above, the most concerning point of view for cybersecurity professionals is that FTP does not encrypt the data during transfer. It breaks the confidential of the CIA triad. If the traffic of FTP has been observed by a malicious hacker, they will able to see the username and password in plain text form. Furthermore, if the malicious hacker accesses the FTP server with a leaked username and password, it can modify the file or data inside the FTP server which further breaks the integrity of the CIA triad.
Alternative secure version
There are 2 secure versions for FTP, SFTP and FTPS. Both SFTP and FTPS implement strong algorithms to encrypt data transferred, but there are a few differences between them.
SFTP stands for SSH File Transfer Protocol, it establishes the connection and data transfers over SSH. Unlike FTP and FTPS, SFTP uses only one data channel for user identity, password, action command, data transfer, etc. Since SFTP uses SSH to authenticate users, we can use SSH keys to log in instead of passwords.
FTPS stands for File Transfer Protocol over SSL, which uses SSL to encrypt the channel. FTPS like FTP has 2 channels, a command channel, and a data channel, we can choose to encrypt either both channels or only the data channel. FTPS supported authenticated methods like passwords, client certificates, and server certificates. To authenticate with the certificate, the FTPS client must have a copy of the server certificate in the trust key store or it signed off by a known certificate authority (CA).
Both SFTP and FTPS implement AES, Triple DES, and similar algorithms to encrypt the data before it transfers to other systems. Hence, malicious hackers are unable to see plain text user identity and password even he/she captures the whole FTP traffic. Moreover, it protects FTP confidential and FTP data integrity.
Conclusion
A powerful automated script can increase the productivity of users doing their work and can avoid the simple process routine with just a single line of command. Furthermore, by reducing the frequency of users typing commands manually, it also reduces the possibility of human typing errors.
On the other hand, although automated scripts are very convenient to use, we need to be aware of what protocol and package the scripts are using. Insecure protocols or outdated packages might post a vulnerability to the machine or user personal information. It is best practice that check what package and protocol the script is using before running automated scripts.
Reference
- Gite, Vivek. “How to Find out If Package Is Installed in Linux.” NixCraft, 30 Apr. 2006
- How can I check if a package is installed and install it if not? (n.d.-a). Stack Overflow.
- Stork, V. (2023, January 18). Bash Array – How to Declare an Array of Strings in a Bash Script. freeCodeCamp.org.
- Passing parameters to a Bash function. (n.d.). Stack Overflow.
- How can I check if a package is installed and install it if not? (n.d.-b). Stack Overflow.
- How to use variables in a bash for loop. (n.d.). Stack Overflow.
- Dancuk, M. (2023, August 2). Bash break: How to Exit From a Loop. Knowledge Base by phoenixNAP
- Cao, D. (2024, May 12). Understanding SSH StrictHostKeyChecking Option. Howtouselinux.
- Amoany, E. (2023, January 12). SSH password automation in Linux with sshpass. Enable Sysadmin.
- Eahall. (2018, March 13). Rsync: What is it and How do I Use it? Pair Networks Blog.
- Hiding output of a command. (n.d.). Ask Ubuntu.
- Using Arguments in Bash Scripts. (2024, February 22). Refine.
- GeeksforGeeks. (2021, October 5). How to Install Nipe tool in Kali Linux? GeeksforGeeks.
- How does `scp` differ from `rsync`? (n.d.). Stack Overflow.
- How to recursively download a folder via FTP on Linux. (n.d.). Stack Overflow.
- Saman, P. (2022, September 1). Bash: Use Local Variables in Functions - Pavel Saman - Medium. Medium.
- sudo echo “something” >> /etc/privilegedFile doesn’t work. (n.d.). Stack Overflow
- Burroughs, B. (2024, April 19). Create a custom Linux log file with rotation. Tech Roads.
- Gite, V. (2007, February 27). [How To Format Date For Display or Use In a Shell Script].
- Kerner, S. M., & Burke, J. (2021, May 6). FTP (File Transfer Protocol). Networking.
- Mitchell, C. (2024, July 3). File Transfer Protocol (FTP) Meaning and Uses. Investopedia.
- RFC959: FTP: Overview. (n.d.).
- ExaVault. (2019, January 7). What is FTP Tutorial: Overview and Business Use Cases.
- GeeksforGeeks. (2024a, January 23). File Transfer Protocol (FTP) in Application Layer. GeeksforGeeks.
- Horan, M. (2024, July 25). The Biggest Disadvantages and Advantages of FTP.
- SFTP vs. FTPS: What’s the Best Protocol for Secure FTP? (n.d.). GoAnywhere MFT.
- GeeksforGeeks. (2024b, July 3). getopts Command in Linux with Examples. GeeksforGeeks.