Python for exploit developers part1

Introduction

Welcome to python for exploit developers course, in this course we’ll focus on how we can use Python programming language for us as exploit developers.

This course doesn’t require any prerequisites, as it starts from scratch, and then dives into the advanced topics.

As exploit development is not only limited to binary exploitation we’ll extend this course to talk about even networking and enumeration with python.

If you are a beginner hacker or network engineer and even if you have very long experience in programming you’ll this course is also for you to expand your skills.

In this post i’ll talk about the usage of the language in general and the syntax such as arrays, lists, dictionaries classes and some networking stuff.

Let’s get started

You can download and install Python on your operating system from here

Once installed, you’ll be able to run the python from the terminal, for this course, I assume you’re using Kali Linux which comes with embedded python and you don’t have to install or download it.

print "I love Buffer Overflow"

Defining variables

msg = "my private message"
print msg

Concatenation (combing strings)

part1 = 'Buffer'
part2 = 'Overflow'
fullWord = part1 + ' ' + part2
print(fullWord)
#Output Buffer Overflow

Working with Lists:A list stores a series of items in a particular order. You access items using an index, or within a loop.

mylist = ['item1', 'item2', 'item3']
mylist.append('item4')
itemVar = mylist[0]
print itemVar
#output item1

#Build a list and print the items in the list
dogs = []
dogs.append('willie')
dogs.append('hootz')
dogs.append('peso')
dogs.append('goblin')
for dog in dogs:
    print("Hello " + dog + "!")
print("I love these dogs!")
print("\nThese were my first two dogs:")
old_dogs = dogs[:2]
for old_dog in old_dogs:
    print(old_dog)
del dogs[0]
dogs.remove('peso')
print(dogs

Dictionaries: Dictionaries store connections between pieces of information. Each item in a dictionary is a key-value pair.

 stuff = {'color': 'black', 'points': 5}
print("Buffer Overflow color is " + stuff['black'])
#output: Buffer Overflow color is black

Tuples: A tuple is like a list, except you can’t change the values in a tuple once it’s defined. Tuples are good for storing information that shouldn’t be changed throughout the life of a program. Tuples are designated by parentheses instead of square brackets. (You can overwrite an entire tuple, but you can’t change the individual elements in a tuple.)

dimensions = (800, 600)

#Looping through a tuple
for dimension in dimensions:
    print(dimension)

#Overwriting a tuple
dimensions = (800, 600)
print(dimensions)
dimensions = (1200, 900)

If statements: used to test for particular conditions and respond appropriately.

myAge = 30
if myAge < 50:
... print "I am still young"

#output I am still young

User Input: Your programs can prompt the user for input. All input is stored as a string.

name = input("What's your name? ")
print("Hello, " + name + "!"

// Prompting for numerical input
age = input("How old are you? ")
age = int(age)

While Loops: A while loop repeats a block of code as long as a certain condition is true.

current_value = 1
while current_value <= 5:
    print(current_value)
    current_value += 1
#Output: 
1
2
3
4
5

#The Range Function
#Printing the numbers 0 to 1000
  for number in range(1001):
    print(number)

#Printing the numbers 1 to 1000
 for number in range(1, 1001):
    print(number)

# Making a list of numbers from 1 to a million
numbers = list(range(1, 1000001))

#Using a loop to generate a list of square numbers
 squares = []
for x in range(1, 11):
    square = x**2
    squares.append(square)

# Using a comprehension to generate a list of square numbers
squares = [x**2 for x in range(1, 11)]

#Using a loop to convert a list of names to upper case
names = ['kai', 'abe', 'ada', 'gus', 'zoe']
upper_names = []
for name in names:
    upper_names.append(name.upper())

Functions: Functions are named blocks of code, designed to do one specific job. Information passed to a function is called an argument, and information received by a function is called a parameter.

def greet_user():
    """Display a simple greeting."""
    print("Hello!")
greet_user()


#Passing an argument
def greet_user(username):
    """Display a personalized greeting."""
    print("Hello, " + username + "!")
greet_user('jesse')

#   Default values for parameters
def make_pizza(topping='bacon'):
    """Make a single-topping pizza."""
    print("Have a " + topping + " pizza!")
make_pizza()
make_pizza('pepperoni')


#  Returning a value
def add_numbers(x, y):
    """Add two numbers and return the sum."""
    return x + y
sum = add_numbers(3, 5)
print(sum)

Exceptions: Exceptions help you respond appropriately to errors that are likely to occur. You place code that might cause an error in the try block. Code that should run in response to an error goes in the except block. Code that should run only if the try block was successful goes in the else block.

prompt = "How many tickets do you need? "
num_tickets = input(prompt)
try:
    num_tickets = int(num_tickets)
except ValueError:
    print("Please try again.")
else:
    print("Your tickets are printing.")

Working with files: Your programs can read from files and write to files. Files are opened in read mode (‘r’) by default, but can also be opened in write mode (‘w’) and append mode (‘a’).

#   Reading a file and storing its lines
filename = 'siddhartha.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line)

#Writing to a file
filename = 'journal.txt'
with open(filename, 'w') as file_object:
     file_object.write("I love programming.")

# Appending to a file
filename = 'journal.txt'
with open(filename, 'a') as file_object:
    file_object.write("\nI love making games.")

Classes: A class defines the behavior of an object and the kind of information an object can store. The information in a class is stored in attributes, and functions that belong to a class are called methods. A child class inherits the attributes and methods from its parent class.

# Creating a dog class
class Dog():
    """Represent a dog."""
    def __init__(self, name):
        """Initialize dog object."""
        self.name = name
    def sit(self):
    """Simulate sitting."""
        print(self.name + " is sitting.")
my_dog = Dog('Peso')
print(my_dog.name + " is a great dog!")
my_dog.sit()

#Inheritance
 class SARDog(Dog):
    """Represent a search dog."""
    def __init__(self, name):
        """Initialize the sardog."""
        super().__init__(name)
    def search(self):
        """Simulate searching."""
        print(self.name + " is searching.")
my_dog = SARDog('Willie')
print(my_dog.name + " is a search dog.")
my_dog.sit()
my_dog.search()

sys module: This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.

import sys
if len(sys.argv)==2:
      name = sys.argv[1]
      print "[+] Hello : "+name

#running the file
root@kali# python file.py bufferOverflow 
[+] Hello : bufferOverflow

For the complete list click here

Leave a Reply