SlideShare uma empresa Scribd logo
1 de 41
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
Jurczyk windows kernel reference count vulnerabilities. case study
Jurczyk   windows kernel reference count vulnerabilities. case studyJurczyk   windows kernel reference count vulnerabilities. case study
Jurczyk windows kernel reference count vulnerabilities. case studyDefconRussia
 
Machine learning in php
Machine learning in phpMachine learning in php
Machine learning in phpDamien Seguy
 
Python na Infraestrutura 
MySQL do Facebook

Python na Infraestrutura 
MySQL do Facebook
Python na Infraestrutura 
MySQL do Facebook

Python na Infraestrutura 
MySQL do Facebook
Artur Rodrigues
 
Python internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvandPython internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvandirpycon
 
What’s eating python performance
What’s eating python performanceWhat’s eating python performance
What’s eating python performancePiotr Przymus
 
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPatrick Allaert
 
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...Piotr Przymus
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
Gae icc fall2011
Gae icc fall2011Gae icc fall2011
Gae icc fall2011Juan Gomez
 
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...Piotr Przymus
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 

Mais procurados (20)

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

Python na Infraestrutura 
MySQL do Facebook
Python na Infraestrutura 
MySQL do Facebook

Python na Infraestrutura 
MySQL do Facebook

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

Semelhante a Python for web security - beginner

An Overview of SystemVerilog for Design and Verification
An Overview of SystemVerilog  for Design and VerificationAn Overview of SystemVerilog  for Design and Verification
An Overview of SystemVerilog for Design and VerificationKapilRaghunandanTrip
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - englishJen Yee Hong
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.pptUdhayaKumar175069
 
Survey of programming language getting started in C
Survey of programming language getting started in CSurvey of programming language getting started in C
Survey of programming language getting started in Cummeafruz
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functionsray143eddie
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.pptAlefya1
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersJayaram Sankaranarayanan
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.pptJoshCasas1
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdflailoesakhan
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxshivam460694
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python ProgrammingDozie Agbo
 
OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical MementoOdoo
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with PythonSushant Mane
 

Semelhante a Python for web security - beginner (20)

An Overview of SystemVerilog for Design and Verification
An Overview of SystemVerilog  for Design and VerificationAn Overview of SystemVerilog  for Design and Verification
An Overview of SystemVerilog for Design and Verification
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
More about PHP
More about PHPMore about PHP
More about PHP
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Survey of programming language getting started in C
Survey of programming language getting started in CSurvey of programming language getting started in C
Survey of programming language getting started in C
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical Memento
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
 

Último

Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 

Último (20)

Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

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