Back to lab listing.
Lab Objective:
Learn how to take advantage of an XML External Entity vulnerability to retrieve files.
Lab Purpose:
An XML External Entity vulnerability
Lab Tool:
Kali Linux.
Lab Topology:
You can use Kali Linux in a VM and Burp Suite for this lab.
Lab Walkthrough:
Task 1:
In this lab, I will be using PortSwiggers web academy to demonstrate an XXE injection attack. You will need to register for an account at the following link to complete this lab:
https://portswigger.net/web-security/dashboard
The lab itself can be accessed at the following link once you have created an account:
https://portswigger.net/web-security/xxe/lab-exploiting-xxe-to-retrieve-files
Task 2:
Once setup on the site, access the lab. You will be presented with a store webpage. Click “View details” button on any product in the store.
Start Burp Suite and turn intercept on.
You will notice a button at the bottom of the screen called “Check Stock”. Once intercepting mode on, press the “Check stock” button and capture the resulting request in Burp Suite.
With the request captured, right-click and press “Send to Repeater”. Navigate to the Repeater tab where we will continue to edit the request.
The way in which the server serves XML requests is vulnerable in that it parses XML input and returns any unexpected values in the response. This means that we are able to execute commands on the server OS.
To do this, we need to locate the section at the end and create a space between the <?xml version=”1.0″ encoding=”UTF-8″?> and <stockCheck>. In this space, we want to enter the following line of code:
<!DOCTYPE test [ <!ENTITY xxe SYSTEM “file:///etc/passwd”> ]>
We need to make another change before we can submit this request. We need to change the number under the <productId> tag to the following:
&xxe;
The following screenshot shows what the full request should look like:
Once the request has been altered, we can submit the request by pressing the “Send” button on the top left of the Burp Suite Repeater window. You can view the response on the right screen.
You will notice that, while the response returned a Bad Request, it also returned the contents of the /etc/passwd file.
So, what we just did is take an advantage of an XXE vulnerability and pass a command to the OS running on the server.
Lab 91 – OWASP A5 Broken Access Control
Back to lab listing.
Lab Objective:
Learn how to take advantage of a broken access control vulnerability to log in as another user.
Lab Purpose:
Broken Access control is what happens when restrictions on what authenticated users can do are not properly enforced. This vulnerability can be exploited by attackers to access unauthorized functionality and or data such as other users’ accounts, modify other users’ data, change access rights, view sensitive files etc.
Lab Tool:
Kali Linux.
Lab Topology:
You can use Kali Linux in a VM and Mutillidae 2 Tool for this lab.
Lab Walkthrough:
Task 1:
In this lab, I will be using Mutillidae 2 to demonstrate a broken access control vulnerability. How to install this environment in Kali VM is explained in detail in lab 87.
To begin, we will first need to register an account on the Mutillidae 2 home page. The Login page can be found at the top left of the home page (1).
Once at the login screen, press on “Register an account” (2). From here, enter the following information:
Username: tester
Password: test
Confirm Password: test
Signature: Hacker
Once this information is entered, click the “Create Account” button (4). We will now have created a new user on the site. Click “Login/Register” link again and wait.
Start Burp Suite and turn intercept mode ON. If you are not sure how to do this, please refer to lab 7 which we had done on Burp Suite. It is important to note that, when accessing the local web application, you will need to add a . after localhost in order for Burp Suite to be able to capture requests. This is what the URL for the user login page should look like:
http://localhost./mutillidae/index.php?page=login.php
Essentially, it is the same, just with an added . right after localhost (1). This will force the web application to transmit data through our Burp Suite proxy, allowing us to capture requests.
Return to the Login/Register page and enter the details for the account we just created (2,3,4).
The captured requests should be available for you in Burp Suite. There will be two of them, right- click on the requests and select “Send to Repeater” (1).
Then, forward the requests (2). The following screenshots are what the captured requests should look like:
On this page, select “Send to Repeater” again (3). Then, click Repeater tab (4).
Task 2:
Here, we can see the two requests we captured. Select the first request and click the “Send” button in the top left (1). Notice the “uid” value that is returned in the response (2). This is the value which we are going to be manipulating.
Now, go to the second request we captured. We can see that the second request is taking the “uid” value from the response the first request received, and including it in the body of the request. This will allow us to manipulate this value.
right-click on this request and select “Send to intruder” (1). Then, navigate to the “Intruder” tab (2).
Task 3:
You will notice that we have our target available, which is the request we just sent here. Go to the “Positions” tab within the Intruder tab. You will notice some sections highlighted in green. Click on the Clear button to the far right to remove all of these areas (1).
Once this is done, navigate to the “uid” value and place one of those symbols either side of the number by pressing the “Add §” button to the far right (2).
Once this is done, navigate to the Payloads tab (3). Then, go to a terminal screen in Kali and create a text file with numbers from 1 to 50 included in the file. Each number should be on a new line with no spaces. You can easily generate this file by executing the following single line command;
for k in $(seq 1 50);do echo -e $k; done > seq.txt
Then, return to the Payloads tab within the Intruder tab and import this file we just created (1,2,3).
You will notice that our payload now contains the numbers 1-50.
Once this is done, click on the “Start Attack” button on the top right of the screen (4). This will start replacing the “uid” value in our origional request with the list of numbers we imported into the payloads section. We can see in the response that the logged-in user is the admin user.
Task 4:
We will now analyse the results of our intruder attack. To do this, we will simply click on each of the different numbers to see if they corresponded with any other user. Click on the first request. You will see the request sent on the bottom panel. Click on the “Response” tab in between the top and bottom panels. This will show us the response from the server.
We now know that the uid value for the “admin” user is 1, and 2 for user “adrian”. We will now use this information to log in as the “admin”.
Task 5:
Go back to Burp Suite and turn intercept mode OFF. Then, navigate to browser where we are logged in as the user tester. right-click on the page and select the “Inspect Element” option (1). Then, navigate to the Storage tab (2).
Click on the Cookies tab. This tab will have stored the cookie for our logged in user, which means we will remain logged-in for the duration of our session on the application. Click on the localhost cookie
and note the uid value here (3).
Double click on the uid value and change it to 1, the admin users uid (4).
Now, return to our browser page and refresh the page. We are now logged-in as the admin user!
Lab 92 – OWASP A6 Security Misconfiguration
Back to lab listing.
Lab Objective:
Learn how to take advantage of a security misconfiguration vulnerability.
Lab Purpose:
Security misconfigurations are one of the most noted vulnerabilities in the wild. This is usually caused by insecure default configurations, incomplete or ad hoc configurations, open cloud storage, misconfigured HTTP headers, and verbose error messages containing sensitive information.
Lab Tool:
Kali Linux.
Lab Topology:
You can use Kali Linux in a VM for this lab.
Lab Walkthrough:
Task 1:
In this lab, I will be using Mutillidae to demonstrate a security misconfiguration vulnerability. How to install this environment in Kali VM is explained in detail in lab 87.
One of the most common security misconfigurations is relying on hidden directories and files, which are not actually hidden. The only thing keeping the application secure in this scenario is the hope that the attacker will not find the names of the hidden resources. These names can be brute forced or guessed.
The first example of a security misconfiguration can be easily found on Mutillidae 2. Simply go to the URL and type the following:
http://localhost/mutillidae/passwords
As you will see, we can clearly see the accounts.txt file here in this supposedly hidden directory. Click on this file and you will notice all of the usernames and passwords listed for every account on Mutillidae 2. This is a common and severe security misconfiguration, where hidden or sensitive directories are not actually hidden.
Task 2:
For the next task, we will be using gobuster tool to discover any other potential security misconfigurations in the form of sensitive files or directories. Download gobuster by typing the following in a terminal in Kali:
sudo apt-get install gobuster
Once the tool is installed, type the following command in a single line to scan the mutillidae site for all potential directories:
gobuster dir -u http://localhost/mutillidae -w \
/usr/share/dirbuster/wordlists/directory-list-1.0.txt -x .txt
This command will search the target site for all directories contained in the directory list text file. It will also search for any files with the .txt extension which are accessible through the URL. Notice
that the only .txt file which turns up is the robots.txt file.
Browse to this file now by typing the following into the URL bar:
localhost/mutillidae/robots.txt
This is another common security misconfiguration whereby the robots.txt file contains sensitive information and is easily accessible. We can see when we open this file, that it contains a list of a number of sensitive directories.
Navigate to a few of these directories by typing them into the URL and notice the range of sensitive information we can uncover.
Lab 93 – OWASP A7 – Cross Site Scripting (XSS)
Lab 94 – OWASP A8 – Insecure Deserialization
Back to lab listing.
Lab Objective:
Learn how to take advantage of an insecure deserialization vulnerability.
Lab Purpose:
Insecure deserialization vulnerabilities often lead to remote code execution, making them very severe vulnerabilities. Even if they do not result in RCE, they can be used to perform attacks including replay attacks, injection attacks, and privilege escalation attacks.
Lab Tool:
Kali Linux.
Lab Topology:
You can use Kali Linux in a VM for this lab.
Lab Walkthrough:
Task 1:
In this lab, I will be using Portswigger’s Web Academy to demonstrate an XSS vulnerability.
In order to access the lab, you will first need to create an account at the following site:
https://portswigger.net/web-security/dashboard
Once you have created an account, you can access the lab at the following link:
https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-modifying-serialized-objects
Task 2:
To begin, access the lab from the link above. You will be presented with a web page which looks like an online shop. Click on the “My account” button at the top right of the screen (1). This will bring you to a login screen. Then, login with the username “wiener” and password “peter” without quotes (2,3,4).
You will then see a screen which allows you to update the email for your account. Start Burp Suite and ensure intercept is turned ON. How to install Burp Suite is explained in detail in lab 7.
Then, enter a random email address into the text box and click update email.
Navigate to Burp where the captured requests should be waiting for you. Forward the first request as we do not need it. The second request is the one we want; it starts with the following header:
GET / HTTP/1.1
Right click on this request and choose the “Send to Repeater” from the option menu (1). Then, navigate to the “Repeater” tab (2).
Task 3:
On the Repeater tab, notice the cookie session value which is assigned to us. This is the value we are looking to manipulate.
Highlight this value (1) and you will notice the automatic decoder to the right of the screen (2) is able to decode the cookie value and show us in clear text what values it is made up of.
With this cookie value highlighted, right-click on the value and select Send to Decoder (3). Then, navigate to the Decoder tab (4).
Task 4:
Once in the Decoder tab, you will see the cookie value that we sent here from our request. Select the “Decode as” button to the right of the text box and select “URL” (1). Another text box will appear with the URL decoded value. Do this again for the second value (2) and a third box will appear with the decoded value. For this third value, select “Decode as”, and then select “Base64” (3). Finally, we are able to see our cookie value in clear text, allowing us to manipulate it (4).
Notice the section which has the following code in it:
“admin”;b:0;}
This is the section we are interested in manipulating. The b:0 value is a boolean value which means false. Essentially, this is indicating to the server that we are not the admin user. If we change this value to b:1, this will now indicate to the server that we are the admin user.
Great! We now need to reformat this value to be the same as the original cookie value. To do this, click the “Encode as” option to the right of the value we just manipulated and select “Base64” (2). A new textbox will appear containing the encoded value. For this new textbox, click on the “Encode as” option to the right of the box, and select “URL” (3). A new textbox will appear containing the URL encoded value.
OK, we now have our manipulated value back to the format of the original cookie value. Copy this value (4) and return to our “Repeater” tab, where the request should still be waiting for us (5).
Task 5:
In the “Repeater” tab, replace the cookie session value with our new value which we copied from the “Decoder” tab (1). Press “Send” in the top left corner and note the response from the server on the right hand side (2). At the bottom of the right hand side panel, there is a search box. In this search box type the word “admin” (3). You should notice 2 results being returned, with a reference to a directory called “/admin”.
Change the header of your request so that it looks like the following (4):
GET /admin HTTP/1.1
Then, “Send” the request again (5). You don’t need to, but if you replace the original GET / request we captured with this new request and new cookie value, whenever you return to the shop, you will notice that you would be logged in as the admin (6).
Task 6:
Search for the word “admin” in the right hand panel again, and you will notice that there are now 4 matches (1). There are an extra two results with headers which allow us to delete the user account for “carlos” (2). Copy the header which deleted the user account for “carlos”. Replace your request header with this value so that it looks like the following (3):
GET /admin/delete?username=carlos HTTP/1.1
Send this request by hitting the “Send” button in the top left (4). You will notice a result of 302 found, indicating that the user account has been deleted (5).
To finish the lab, select all the text in the left hand panel and copy it to your clipboard (6). Return to your “Proxy” tab, where your request should still be waiting (7). Replace all the text on this screen with the copied text from the “Repeater” tab (8) and “Forward” the request (9). Once this is done, turn off intercept (10) and return to the lab in your browser.
Congratulations! The lab is solved! We have managed to login as the user “carlos” by exploiting an insecure deserialization vulnerability and delete the user account for “carlos”.
Lab 95 – OWASP A9 – Using components with Known Vulnerabilities
Back to lab listing.
Lab Objective:
Learn how to take advantage of integrated components in a web application with known vulnerabilities.
Lab Purpose:
Components—such as libraries, frameworks, and other software modules—run with the same privileges as the application. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications and APIs using components with known vulnerabilities may undermine application defences and enable various attacks and impacts.
Lab Tool:
Kali Linux.
Lab Topology:
You can use Kali Linux in a VM for this lab.
Lab Walkthrough:
Task 1:
In this lab, we will be using Mutillidae 2 to demonstrate how to take advantage of a web application using components with known vulnerabilities. How to install this environment in Kali VM is explained in detail in lab 87.
This is a very simple lab. In this lab, we will learn how to uncover whether an application has integrated components with known vulnerabilities.
Navigate to the “Secret PHP Server Configuration Page” which can be found at the following location in the Mutillidae 2 menu:
Once here, you will find that this page contains all the information about the different versions of software and components used withing the configuration of the Mutillidae 2 site. From here, we are able to hone in on specific versions of software, for example the Apache version or PHP version that the site is using, and search exploit databases for any known vulnerabilities.
For example, we can see that the site is using PHP version 7.4. If we run a quick google search for “PHP 7.4 vulnerabilities” we can see the first two links contain the information we are looking for. The link to the tenable site describes some known vulnerabilities for PHP versions under 7.4.11, which include the Mutillidae 2 site as it is using PHP 7.4. An attacker would conduct research such as this to discover any known vulnerabilities and then either search for a working exploit or develop their own.
We can do the same for the Apache version. We can see from this webpage that the server is running Apache 2.0. A quick Google search of “Apache 2.0 vulnerabilities” will lead us to the following site detailing some of the vulnerabilities:
https://www.cvedetails.com/vulnerability-list/vendor_id-45/product_id-66/version_id-6333/Apache-Http-Server-2.0.html
As you can see, there are numerous vulnerabilities with varying degrees of severity for the service Apache 2.0. We can use this information to exploit this vulnerable service.
In reality, there will rarely be a web page with all of this information; an attacker will have to manually gather this information by interacting with the server itself and reading its headers as well as the different responses it sends to determine which components are integrated and what their version is.
Lab 96 – OWASP Top 10 – A10 Unvalidated Redirects and Forwards
Back to lab listing.
Lab Objective:
Learn how to take advantage of unvalidated redirects and forwards vulnerability.
Lab Purpose:
Unvalidated redirects and forwards are possible when a web application accepts untrusted input that could cause the web application to redirect the request to a URL contained within untrusted input. By modifying untrusted URL input to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials.
Unvalidated redirect and forward attacks can also be used to maliciously craft a URL that would pass the application’s access control check and then forward the attacker to privileged functions that they would normally not be able to access.
Lab Tool:
Kali Linux.
Lab Topology:
You can use Kali Linux in a VM for this lab.
Lab Walkthrough:
Task 1:
In this lab, I will be using Mutillidae 2 to demonstrate how to take advantage of an unvalidated redirects and forwards vulnerability. How to install this environment in Kali VM is explained in detail in lab 87.
To begin, navigate to the Credits page, which can be found at the following location in the Mutillidae 2 menu:
Once here, you will find a very simple page which gives credit to the creators of Mutillidae 2. This page, however, is vulnerable to unvalidated redirects and forwards. It is normal for web application to frequently redirect and forward users to other websites and pages while using untrusted data to determine the destination pages. If, however, this is done without proper validation, attackers are able to redirect users to malware or phishing sites, or use forwards to access unauthorized pages.
Task 2:
To take advantage of this vulnerability, copy and paste following URL to address bar:
http://localhost/mutillidae/index.php?page=redirectandlog.php&forwardurl=http://www.owasp.org
This URL will send the user to the OWASP web page instead of the Mutillidae 2 site. In this URL, the forwardurl parameter specifies the redirection URL and the attacker can point the user to a malicious webpage.
Unvalidated redirects are often used to increase the success rate of phishing attacks and campaigns. This is due to the fact that the first part of the link looks legitimate as it will include a link to a legitimate site.
Take the URL we just entered for example. Looking at the first half of the link, it looks like the link is taking us to the Mutillidae 2 site, which is where we want to go. Often, users will only check the first half of the link to see if it is leading to a legitimate site. It is the second half of the link which turns out to be malicious as it redirects us to the OWASP site.
If this was a phishing campaign, an attacker could take advantage of the PayPal site for example (if it was vulnerable to unvalidated redirects) and send users a link. Users would think that the link was legitimate as it is coming from PayPal.com, but in reality, the attacker can redirect them to any site they like.
This lab concludes our look at the OWASP Top 10.
Lab 97 – Introduction to Python scripting
Back to lab listing.
Lab Objective:
Learn some fundamental concepts surrounding the Python language.
Lab Purpose:
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built-in data structures, combined with dynamic typing and dynamic binding, making it incredibly attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
Lab Tool:
Kali Linux.
Lab Topology:
You can use Kali Linux in a VM for this lab.
Lab Walkthrough:
Task 1:
In this lab, we will be looking at some fundamental concepts around scripting with Python. Python is a good coding language to learn as its syntax is quite simple and straightforward. Python is also very versatile and can import massive amounts of code from libraries, shortening the workload on developers.
To begin, we will make a very simple first script. Open a terminal in Kali and create a new document with nano. Type the following:
nano sample1.py
print(“Hello Everybody!”)
Save this file and exit.
Finally, execute this script by typing:
python3 sample1.py
If we want to run the script on its own, it is necessary to write the full path of the interpreter with “#!” suffix on the first line of each code and then make the script executable. If you do not know the full path of python interpreter in Kali, type this on the command line:
which python
Copy the path of binary, then open the same script with an editor and add the following to the very first line;
#!/usr/bin/python
Then, make this file executable by typing the following:
chmod +x sample1.py
./sample1.py
This first line we have added has no effect on the actual code, and tells the shell that this script will be run by python.
Task 2:
Ok, so we are now familiar with how to create and run python scripts. For the rest of the tasks, we can create scripts with different names each time.
We will now look at mathematical operators. These allow us to add, subtract, etc., in our scripts. Here is a list of the different operators available in Python and their syntax:
- Addition
- Subtraction
- Multiplication
- Division
- Modulus
- Exponent
- Floor Division
So, if we wanted to perform simple multiplication, we could type 5 * 5 and this would multiply 5 by 5 and give us the result of 25.
There are also comparison operators available to us, as in any coding language. These are the following:
- Greater than
- Less than
- Equal to
- Not Equal to
- Greater than or equal to
- Less than or equal
Task 3:
Now, we will look at variables. Variables are how Python stores information. There are a number of different variables in Python. They are listed here:
- String – Used to define text
- Integer – Whole numbers e.g 12
- Float – Decimal numbers e.g 3.2
- Boolean – Used to define true or false, it can only be one or the other
- List – Used to store a series of data types in a collection
Variables are created in a very simple way in Python. We can create a variable and print its contents very simply in Python. Create a new script and add Python3 interpreter path on the first line as usual. Then, type the following:
#!/usr/bin/python3
number = 5 print (“number = “, number)
|
Make executable this new script then run:
chmod +x sample2.py
./sample2.py
We will see the “number = 5” returned in the console. To receive input from the user when executing a script, we use the following:
input
So, if we want to ask a user to enter a number, compare the number to another number, and then print the answer to the screen. Change the same script to be like this:
Save script and execute it. Enter a number when asked and you will see that it is printed back to you in the console.
Task 4:
Now that we have some of the basic concepts established, we will look at if statements. This is one of the most useful tools when it comes to Python scripting. An if statement looks like the following:
if x == y
Do this
else:
Do something else
If x is equal to y, the first “Do this” command will run. If it is not equal, the second “Do something else” will be run.
Let’s use this knowledge to create a more comprehensive script. Create a new script file and type the following:
#!/usr/bin/python3
number = int( input(“Enter a number: “) )
if number < 5:
print(number,”is less than 5″)
elif number >= 5:
print(number,”is greater than or equal to 5”)
else:
print(“Error occurred!”)
|
Save your new script, make executable, then execute. Notice the different responses printed to the console depending on the number you enter.
Lab 98 – More Python Scripting
Back to lab listing.
Lab Objective:
Learn some more concepts surrounding the Python language.
Lab Purpose:
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built-in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
Lab Tool:
Kali Linux.
Lab Topology:
You can use Kali Linux in a VM for this lab.
Lab Walkthrough:
Task 1:
In this lab, we will be looking at some more concepts around scripting with Python. Python is a good coding language to learn as its syntax is very simple and straightforward. Python is also very versatile and can import massive amounts of code from libraries, shortening the workload on developers.
We will begin by talking about functions. Functions are like blocks of code which are executed together. Functions make it easier to use the output of the function in another statement instead of having to write all of the lines of code again. For example, say we have a complex formula to calculate a sum. If we want to include the output of this complex formula in another sum, we can simply call the function instead of re-writing all of the lines of code again.
In the Python language, functions are known as definitions. Let’s create one now. Create a new script and edit its contents so that the script looks like the following:
!/usr/bin/python3
number = int(input(“Enter a number:”))
def calculation (number):
if number < 5:
print(number,”is less than 5″)
elif number >= 5:
print(number,”is greater than or equal to 5″)
else:
print(“Error”)
return
calculation(number)
|
Let’s break down what this script is doing.
- 1) The first line is creating a variable which will store an integer when the user enters one after they are prompted.
- 2) This is our definition (or function) and is using the number variable throughout the definition.
- 3) This section contains simple calculations.
- 4) This line is returning the result of the calculations back to the definition in section 3 and is updating the number variable inside the definition.
- 5) This is printing the “number” variable after the definition has performed some function on it.
Save this script and execute it in the usual fashion. Enter some random numbers when prompted, and note the different responses you receive.
Task 2:
We will now touch on parameters. Notice how we passed the value of the number variable to the definition calculation? This number variable is called a parameter. Since we passed the parameter to the definition function when we created it, it will be expecting this value when it is called. Note that the number parameter is merely there for accessing the data within the function, and that parameters and variable names don’t have to match.
Have a look at the screenshot below:
In the above screenshot, we are passing number to the definition calculation even though the parameter is named integer. The parameter name is merely there for accessing the data within the definition.
#!/usr/bin/python3
def calculation (num):
if num < 5:
print(num,”is less than 5″)
elif num >= 5:
print(num,”is greater than or equal to 5″)
else:
print(“Error”)
return
number = int(input(“Enter a number:”))
calculation (number)
|
Create your script so that it looks like the above, save it, make it executable, then run.
Task 3:
Let’s look at introducing some of the logic operators we learned about in the previous lab. These are very useful to include in if statements as they can provide much more functionality to the statement. Typical login statements include and, or, not. These can be used in conjunction with if statements to provide the statement with an extra condition which needs to be met in order for the statement to be true. For example, create another script so that it looks like the following:
Each if statement here has now got an added logic statement. When the AND logic operator is used, both statements must be true for the statement to run. If the statement is not true, the code will move on to the next if statement (or elif statement or else statement).
For the second elif statement, the OR logic operator is used. This means that either statement in this line must be true for the code to execute. If neither are true, the code wil move onto the next if statement or else statement.
#!/usr/bin/python3
def calculation (num):
if num < 5 and number > 0:
print(num,”is between 0 and 5″)
elif num >= 5 and num < 10:
print(num,”is equal or greater than 5 less than 10″)
elif num > 10 or num < 0:
print(num,”That number is not between 1 and 10!”)
else:
print(“out of range”)
return
number = int(input(“Enter a number:”))
calculation (number)
|
Save this as a new script and execute it. Experiment with entering different numbers when prompted and note the differences.
Back to lab listing.
Lab Objective:
Learn some more advanced concepts surrounding the Python language.
Lab Purpose:
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built-in data structures, combined with dynamic typing and dynamic binding, make it attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
Lab Tool:
Kali Linux.
Lab Topology:
You can use Kali Linux in a VM for this lab.
Lab Walkthrough:
Task 1:
In this lab, we will be looking at some more advanced concepts around scripting with Python. Python is a good coding language to learn as its syntax is quite simple and straightforward. Python is also very versatile and can import massive amounts of code from libraries, shortening the workload on developers.
We will begin by looking at loops. Loops are incredibly useful in scripting languages. There are two types of loops in Python: for loops and while loops.
For loops look like the following:
names = [‘Mark’, ‘Darragh’, ‘Lee’]
for i in names: print (i)
|
This is a very basic for loop. This loop uses the contents of the names array in the loop. The for loop itself will iterate for every entry within the array and print the result. So, in our console, we should be returned with the three names in the array above.
Copy this code and paste it into your script. Save the script, execute it, and note the output.
This script will execute until every name in the array is output to the console and will end when there are no names left. This is how a for loop works.
We can add some more code to this script to make the for look more comprehensive. For loops provide us with the functionality to iterate with datasets. This can be done with the following piece of code:
for i in range(0,10):
print(i)
|
This code will iterate through the array, printing the first 10 items to the console. let’s use this in our script so that we can get a better understanding of how it works. Copy and paste this next snippet of code into our script in Kali:
#!/usr/bin/python3
randomNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in range(0,5):
print(i)
|
Save this script and execute it.
Notice we receive the output of 0, 1, 2, 3, 4 to the console. This is because of the way indexing works. We specified in the range(0,5) part above that we want to print the first 5 numbers from the array randomNumbers. The first 5 numbers are 0-4.
If we want to print numbers 1-5, we would have to specify range(1,6).
Note that the first parameter supplied to the range function is the start point of the for loop. The second function is the end point where the loop will finish.
We can also add a third parameter which will specify to the loop how much we want it to increment by. For example, if we type range(0, 15, 3) this will increment through our array by 3. Edit your script so it looks like the following:
#!/usr/bin/python3
randomNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in range(0,16,3):
print(i)
|
Now, save it and execute. Note that we are incrementing through our dataset of numbers in increments of 3. The second parameter is 16 as we want to display the number at index 16, which is the number 15 (remember the first number in an array has always index 0).
Finally, we will look at adding an else statement to our for loop. This is very simple and is similar to how else statements are added to if statements. Edit your code so that it looks like the following:
#!/usr/bin/python3
randomNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in range(0,16,3):
print(i)
else:
print(“Script has finished running :)”)
|
Then, save and execute it. Note how the else statement will execute when the script is finished running. This is a simple implementation of an else statement in a for loop.
Task 2:
Now, we will briefly touch on how Python can be used to interact with files. Create a new script so that it looks like the following:
#!/usr/bin/python3
fileInput = input (‘Please input the filename you would like to read:’)
file = open(fileInput, ‘r’)
print( file.read() )
|
Let’s break down what this script is doing:
- The first line after the “#!” is asking the user to input the name of the file they would like to read and is assigning the value of the users input to the variable fileInput.
- The next line is opening the file specified and reads all of its contents. It stored the contents of the specified file to the variable file.
The final line prints the contents stored in the variable file to the console.
Save this script and execute it. When asked, input the name of the file you would like to read and notice how its contents are printed to the console. This is a brief example of how Python can be used to interact with files.
Task 3:
In this lab, we will see how we can run system commands from within the python script. In Python, we use the “import” keyword to make the code in one module available in another. Create a new script so that it looks like the following;
#!/usr/bin/python3
import subprocess
subprocess.run([“ping”, “-c 3”, “scanme.nmap.org”])
subprocess.run([“nmap”, “scanme.nmap.org”, “-sT”])
|
Let’s break down what this script is doing:
- The first line after the “#!” is declares which module we need to import python runtime environment.
- The next line runs ping command with a “-c 3” parameter against a host.
- The final line starts a nmap scan to same host above. Also we are using another parameter which nmap needs.
Save this script and execute it. As you can see, our python script first executes a 3-count ping command to scanme.nmap.org (1). When first command finishes, it starts a portscan to the same target (2).
Using system commands in Python allows us to perform a smarter security scan within a certain logic pattern, taking into account the results of previous command outputs.
Back to lab listing.
Lab Objective:
Learn how to use some basic PowerShell commands and functions.
Lab Purpose:
PowerShell is a task automation and configuration management framework from Microsoft. It consists of a command-line shell and the associated scripting language.
Lab Tool:
Kali Linux and Windows
Lab Topology:
You can use a Windows machine for this lab.
Lab Walkthrough:
Task 1:
In this lab, we will be covering some basics surrounding PowerShell. PowerShell commands are called cmdlet’s, and are written in .NET. The output of these cmdlet’s are objects. This means that we can perform actions on the output object by running cmdlets. The typical cmdlet is constructed using a verb-noun format. For example, the Get-Help command is used to get help about a particular cmdlet. Some of the most common verbs used include the following:
- Get — To get something
- Start — To run something
- Out — To output something
- Stop — To stop something that is running
- Set — To define something
- New — To create something
You can launch PowerShell by searching for the following on your Windows machine:
PowerShell
Task 2:
Let’s look at some of the most basic PowerShell commands. Keep in mind throughout this lab that you can use Get-Help at any time to get some information about a command. You can also use the -examples flag which would return some examples of how this command is used. This is what that would look like:
Get-Help Get-Command -Examples
The “Get-Command” can be used to get all of the cmdlet’s installed. We can use this command to search for a particular cmdlet for a specific verb or noun by typing like the following:
Get-Command Start-*
Task 3:
Let’s now have a quick look at variables. Variables should start with $ in PowerShell. The following is an example of a variable in PowerShell:
$location = “Earth”
This command will create a variable called $location and assign it the output of Get-Location cmdlet. This variable will now contain the current location. To call the variable, we simple type the following:
$location
Task 4:
We will now look at writing our first PowerShell script. Before we are able to execute any scripts, we will first need to change to execution policy on our Windows machine. It is recommended to do this in a Windows virtual machine, or another machine which is not your main or host OS. Changing the execution policy will allow your machine to execute any PowerShell script. If you download a PowerShell file containing a virus, this could be disasterous for your PC. To change the execution policy, open PowerShell and type the following commands one after the other:
- Get-ExecutionPolicy
- Set-executionpolicy unrestricted
- Enter Y in the prompt
- Get-ExecutionPolicy
Before doing this, make sure you opened powershell with Administrator permissions. Your execution
policy should now be set to unrestricted, and we can proceed with the lab.
Now, create a new file in notepad and type the following:
$Info = “Hello!”
Write-Host $Info
|
Save this script to your Documents with the name script.ps1.
Now, open PowerShell if you have not already done so, by searching for PowerShell. Then, call the script with the following command:
& “C:\Users\IEUser\Documents\script.ps1”
You have to write the full path of the script that you’re trying to run.
Notice how Hello! is printed to the console. Ok, we have executed our first PowerShell script!