Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

BSc(H)-ANCS2021 6th Sem

Vulnerability Analysis / Penetration Testing (BNCSD601B)


Sec- A/B/C
2023-24

Study Material
Vulnerability Analysis / Penetration Testing (BNCSD601B)
_____________________________________________________________________________________________

Table of Contents Page Number

Module 1: 2

Module 2: 27

Module 3: 73

Module 4: 90

Module 5: 123

Module 6: 140

Module 7: 165

Module 8: 180

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 1
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Module 1: Introduction to Python


1.1 Python2 Vs Python3 2

1.2 Installing and using Python IDE 2

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 2
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

1.1 Python2 Vs Python3

1.2 Installing and using Python IDE

Installing Python:-
there are three ways to install the official Python distribution on Windows:

1. Microsoft Store package: The most straightforward installation method on Windows involves
installing from the Microsoft Store app. This is recommended for beginner Python users looking
for an easy-to-set-up interactive experience.
2. Full Installer: This approach involves downloading Python directly from the Python.org website.
This is recommended for intermediate and advanced developers who need more control during
the setup process.
3. Windows Subsystem for Linux (WSL): The WSL allows you to run a Linux environment directly
in Windows.

In this section, we’ll focus on only the first two options, which are the most popular installation methods
in a Windows environment.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 3
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

The two official Python installers for Windows aren’t identical. The Microsoft Store package has some
important limitations.

The Microsoft Store package is an easily installable Python interpreter that is intended mainly for
interactive use, for example, by students.
The key takeaway here is that the Microsoft Store package is “intended mainly for interactive use.” That
is, the Microsoft Store package is designed to be used by students and people learning to use Python for
the first time.
In addition to targeting beginning Pythonistas, the Microsoft Store package has limitations that make it ill-
suited for a professional development environment. In particular, it does not have full write access to
shared locations such as TEMP or the registry.

Windows Installer Recommendations

If you’re new to Python and focused primarily on learning the language rather than building professional
software, then you should install from the Microsoft Store package. This offers the shortest and easiest
path to getting started with minimal hassle.

On the other hand, if you’re an experienced developer looking to develop professional software in a
Windows environment, then the official Python.org installer is the right choice. Your installation won’t be
limited by Microsoft Store policies.

How to Install From the Microsoft Store


If you’re new to Python and looking to get started quickly, then the Microsoft Store package is the best
way to get up and running without any fuss. You can install from the Microsoft Store in two steps.

Step 1: Open the Python App Page in the Microsoft Store


Open the Microsoft Store app and search for Python.

You’ll likely see multiple versions that you can choose to install:

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 4
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Select Python 3.8, or the highest version number you see available in the app, to open the installation
page.

Warning: Make sure that the Python application you’ve selected is created by the Python Software
Foundation.

The official Microsoft Store package will always be free, so if the application costs money, then it’s
the wrong application.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 5
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Alternatively, you can open PowerShell and type the following command:

C:\> python
If you don’t already have a version of Python on your system, then when you press Enter, the Microsoft
Store will automatically launch and take you to the latest version of Python in the store.

Step 2: Install the Python App


After you’ve selected the version to be installed, follow these steps to complete the installation:

1. Click Get.
2. Wait for the application to download. When it’s finished downloading, the Get button will be
replaced with a button that says Install on my devices.
3. Click Install on my devices and select the devices on which you’d like to complete the installation.
4. Click Install Now and then OK to start the installation.
5. If the installation was successful, then you’ll see the message “This product is installed” at the top
of the Microsoft Store page.

Congratulations! You now have access to Python, including pip and IDLE!

How to Install From the Full Installer


For professional developers who need a full-featured Python development environment, installing from
the full installer is the right choice. It offers more customization and control over the installation than
installing from the Microsoft Store.

You can install from the full installer in two steps.

Step 1: Download the Full Installer


Follow these steps to download the full installer:

1. Open a browser window and navigate to the Python.org Downloads page for Windows.
2. Under the “Python Releases for Windows” heading, click the link for the Latest Python 3 Release
- Python 3.x.x. As of this writing, the latest version was Python 3.8.4.
3. Scroll to the bottom and select either Windows x86-64 executable installer for 64-bit or Windows
x86 executable installer for 32-bit.

If you aren’t sure whether to select the 32-bit or the 64-bit installer, then you can expand the box below
to help you decide.

Step 2: Run the Installer

Once you’ve chosen and downloaded an installer, run it by double-clicking on the downloaded file. A
dialog box like the one below will appear:

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 6
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

There are four things to notice about this dialog box:

1. The default install path is in the AppData/ directory of the current Windows user.
2. The Customize installation button can be used to customize the installation location and which
additional features get installed, including pip and IDLE.
3. The Install launcher for all users (recommended) checkbox is checked default. This means every
user on the machine will have access to the py.exe launcher. You can uncheck this box to restrict
Python to the current Windows user.
4. The Add Python 3.8 to PATH checkbox is unchecked by default. There are several reasons that
you might not want Python on PATH, so make sure you understand the implications before you
check this box.

The full installer gives you total control over the installation process.

Warning: If you don’t know what PATH is, then it’s highly recommended that you do not install with the
full installer. Use the Microsoft Store package instead.
Customize the installation to meet your needs using the options available on the dialog box. Then
click Install Now. That’s all there is to it!

Congratulations—you now have the latest version of Python 3 on your Windows machine!

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 7
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Installing Python in Kali Linux:-


