SlideShare a Scribd company logo
Python for Web Security
Code Warriors
Sanjeev Jaiswal (Jassi)
#NullHyd
1
author_profile
{
“Name” : “Sanjeev Jaiswal”
“Nickname” : “Jassi”
“Twitter_handle” : “jassics”
“Mail_id” : “jassics[at]gmail[dot]com”
“Skills” : [“AppSec”, “AWS Security”, “Perl”, “Python”]
“Interests” : {
“Learning” : “AWS Security Automation”,
“Want_to_learn” : “Security Automation in DevOps pipeline”
}
}
2
(“My”, “Assumptions”)
● You have python and pip installed in your machine
● You can execute python scripts
● You can install dependent libraries using pip
● You can write basics of python program
● You can understand python script
● You understand web security basics
● You know how request response of a web url works
● Burp is installed and configured to get proxy request
3
[List of Items]
● Why Python
● Fundamentals of Python (Minimal)
● Quick walk through of existing scripts
● Writing few web security scripts
● Creating minimal Burp plugin
● Resources for Learning
● What’s Next
4
Why Python
● Easy to learn and Clean Syntax Code
● Widely being used in security domain
● Open- Source and Vast Community Support
● Automated memory management
● Support to Glue for other languages
● Good for quick and dirty jobs in security ;)
● Lots of security tools available in Python m/
5
Fundamentals of Python (quick tour)
● Variable names
● Numbers and Strings
● Basic Operators
● Loops and statements
● Functions
● Data Structures i.e. Lists, Tuples, Dictionary
● File handling
● Regular Expression glimpse
● Modules 6
Python Fundamentals
7
Variable Names
● Make it human readable
● Keep it short but descriptive
● Don’t start with number
● Don’t use $ in your variable name
● all_lowercase_with_underscore
● Advisable not to start with underscore i.e. _var_name
● Also not advisable to use var.__name or __var_name
● Variable types depend upon the data being used.
8
Numbers and Strings
● Integer: 2, 4, -13, 130
● Float: 2.41564, 2.45, -1.2, 97.99
● String: ‘Apple’, “Hello, How are you doing?”
● int() for integer
● float() for float
● str() for string
9
Basic Operators
That operates pythonic way
10
Arithmetic Operators
● + : used for addition of two digits
● - : used for subtraction of two numbers
● * : used for multiplication
● / : used for division, you will get results in float
● //: floor division, you will get the quotient
● %: modulo division, you will get remainder as a result
11
Relational Operators
● > : greater than
● < : less than
● == : equals to
● != : not equal to
● >= : greater than equal to
● <= : less than equal to
12
Logical Operators
● and : returns True if both statements are true
● or : returns True if any of the statements are true
● not : returns False if the result is true
13
Bitwise Operators
● ~ : inverts all the bits
● | : sets bits to 1 if one of the bits is 1
● ^ : sets each bit to 1 only one of two bits are 1
● & : sets each bit to 1 if both bits are 1
● >> : signed right shift
● << : left shift
14
Assignment Operators
● = : assigns right side value to left side variable
● += : x+=3 means x = x+3
● -= : x-=3 means x = x-3
● *= : x*=5 means x = x*5
● /= : x/=4 means x = x/4
● //= : x//7 means x = x//7
● %= : x%=2 means x = x%2
● **= : x**=2 means x = x**2
15
Data Structure
List, Tuples, Dictionary
16
Lists
● Most important and widely used in python
● Its like array in C
● It is accessed by using index number
● Index number starts with 0
● You can use list methods like pop, append, insert, extend, sum, len, min, max, sort,
reverse, del, remove, clear
● Syntax:
List_variable_name = [] #empty list
List_with_value = [21, 25, 80, ‘ssl’, ‘web server’, 21, 80, 8080, 21]
17
Tuples
● Similar to list
● But immutable
● Denoted by () where as list is denoted by []
● You can use count and index
● You can join two tuples
● You cannot insert, delete
● (‘single item’,) is a tuple, but (‘single item’) is a string
● only_allowed_ports = (80, 443, 8000, 8080, 9001)
18
Dictionary
● When you need key value pair like port number with port service name
● Dictionary_var = {“key” : value}
● Value can be any object, it can be even another dictionary
● dict_var = dict() or dict_var = {} # for empty dictionary
● port_service = {“ssh”: 23, “ftp”: 21, “http”: 80}
● for service in port_service:
print(“{} : {}”.format(service, port_service[service]))
● port_service.pop(“http”)
● port_service.update({“ssl”: 443})
● port_with_service = port_service.items()
● print(port_with_service)
19
Loops
Let’s iterate over items
20
for loop
for iterator in sequence:
statement(s)
Example 1
print("Port List Iteration")
ports = [22, 25, 80, 443]
for port in ports:
print(port)
Example 2
print("Dictionary Iteration")
port_dict = {
‘Ftp’ = 21
‘ssh’ = 23
‘Smtp’ = 25
‘Https’ = 443
}
for service in port_dict :
print("%s : %d" %(service,
port_dict[service]))
21
while loop
while expression:
statement(s)
while expression:
statement(s)
else:
Some other
statement(s)
22
Example 1
x = 10
while x>0:
print(x)
x--
Example 2
x = 0
while x>10:
x += 1
print(x)
else:
print(‘Came out of the
loop’)
Statements
Decision Making Statement
● if statement
● if else statement
● If elif else ladder
● Nested if else
Loop Control Statements
● break
● pass
● continue
23
Let’s write functions
● Reusable block of codes
● Can pass arguments to it
● Built-in functions: print(), len(),
sorted(), int(), str() …
● Structure:
○ Start with keyword def and then
function name with parameters inside
parenthesis as optional
○ Ex: def print_status_code(url):
○ It can have return statement
● Call named function with
function name. Ex:
print_status_code(url) 24
import requests
url = ‘https://opsecx.com ’
def get_status_code(url):
response = requests.get(url)
return response.status_code
status_code = get_status_code(url)
print (status_code)
File Handling
● Python provided an in-built function to read and write files
● Syntax:
○ file_input = open(“file_name”, “mode”)
○ Mode can be r for read, w for write, a for append
○ + suffix to mode means, create if it doesn’t exists
○ Ex: file_input = open(“ip-ranges.json”, w+)
○ Write to file_input. file_input.write(“127.0.0.1n”)
○ Close the file. file_input.close()
● Other modes are x for creation, b for binary (t for text, by default)
● Read the file content by using read(chars), readline() or readlines()
● Another way to read file is with open(...) as file_input:
for line in file_input:
# do something with that line
25
Regular Expression
● Learn regex basics from here: https://www.regular-expressions.info/quickstart.html
● import re # import regular expression module in Python
● Python module re provides full support for Perl-like regular expressions in Python
● re.match(), re.search(), re.sub()
● Modifiers or optional flags in re: re.S, re.M, re.I etc.
● Get the matched content using group(num) or groups()
● You can compile the pattern as well. re.compile(pattern)
● matched = re.search(pattern, string) ie equivalent to
comp_pattern = re.compile(pattern)
matched = comp_pattern.match(string)
26
Let’s use Modules
● Think it like a library
● Just an another file with python codes
● It can define classes, functions, variables etc
● Use any of the below way to use python module:
○ import module_name
○ import module1, module2, module3, moduleN
○ import some_module as your_convenient_name
○ from module1 import *
○ from module_name import <specific>
27
Commonly used modules in security
● re : used for regular expression
● os, sys, socket : system based calls
● requests, webbrowser, wappalyzer, urllib3, pyautogui : website manipulation
● json, csv, xml
● from scapy.all import *
● from ftplib import FTP
● from faker import Faker
● from bs4 import bs
● nmap, dns, whois, ipaddress
● pip install pycrypto, hashlib, base64
● Anything else? Please add here
28
walkthrough_existing_security_scripts
● Python wappalyzer
● Gittyleaks or trufflehog
● KickS3 orS3 Recon
● Analyse Security Headers
● Bruteforce Login or Instagram Account Bruteforce
● Scapy
29
Writing Scripts
Get hands dirty
30
#1 Fetch request and response headers of a url
1. url is provided
2. Use requests modules in your script
3. Instantiate a requests object
4. Use get method on url using that created object as in #3
5. Save request and response headers in variables respectively
6. Loop through request and response headers respectively and
7. Print the header contents
31
#2 Filter request and response headers of a url
1. url is provided
2. Use requests modules in your script
3. Instantiate a request object
4. Use get method on url using a request object
5. Save response headers in variable
6. Create a list of filtered header contents
7. Loop through response headers and
8. Check if that header is in our filtered header content
9. Print the header content, if it’s in filtered response header
32
#3 [TRY AT HOME]: Scan and Report Security headers gap
● Simulate in cli: https://securityheaders.com/?q=null.co.in&followRedirects=on
● Use requests and colorama module
● Get the response headers
● Look for security headers that exists in your suggested security headers dictionary
● If missing, print in red color with the suggestions saved in dictionary against that header
● If security header found
○ Print in green color, if header is implemented properly
○ Print in red color, if that security header is missing some implementations
● Once done all, you can give your own rating based on your rating calculator (Future)
33
Smart Password Generator based on victim’s details (Project?)
● There are many password files available, but generic
● How about generating passwords based on these combination:
○ Name (firstname, lastname, nickname etc.)
○ Hobbies
○ Locations
○ Favorite (Food, pet, movie, family members etc)
○ Date of [Birth, marriage, family’s other dates)
○ Profession
○ And password character ranges
● Either gather the information and pass to the script as an input file
● Or Ask all those questions through cli
● And finally generate possible passwords and output as victim_password.txt
34
Writing Custom Burp Plugin
35
Basic Burp Extension using Python: Part 1
● It is based on
https://portswigger.net/burp/extender/writing-your-first-burp-suite-extension
● Create a directory to store your extensions scripts, we will use this directory now
onwards for our extension
● Download Jython standalone (.jar) from here: https://www.jython.org/download.html
● Keep this jar file in the same extension directory for convenience
● Configure Burp to use Jython. Extender -> Options -> Python Environment
● Create a python script and import necessary modules in that script
● Write BurpExtender Class i.e. class BurpExtender(IBurpExtender):
● Add your custom written Python script in Burp Extension
● Check for output or any error in popup window
36
Basic Burp Extension using Python: Part 2
● Once Burp extension Part 1 exercise is successful
● Add Own custom tab in HTTP request
● Show headers just like request headers in custom tab
● You would need to use
○ from burp import IMessageEditorTabFacory
○ from burp import IMessageEditorTab
● Add IMessageEditorTabFactory in class
● Get helpers object: self._helpers = callbacks.getHelpers()
● Register the object: callbacks.registerMessageEditorTabFactory
● Create a new instance to DisplayValues
● Define DisplayValues class with all the essential functions
● Verify if it’s showing the tab and contents within that tab
37
Basic Burp Extension using Python: Part 3 (Try at Home)
● Once Burp extension Part 2 exercise is successful
● Create similar tab under Proxy->HTTP History->Response tab
● Loop through the response header contents
● Create a dictionary of security header with suggestions
● Look for security headers and
○ Show present or absent based on header presence compared with your list
○ Show if present security header is implemented properly
● Note: You might need to go through few of the Burp Extender
APIs Code snippets
38
Learning Resources
● Violent Python
● Black hat Python
● Automating boring stuffs
● Python for Pentesters by Vivek Ramachandran
● Python for everybody specialization (Coursera)
● Black Hat Python for Pentesters and Hackers - Video (PackT)
● Cracking Codes with Python
39
What’s Next
● Python for Network Security
● Python for Security Automation
● Exploits in Python
● Secure Coding in Python
● AI/ML in Cybersecurity using
Python
● Python for Crypto
● Malware Analysis using Python
● Forensics using Python
● And many more
40
41

