Python Fundamentals

Hello all,

It's time to take a bit of a tangent and discuss a very readable, maintainable, c based, and large community supported language, Python! Why are we looking into Python? Python is used to write many tools that pen testers/hackers use on a daily basis, such as nmap. It can also be easily invoked in a shell which has many uses.

Recall the first post on buffer overflow attacks? Python can be invoked in gdb (an assembler debugging tool) to execute shell code for a buffer overflow attack:

(gdb) run $(python -c '"\x90" * bytes + "\x31\xc0\x83\xec\x01\x88\x04\x24\x68\x2f\x7a\x73\x68\x68\x2f\x62\x69\x6e\x68\x2f\x75\x73\x72\x89\xe6\x50\x56\xb0\x0b\x89\xf3\x89\xe1\x31\xd2\xcd\x80\xb0\x01\x31\xdb\xcd\x80" + "return_addr" * 10)

Where bytes is the number of bytes required to overwrite a program's return address and return_addr is any address that returns the program into the NOP sled.

Python is powerful! So it is worth while to learn it. Let's create a simple port scanner to look at some of the language features of Python. The program is below:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = '<server ip or domain name>'

def pscan(port):
    try:
        s.connect((server,port))
        return True
    except:
        return False

for port_num in range(1,65535):
    if pscan(port_num):
        print(port_num,'is open')
    else:
        print(port_num,'is closed')

In the program above, we are importing the socket library which gives us access to the connect and socket functions. We define a pscan function which accepts a port as parameter and tries to connect to the server's address and passed in port number. The for loop at the bottom iterates through all 65,535 ports and if the pscan is able to successfully connect to the port, it will indicate the port is open.

Notice that unlike other languages, python does not require semicolons to terminate lines. Lines are instead terminated by a new line and blocks of code are indicated by 4 spaces which forces indentation. A lot of these concepts are explained by the zen of python which is pep 20 in the python documentation found below:

https://www.python.org/dev/peps/pep-0020/

Another great tutorial channel is Sentdex. The program above was barrowed from him and his citation is below:

sentdex. (2014, Aug 17). Python 3 Programming Tutorial - Sockets simple port scanner. Retrieved From  https://www.youtube.com/watch?v=szm3camsf8k

Comments

Popular posts from this blog

Covering Your Tracks

Covering Your Tracks - Anti-forensics for the Cloud - Introduction

Cross-Site Scripting (XSS) Introduction