1. Download the python 3.11.1 from python.org
link.
2. Choose the os as Linux/UNIX.
3. Choose the option “Download XZ compressed
source
4. Click on save and then OK.
5. Extract the file on a specific location.
6. Go to terminal and change the path accordingly
7. Then type ‘cd python-3.11.1’ and then type ‘ls’
8. Then type ‘./configure’ as root user
9. Then run the command ‘./configure –enable-
optimizations’
10. Then type ‘make’
11. Then run the command ‘make install’

Vulnerability:- It is a weakness in an IT system that can be


exploited by an attacker to deliver a successful attack. They
can occur through flaws, features or user error, and
attackers will look to exploit any of them, often combining
one or more, to achieve their end goal.
Security Vulnerability Types:-
Network Vulnerabilities. These are issues with a network’s
hardware or software that expose it to possible intrusion
by an outside party. Examples include insecure Wi-Fi
access points and poorly-configured firewalls.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 8
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Operating System Vulnerabilities. These are vulnerabilities


within a particular operating system that hackers may
exploit to gain access to an asset the OS is installed on—or
to cause damage. Examples include default superuser
accounts that may exist in some OS installs and hidden
backdoor programs.
Human Vulnerabilities. The weakest link in many
cybersecurity architectures is the human element. User
errors can easily expose sensitive data, create exploitable
access points for attackers, or disrupt systems.
Process Vulnerabilities. Some vulnerabilities can be
created by specific process controls. One example would
be the use of weak passwords (which may also fall under
human vulnerabilities).
What is Vulnerability analysis?
• A vulnerability assessment is a systematic review of
security weaknesses in an information system. It
evaluates if the system is susceptible to any known
vulnerabilities, assigns severity levels to those
vulnerabilities, and recommends remediation or
mitigation, if and whenever needed.
• A vulnerability assessment provides an organization
with details on any security weaknesses in its
environment. It also provides direction on how to
assess the risks associated with those weaknesses.
What is Penetration testing?
• A penetration test (pen test) is an authorized
simulated attack performed on a computer system
to evaluate its security. Penetration testers use the
same tools, techniques, and processes as attackers to
Hemanta Kumar Sahu
Assistant Professor, CST Department
Brainware University, Kolkata 9
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

find and demonstrate the business impacts of


weaknesses in a system.
• Penetration testing (or pen testing) is a security
exercise where a cyber-security expert attempts to
find and exploit vulnerabilities in a computer system.
The purpose of this simulated attack is to identify
any weak spots in a system's defenses which
attackers could take advantage of.

Advantages of pen testing-


1. Reveal vulnerabilities. ...
2. Show real risks. ...
3. Test your cyber-defence capability. ...
4. Ensure business continuity. ...
5. Have a third party expert opinion. ...
6. Follow regulations and certifications. ...
7. Maintain trust.
More about pen testing-
• The methodology of penetration testing is split into
three types of testing: black-box assessment(no
information is provided to the tester at all), white-
box assessment(grants testers access to the system
in question), and gray-box assessment(only limited
information is shared with the tester).
• The different types of penetration tests
include network services, applications, client side,
wireless, social engineering, and physical.
• There are five penetration testing phases:
reconnaissance, scanning, vulnerability assessment,
exploitation, and reporting.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 10
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

• The top 5 penetration testing methodologies


are OSSTM(Open Source Security Testing
Methodology Manual), OWASP(Open Web
Application Security Project ), NIST(National
Institute of Standards and Technology),
PTES(Penetration Testing Execution Standard ), and
ISSAF(Information Systems Security Assessment
Framework).
• Which language is best for penetration testing?
Python is a must-know programming language for
anyone seeking a career in penetration testing.

Skills you might find on a pen tester job description


include:
 Network and application security.
 Programming languages, especially for scripting
(Python, BASH, Java, Ruby, Perl)
 Threat modelling.
 Linux, Windows, and MacOS environments.
 Security assessment tools.
 Pentest management platforms.

Is penetration testing manual or automatic?


Penetration testing can be performed both manually, using
humans, and automatically using tools. Each one has
different pros and cons, and it's not always obvious which
one is suitable.
Risks in pen testing:-
Tests that are not done properly can crash servers, expose
sensitive data, corrupt crucial production data, or cause a
Hemanta Kumar Sahu
Assistant Professor, CST Department
Brainware University, Kolkata 11
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

host of other adverse effects associated with mimicking a


criminal hack.

Top 10 Penetration Testing Companies and Services:-


Astra Security
Intruder
Detectify
Invicti
Rapid7
Acunetix
Cobalt.io
Sciencesoft
SecureWorks
Cyberhunter
What is the difference between penetration testing and
security testing?
In security testing (barring aside Pen Testing), testers do
not exploit the security vulnerabilities. Due to this, they do
NOT have any detailed guide on how to fix the issues. On
other hand, testers performing penetration testing always
exploit the security vulnerabilities and provide a detailed
fixation guide

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 12
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

About Python:-
Python is a high-level, general-purpose programming
language. Its design philosophy emphasizes code
readability with the use of significant indentation. Python is
dynamically typed and garbage-collected. It supports
multiple programming paradigms, including structured,
object-oriented and functional programming.

Designed by: Guido van Rossum


First appeared: 20 February 1991; 31 years ago
OS: Windows, macOS, Linux/UNIX, Android and more

