CHAPTER 4. Basic Shell Programming
In this chapter, we will dive into one of the hacker's secrets weapons that are scripting. There is quite a small difference between programmers and hackers. Programmers use scripting to build systems whereas hackers use scripting to exploit systems. Without creating their scripts, a novice hacker can never become a professional Hacker but will remain as a script kiddie who just uses other tools to crack systems. Thus, scripting knowledge is a must in the checklist for anyone trying to master hacking. To help you out this chapter will introduce a lot of bash scripting concepts with real-world coding examples. Let's have fun with some scripting now!
First of all, we need to know about the shell in detail.
What is a Shell?
A shell is that cursor you observe when you first connect to a server using a password or when you make yourself connected to a system using remote desktop tools like SSH. In other words, if you want it to look solely from a programming point of view you would be delighted because it acts just as an interpreter between the user and system just like how an operating system does.
But it just sends the input advises from the user to the Linux kernel and sends the output that is the result back to the system user.
Types of shell
There are types of shells that exist according to the Linux official documents. Out of both the first one stands for a GUI whereas the second one stands for CLI.
There are a lot of shells that have been manufactured with the Distros like Bourne shell, C shell, korne shell, and Bash shell.
Out of all different types of shells that are present bash shell is one of the most famous that ever existed. It is pre-installed in almost all the famous Linux Distros. It also acts as an interceptive language that helps the Linux kernel understand the instructions we are giving logically.
How does the bash shell work?
There are two types of modes that one can work shell with. Out of which one is an interactive mode and the other is a script mode.
a) Interactive mode
In this mode, the Linux user can enter the functions or the bash code one by one and wait until the result is given. If there is an error in the middle the user cannot proceed further. It just works interactively like in an old handheld video game.
b) Script mode
In this mode first of all the bash code will be written in a text file and then will make to run the script file using the command-line interface. While using this mode the user can get all the results that he was looking for all at once. Hackers need to be more perfect in script mode because it will be easy to exploit systems fast using this way. However, programmers that are who create systems will prefer interactive mode more.
Before knowing more about the grammatical structure of the shell it would be better if we have a good overview of the advantages of the shell.
Advantages of the shell
1) It is very easy to learn inline programming languages that differ a lot in both execution and implementation.
2) It has a lot of help documents that will help the hackers to rectify the errors as soon as possible.
3) It has an added advantage because it is an explanatory language. That is, it need not be compiled before running. So, hackers can easily cross-check the code before trying to implement it on the victim's system.
Apart from this shell is also fast and works efficiently. Due to all these reasons, hackers should mandatorily learn about the implementation of the shell.
Let's go!
First shell script
Let us create a shell script of the name sample.sh. create a shell script using the following command.
cat sample.sh
Location of the shell program
echo " This is very regressive"
Now we will explain this in detail. Line by line.
a) #! This represents the starting of a shell script that we are trying to write.
b) If it starts with only a hash # then it is called a comment. Comments are annotations that are used to make it easy for reference or for other users that want to look at the code. It may seem unnecessary to write comments for small shell scripts. But it is a good practice to start writing comments.
c) echo is a shell default command that lets the interpreter display the content that is written.
Here to run the shell you need to use the following command:
bash sample.sh
And then the output will appear
For this example, the output is as follows:
This is very regressive
There is also another feature that will let you run the script with additional permissions. As we discussed earlier Linux has a set of permissions and if you don't provide with necessary permissions the script may not run perfectly. So, to provide permission use the following command
Debugging is one of the most important programming tasks. Even hackers need to be perfect at this because wrong debugging of code may result in bad adaptation of the task.
Debugging the shell scripts
Normally when you enter a wrong default command in the script such as shown below in the code.
vulnerhost @ example: ech 7898
This code will not run and show an error as shown below
the ech command is not found
This is exactly what debugging is. Debugging features informs the user about the errors in the script.
There are also a lot of shell debugging tools that perform the tasks we do in a command-line interface. Tools like bashdb are famous for this. This section will help hackers understand the basics of shell programming effectively. Let's go!
Built-in Shell Commands
Before entering into a deep discussion about the built-in commands it is important to know that these built-in commands cannot be used as variable names. Variables are an important functionality of shell programming that helps to define things.
Linux provides a command called type that will let you cross-check whether a command is a built-in command or not.
The command works as follows:
type echo
The output is as follows:
echo is a built-in shell
Another example,
type trump
The output is as follows:
Trump is not a built-in shell
Also, remember that two dots that is (••) is used to determine the successful working or execution of the script. Here are the in-built commands we are going to discuss in detail.
1) Alias
Normally Linux commands are a little trickier to type. I suppose you have to type echo every time it may be difficult. For this reason, you can use an alias to give shortcut for a command.
Below we describe the command that needs to be entered to make alias work.
example@ linuxwar : Alias groupecho
However, it should be remembered that aliases work only until the shell environment is open. That is if the shell is exited there is no way to access it again. Also, the alias functions are stored in the bashrc directory of the user environment. Aliases are an easy way to increase productivity. Hackers use a lot of aliases to make deciphering the script a lot trickier.
2) Unalias
As you might have guessed already unalias is used to delete the alias systems that are present. By using this command, you can delete any alias command that you have created before.
Below is the command that will let us understand how it works:
example@ linuxwar : unalias groupecho
You can also use -a to delete all the aliases that are present at once. However, as we said before ending a shell environment will delete all the aliases that are present but using unalias. will help you to delete things while you are still scripting.
3) bg,fg,jobs
A lot of shellcode is done in interactive mode. Sometimes when you are trying to exploit a system you need to perform various tasks at once. These tasks are called jobs in Linux terms. So for everyone's convenience jobs are divided into two types. The first one is a foreground job where we can see the procedure that is going on. The classic example of foreground jobs is the installation of system programs. You can't handle other jobs while doing foreground jobs.
Solely, for this reason, background jobs are developed. Background jobs can help things run in the background. Hackers should be well aware of this because they are ought to work with multiple processes.
Below are the commands for the job functionalities:
example@ linuxwar : bg job1
example@ linuxwar : fg job2
example@ linuxwar : view jobs
4) cd
Cd is the classic Linux shell command that is famous for its huge usage. When performing tasks users usually are thrown into the root directory by the shell. Huge usage of root directory can make it scattered and messy. For this reason, Linux users use CD to change their directory and perform actions.
Below is the command for the change directory:
example@ linuxwar : cd /etc/read
5) Declaring variables
Variables are classic programming declarations. They are usually used to declare a position for the data. Variables also have a type declaration known as data types. With this, we can easily assign the type they are ought to use. There are many data types such as int, float, string.
6) Break
Scripting languages usually include Conditionals and loops that are used for repetitive and logical tasks. They can be used for both of them aligned. While doing repetitive tasks it is obvious that there should be some endpoints for better interaction and processing.
For this reason, shell language uses a statement called break that will stop the task of the logic it has provided satisfies. Break statements can also be used to print the statements using the echo command.
Here is an example for break command:
example@ linuxwar : beep.sh
for(i=0)
x>1
y>2
if(b>2)
break:
7) Continue
In loops where a break can stop the loop at once, there is a statement called continue that can help to switch the available loops. Suppose if there are five loop statements in the shellcode by using continue the loops can be interchanged. This will help to create a detailed exploiting code that can compromise systems and do multiple cross re-checks.
Below is an example of the continue statement:
example@ linuxwar : beep.sh
for(i=0)
x>1
y>2
if(b>2)
continue:
8) Eval
Linux and shellcode usually consist of a lot of arguments that need to be processed. There will be a lot of problems if strings and variables are parsed in the same way. For this reason, a command called eval is introduced in the bash shell.
eval command replaces the arguments that are present with the variables that are pointed out. You can even use eval command to parse strings into commands for execution as shown below.
example@ linuxwar : eval beep.sh
9) Exec
Execution is a process that is said to start the task. Every installation file is an execution format because it starts a new system shell in the background. Hackers should be aware of execution shells because they perform a lot of initiation and analysis tasks.
When the exec command is entered in the Linux command shell the screen or the interface that we are working on refreshes out.
This is the command that explains exec command in detail:
example@ linuxwar : exec beep.sh
10) Exit
A shell window is complex and deals with a lot of tasks. However, when you complete the task it is a good practice to exit the shell. If not, the processes would still be running and may result in unnecessary system power consumption. For this, a quick command called exit has been introduced in the shell language for this exact reason.
Exit command also clears all the tasks that are present. So, make sure that everything is fine before making this happen. You can also exit individual processes or programs with a shell script.
Below is a simple command example for exit:
example@ linuxwar : exit shell.sh
11) Export
Usually when the system boots up the first shell command is created in the kernel system. This is called a parent shell. And the next ones that followed are called child shells unless the parent shell is exited or killed.
So, while working with the different numbers of shells we will deal with a lot of variables. And sometimes we may need the same variables that we used in the other shell environments. For this exporting of variables, the shell provides us with an export option.
After using the export command all the child shells can use the parent variables. However, remember that the child shells cannot use their sibling's variables that are the other child shells that are present.
Here is an example that demonstrates this process:
example@ linuxwar : export example.sh to /etc/dir
12) Kill
Killing processes is an important skill to learn for hackers. Processes have three distinct distinctions. One of them is an interaction that is a usual shell interface. The second one is a batch process where everything that needs to be applied is done in a sequential process. And the last one is monitoring the process where everything that is being done is monitored. For example, a task management system.
When you are running a bunch of these processes you may get distracted with signals that they come with. For this reason, killing processes is a good process if you find that they are unnecessary. When you are trying to exploit a system you need to kill the antivirus process that is running in the background. You can even use the killing process to stop the logging files that record your every move.
Below is the simple demonstration of kill command:
example@ linuxwar : kill process
example@ linuxwar : killall
13) Read
Read command can be used to read the bash scripts when you are performing the tasks. Or it can be even used to perform a thorough check of the shellcode that has been written. Read statement is a basic shell command and can help hackers interpret and cross-check things easily.
Here is the command with an example:
example@ linuxwar : read bash.sh
14) ulimit
Priority is one of the most underused functionalities of the shellcode. Priority can be both incremental and decrement also. By using ulimit the hacker can increase or decrease the priority of the process.
Why prioritizing processes is necessary?
When a user is dealing with a lot of background processes that are constantly functioning this may decrease the processing speed of other processes. For this reason, administrators prioritize anti-virus software's at first level of the priority. With this method, any boot level executions can be eliminated.
However, a lot of system administrators don't take this problem seriously and make hackers exploitation easy. Below is the example command that explains how to prioritize the processes that are present.
example@ linuxwar : ulimit PID 2345
Always remember that PID is the most necessary thing that needs to be used to prioritize.
15) Test
Shellcode consists of a lot of loop and conditional codes. Before experimenting with these repetitive tasks with a system shell it is a good practice to check them in the old shell. For this purpose, the test command is introduced.
Below is the command that takes care of the testing:
example@ linuxwar : test PID 3634
With this, we have completed an explanation about some of the built-in shell commands that are present in Linux systems. This should have given a good overview of the hacking environment to you.
But before learning about it let us learn about the installation of a bash shell, the most famous shell environment.
Installation of bash environment
1) you can use wget to get the system files that are present in the server. The below command will download the files from the mirror websites and will help users install them in their system.
wget bash.com/download
2) in the next step you need to mention or input the configuration of the system that you are using. Otherwise, it may not get installed.
3) After installation, you may need to check the settings and input the default directory. Normally it is entered as the root directory. Also, the shell versions can be easily known using the help command.
With this, we have installed the bash environment and good to go to learn about some fundamentals of shell programming. Remember that these topics very much coincides with python scripting which is another good alternative scripting language for hackers.
Fundamentals of Shell Programming
The shell consists of a group of systematic instructions or commands. Let us go and learn about some of the basic components that comprise the shell language.
Variables
Variables are a piece of memory in the computer random access system that is used to store the data. As discussed before variables are the most important components of a programming language and it is often called while writing functions or templates.
Usually, there are two types of variables:
a) Local variables
b) environmental variables
Let us discuss the functionalities of these variables in detail along with few command-line examples.
a) Local variables
Local variables are the one can which can be used in a private or single environment that is these cannot be used in other shell scripts even with a reference. These types of variables are used in short shell scripts.
b) Global variables
Global variables are also known as environmental variables. These variables differ from the first one because these can be used in any shell script with a reference. For using the global variables, you need to export them to the local shell script file.
Variable naming
Variables present in the shell language should follow some varied instructions while naming. Remember that shell in-built commands like exit cannot be used for the names of variables.
Here are the instructions that need to be followed for naming a variable:
a) In shell language, variables differ from the capital and small letters.
b) A variable name should never start with a number or special character. Doing this may give an error saying that the variable name cannot be initialized.
Here are some of the various examples that can be used
love
dude
ra344
And here are some of the variable names that cannot be used
1hjsd
#fege
Variable assignments
Variable assignments are the assignment values that are used to give a value to the variable.
It works in the following way:
variable name = variable value
You can insert a lot of data types in the variable value. Data types are the ones in which variables are defined. Some data types consist of integers, floating-point numbers, and even strings sometimes.
Here is an example that describes the assignment value:
sample = 22
Special variables
Special variables such as usnet can be used to delete a defined variable from the memory. In this, we can store the random memory management.
There are also special variables that start with a $ parameter. These variables can be used to define additional parameters that the system may require during the process execution or advanced shell analysis.
Here is the example for some of the special variable commands with a $
$dude = ' string'
The biggest advantage of using special variables is that they can be easily filtered and aliased with the help of the character that is present at the beginning of the variable.
Arrays
The array is a famous data structure that is capable of holding multiple items of elements. Programming languages use a lot of arrays because they are easy to implement unlike other data structures like trees or graphs and also they are fast. Shell also supports arrays to input elements. In this section, we will discuss arrays in detail.
a) definition of array
Normally arrays consist of a subscript that defines the number of the element along with the name of the array.
Here is the command for an array example:
example[]
b) Giving value to an array
All elements that are present in an array can be given a value using the symbol. You can also give the value using the individual array assignment like as shown below
sample = “America”
You can insert any data type in arrays just like variables and the use of arrays can be very essential when you are dealing with loops and conditionals with complex code in it.
You can even connect both arrays to get the desired results. This scenario is shown below for your better understanding:
sample = value
Constants
As we all know already that constant means something that cannot be changed. Constant values exist always and can be used to explain values like pi that have a constant numerical value. Whenever you try to change this constant variable an error or warning will appear in front of the shell that says this cannot be possible.
Here is an example of the constant command:
pi = 3.1427
Namespaces
We already have discussed variables in detail and namespaces mean that variables that are in a defined scope. These are created for a reason that whenever users try to create variables that are of similar type a conflict always occurs and makes things difficult to organize.
For this exact reason, namespaces are invented and are used to define citations and references which can be used multiple times in a shell interface or a shell script.
Here is an example that explains in detail about this concept:
Operators
Operators are the most important regions of a scripting language. Operators can help to mix or change the variable values. As of the shell, programming goes there are a lot of operators that can be used. We will discuss some of them now in detail:
1) Arithmetic operators
Arithmetic operators deal with mathematical calculations such as addition and subtraction. These are important for programming because they can add up things and multiply variable count easily.
Here is an example command for the arithmetic operators:
>>> 2+3
>>> 2-1
>>> 6 * 2
>>> 7/3
>>> 4 % 7
2) Relational operators
Relational operators are significant operators and can be used to change things easily. They can be used to compare two things easily. Few of the relational operators are AND, OR and NOT. These relational operators can be easily implemented in any shell language code.
Here is a command-line example that deals with relational operators:
>>>> 2 ! = 7
>>>> x === y
3) Assignment operator
The assignment operator just gives the value to a variable or loop code. By using this operator one can easily assign things to the element.
Here is the example for the assignment operator:
x = 7
With this, we have completed a brief exploration of the scripting world. Shell language is a must for any hacker that is serious about his job. You can also implement these concepts with python programming for doing advanced tasks in hacking. Let us start!