More Related Content

PPTX
03 standard class library
ODP
Hands on Session on Python
PDF
PDF
Python in 90 minutes
PDF
Pemrograman Python untuk Pemula
ODP
An Intro to Python in 30 minutes
PPTX
PDF
PHP unserialization vulnerabilities: What are we missing?
03 standard class library
Hands on Session on Python
Python in 90 minutes
Pemrograman Python untuk Pemula
An Intro to Python in 30 minutes
PHP unserialization vulnerabilities: What are we missing?

What's hot (20)

PPTX
Programming in Python
PPTX
Pythonppt28 11-18
PDF
Jurczyk windows kernel reference count vulnerabilities. case study
PDF
Machine learning in php
PDF
Python na Infraestrutura 
MySQL do Facebook

PDF
ODP
Python internals and how they affect your code - kasra ahmadvand
PDF
What’s eating python performance
PDF
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PDF
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
PPTX
FUNDAMENTALS OF PYTHON LANGUAGE
KEY
Gae icc fall2011
PDF
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
ODP
Python course Day 1
PDF
Porting to Python 3
PDF
IO Streams, Files and Directories
PDF
Trafaret: monads and python
PPT
Initial Java Core Concept
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
ODP
Programming in Python
Pythonppt28 11-18
Jurczyk windows kernel reference count vulnerabilities. case study
Machine learning in php
Python na Infraestrutura 
MySQL do Facebook