Filename extensions: .py,.pyi,.pyc,.pyd,.pyw,.pyz (since 3.5),.pyo (prior to 3.5)


Parent company: Python Software Foundation

What is Python used for :-


Python is a computer programming language often used to build
websites and software, automate tasks, and conduct data analysis.
Python is a general-purpose language, meaning it can be used to
create a variety of different programs and isn't specialized for any
specific problems
Python is extensively applied in data science, data analysis, machine
learning, data engineering, web development, software development,
and other fields.
Learning Python Programming Language
 Properties. Python is implicitly and dynamically typed, so you do not have to declare variables.
...
 Data types. Let's move ahead to data types. ...
 Strings. Let's move on to strings. ...
 Flow control statements. ...
 Functions. ...
 Classes. ...

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 13
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

 Exceptions. ...
 File I/O.

Which software is used for Python?


Python is a programming language with many different IDEs available. Some popular IDEs
include PyCharm, Atom, and Visual Studio Code. Each IDE has its unique features and
benefits.

Features of Python:-
 Easy to Code. Python is a very high-level programming language, yet it is effortless to learn. ...
 Easy to Read. ...
 Free and Open-Source. ...
 Robust Standard Library. ...
 Interpreted. ...
 Portable. ...
 Object-Oriented and Procedure-Oriented. ...
 Extensible.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 14
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Possible MCQs:-
Correct Answer
Answer Answer Answer Answer Number
Question
Number 1 Number 2 Number 3 Number 4 (Numeric eg:
1,2)
Who developed Python
Wick van Rasmus Guido van
Programming Niene Stom 3
Rossum Lerdorf Rossum
Language?
Which type of object-
structured functional all of the
Programming does oriented 4
programming programming mentioned
Python support? programming
Discover that "Is Python
case sensitive when machine none of the
No yes 2
dealing with dependent mentioned
identifiers?".
Which of the following is
the correct extension of .python .pl .py .p 3
the Python file?
Python code is Python code is
Python code is
Is Python code both compiled neither Python code is
only 1
compiled or interpreted? and compiled nor only compiled
interpreted
interpreted interpreted

What will be the value of


the following Python 7 2 4 1 1
expression? 4 + 3 % 5.

Which of the following is


used to define a block of All of the
Key Indentation Brackets 2
code in Python mentioned
language?
Which keyword is used
for function in Python Define def Fun Function 2
language?
Which of the following
character is used to give
// /* ! # 4
single-line comments in
Python?
What will be the output
of the following Python
1 2 4 8 4
code snippet if x=1?
x<<2.
Preferred Preferred
What does pip stand for Pip Installs Pip Installs
Installer Installer 3
python? Python Packages
Program Program

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 15
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

underscore all private


and ampersand members
Which of the following is
are the only unlimited must have none of the
true for variable names 2
two special length leading and mentioned
in Python?
characters trailing
allowed underscores

Which of the following is


the truncation division | // / % 2
operator in Python?

Which of the following


functions is a built-in factorial() print() seed() sqrt() 2
function in python?

Which of the following is Every object Id returns the


All of the None of the
the use of id() function doesn’t have a identity of the 2
mentioned mentioned
in python? unique id object

Which of the following is


not a core data type in Tuples Lists Dictionary Class 4
Python programming?

What arithmetic
operators cannot be All of the
* + – 3
used with strings in mentioned
Python?

Short Questions:-
1. What are the different popular python IDEs?
2. What are the different methods we can use to install Python?

Long Questions:-
1. How to install Python in a Windows machine?
2. How to install Python in a Linux machine?
3. How to install any popular IDE like VS Code in Windows Machine?
4. Compare between Python2 and Python3.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 16
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Module 2: Writing a MAC Changer


2.1 MAC address and how to change it 18

2.2 Writing a MAC Changer 22

2.3 Variables and Strings in Python 23

2.4 Python Functions 27

2.5 Decision making in Python 27

2.6 Introduction to Algorithm 28

2.7 Introduction to REGEX 31

2.8 Extracting substring using REGEX 31

2.9 Implementing validation algorithm 32

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 17
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

2.1 MAC address and how to change it


MAC Addresses are unique 48-bits hardware number of a computer, which is
embedded into a network card (known as a Network Interface Card) during the time of
manufacturing. MAC Address is also known as the Physical Address of a network
device. In IEEE 802 standard, Data Link Layer is divided into two sublayers –
1. Logical Link Control(LLC) Sublayer
2. Media Access Control(MAC) Sublayer

MAC address is used by the Media Access Control (MAC) sublayer of the Data-Link
Layer. MAC Address is worldwide unique since millions of network devices exist and we
need to uniquely identify each.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 18
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Format of MAC Address –

MAC Address is a 12-digit hexadecimal number (6-Byte binary number), which is mostly
represented by Colon-Hexadecimal notation. The First 6-digits (say 00:40:96) of MAC
Address identifies the manufacturer, called OUI (Organizational Unique Identifier).
IEEE Registration Authority Committee assigns these MAC prefixes to its registered
vendors.
Here are some OUI of well-known manufacturers :

CC:46:D6 - Cisco
3C:5A:B4 - Google, Inc.
3C:D9:2B - Hewlett Packard
00:9A:CD - HUAWEI TECHNOLOGIES CO.,LTD
The rightmost six digits represent Network Interface Controller, which is assigned by
the manufacturer.

