BASH scripts are an integral part of the Linux operating system and play an important role in performing automated tasks, scripting, and system administration. BASH (Bourne Again SHell) is a command line interface and scripting language that allows users to create sequences of commands to perform various tasks directly from the command line. From initial application startup to complex automated tasks, BASH scripts provide a powerful toolkit for managing a Linux system. Flexibility and Efficiency: BASH scripts give users a lot of flexibility in performing tasks. They allow you to automate routine operations, simplify the processes of working with files and directories, and allow you to create sequences of commands to perform complex tasks.
Scripting and Interactivity: You can create BASH scripts that automate tasks and execute them automatically, or use interactive mode to interact with the system while executing commands. Working with Files and Directories: BASH scripts provide powerful tools for managing files and directories. They allow you to copy, move, rename, delete and view the contents of files and directories. Tasks and Schedules: You can create BASH scripts to automate tasks and schedules that allow certain actions to be performed at specified times or under specified conditions. System Management: BASH scripts allow you to manage system resources, services, users, and other parameters of the Linux operating system. Ease of Learning and Application: Learning BASH scripting is quite accessible for both beginners and advanced users. Scripts can be written in a text editor and run from the command line. Community and Resources: Linux has a large community of users, which means you can find lots of resources to help you develop and develop your BASH scripting skills. BASH scripting in Linux is a powerful tool for automating, managing, and developing operating systems. They allow you to perform various tasks, ranging from simple commands to complex automated processes, and open up a wide range of possibilities for working with Linux.
In this section, we create some simple bash shell scripts to get you started with scripting. We will be adding capabilities and features as we progress, eventually creating a script capable of finding potential attack targets across a range of IP addresses.
To become an elite hacker, you’ll also need to be able to script in one of the widely used scripting languages, such as Ruby (the Metasploit exploits are written in Ruby), Python (many hacking tools are Python scripts), or Perl (Perl is the best text-based scripting language) .
The shell is an interface between the user and the operating system that allows you to manipulate files and run commands, utilities, programs and much more. The advantage of the shell is that you perform these tasks directly from the computer, and not through an abstraction such as a graphical interface, which allows you to customize your task to your needs. A number of different shells are available for Linux, including the Korn shell, the Z shell, the C shell, and the Born shell, better known as bash.
Since the bash shell is available in almost all Linux and UNIX distributions (including macOS and Kali), we will use the bash shell exclusively.
The bash shell can run any system commands, utilities, or programs that your regular command line can run, but it also includes some built-in commands of its own. Table 81 later in the chapter links to some useful commands found in the bash shell.
In previous chapters, you used the cd, pwd, set, and umask commands. In this chapter, you will use two more commands: the echo command, first used in Chapter 7, which displays a message on the screen, and the read command, which reads data and stores it somewhere else. Just learning these two commands will allow you to create a simple yet powerful tool.
You will need a text editor to create shell scripts. You can use any Linux text editor you like best, including vi, vim, emacs, gedit, kate, etc. I will be using Leafpad in these tutorials, as I have in previous chapters. Using a different editor should make no difference to your script or its functionality.
For your first script, we’ll start with a simple program that returns a message to the screen that says “Hey Hackers Stand Up!” Open a text editor and go. First, you need to tell your operating system which interpreter you want to use for the script. To do this, enter the shebang, which is a combination of a hash mark and an exclamation mark, like this:
Then you follow the shebang (#!) with /bin/ bash to indicate that you want the operating system to use the bash shell interpreter. As you will see in the following sections, you can also use the shebang to use other interpreters such as Perl or Python. Here you want to use the bash interpreter, so type the following:
Next, enter the command echo , which tells the system to simply repeat (or echo) your monitor whatever is executing the command.
In this case, we want the system to respond to us with “Hello hackers-stand up!”, as done in Listing 81. Note that the text or message we want to repeat must be enclosed in double quotes.
Here you also see a string preceded by a hash (#). This is a comment you leave to yourself or someone else reading the code to explain what you are doing in the script. Programmers use comments in every coding language. These comments are not read or executed by the interpreter, so you don’t have to worry about your code getting messed up. They are visible only to humans. The bash shell knows that a line is a comment if it starts with the # character.
Now save this file as HelloHackersArise without extension and close the text editor.
By default, the newly created bash script is not executed even by you, the owner. Let’s take a look at the permissions for our new file on the command line by using cd to move to the directory and then typing ls -l. It should look something like this:
kali >ls-l snip rwrr 1 root root 42 Oct 22 14:32 HelloHackersArise snip
As you can see, our new file has permissions rw-r–r– (644). As you learned in Chapter 5, this means that the owner of this file only has read (r) and write (w) permissions, but no execute (x) permissions. The group and all other users have read-only permissions. We need to give ourselves execute permissions to run this script. We change permissions with the chmod command, as you saw in Chapter 5. To give owner, group, and everyone else execute permissions, type the following:
Now, when we do a long list in the file, for example, we see that we have execute permissions:
kali >ls-l snip rwx rx rx 1 root root 42 Oct 22 14:32 HelloHackersArise snip
The script is now ready to run!
To run our simple script, type the following:
The ./ symbol in front of the file name tells the system that we want to execute this script in the HelloHackersArise file from the current directory. It also tells the system that if there is another file named HelloHackersArise in another directory, please ignore it and run HelloHackersArise only in the current directory. It may seem unlikely that you have another file with this name on your system, but it is recommended to use ./ when executing files, as this localizes the execution of the file to the current directory, and many directories will have duplicate filenames such as start and setup.
When we press ENTER, our very simple script returns our message to the monitor: Hello HackersArise! Success! You have just completed your first shell script!
So now we have a simple scenario. All it does is echo the message to standard output.
If we want to create more advanced scripts, we will most likely need to add some variables.
A variable is a storage area that can hold something in memory. This “something” can be some letters, words (strings) or numbers. It is known as a variable because the values it contains are mutable; This is an extremely useful feature for adding functionality to a script.
In our next script, we’ll add functionality to ask the user for their name, put whatever they type into a variable, then ask the user what chapter they’re in in this book, and put that keyboard input into a variable. We will then repeat a welcome message to the user that includes their name and section. Open the new file in a text editor and enter the script shown in Listing 82.
➊ #! /bin/bash
➋ # This is your second bash script. In this you tell /# the user to input, put the input into a variable and /# display the contents of the variable in a string.
➌ echo “What’s your name?” read the title
➍ echo “Which chapter are you reading in Linux Basics for Hackers?” read the chapter
➎ echo “Welcome” $name “to” $chapter “Linux Basics for Hackers!”
Listing 82: A simple script that uses variables
We open with #! /bin/bash to tell the system that we want to use the bash interpreter for this script ➊. Then we add a comment that describes the script and its functionality ➋. After that, we ask the user for their name and ask the interpreter to read the input and put it into a variable we call name ➌. We then prompt the user to enter the chapter they are currently working on in that book, and we again read the keyboard input into a variable, this time called chapter ➍.
In the final line, we build an output line that welcomes the reader by name to the section he is in ➎. We use the echo command and provide the text we want to display on the screen in double quotes. Then fill in the name and chapter number
We add variables to the entered user where they should appear in the message. As mentioned in Chapter 7, to use the values contained in variables, you must precede the variable name with a $ character.
Save this file as WelcomeScript.sh. The .sh extension is a convention for script files. You may have noticed that we didn’t include the extension earlier; This is optional, and if you leave the extension disabled, the file will be saved as a default shell script file.
Now let’s run this script. Don’t forget to give yourself permission first with chmod ; otherwise, the operating system will scold you with a “Permission Denied” message.
kali >./WelcomeScript.sh What is your name? OccupytheWeb What chapter are you on in Linux Basics for Hackers? 8 Welcome OccupytheWeb to Chapter 8 of Linux Basics for Hackers!
As you can see, your script took inputs from the user, placed them in variables, and then used those inputs to greet the user.
It’s a simple script, but it taught you how to use variables and accept keyboard input. These are both the most important concepts in the script that you will need to use in more complex scenarios in the future.
Now that you have some basic scripting skills, let’s move on to some slightly more advanced scripts that have real-world hacking applications. We will use an example from the world of black hat hacking. Dark hackers are those with malicious intent, such as stealing credit card numbers or defacing websites. White hackers are those who have good intentions, such as helping software developers or system administrators make their systems more secure. Gray hat hackers are those who tend to move between these two extremes.
Before proceeding, you need to familiarize yourself with a simple but important tool called nmap, which is installed by default on Kali. You have probably heard this name; Nmap is used to probe a system to see if it is connected to a network and to find out what ports are open. From the detected open ports it can be assumed that
Services work according to the target system. This is the most important skill for any hacker or system administrator.
In its simplest form, the syntax for running an nmap scan looks like this:
nmap <type of scan><target IP><optionally, target port>
Not too difficult. The simplest and most reliable nmap scan is the TCP connect scan indicated by the -sT switch in nmap. So, if you want to scan the IP address 192.168.181.1 using a TCP scan, you would type the following:
nmap -sT 192.168.181.1
To take it a step further, if you wanted to perform a TCP scan of 192.168.181.1 to see if port 3306 (the default port for MySQL) was open, you could type this:
nmap -sT 192.168.181.1 -p 3306
Here -p indicates the port to be scanned. Try it now on your Kali system.
As of this writing, there is a hacker serving time in a US federal prison named Max Butler, also known in the hacker world as Max Vision. Max was a kind of hacker in a gray hat. By day he was an IT security professional in Silicon Valley, and by night he stole and sold credit card numbers on the black market. At one time, he ran the world’s largest credit card black market, CardersMarket. Max is now serving a 13-year prison sentence while helping the Computer Emergency Response Team (CERT) in Pittsburgh defend against hackers.
A few years before Max was caught, he realized that the Aloha Point of Sale (POS) system used by many small restaurants had a built-in technical support backdoor. In this case, the backdoor allowed tech support to help their customers. Aloha Technical Support could access the end user’s system via port 5505 to provide assistance when the user called for assistance. Max realized that if he found a system connected to the Internet with an Aloha POS system, he could gain access to the system with sysadmin privileges over port 5505. Max was able to log into many of these systems and steal tens of thousands of credit card numbers.
Ultimately, Max wanted to find every system that had port 5505 open so he could go from stealing thousands of credit card numbers to stealing millions. Max decided to write a script that would scan millions of IP addresses for systems with open port 5505. Of course, most systems don’t have port 5505 open, so if they did, they were most likely running the doomed Aloha point of sale . He could run this script during the day and then at night compromise those systems that were identified as having port 5505 open.
Our task is to write a script that will be almost identical to Max’s script, but instead of scanning port 5505 like Max did, our script will scan systems connected to the ubiquitous online MySQL database. MySQL is an open source database used by millions of websites; we’ll be working with MySQL in Chapter 12. By default, MySQL uses port 3306. Databases are the “golden fleece” that almost every black hat hacker looks for because they often contain credit card numbers and personally identifiable information (PII), which is very valuable on the black market.
Before we write a script to scan public IP addresses on the Internet, let’s tackle a much smaller task. Instead of scanning the globe, let’s first write a script to scan port 3306 on the local network to see if our script actually works. If so, we can easily edit it to do a much bigger job.
In a text editor, type the script shown in Listing 83.
➊ #! /bin/bash ➋ # This script is designed to find hosts with MySQL installed nmap ➌sT 192.168.181.0/24 ➍p 3306 ➎>/dev/null ➏oG MySQLscan ➐ cat MySQLscan | grep open > MySQLscan2 ➑ cat MySQLscan2
Let’s start with the shebang and the translator to use ➊. Let’s follow it up with help
comment to explain what the script ➋ does.
Now let’s use the nmap command to request a TCP scan ➌ on our local network, looking for port 3306 ➍. (Note that your IP addresses may be different; in your terminal, use the ifconfig command on Linux or the ipconfig command on Windows to determine your IP address.) To stay hidden, we also send nmap standard output, which is usually appears on the screen, to a special place in Linux where it disappears ➎. We’re doing this on a local machine, so it doesn’t really matter, but if you want to use the script remotely, you’ll want to hide the nmap output. We then send the scan output to a file named MySQLscan in grepable format ➏, which means a format that grep can work on.
The next line shows the MySQLscan file in which we saved the output, followed by pipelines that output for grep to filter out lines that contain the keyword open ➐. We then put these lines into a file called MySQLscan2 ➑.
Finally, you display the contents of the MySQLscan2 file. This final file should only contain lines of output from nmap with hosts that have port 3306 open. Save this file as MySQLscanner.sh and give yourself execute permissions with chmod 755.
Run the script like this:
kali >./MySQLscanner.sh host: 192.168.181.69 () Ports: 3306/open/tcp//mysql///
As we can see, this script was able to identify a single IP address on my local network running MySQL. Your results may vary depending on whether or not any MySQL installation ports are running on your local network, of course.
Now we want to adapt this script to make it applicable to more than just your own local network. This script would be much easier to use if it could ask the user for the range of IP addresses they wanted to scan and the port to search and then use that data.
Let’s see how you can use variables to make this script more flexible and efficient. Adding hints and variables to our hack script.
In a text editor, enter the script:
#! /bin/bash ➊ echo "Введіть початкову IP-адресу: " ➋ читайте FirstIP ➌ echo "Введіть останній октет останньої IP-адреси: " читайте LastOctetIP ➍ echo "Введіть номер порту, який потрібно сканувати: " читати порт ➎ nmap sT $FirstIP$LastOctetIP p $port >/dev/null oG MySQLscan ➏ cat MySQLscan | grep open > MySQLscan2 ➐ cat MySQLscan2
Listing 84: Your advanced MySQL port scanner
The first thing we need to do is replace the specified subnet with a range of IP addresses. We will create a variable named FirstIP and a second variable named LastOctetIP to create the range, and a variable named port for the port number (the last octet is the last group of digits after the third period in the IP address. In the IP address 192.168.1.101, the last octet – 101).
We also need to prompt the user for these values. We can do this using the echo command we used in Listing 81.
To get the value for the FirstIP variable, echo “Enter the starting IP address : ” to the screen, asking the user for the first IP address they want to scan ➊. After seeing this prompt on the screen, the user will enter the first IP address, so we need to capture this data from the user.
We can do this by using the read command followed by the name of the variable we want to store on the input ➋. This command will put the IP address entered by the user into the FirstIP variable. We can then use this value in FirstIP throughout our script.
We’ll do the same for the LastOctetIP ➌ and Port ➍ variables, prompting the user for input and then using the read command to grab it.
Next, we need to edit the nmap command in our script to use the variables we just created and populated. To use the value stored in a variable, we simply preface the variable name with $, as in $port, for example. So, at ➎ we scan the range of IP addresses starting from the user’s first IP address through the user’s second input IP address and look for a specific port input by the user. We used variables instead of subnet to scan and port to define what to scan. The redirect symbol > tells nmap’s standard output, which normally goes to the screen, to go to /dev/null instead (/dev/null is just a place to send the output so it disappears). We then send the output in a viewable format to a file we named MySQLscan.
The next line is the same as in our simple scanner: it outputs the contents of the MySQLscan file, passes it to grep, where it filters for lines that contain the keyword open, and then sends that output to a new file named MySQLscan2 ➏. Finally, we show the contents of the MySQLscan2 file ➐.
If everything works correctly, this script scans the IP addresses from the first input address to the last input address, looks for the input port, and then reports only the IP addresses for which the specified port is open. Save the script file as MySQLscannerAdvanced, making sure to give yourself execute permission.
Now we can run our simple scanner script with variables that define which IP address range and port to scan without having to edit the script every time we want to run a scan:
kali >./MySQLscannerAdvanced.sh Enter the starting IP address : 192.168.181.0 Enter the last IP address : 192.168.181.255 Enter the port number you want to scan for : 3306 Host: 192.168.181.254 ()Ports:3306/open/tcp//mysql/
The script prompts the user for the first IP address, the last IP address, and then the port to scan. After collecting this information, the script performs an nmap scan and generates a report of all IP addresses in the range for which the specified port is open. As you can see, even the simplest scenarios can create a powerful tool.
As promised, Table 81 gives you a list of some useful commands built into bash.
Table 81: Built-in Bash commands
: Returns 0 or true (Returns 0 or true)
. Executes a shell script
bg Moves work to the background
break Exits the current loop
cd Changes directory
continue Resumes the current cycle
echo Displays the command’s arguments
eval Evaluates the following expression
exec Executes the following command without creating a new process
exit Exits the shell
export Makes a variable or function available to other programs
fg Brings work to the foreground
getopts Parses shell script arguments
jobs Lists background (bg) jobs
pwd Displays the current directory
read Reads a line from standard input
readonly Declare a variable as read-only
set Lists all variables
shift Moves parameters to the left
test Evaluates the arguments
[ Performs a conditional check
times Prints user and system time
trap Traps a signal
type Indicates how each argument will be interpreted as a command
umask Changes the default permissions for a new file
unset Removes a value from a variable or function
wait Waits for a background process to complete
Scripting is an essential skill for any hacker or system administrator. This allows you to automate tasks that would normally take hours of your time, and once the script is saved, it can be used over and over again.
We used materials from the book “LINUX BASICS FOR HACKERS” written by William Pollock