0% found this document useful (0 votes)
34 views18 pages

Cyber Security Lab Manual

The document is a lab manual for a B.Tech III Year Cybersecurity course, detailing objectives and weekly tasks focused on various cybersecurity concepts and practical Python programming exercises. It covers topics such as cyber-attacks, encryption algorithms, hashing, socket programming, network packet analysis, web scraping, penetration testing, and API interactions. Each week includes specific objectives and Python code examples to facilitate hands-on learning in cybersecurity techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views18 pages

Cyber Security Lab Manual

The document is a lab manual for a B.Tech III Year Cybersecurity course, detailing objectives and weekly tasks focused on various cybersecurity concepts and practical Python programming exercises. It covers topics such as cyber-attacks, encryption algorithms, hashing, socket programming, network packet analysis, web scraping, penetration testing, and API interactions. Each week includes specific objectives and Python code examples to facilitate hands-on learning in cybersecurity techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

LAB MANUAL

ON
CYBERSECURITY

B.TECH III YEAR–II SEM(R22)

(2024-2025)
DEPARTMENT OF CYBER SECURITY

MALLAREDDYCOLLEGEOFENGINEERING
MALLAREDDYCOLLEGEOFENGINEERINGANDTECHNOLOGY

IV YearB.TechCSE(CyS)–IISem(R22) L/T/P/C
0/-/2/1
(CYBERSECURITYLAB)
Courseobjectives:
1. Tounderstandvarioustypesofcyber-attacks andcyber-crimes
2. Tolearnthreatsandriskswithincontextofthecybersecurity
3. Tohaveanoverviewofthecyberlaws&conceptsofcyber forensics
4. Tostudythedefensivetechniquesagainstthese attacks
5. Tounderstandvariouscybersecurityprivacyissues

WEEK-1
WritingsimplePythonscriptsfortaskslikestringmanipulation,readingfromandwritingtofiles, basicnetwork
communication.

WEEK-2
ImplementingbasicencryptionanddecryptionalgorithmsinPythonCaesarcipher,AES, DES

WEEK-3
Usingpythontogenerateandverifyhashes(MD5,SHA-256)forfilesandmessages.

WEEK-4
Building asimplePythonClient-Serverapplication,understandingsockets.