As discussed above, the MAC address is represented by Colon-Hexadecimal notation.


But this is just a conversion, not mandatory. MAC address can be represented using
any of the following formats:

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 19
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Types of MAC Address:

1. Unicast: A Unicast addressed frame is only sent out to the interface leading to a
specific NIC. If the LSB (least significant bit) of the first octet of an address is set to
zero, the frame is meant to reach only one receiving NIC. MAC Address of source
machine is always Unicast.
2. Multicast: The multicast address allows the source to send a frame to a group of
devices. In Layer-2 (Ethernet) Multicast address, LSB (least significant bit) of the
first octet of an address is set to one. IEEE has allocated the address block 01-80-
C2-xx-xx-xx (01-80-C2-00-00-00 to 01-80-C2-FF-FF-FF) for group addresses for
use by standard protocols.

3. Broadcast: Similar to Network Layer, Broadcast is also possible on the underlying


layer( Data Link Layer). Ethernet frames with ones in all bits of the destination
address (FF-FF-FF-FF-FF-FF) are referred to as the broadcast addresses. Frames
that are destined with MAC address FF-FF-FF-FF-FF-FF will reach every
computer belonging to that LAN segment.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 20
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Characteristics of MAC address:

Media Access Control address (MAC address) is a unique identifier assigned to most
network adapters or network interface cards (NICs) by the manufacturer for identification
and used in the Media Access Control protocol sub-layer.
An Ethernet MAC address is a 48-bit binary value expressed as 12 hexadecimal digits
(4 bits per hexadecimal digit). MAC addresses are in a flat structure and thus they are
not routable on the Internet. Serial interfaces do not use MAC addresses. It does NOT
contain a network and host portion with the address. It is used to deliver the frame to the
destination device.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 21
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

How to change MAC address:-


In Windows->
RC on Start button  Device ManagerNetwork AdaptersDouble click on the NIC
card listed there Go to ‘Advanced’ Tab Click on ‘Locally Administered Address’
Give a 12 digit no(alphanumeric) in the ‘value’ field(Radio button).--
>1A2B3C4D5E6FPress ‘OK’

In Kali Linux ->


Open command interface
# ifconfig eth0 down
# ifconfig eth0 hw ether 00:1a:2b:3c:4b:5e:6f
# ifconfig eth0 up
#ifconfig

2.2 Writing a MAC Changer

Mac_changer.py
#! /usr/bin/env python
import subprocess
interface = input(”Enter interface name: ”)
newmac = input(”Enter new MAC address: ”)

subprocess.call(“ifconfig”, interface, “down”)


subprocess.call(“ifconfig”, interface, “hw”, “ether”, newmac)
subprocess.call(“ifconfig”, interface, “up”)

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 22
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

2.3 Variables and Strings in Python:-

There are 2 types of data types in python-


1. Mutable
 List
 Sets
 Dictionary
2. Immutable
 Numbers
 String
 Tuples

Python Lists are just like dynamically sized arrays, declared in other languages (vector
in C++ and ArrayList in Java). In simple language, a list is a collection of things, enclosed
in [ ] and separated by commas.
The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 23
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']


print("\nList with the use of Mixed Values: ")
print(List)

A Set is an unordered collection data type that is iterable, mutable, and has no duplicate
elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set. This is based on
a data structure known as a hash table. Since sets are unordered, we cannot access
items using indexes as we do in lists.

var = {"Geeks", "for", "Geeks"}


type(var)

Dictionary in Python is a collection of keys values, used to store data values like a
map, which, unlike other data types which hold only a single value as an element.
Example of Dictionary in Python
Dictionary holds key:value pair. Key-Value is provided in the dictionary to make it
more optimized.
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}


print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

Number data types store numeric values. They are immutable data types, which means
that changing the value of a number data type results in a newly allocated object.
Different types of Number data types are :
 int
 float
 complex

Let’s see each one of them:


Int type
int (Integers) are the whole number, including negative numbers but not fractions. In
Python, there is no limit to how long an integer value can be.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 24
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

num = -8
# print the data type
print(type(num))

Float type
This is a real number with floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer may be
appended to specify scientific notation. . Some examples of numbers that are
represented as floats are 0.5 and -7.823457.
They can be created directly by entering a number with a decimal point, or by using
operations such as division on integers. Extra zeros present at the number’s end are
ignored automatically.

num = 3/4

print(type(num))

Complex type
A complex number is a number that consists of the real and imaginary parts. For
example, 2 + 3j is a complex number where 2 is the real component, and 3 multiplied by
j is an imaginary part.
num = 6 + 9j
print(type(num))

A string is a data structure in Python that represents a sequence of characters. It is an


immutable data type, meaning that once you have created a string, you cannot change
it. Strings are used widely in many different applications, such as storing and
manipulating text data, representing names, addresses, and other types of data that
can be represented as text.
Example:
"Geeksforgeeks" or 'Geeksforgeeks'
Python does not have a character data type, a single character is simply a string with a
length of 1. Square brackets can be used to access elements of the string.
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 25
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

String1 = "I'm a Geek"


print("\nString with the use of Double Quotes: ")
print(String1)

String1 = '''I'm a Geek and I live in a world of "Geeks"'''


print("\nString with the use of Triple Quotes: ")
print(String1)

String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

Tuple is a collection of objects separated by commas. In some ways, a tuple is similar


