โ˜„๏ธBash Scripting

Bourne Again Shell

  • Bash is a scripting language used to communicate with Unix-based OS and give commands to the system.

  • Windows Subsystem for Linux, introduced in May 2019, allows using Bash in a Windows environment.

  • Mastering Bash is essential for efficient work.

  • Scripting languages, like Bash, do not require code compilation for execution.

  • Penetration testers need to work with different operating systems, including Windows and Unix-based.

  • Efficiency in privilege escalation depends on system knowledge, terminal usage, data filtering, and process automation.

  • Large Unix-based enterprise networks require sorting and filtering large amounts of data for quick identification of gaps and information.

  • Scripting combines commands and improves speed and efficiency.

  • Scripting languages share a structure with programming languages, including input/output, variables, conditional execution, loops, etc.

  • Automation of processes and handling large data volumes is common in scripting.

  • Scripts are executed by an interpreter, such as Bash, without creating separate processes.

  • Script execution involves specifying the interpreter and the script to be processed (e.g., bash script.sh <optional arguments>).

Like a programming language, a scripting language has almost the same structure, which can be divided into:

  • Input & Output

  • Arguments, Variables & Arrays

  • Conditional execution

  • Arithmetic

  • Loops

  • Comparison operators

  • Functions

Working Components

Conditional Execution

It allows us to control the flow of a script, by reaching different conditions. It is like if statements in Python.

  • #!/bin/bash - Shebang.

  • if-else-fi - Conditional execution.

  • echo - Prints specific output.

  • $# / $0 / $1 - Special variables.

  • domain - Variables.

  • -eq - Comparison Operator

Shebang

  • Top of the script

  • Starts with #!

  • Contains path to the specified interperter (/bin/bash)

Use different interperters like Python and Perl.

If-Else-Fi

  • Different conditions

    • If-else conditions

    • Case statements

If-Only.sh

If-Only.sh - Execution

If-Elif-Else.sh

If-Elif-Else.sh - Execution

If-Elif-Else.sh - Execution

Several Conditions - Script.sh

Example of different conditions in bash.

Exercise Script

Q: Create an "If-Else" condition in the "For"-Loop of the "Exercise Script" that prints you the number of characters of the 35th generated value of the variable "var". Submit the number as the answer.

I need to make a if-else condition inside of the for-loop. I will use the provided code for counting the number of characters in a variable echo $variable | wc.

This is my solution for the if-else condition

Final script

Arguments, Variables, and Arrays

Pass up to 9 argument

  • Special variables

  • Placeholders

CIDR.sh

Special Variables

  • Internal Field Seperator (IFS)

IFS

Description

$#

This variable holds the number of arguments passed to the script.

$@

This variable can be used to retrieve the list of command-line arguments.

$n

Each command-line argument can be selectively retrieved using its position. For example, the first argument is found at $1.

$$

The process ID of the currently executing process.

$?

The exit status of the script. This variable is useful to determine a command's success. The value 0 represents successful execution, while 1 is a result of a failure.

Variables

No space between names and values

Dollar sign intended to allow this variable value to be used in other code sections

  • Like a global variable

  • No differentiation in recognition of variables like

    • Strings

    • Integers

    • Boolean

  • All content treated as string characters

Arrays

  • Assigning several values

    • Scan multiple domains or IP adresses

  • Index starts at 0

Arrays.sh

This will print out the first adress


This will print them all since they are in a " "

Q: Submit the echo statement that would print "www2.inlanefreight.com" when running the last "Arrays.sh" script.

Here is the script

The first thing that I see is that the three adresses is in a quotation mark, so to print out the last adress we need to access the index [1].

To do this we edit the echo command to this echo ${domains[1]}

Comparison Operators

  • String operators

  • Integer operators

  • File operators

  • Boolean operators

String operators

Operator

Description

==

is equal to

!=

is not equal to

<

is less than in ASCII alphabetical order

>

is greater than in ASCII alphabetical order

-z

if the string is empty (null)

-n

if the string is not null

  • Note: when the variable is $1, we need to put it in double-quotes.

    • This is becasue the content should be handled as a string

  • Comparisons only work within the double square brackets [[ <condition> ]]

ASCII table

ASCII Table

Decimal

Hexadecial

Character

Description

0

00

NUL

End of a string

...

...

...

...

65

41

A

Capital A

66

42

B

Capital B

67

43

C

Capital C

68

44

D

Capital D