WEEK-5
Writingapythonscripttocaptureandanalyzenetworkpackets(usinglibrarieslikeScapyorPySpark

WEEK-6
CreatingawebscraperinPythontogatherdatafromwebsites(usingBeautifulSoup,Selenium)

WEEK-7
SimplepenetrationtestingtasksusingPython(Eg:portscanning,vulnerabilityscanningwithtoolslikeNmapin
Python.

WEEK-8
Usingpythontointeractwithsecurity-relatedAPIs(eg.VirusTotal,Shodan)

WEEK-9
Writingpythonscriptsforbasicstaticmalwareanalysis(filesignatureanalysis,stringextraction).

WEEK-10

DevelopingasimpleIDSusingPython

1|Page
Week-1:writingsimplePythonscriptsthat includestring manipulation,reading fromandwritingtofiles, and basic
network communication.

Objective:
● Performstringmanipulation
● Readfromandwritetoa file
● Implementabasicexampleofnetworkcommunication

PythonCode:
importsocket

#StringManipulationFunction def
reverse_string(s):
returns[::-1]

#FileReadandWriteFunction
def read_and_reverse_write(input_file, output_file):
with open(input_file, 'r') as file:
content=file.read()
reversed_content =reverse_string(content)
with open(output_file, 'w') as file:
file.write(reversed_content)

#BasicNetworkCommunicationFunction def
simple_server(port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', port))
server_socket.listen(1)
print(f"Serverlisteningonport{port}...")
conn, addr = server_socket.accept()
print(f"Connected by {addr}")
whileTrue:
data=conn.recv(1024) if
not data:
break
conn.sendall(data)
conn.close()

#MainExecution
if name =="main": #
String Manipulation
original_string = "Hello,
World!"reversed_str =
reverse_string(original_string)
print(f"Original String: {original_string}")
print(f"Reversed String: {reversed_str}")
2|Page
# File Read and Write
read_and_reverse_write('input.txt', 'output.txt')

#SimpleNetworkCommunication(Uncommenttoruntheserver)
#Note:Runningtheserverwillrequireaclienttoconnectandsenddata.#
simple_server(65432)

InstructionsforExecution:
1. StringManipulation:Thispartofthescriptreversesagivenstring.
2. FileReadandWrite:
a. Createafilenamedinput.txtinthesamedirectoryasthescriptwithsomecontent.
b. Thescriptwillreadthisfile,reverseitscontent,andwriteittooutput.txt.
3. BasicNetworkCommunication:
a. Thisisasimpleserverthatechoesreceivedmessages.
b. Totestthis,you willneedtowriteaseparateclientscriptoruseanetworktooltosenddatatothe server.
c. Uncommentthesimple_server(65432)linetoruntheserver.

3|Page
Week-2:thefocusisonimplementingbasicencryptionanddecryptionalgorithmsinpython.

Objective:
● ImplementtheCaesarCipherencryptionanddecryption
● ImplementAESandDESencryptionanddecryption

PythonCode:
fromCrypto.CipherimportAES,DES
fromCrypto.Randomimport get_random_bytes
from Crypto.Util.Padding import pad, unpad
import base64

#CaesarCipher
defcaesar_cipher_encrypt(text, shift):
result = ""
foriinrange(len(text)):
char = text[i]
ifchar.isupper():
result+=chr((ord(char)+shift-65)%26+
65)else:
result+=chr((ord(char)+shift-97)%26+
97)return result

def caesar_cipher_decrypt(text, shift):


return caesar_cipher_encrypt(text, -shift)

# AES Encryption/Decryption
defaes_encrypt(plain_text, key):
cipher=AES.new(key,AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(plain_text.encode('utf-8'), AES.block_size))
iv = base64.b64encode(cipher.iv).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
return iv, ct

def aes_decrypt(iv, ct, key):


iv=base64.b64decode(iv)
ct=base64.b64decode(ct)
cipher=AES.new(key,AES.MODE_CBC,iv) pt
= unpad(cipher.decrypt(ct), AES.block_size)
return pt.decode('utf-8')

# DES Encryption/Decryption
defdes_encrypt(plain_text, key):
cipher=DES.new(key,DES.MODE_CBC)
ct_bytes=cipher.encrypt(pad(plain_text.encode('utf-8'),DES.block_size))
4|Page
iv=base64.b64encode(cipher.iv).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
return iv, ct

def des_decrypt(iv, ct, key):


iv=base64.b64decode(iv)
ct=base64.b64decode(ct)
cipher=DES.new(key,DES.MODE_CBC,iv) pt
= unpad(cipher.decrypt(ct), DES.block_size)
return pt.decode('utf-8')

#MainExecution
ifname=="main ": # Caesar
Cipher Example shift = 4
original_text="HelloWorld"
encrypted = caesar_cipher_encrypt(original_text, shift)
decrypted = caesar_cipher_decrypt(encrypted, shift)
print(f"CaesarCipher:{original_text}->{encrypted}->{decrypted}")

#AESExample
aes_key=get_random_bytes(16)#AESkeymustbeeither16,24,or32byteslong iv,
encrypted = aes_encrypt(original_text, aes_key)
decrypted=aes_decrypt(iv,encrypted,aes_key)
print(f"AES: {original_text} -> {encrypted} ->
{decrypted}")

#DESExample
des_key=get_random_bytes(8)#DESkeymustbe8byteslong iv, encrypted =
des_encrypt(original_text, des_key)
decrypted=des_decrypt(iv,encrypted,des_key)
print(f"DES: {original_text} -> {encrypted} ->
{decrypted}")

InstructionsforExecution:
1. CaesarCipher:Demonstratesbasicshift-basedencryptionanddecryption.
2. AESandDES:
a. ThesesectionsusethepycryptodomelibraryforAESandDESencryption.
b. Installthelibraryusing“pipinstallpycryptodome”ifnotalreadyinstalled.
c. Thescriptdemonstratesencryptionanddecryptionwithrandomlygeneratedkeys.

5|Page
Week-3:thefocusisonusingpythontogenerateandverifyhashesfor filesandmessages,utilizinghashing algorithms
like MD5 and SHA-256.
Objective:
● GenerateMD5andSHA-256hashesforstrings.
● Verifyhashesofstrings
PythonCode:
importhashlib

#FunctiontogenerateMD5 hash
def generate_md5_hash(input_string):
md5_hash = hashlib.md5()
md5_hash.update(input_string.encode())
return md5_hash.hexdigest()

# Function to generate SHA-256 hash


defgenerate_sha256_hash(input_string):
sha256_hash = hashlib.sha256()
sha256_hash.update(input_string.encode())
return sha256_hash.hexdigest()

#Functiontoverifyahash
defverify_hash(input_string, known_hash):
# Generate hash for the input string
generated_hash=generate_md5_hash(input_string)iflen(known_hash)==32else
generate_sha256_hash(input_string)

#Comparethegeneratedhashwiththeknownhashreturn
generated_hash == known_hash

#MainExecution
if name =="main": #
Example strings
example_string1 =
"HelloWorld"example_string2="HelloWorld!"

#Generatehashes
md5_hash_example1 = generate_md5_hash(example_string1)
sha256_hash_example1 = generate_sha256_hash(example_string1)

print(f"MD5Hashof'{example_string1}':{md5_hash_example1}")
print(f"SHA-256 Hash of '{example_string1}':
{sha256_hash_example1}")

6|Page
#Verifyinghashes
print(f"VerifyingMD5Hashof'{example_string1}':{verify_hash(example_string1,md5_hash_example1)}")
print(f"Verifying SHA-256 Hash of '{example_string1}': {verify_hash(example_string1,
sha256_hash_example1)}")

#Verifyingincorrecthash
print(f"VerifyingSHA-256Hashof'{example_string2}'withhashof'{example_string1}':
{verify_hash(example_string2,sha256_hash_example1)}")

InstructionsforExecution:
1. GenerateMD5andSHA-256hashes:Thescriptgenerates hashesforinputstringsusingMD5andSHA-256
algorithms.
2. Verifyhashes:Thescriptchecksifagivenstringmatchesaknownhash,demonstratinghash
verification.

7|Page
Week-4:thefocusisonbuildingasimplepythonclient-serverapplicationtounderstandthebasicsofsocket
programming.

Objective:
● CreateasimpleTCPServerandClient.
● UnderstandthebasicsofsocketprogramminginPython.

PythonCodes:
server.py(ServerScript)
importsocket

defstart_server(host='localhost',port=65432):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((host, port))
s.listen()
print(f"Server listening on{host}:{port}")
conn, addr = s.accept()
withconn:
print(f"Connectedby{addr}")
while True:
data=conn.recv(1024)
if not data:
break
conn.sendall(data)

if name =="main":
start_server()

Client.py(ClientScript)
importsocket

defstart_client(host='localhost',port=65432):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
s.sendall(b'Hello,server')
data = s.recv(1024)
print(f"Received{data.decode()}")

if name =="main":
start_client()

8|Page
InstructionsforExecution:
1. RuntheServerScript:Starttheserverfirst.Itwilllistenforincomingconnections onlocalhost
(127.0.0.1) and port 65432.
2. RuntheClientScript:Oncetheserver isrunning, runtheclientscript.Theclient willconnecttotheserver, send a
message, and receive an echo back from the server.
3. SocketProgramming:ThisdemonstratesabasicTCP/IPsocketconnectionwheretheserverlistensfor
connections and the client sends a message.

9|Page
Week-5:thefocusisonwritingapythonscriptto captureandanalyzenetworkpackets.

Objective:
● CapturenetworkpacketsusingScapy.
● Analyzeandprintthedetailsofcapturedpackets.

PythonCode:

fromscapy.allimportsniff

#Packetprocessingfunction
defprocess_packet(packet):
print(packet.summary())
#Addmoreanalysisasneeded,e.g.,checkingforspecificprotocols,ports,etc.

#Startpacketsniffing
def start_sniffing():
print("Startingpacketsniffing...")
sniff(prn=process_packet,count=10)#Capturing10packetsfordemonstration

if name =="main":
start_sniffing()

InstructionsforExecution:
1. InstallScapy:Ifnotalreadyinstalled,youcaninstallScapyusingpipinstallscapy.
2. RuntheScript:Thisscriptwillstartcapturingpacketsandprocess10packetsfordemonstration.Eachpacket's
summary information will be printed.
3. CustomizePacketAnalysis:Youcanextendtheprocess_packetfunctiontoperformmoredetailed
analysis, such as filtering specific types of packets, analyzing packet contents, etc.

10|Page
Week-6:thefocusisoncreatingawebscraperinpythontogatherdatafromwebsites.

Objective:
● ScrapedatafromawebpageusingBeautifulSoap.
● Extractandprintspecificelementsfromthewebpage.

PythonCode:
importrequests
frombs4import BeautifulSoup

#Functiontoscrapeawebpage def
scrape_website(url):
#SendanHTTPrequesttotheURL response
= requests.get(url)
#ParsetheHTMLcontentofthe page
soup=BeautifulSoup(response.text,'html.parser')

#Example:Extractandprintallparagraphtexts
paragraphs = soup.find_all('p')
for para inparagraphs:
print(para.get_text())

#MainExecution
ifname =="main":
url="http://example.com"#ReplacewiththeURLofthewebsite youwantto scrape scrape_website(url)

InstructionsforExecution:
1. InstallBeautifulSoupandRequests:Ifnotalreadyinstalled,installthemusingpipinstall
beautifulsoup4 requests.
2. RuntheScript:ThescriptsendsarequesttothespecifiedURL,parsestheHTMLcontent,andprints thetext of all
paragraphs. You can modify the script to scrape different elements as needed.
3. CustomizeforDifferentWebsites:ChangetheURLandtheelementsyouwanttoscrapeaccordingtoyour
requirements.

11|Page
Week-7:thefocusisonsimplepenetrationtestingtasksusingpython.

Objective:
● CreateasimpleportscannerusingPython.
● Scanatargethosttoidentifyopenports.

PythonCode:
importsocket

#Functiontoscanasingleport def
scan_port(ip, port):
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(1)# Timeout of 1 second
result=s.connect_ex((ip,port))
if result == 0:
returnTrue
else:
returnFalse
exceptsocket.error:
returnFalse

# Main function to scan portson a host


defport_scanner(target_ip, port_range):
print(f"Startingscanonhost:{target_ip}")
for port in range(*port_range):
if scan_port(target_ip, port):
print(f"Port{port}isopen")

#MainExecution
ifname =="main":
target_ip="192.168.1.1"#ReplacewiththetargetIPaddress
port_range = (1, 1025) # Scanning the first 1024 ports
port_scanner(target_ip, port_range)

InstructionsforExecution:
1. SetTargetIPandPortRange:Replacetarget_ipwiththeIPaddressofthetargethost.Adjustthe
port_rangeasneeded(thecurrentrangeis1to1024).
2. RuntheScript:ThescriptwillscanthespecifiedportrangeonthetargetIPandreportopenports.

12|Page
Week-8:thefocusisonusingpythontointeractwithsecurityrelatedAPIs.(VirusTotalAPI). [VirusTotal API :

https://www.virustotal.com/gui/home/upload]

Objective:
● UsingpythontoquerytheVirusTotalAPI.
● AnalyzeaURLorFileforPotentialSecurityThreats.

PythonCode:
importrequests

#FunctiontocheckaURLusingtheVirusTotalAPI def
check_url_virustotal(api_key, url):
params={'apikey':api_key,'resource':url}
response = requests.post('https://www.virustotal.com/vtapi/v2/url/report', params=params)
return response.json()

#MainExecution
ifname =="main":
api_key="YOUR_VIRUSTOTAL_API_KEY"#ReplacewithyourVirusTotalAPIkey
url_to_check = "http://example.com"# Replace with the URL you want to analyze

result = check_url_virustotal(api_key, url_to_check)


if result.get('positives', 0) > 0:
print(f"URL{url_to_check}detectedaspotentiallymalicious.")
print("Details:", result)
else:
print(f"URL{url_to_check}appearstobesafe.")

InstructionsforExecution:
1. GetaVirusTotalAPIKey:SignuponVirusTotalandobtainyourAPIkey.
2. SettheAPIKeyandURL:ReplaceYOUR_VIRUSTOTAL_API_KEYwithyourownkeyand
http://example.com with the URL you wish to analyze.
3. RuntheScript:ThescriptwillsendtheURLtoVirusTotalandprinttheanalysisresults.

13|Page
Week-9:thefocusisonwritingpythonscriptsforbasicstaticmalwareanalysis.

Objective:
● Performbasicstaticanalysisonfilestoidentifypotentialmalware.
● Calculatefilehashes,extractstrings,andanalyzefileheaders.

PythonCode:
Beforeyou begin,youmightneedto installadditionallibraries,like pefileforPEfile analysisand
hashlibforhashing(includedinPythonStandardLibrary).

import pefile
importhashlib
import re
import sys

#Functiontocalculateafile'shash
def calculate_hash(filename):
hasher =
hashlib.sha256()withopen(file
name,'rb')asfile:
buf = file.read()
hasher.update(buf)
returnhasher.hexdigest()

#Functiontoextractprintablestringsfromthefile def
extract_strings(filename):
withopen(filename,'rb')asfile:
content = file.read()
strings = re.findall(b'[\\x20-\\x7E]{4,}', content)
return [s.decode('utf-8') for s in strings]

#FunctiontoanalyzePEfileheaders
def analyze_pe_file(filename):
try:
pe = pefile.PE(filename)
returnTrue,pe.dump_info()
except pefile.PEFormatError:
returnFalse,"NotavalidPEfile."

#MainExecution
ifname =="main":
filename=sys.argv[1]#Replacewiththefileyouwanttoanalyze

14|Page
print(f"Analyzing file: {filename}")
print("\n[+]Calculatingfilehash...")
file_hash=calculate_hash(filename)
print(f"SHA-256 Hash: {file_hash}")

print("\n[+] Extracting strings...")


strings=extract_strings(filename)
print(f"Extractedstrings:{strings[:5]}...")#Printfirst5stringsforbrevity

print("\n[+]AnalyzingPEfile...")
is_pe,pe_info=analyze_pe_file(filename)
if is_pe:
print(pe_info)
else:
print(pe_info)

InstructionsforExecution:
1. Installpefile:Usepipinstallpefileifnotalreadyinstalled.
2. RuntheScript:Passthefileyou wanttoanalyzeasacommand-lineargument.Example:python
script.py sample.exe
3. AnalyzetheOutput:
a. ThescriptcalculatestheSHA-256hashofthefile.
b. Itextractsprintablestringsthatcouldbeofinterest.
c. ForPE(PortableExecutable)files,itanalyzesandprintsfileheaders

15|Page
Week-10:thetaskistodevelopasimpleIntrusionDetectionSystem(IDS)usingPython.

Objective:
● Createabasicnetwork-basedIntrusionDetectionSystem(IDS).
● Monitorandanalyzenetworkpacketsforsuspiciouspatterns.

PythonCode:
This script usesthe Scapy library for packet capturing and analysis. We'll look for a simple pattern - for
example,detectingalargenumberofHTTPrequeststoaspecificserver,whichmight indicateaDoSattack.

fromscapy.allimportsniff
fromcollectionsimportCounter
import time

#Configuration
MONITOR_DURATION = 60# Time in seconds to monitor the traffic
THRESHOLD_REQUESTS=100#Thresholdfornumberofrequeststotriggeranalert TARGET_IP
= "192.168.1.1"# IP of the target server to monitor

#Globalcounterforrequests
request_counter=Counter()

#Packetprocessingfunction
defprocess_packet(packet):
ifpacket.haslayer("IP")andpacket.haslayer("TCP"):
ip_src = packet["IP"].src
ip_dst = packet["IP"].dst
tcp_dport =packet["TCP"].dport

#Example:Detectmultiplerequeststoaspecificserver(HTTPport80) if
ip_dst == TARGET_IP and tcp_dport == 80:
request_counter[ip_src]+=1

#IntrusionDetectionFunction
def detect_intrusion():
print("Startingnetworkmonitoring...")
sniff(prn=process_packet,
timeout=MONITOR_DURATION)

#CheckifanysourceIPexceededthethreshold for
ip, count in request_counter.items():
ifcount>THRESHOLD_REQUESTS:
print(f"Potentialintrusiondetectedfrom{ip}.Totalrequests:{count}") if

name == "main":
16|Page
detect_intrusion()
InstructionsforExecution:
1. InstallScapy:Ifnotalreadyinstalled,usepipinstallscapy.

2. RuntheScript:Executethescripttostartmonitoringnetworktrafficforthespecifiedduration.

3. ReviewAlerts:ThescriptwillreportanysourceIPsthatexceedthethresholdforrequeststothetargetIP.

17|Page

You might also like