to a list in terms of indexing, nested objects, and repetition but a tuple is immutable,
unlike lists which are mutable.
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)

Variables in Python:-
Python Variable is containers which store values. Python is not “statically typed”. We
do not need to declare variables before using them or declare their type. A variable is
created the moment we first assign a value to it. A Python variable is a name given to a
memory location. It is the basic unit of storage in a program.
Rules for creating variables in Python
 A variable name must start with a letter or the underscore character.
 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ ).
 Variable names are case-sensitive (name, Name and NAME are three different
variables).
 The reserved words(keywords) cannot be used naming the variable.

# An integer assignment
age = 45

# A floating point
salary = 1456.8

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 26
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

# A string
name = "John"

print(age)
print(salary)
print(name)

2.4 Python Functions:-

This is a block of statements that return the specific task.


The idea is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different inputs,
we can do the function calls to reuse code contained in it over and over again.
Syntax: Python Functions

# A simple Python function

def fun():
print("Welcome to GFG")

# Driver code to call a function


fun ( )

2.5 Decision making in Python:-

if statement is the most simple decision-making statement. It is used to decide whether


a certain statement or block of statements will be executed or not i.e if a certain
condition is true then a block of statement is executed otherwise not.
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 27
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

# Python program to illustrate if-elif-else ladder


#!/usr/bin/python

i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

2.6 Introduction to Algorithm:-

The word Algorithm means ” A set of finite rules or instructions to be followed in


calculations or other problem-solving operations ” Or ” A procedure for solving a
mathematical problem in a finite number of steps that frequently involves recursive
operations”.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 28
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

The Algorithm designed are language-independent, i.e. they are just plain instructions
that can be implemented in any language, and yet the output will be the same, as
expected.

Types of Algorithms:
There are several types of algorithms available. Some important algorithms are:
1. Brute Force Algorithm: It is the simplest approach for a problem. A brute force
algorithm is the first approach that comes to finding when we see a problem.
2. Recursive Algorithm: A recursive algorithm is based on recursion. In this case, a
problem is broken into several sub-parts and called the same function again and again.
3. Backtracking Algorithm: The backtracking algorithm basically builds the solution
by searching among all possible solutions. Using this algorithm, we keep on building
the solution following criteria. Whenever a solution fails we trace back to the failure
point and build on the next solution and continue this process till we find the solution or
all possible solutions are looked after.
4. Searching Algorithm: Searching algorithms are the ones that are used for
searching elements or groups of elements from a particular data structure. They can be
of different types based on their approach or the data structure in which the element
should be found.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 29
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

5. Sorting Algorithm: Sorting is arranging a group of data in a particular manner


according to the requirement. The algorithms which help in performing this function are
called sorting algorithms. Generally sorting algorithms are used to sort groups of data
in an increasing or decreasing manner.
6. Hashing Algorithm: Hashing algorithms work similarly to the searching algorithm.
But they contain an index with a key ID. In hashing, a key is assigned to specific data.
7. Divide and Conquer Algorithm: This algorithm breaks a problem into sub-
problems, solves a single sub-problem and merges the solutions together to get the
final solution. It consists of the following three steps:
 Divide
 Solve
 Combine
8. Greedy Algorithm: In this type of algorithm the solution is built part by part. The
solution of the next part is built based on the immediate benefit of the next part. The
one solution giving the most benefit will be chosen as the solution for the next part.
9. Dynamic Programming Algorithm: This algorithm uses the concept of using the
already found solution to avoid repetitive calculation of the same part of the problem. It
divides the problem into smaller overlapping subproblems and solves them.
10. Randomized Algorithm: In the randomized algorithm we use a random number so
it gives immediate benefit. The random number helps in deciding the expected
outcome.

Example: Consider the below algorithm for Linear Search


Step 1: START
Step 2: Get n elements of the array in arr and the number to be searched in x
Step 3: Start from the leftmost element of arr[] and one by one compare x with each
element of arr[]
Step 4: If x matches with an element, Print True.
Step 5: If x doesn’t match with any of the elements, Print False.
Step 6: END

Here, There are 2 variables arr[], and x, where the arr[] is the variable part of n
elements and x is the fixed part. Hence S(P) = 1+n. So, the space complexity depends
on n(number of elements). Now, space depends on data types of given variables and
constant types and it will be multiplied accordingly.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 30
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

2.7 Introduction to REGEX:-


A regular expression is a sequence of characters that specifies a search pattern in text. Usually such
patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings,
or for input validation.
 In Python re is a module.
 It is a collection of pre-defined functions.
 It is used to process the input text.
Some functions are discussed here-
Match( ):- To test the input string starts with specified pattern or not.
Search( ):- To test the specified pattern is present or not in the given string.
Findall( ):- To find duplicates for specified pattern.
Split( ):- How to split the input string
Sub( ):- to replace the sub-string
Compile( ):- Used to create pattern object and can be reused.

2.8 Extracting substring using REGEX:-


#find all mac addresses
import re

import subprocess

def find_mac_address():

output = subprocess.check_output(["ipconfig", "/all"])

mac_regex = re.compile(r"(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})")

mac_address = re.findall(mac_regex, output.decode())

if mac_address:

return list(set(mac_address))

else:

return "MAC address not found."

mac_address_list = find_mac_address()

print(mac_address_list)

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 31
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

#find the first MAC address

import re
import subprocess