Python internals and how they affect your code - kasra ahmadvand
What’s eating python performance
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
FUNDAMENTALS OF PYTHON LANGUAGE
Gae icc fall2011
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
Python course Day 1
Porting to Python 3
IO Streams, Files and Directories
Trafaret: monads and python
Initial Java Core Concept
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Ad

Similar to Python for web security - beginner (20)

PDF
An Overview of SystemVerilog for Design and Verification
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
PDF
More about PHP
PDF
2018 cosup-delete unused python code safely - english
PPT
270_1_ChapterIntro_Up_To_Functions (1).ppt
PPT
270_1_CIntro_Up_To_Functions.ppt 0478 computer
PPT
CIntro_Up_To_Functions.ppt;uoooooooooooooooooooo
PPT
270 1 c_intro_up_to_functions
PPT
270_1_CIntro_Up_To_Functions.ppt
PPT
270_1_CIntro_Up_To_Functions.ppt
PPT
Survey of programming language getting started in C
PDF
Functional Programming 101 for Java 7 Developers
PPTX
Python fundamentals
PPTX
1P13 Python Review Session Covering various Topics
PPTX
Unit 8.4Testing condition _ Developing Games.pptx
PDF
c++ referesher 1.pdf
PDF
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
PPTX
Nitin Mishra 0301EC201039 Internship PPT.pptx
An Overview of SystemVerilog for Design and Verification
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
More about PHP
2018 cosup-delete unused python code safely - english
270_1_ChapterIntro_Up_To_Functions (1).ppt
270_1_CIntro_Up_To_Functions.ppt 0478 computer
CIntro_Up_To_Functions.ppt;uoooooooooooooooooooo
270 1 c_intro_up_to_functions
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
Survey of programming language getting started in C
Functional Programming 101 for Java 7 Developers
Python fundamentals
1P13 Python Review Session Covering various Topics
Unit 8.4Testing condition _ Developing Games.pptx
c++ referesher 1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
Nitin Mishra 0301EC201039 Internship PPT.pptx
Ad