...

...

...

...

127

7F

DEL

Delete

Integer Operators

  • Comparing integers

Operator

Description

-eq

is equal to

-ne

is not equal to

-lt

is less than

-le

is less than or equal to

-gt

is greater than

-ge

is greater than or equal to

File Operators

  • Find out specific premissions or if they exist

Operator

Description

-e

if the file exist

-f

tests if it is a file

-d

tests if it is a directory

-L

tests if it is if a symbolic link

-N

checks if the file was modified after it was last read

-O

if the current user owns the file

-G

if the fileโ€™s group id matches the current userโ€™s

-s

tests if the file has a size greater than 0

-r

tests if the file has read permission

-w

tests if the file has write permission

-x

tests if the file has execute permission

Boolean and Logical Operators

  • True or false

  • We can use string operators

    • If they match, we get a boolean value

Logical Operators

  • Define several conditions within one

    • All conditions must match before the code can be executed

Operator

Description

!

logical negotation NOT

&&

logical AND

|

logical OR

Exercise Script

Q: Create an "If-Else" condition in the "For"-Loop that checks if the variable named "var" contains the contents of the variable named "value". Additionally, the variable "var" must contain more than 113,450 characters. If these conditions are met, the script must then print the last 20 characters of the variable "var". Submit these last 20 characters as the answer.

When I tackled this problem my first idea was to have this If loop

And for the printing of the 20 last characters with this

But it turned out this was the wrong way, since -20 gives me the wrong answer

To find the last 20 characters you needed to use -19 to get the output

Solvescript

Arithmetic

  • We have 7 different arithmetic operators

  • Perform different operations or to modify integers

Arithmetic Operators

Operator

Description

+

Addition

-

Substraction

*

Multiplication

/

Division

%

Modulus

variable++

Increase the value of the variable by 1

variable--

Decrease the value of the variable by 1

Calculate the length of a variable with ${#variable}. Example is down below

VarLength.sh

Output:

CIDR.sh

Script Control

Input and Output Control

Input Control

Controling the input based upon what we want to run next after a manual check

Output Control

  • Output redirections

  • Tee utility

    • Transfer output and use the pipe (|) to forward it to tee

    • -a / --append

      • Ensures that the file is not overwritten

      • Supplemented with new results

CIDR.sh

Flow Control - Loops

  • Branches:

    • If-Else Conditions

    • Case Statements

  • Loops:

    • For Loops

    • While Loops

    • Until Loops

For Loops

Examples

Can also write it in a single line

Now edit the CIDR.sh script

CIDR.sh

Now we are running through the array ipadrr. Output is stored in the CIDR.txt file.

While Loops

  • A statement is executed as long as a condition is fulfilled (true)

CIDR.sh

WhileBreaker.sh

Until Loops

  • The code inside a until loop is executed as long as the particular condition is false.

Until.sh

Exercise Script

Q: Create a "For" loop that encodes the variable "var" 28 times in "base64". The number of characters in the 28th hash is the value that must be assigned to the "salt" variable.

To make the For Loop I created it with making it itterate through 28 times. And when I ran the original script the salt="" created some weird things in my solution, and other peole have encountered the same problem, so I just deleted it.

Here is the solvescripts:

And here is the output I got

Booyah. HTBL00p5r0x.

Flow Control - Branches

As we have already seen, the branches in flow control include if-else and the case statements. We have already discussed the if-else statements in detail and know how this works. Now we will take a closer look at the case statements.

Case Statements

  • Switch case

    • Compares variable with exact value

  • If-else

    • Check Boolean

Syntax - Switch-Case

We need double semicolons for statements to work

CIDR.sh

Execution Flow

Functions

Method 1 - Functions

Method 2 - Functions

CIDR.sh

Function Execution - CIDR.sh

Parameter Passing

Passing through $1 - $9 (${n}), or $variable

PrintPars.sh

PrintPars.sh

Return Values

Return Code

Description

1

General errors

2

Misuse of shell builtins

126

Command invoked cannot execute

127

Command not found

128

Invalid argument to exit

128+n

Fatal error signal "n"

130

Script terminated by Control-C

255\*

Exit status out of range

Return.sh

Debugging

Bash allows us to debug our code by using the "-x" (xtrace) and "-v" options. Now let us see an example with our CIDR.sh script.

CIDR.sh - Debugging

CIDR.sh - Verbose Debugging

-v for verbose Debugging

Last updated