def find_mac_address():
output = subprocess.check_output(["ipconfig", "/all"])
mac_regex = re.compile(r"(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})")
mac_address = re.search(mac_regex, output.decode())
if mac_address:
return mac_address.group()
else:
return "MAC address not found."
mac_address_list = find_mac_address()
print(mac_address_list)

2.9 Implementing validation algorithm

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 32
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Possible MCQs:-

Media Area Memory Access Memory Area Media Access


MAC stands for. 4
Control Control Control Control
The original IEEE
802 MAC address Ethernet
MAC address IP address Http 3
comes address
from________.
Which of the
following functions
re.sub() re.pos() re.purge() re.subn() 3
clears the regular
expression cache?
What will be the
output of the
following Python
8 16 64 256 4
code.
import re
re.ASCII
Which of the
following functions
re.A re.U re.I re.X 3
results in case
insensitive matching.
Which of the
following is incorrect?
Identify how as pseudo codes as syntax as programs as flowcharts 2
Algorithms can be
represented.
Identify that when an
algorithm is written in
the form of a
Flowchart Program Pseudo code Syntax 2
programming
language, it becomes
a _________.
Identify that the word
____________comes
from the name of a
Persian
Flowchart Flow Algorithm Syntax 3
mathematician Abu
Ja’far Mohammed
ibn-i Musa al
Khowarizmi.
What is the
timeframe from when
the loophole in
Time-frame of Window of Time-lap of Entry-door of
security was 2
vulnerability vulnerability vulnerability vulnerability
introduced till the
time when the bug
was fixed.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 33
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

All keywords in
None of the
Python are in Capitalized lower case UPPER CASE 4
mentioned
_________.
Which of the
following functions
can help us to find
sys.version(1) sys.version(0) sys.version() sys.version 4
the version of python
that we are currently
working on.
conversion of
The process of conversion of a
conversion of a byte stream conversion of a
pickling in Python Python object
a datatable into into Python list into a 1
includes hierarchy into
a list object datatable
____________. byte stream
hierarchy
What is the correct
output of the
following Python
56.236 56.23 56.00 56.24 4
expression if
x=56.236.
print("%.2f"%x).
What is the correct
output of the
following Python Error 6 4 3 3
function.
len(["hello",2, 4, 6])
Find the module in
the python standard
library that parses getarg getopt main Os 2
options received from
the command line.
To add a new
element to a list we
list1.addEnd(5) list1.addLast(5) list1.append(5) list1.add(5) 3
use which Python
command.
What is the maximum
possible length of an 79 characters 65 characters 32 characters None 4
identifier in Python.
Which of the
following is a Python {1, 2, 3} {} [1, 2, 3] (1, 2, 3) 4
tuple?
Find the correct
output of 9.0 6.0 3.0 None 1
print(math.pow(3, 2)).

On wireless networks
________ filtering is OUI IP NIC MAC 4
the security measure.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 34
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Select the correct


answer.

The IEEE 802 MAC


Ethernet
address comes MAC address IP address None 3
address
from________.
Cyber Security
Cyber Security Cyber Security
provides
What is Cyber provides protects a All of the
security 4
Security. security against system from mentioned
against cyber-
malware cyber attacks
terrorists
Select who is the
August
father of computer Bob Thomas Robert Charles 1
Kerckhoffs
security.
Which of the
following is defined
as an attempt to
steal, spy, damage or Computer
Cyber attack Cryptography Digital hacking 1
destroy computer security
systems, networks,
or their associated
information?
Which of the
Network Application
following is a type of Cloud Security All of the above 4
Security Security
cyber security.
Discover what are Defense
Threat All of the
the features of cyber Compliance against internal 4
Prevention above
security. threats
___________ is a
System with a
weakness that can System with System without System with
strong 3
be exploited by Virus firewall vulnerabilities
password
attackers.

What is the sum of all


the possible points in
software or system
where unauthorized Attack vector Attack surface Attack point Attack arena 2
users can enter as
well as extract data
from the system.

Select the cyclic


practice for
Vulnerability Vulnerability
identifying & Bug protection Bug bounty 4
measurement management
classifying and then
solving the

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 35
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

vulnerabilities in a
system.

Find the type of


exploit requires
accessing to any
Remote System Network
vulnerable system for Local exploits 1
exploits exploits exploits
enhancing privilege
for an attacker to run
the exploit.
Find the technique
used by penetration
testers to
compromise any Exploiting Cracking Hacking Pivoting 4
system within a
network for targeting
other systems.
Find the software bug
that attackers can
Bugged
take advantage to System error Security bug System virus 3
system
gain unauthorized
access in a system.

Short Questions:-

1. How to identify the MAC address of your device?


2. What is a variable with example in python?
3. Define what an algorithm is.
4. Explain the implementation of regex with example.
5. Explain with a code how to implement if…else in python.
6. Describe what network vulnerability is.
7. What is vulnerability?
8. Define what penetration testing is.
9. What are the phases of pen-testing?
10. Describe what skills you must have to be a pen-tester.
11. List top 5 pen-testing companies.
12. Define about python programming.

13. Explain with the help of a code how to implement" if…elif…else".


14. Define the rules how to create variables in python.
15. Describe what is 're' module with a small example.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 36
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Long Questions:-
1. What is a MAC address and what are its types?

2. What are the types of data types in python with examples.

3. Write a python function how to change mac address.

4. How to change MAC address usning Linux command?