Recently uploaded (20)

PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
PDF
01-Introduction-to-Information-Management.pdf
PDF
Business Ethics Teaching Materials for college
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
The Final Stretch: How to Release a Game and Not Die in the Process.
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Week 4 Term 3 Study Techniques revisited.pptx
Open folder Downloads.pdf yes yes ges yes
Anesthesia in Laparoscopic Surgery in India
Open Quiz Monsoon Mind Game Prelims.pptx
Microbial disease of the cardiovascular and lymphatic systems
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
01-Introduction-to-Information-Management.pdf
Business Ethics Teaching Materials for college
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Microbial diseases, their pathogenesis and prophylaxis
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...

Python for web security - beginner

  • 1. Python for Web Security Code Warriors Sanjeev Jaiswal (Jassi) #NullHyd 1
  • 2. author_profile { “Name” : “Sanjeev Jaiswal” “Nickname” : “Jassi” “Twitter_handle” : “jassics” “Mail_id” : “jassics[at]gmail[dot]com” “Skills” : [“AppSec”, “AWS Security”, “Perl”, “Python”] “Interests” : { “Learning” : “AWS Security Automation”, “Want_to_learn” : “Security Automation in DevOps pipeline” } } 2
  • 3. (“My”, “Assumptions”) ● You have python and pip installed in your machine ● You can execute python scripts ● You can install dependent libraries using pip ● You can write basics of python program ● You can understand python script ● You understand web security basics ● You know how request response of a web url works ● Burp is installed and configured to get proxy request 3
  • 4. [List of Items] ● Why Python ● Fundamentals of Python (Minimal) ● Quick walk through of existing scripts ● Writing few web security scripts ● Creating minimal Burp plugin ● Resources for Learning ● What’s Next 4
  • 5. Why Python ● Easy to learn and Clean Syntax Code ● Widely being used in security domain ● Open- Source and Vast Community Support ● Automated memory management ● Support to Glue for other languages ● Good for quick and dirty jobs in security ;) ● Lots of security tools available in Python m/ 5
  • 6. Fundamentals of Python (quick tour) ● Variable names ● Numbers and Strings ● Basic Operators ● Loops and statements ● Functions ● Data Structures i.e. Lists, Tuples, Dictionary ● File handling ● Regular Expression glimpse ● Modules 6
  • 8. Variable Names ● Make it human readable ● Keep it short but descriptive ● Don’t start with number ● Don’t use $ in your variable name ● all_lowercase_with_underscore ● Advisable not to start with underscore i.e. _var_name ● Also not advisable to use var.__name or __var_name ● Variable types depend upon the data being used. 8
  • 9. Numbers and Strings ● Integer: 2, 4, -13, 130 ● Float: 2.41564, 2.45, -1.2, 97.99 ● String: ‘Apple’, “Hello, How are you doing?” ● int() for integer ● float() for float ● str() for string 9
  • 10. Basic Operators That operates pythonic way 10
  • 11. Arithmetic Operators ● + : used for addition of two digits ● - : used for subtraction of two numbers ● * : used for multiplication ● / : used for division, you will get results in float ● //: floor division, you will get the quotient ● %: modulo division, you will get remainder as a result 11
  • 12. Relational Operators ● > : greater than ● < : less than ● == : equals to ● != : not equal to ● >= : greater than equal to ● <= : less than equal to 12
  • 13. Logical Operators ● and : returns True if both statements are true ● or : returns True if any of the statements are true ● not : returns False if the result is true 13
  • 14. Bitwise Operators ● ~ : inverts all the bits ● | : sets bits to 1 if one of the bits is 1 ● ^ : sets each bit to 1 only one of two bits are 1 ● & : sets each bit to 1 if both bits are 1 ● >> : signed right shift ● << : left shift 14
  • 15. Assignment Operators ● = : assigns right side value to left side variable ● += : x+=3 means x = x+3 ● -= : x-=3 means x = x-3 ● *= : x*=5 means x = x*5 ● /= : x/=4 means x = x/4 ● //= : x//7 means x = x//7 ● %= : x%=2 means x = x%2 ● **= : x**=2 means x = x**2 15
  • 17. Lists ● Most important and widely used in python ● Its like array in C ● It is accessed by using index number ● Index number starts with 0 ● You can use list methods like pop, append, insert, extend, sum, len, min, max, sort, reverse, del, remove, clear ● Syntax: List_variable_name = [] #empty list List_with_value = [21, 25, 80, ‘ssl’, ‘web server’, 21, 80, 8080, 21] 17
  • 18. Tuples ● Similar to list ● But immutable ● Denoted by () where as list is denoted by [] ● You can use count and index ● You can join two tuples ● You cannot insert, delete ● (‘single item’,) is a tuple, but (‘single item’) is a string ● only_allowed_ports = (80, 443, 8000, 8080, 9001) 18
  • 19. Dictionary ● When you need key value pair like port number with port service name ● Dictionary_var = {“key” : value} ● Value can be any object, it can be even another dictionary ● dict_var = dict() or dict_var = {} # for empty dictionary ● port_service = {“ssh”: 23, “ftp”: 21, “http”: 80} ● for service in port_service: print(“{} : {}”.format(service, port_service[service])) ● port_service.pop(“http”) ● port_service.update({“ssl”: 443}) ● port_with_service = port_service.items() ● print(port_with_service) 19
  • 21. for loop for iterator in sequence: statement(s) Example 1 print("Port List Iteration") ports = [22, 25, 80, 443] for port in ports: print(port) Example 2 print("Dictionary Iteration") port_dict = { ‘Ftp’ = 21 ‘ssh’ = 23 ‘Smtp’ = 25 ‘Https’ = 443 } for service in port_dict : print("%s : %d" %(service, port_dict[service])) 21
  • 22. while loop while expression: statement(s) while expression: statement(s) else: Some other statement(s) 22 Example 1 x = 10 while x>0: print(x) x-- Example 2 x = 0 while x>10: x += 1 print(x) else: print(‘Came out of the loop’)
  • 23. Statements Decision Making Statement ● if statement ● if else statement ● If elif else ladder ● Nested if else Loop Control Statements ● break ● pass ● continue 23
  • 24. Let’s write functions ● Reusable block of codes ● Can pass arguments to it ● Built-in functions: print(), len(), sorted(), int(), str() … ● Structure: ○ Start with keyword def and then function name with parameters inside parenthesis as optional ○ Ex: def print_status_code(url): ○ It can have return statement ● Call named function with function name. Ex: print_status_code(url) 24 import requests url = ‘https://opsecx.com ’ def get_status_code(url): response = requests.get(url) return response.status_code status_code = get_status_code(url) print (status_code)
  • 25. File Handling ● Python provided an in-built function to read and write files ● Syntax: ○ file_input = open(“file_name”, “mode”) ○ Mode can be r for read, w for write, a for append ○ + suffix to mode means, create if it doesn’t exists ○ Ex: file_input = open(“ip-ranges.json”, w+) ○ Write to file_input. file_input.write(“127.0.0.1n”) ○ Close the file. file_input.close() ● Other modes are x for creation, b for binary (t for text, by default) ● Read the file content by using read(chars), readline() or readlines() ● Another way to read file is with open(...) as file_input: for line in file_input: # do something with that line 25
  • 26. Regular Expression ● Learn regex basics from here: https://www.regular-expressions.info/quickstart.html ● import re # import regular expression module in Python ● Python module re provides full support for Perl-like regular expressions in Python ● re.match(), re.search(), re.sub() ● Modifiers or optional flags in re: re.S, re.M, re.I etc. ● Get the matched content using group(num) or groups() ● You can compile the pattern as well. re.compile(pattern) ● matched = re.search(pattern, string) ie equivalent to comp_pattern = re.compile(pattern) matched = comp_pattern.match(string) 26
  • 27. Let’s use Modules ● Think it like a library ● Just an another file with python codes ● It can define classes, functions, variables etc ● Use any of the below way to use python module: ○ import module_name ○ import module1, module2, module3, moduleN ○ import some_module as your_convenient_name ○ from module1 import * ○ from module_name import <specific> 27
  • 28. Commonly used modules in security ● re : used for regular expression ● os, sys, socket : system based calls ● requests, webbrowser, wappalyzer, urllib3, pyautogui : website manipulation ● json, csv, xml ● from scapy.all import * ● from ftplib import FTP ● from faker import Faker ● from bs4 import bs ● nmap, dns, whois, ipaddress ● pip install pycrypto, hashlib, base64 ● Anything else? Please add here 28
  • 29. walkthrough_existing_security_scripts ● Python wappalyzer ● Gittyleaks or trufflehog ● KickS3 orS3 Recon ● Analyse Security Headers ● Bruteforce Login or Instagram Account Bruteforce ● Scapy 29
  • 31. #1 Fetch request and response headers of a url 1. url is provided 2. Use requests modules in your script 3. Instantiate a requests object 4. Use get method on url using that created object as in #3 5. Save request and response headers in variables respectively 6. Loop through request and response headers respectively and 7. Print the header contents 31
  • 32. #2 Filter request and response headers of a url 1. url is provided 2. Use requests modules in your script 3. Instantiate a request object 4. Use get method on url using a request object 5. Save response headers in variable 6. Create a list of filtered header contents 7. Loop through response headers and 8. Check if that header is in our filtered header content 9. Print the header content, if it’s in filtered response header 32
  • 33. #3 [TRY AT HOME]: Scan and Report Security headers gap ● Simulate in cli: https://securityheaders.com/?q=null.co.in&followRedirects=on ● Use requests and colorama module ● Get the response headers ● Look for security headers that exists in your suggested security headers dictionary ● If missing, print in red color with the suggestions saved in dictionary against that header ● If security header found ○ Print in green color, if header is implemented properly ○ Print in red color, if that security header is missing some implementations ● Once done all, you can give your own rating based on your rating calculator (Future) 33
  • 34. Smart Password Generator based on victim’s details (Project?) ● There are many password files available, but generic ● How about generating passwords based on these combination: ○ Name (firstname, lastname, nickname etc.) ○ Hobbies ○ Locations ○ Favorite (Food, pet, movie, family members etc) ○ Date of [Birth, marriage, family’s other dates) ○ Profession ○ And password character ranges ● Either gather the information and pass to the script as an input file ● Or Ask all those questions through cli ● And finally generate possible passwords and output as victim_password.txt 34
  • 35. Writing Custom Burp Plugin 35
  • 36. Basic Burp Extension using Python: Part 1 ● It is based on https://portswigger.net/burp/extender/writing-your-first-burp-suite-extension ● Create a directory to store your extensions scripts, we will use this directory now onwards for our extension ● Download Jython standalone (.jar) from here: https://www.jython.org/download.html ● Keep this jar file in the same extension directory for convenience ● Configure Burp to use Jython. Extender -> Options -> Python Environment ● Create a python script and import necessary modules in that script ● Write BurpExtender Class i.e. class BurpExtender(IBurpExtender): ● Add your custom written Python script in Burp Extension ● Check for output or any error in popup window 36
  • 37. Basic Burp Extension using Python: Part 2 ● Once Burp extension Part 1 exercise is successful ● Add Own custom tab in HTTP request ● Show headers just like request headers in custom tab ● You would need to use ○ from burp import IMessageEditorTabFacory ○ from burp import IMessageEditorTab ● Add IMessageEditorTabFactory in class ● Get helpers object: self._helpers = callbacks.getHelpers() ● Register the object: callbacks.registerMessageEditorTabFactory ● Create a new instance to DisplayValues ● Define DisplayValues class with all the essential functions ● Verify if it’s showing the tab and contents within that tab 37
  • 38. Basic Burp Extension using Python: Part 3 (Try at Home) ● Once Burp extension Part 2 exercise is successful ● Create similar tab under Proxy->HTTP History->Response tab ● Loop through the response header contents ● Create a dictionary of security header with suggestions ● Look for security headers and ○ Show present or absent based on header presence compared with your list ○ Show if present security header is implemented properly ● Note: You might need to go through few of the Burp Extender APIs Code snippets 38
  • 39. Learning Resources ● Violent Python ● Black hat Python ● Automating boring stuffs ● Python for Pentesters by Vivek Ramachandran ● Python for everybody specialization (Coursera) ● Black Hat Python for Pentesters and Hackers - Video (PackT) ● Cracking Codes with Python 39
  • 40. What’s Next ● Python for Network Security ● Python for Security Automation ● Exploits in Python ● Secure Coding in Python ● AI/ML in Cybersecurity using Python ● Python for Crypto ● Malware Analysis using Python ● Forensics using Python ● And many more 40
  • 41. 41