5. Devise a function in python how to print any pyramid.

6. Illustrate a python function to implement "re" module.

7. Illustrate python function how to find MAC address.

8. How to write an algorithm? Give an example.

9. Devise a code how to implement decision making in python.

10. What are dictionaries with examples?

11. Devise a code using nested if .

12. What are the security vulnerability types? Analyse.

13. Analyse the advantages of pen-testing.

14. Analyse the different types of pen-testing.

15. Compare between pen-testing and security testing.

16. Analyze the format of MAC Addresses.

17. Analyze the top 5 penetration testing methodologies.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 37
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Module 3: Programming a Network Scanner


3.1 Introduction to ARP 39

3.2 Designing an algorithm to discover protocols 40

3.3 Combining frames to broadcast 40

3.4 Lists and Dictionaries in python 41

3.5 Installing nested data structure 43

3.6 Testing the network scanner with Python 44

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 38
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

3.1 Introduction to ARP

Address Resolution Protocol (ARP) is a procedure for mapping a dynamic IP address to a


permanent physical machine address in a local area network (LAN). The physical machine
address is also known as a media access control (MAC) address.

The job of ARP is essentially to translate 32-bit addresses to 48-bit addresses and vice versa. This is
necessary because IP addresses in IP version 4 (IPv4) are 32 bits, but MAC addresses are 48 bits.

ARP works between Layers 2 and 3 of the Open Systems Interconnection model (OSI model). The
MAC address exists on Layer 2 of the OSI model, the data link layer. The IP address exists on Layer
3, the network layer.

ARP can also be used for IP over other LAN technologies, such as token ring, fiber distributed data
interface (FDDI) and IP over ATM.

How ARP works

When a new computer joins a LAN, it is assigned a unique IP address to use for identification and
communication. When an incoming packet destined for a host machine on a particular LAN arrives at
a gateway, the gateway asks the ARP program to find a MAC address that matches the IP address.
A table called the ARP cache maintains a record of each IP address and its corresponding MAC
address.

All operating systems in an IPv4 Ethernet network keep an ARP cache. Every time a host requests a
MAC address in order to send a packet to another host in the LAN, it checks its ARP cache to see if
the IP to MAC address translation already exists. If it does, then a new ARP request is unnecessary.
If the translation does not already exist, then the request for network addresses is sent and ARP is
performed.

ARP broadcasts a request packet to all the machines on the LAN and asks if any of the machines are
using that particular IP address. When a machine recognizes the IP address as its own, it sends a
reply so ARP can update the cache for future reference and proceed with the communication.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 39
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Host machines that don't know their own IP address can use the Reverse ARP (RARP) protocol for
discovery.

ARP cache size is limited and is periodically cleansed of all entries to free up space. Addresses tend
to stay in the cache for only a few minutes. Frequent updates enable other devices in the network to
see when a physical host changes their requested IP addresses. In the cleaning process, unused
entries are deleted along with any unsuccessful attempts to communicate with computers that are not
currently powered on.

3.2 Designing an algorithm to discover protocols:-

3.3 Combining frames to broadcast

Network scanner algorithm:-

Goal  Discover clients in network

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 40
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Steps-
1. Create ARP request directed to broadcast MAC asking for IP
Two main parts-
 Use ARP to ask who has the target IP
 Set destination MAC to broadcast MAC

import scapy.all as scapy


def scan(ip):
arp_request = scapy.ARP(pdst=ip)
print (arp_request. summary ())
scan (“172.16.16.5/21”) #gateway address

import scapy.all as scapy


def scan(ip):
arp_request = scapy.ARP(pdst=ip)
arp_request. show ()
#scapy.ls(scapy.Ether())
broadcast = scapy.Ether(dst = “ff:ff:ff:ff:ff:ff”)
broadcast.show()
arp_request_broadcast = broadcast/arp_request
arp_request_broadcast. Show ()

scan (“172.16.16.5/21”) #Gateway address

3.4 Lists and Dictionaries in python:-

Lists are used to store multiple items in a single variable.Lists are one of 4 built -in data types in
Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different
qualities and usage.

Lists are created using square brackets:

thislist = ["apple", "banana", "cherry"]


print(thislist)

List items are ordered, changeable, and allow duplicate values.List items are indexed, the first
item has index [0], the second item has index [1] etc.

When we say that lists are ordered, it means that the items have a defined order, and that order will
not change. If you add new items to a list, the new items will be placed at the end of the list.

The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created. Since lists are indexed, lists can have items with the same value:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 41
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

To determine how many items a list has, use the len() function:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List items can be of any data type:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

list1 = ["abc", 34, True, 40, "male"]

From Python's perspective, lists are defined as objects with the data type 'list':

mylist = ["apple", "banana", "cherry"]


print(type(mylist))

Dictionaries:-

These are used to store data values in key:value pairs. A dictionary is a collection which is ordered*,
changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary items are ordered, changeable, and does not allow duplicates. Dictionary items are
presented in key:value pairs, and can be referred to by using the key name.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

When we say that dictionaries are ordered, it means that the items have a defined order, and that
order will not change.

Unordered means that the items does not have a defined order, you cannot refer to an item by using
an index.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 42
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary
has been created.

Dictionaries cannot have two items with the same key.

The values in dictionary items can be of any data type:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

3.5 Installing nested data structure:-

Nested Lists:-

li = [10, 20, [30, 40, 50, 60]]


len(li) #output is 3
li[0] #output is 10
li[0][-1] #output is 60
li[2][:] # output is [30, 40, 50, 60]
li[2][1:3] #output is [40, 50] because outer range 3 is excluded
li[2][ : :2] #output is [30, 50] where 2 is the step

Nested Dictionary: -

d = { ‘Course’ : ‘Python’, ‘Fees’ : 20000, 1 : { ‘Course’ : ‘Java Script’, ‘Fees’ :15000} }


for i in d:
print (d)
for i in d:

if type (d [ i ] ) in dict:
for k in d [ i ] :
print (k, ‘=’, d[i][k])
else:
print (i, ‘=’, d[i])

Output:-
Course
Fees
1
----------------
Course = Python
Fees = 20000
Course = Java Script
Fees = 15000

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 43
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

3.6 Testing the network scanner with Python

A network scanner is a software tool that scans the network for connected devices. It is also used for

diagnostic and investigative purposes to find and categorize what devices are running on a network.

This tool takes an IP address or a range of IP addresses as input and then scans each IP Addresses

sequentially and determines whether a device is present on that particular IP address or not. It scans

the network and returns an IP address and it’s corresponding MAC address if the device is present. A

popular tool that’s commonly used CyberSecurity professionals is nmap.

Network Scanner uses ARP Request and Response to scan the entire network to find active devices

on the network and also to find their MAC Addresses.

If it is still not clear what ARP is and how it works then refer to the images below.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 44
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Let’s start writing the script.


Step 1: Import the modules discussed above.
Step 2: Implementing the functionality to allow the users to pass command line arguments.
Step 3: Writing function that scans the network

In this function, we’ll have to do the following things to be able to scan the network:
 Create an ARP Request.
 Create an Ethernet Frame.
 Place the ARP Request inside the Ethernet Frame.
 Send the combined frame and receive responses.
 Parse the responses and print the results.

Step 4: Writing function to print the results in a certain format.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 45
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

All Possible MCQs:-

What connects IP
Address Transmission
address to the File Transfer File Transfer
Resolution Control 1
Physical address of Protocol Protocol
Protocol Protocol
devices?
The ARP protocol
operates on which
Physical Data Link Network Transport 2
layer of the OSI
model?
Find in which year
ARP was defined
1982 1992 2002 2012 1
first time in Request
for Comment.
Select which of the
following RFC
RFC820 RFC822 RFC824 RFC826 4
number is used for
ARP.
Which of the
following list1 = list([1, all of the
list1 = list() list1 = [] 4
commands will 2, 3]) mentioned
create a list?
Find the output
[‘h’, ‘e’, ‘l’, ‘l’,
when we execute [‘hello’] [‘llo’] [‘olleh’] 1
‘o’]
list(“hello”).
Suppose list1 is [4,
2, 2, 4, 5, 2, 1, 0],
Which of the all of the
print(list1[2:]) print(list1[:2]) print(list1[:-2]) 4
following is correct mentioned
syntax for slicing
operation.
Suppose list1 is [2,
33, 222, 14, 25].
Error 2 25 None 3
Find what is list1[-
1].
Which of the d=
following d = {“john”:40, All of the
d = {} {40:”john”, 4
statements create a “peter”:45} mentioned
45:”peter”}
dictionary?
Suppose d =
{“john”:40,
“peter”:45}, to
d.delete(“john”: del
delete the entry for del d[“john”] 3
40) d.delete(“john”) d(“john”:40)
“john” what
command do we
use.

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 46
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Select the protocol


that can be used to
urllib bs4 HTTP none 3
retrieve web pages
using python.
Find the python
library that can be
used to send and urllib HTTP scapy none 1
receive data over
HTTP.
Find that how many
types of scanning in
1 2 3 4 3
cyber security is
there.
Which of them is Identifying
Check for live Check for Identifying of
not a scanning the malware 3
systems open ports services
methodology. in the system
Find the process by
which search
engines retrieve
Scrape BeautifulSoup BS4 spider 4
webpages and build
a search index
called.
Find that what are Built-in
the two main types System Custom function &
User function 3
of functions in function function User defined
Python. function
Find the value of
the following Python
1 2 3 None 2
expression.
(4+3)%5
Find the output of
the following Python
bc abc ab bca 2
statement.
>>>"a"+"bc"

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 47
BSc(H)-ANCS2021 6th Sem
Vulnerability Analysis / Penetration Testing (BNCSD601B)
Sec- A/B/C
2023-24

Short Questions:-

1. Explain how ARP works.

2. What is a list in python with example?


3. What is a dictionary in python with example?
4. Describe different types of functions in python.

5. Discuss the immutable variables of python.

6. What are the different types of number variables in python?

7. What is a function in python with example?


8. Describe what are the sets in python.
9. Describe what are the tuples in python.
10. What is a network scanner?
11. Explain with a code how to create ARP response.
12. What is a nested data structure with example?

Long Questions:-
1. What is ARP spoofing ?

2. Write a code which will combine frames into a packet.

3. What are lists with examples?


4. Write a code explaining how to implement nested data structures.
5. Write a python module to scan a network.

6. Write a code using nested loops.

7. What are the different networking scanning tools?


8. Compare between mutable and immutable data types in python.
9. How to write a script for network scanner?

Hemanta Kumar Sahu


Assistant Professor, CST Department
Brainware University, Kolkata 48

You might also like