2. Agenda
• About me
• History of Python
• About Python
• Python’s uses
• Python basics (Python 101)
• CSAW Crypto Redux
• Extra credit
• Resources
• Tips, tricks, observations
3. About me
Who am I?
• Husband/father/geek/gets distracted by shiny
objects easy
• Career path switched to IT in 1999, professionally an
IT guy since 2001
– Started the infosec career path switch in
2009, officially an infosec professional since
2012(?)
• Vbscript – 2007
• Python – 2011
4. History of Python
• Conceived in the late 1980’s by Guido van Rossum at CWI.
• Was designed to be a successor to the ABC programming
language
• Benevolent Dictator for Life (BDFL)
• Currently employed by Google where he spends half his time
working on Python development
• Python 2.0 was release on October 16th, 2000
• Contained many major new features
• Full garbage collector (automatic memory management)
• Unicode support
• Biggest change – development process with a shift towards
more transparent and community-backed process
• Python 3.0 was released on December 2008
• Many major features have been back ported to Python 2.6 and
2.7
5. About Python
• What is Python?
• Python is a general-purpose, high-level programming language whose
design philosophy emphasizes code readability. Python claims to
"[combine] remarkable power with very clear syntax", and
its standard library is large and comprehensive. Its use of indentation
for block delimiters is unique among popular programming languages.
• Why is it called Python?
• When he began implementing Python, Guido van Rossum was also
reading the published scripts from “Monty Python’s Flying Circus”, a
BBC comedy series from the 1970s. Van Rossum thought he needed a
name that was short, unique, and slightly mysterious, so he decided
to call the language Python.
• Fun fact - The built in IDE is named after Eric Idle, a member of
Monty Python.
6. What is Python good for?
• Python comes with a large standard library that covers areas such as;
• string processing (regular expressions, Unicode, calculating differences between
files)
• Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming)
• software engineering (unit testing, logging, profiling, parsing Python code)
• operating system interfaces (system calls, file systems, TCP/IP sockets)
• Artificial intelligence (because of similarities to Lisp)
• Extensive use in the information security industry, including exploit development.
• Network, debugging and reverse engineering, fuzzing, web, forensics, malware
analysis, PDF, etc.
• Easy to write short scripts for system admin work.
• Python code is easy to understand.
• Once the basic syntax is learned, even the most complicated scripts can make
sense.
• Python is cross platform!!
• It will work on Linux, Windows, Mac and most every other OS.
• Many, many resources and a big, friendly community
8. Python’s uses
• Applications • GUI frameworks
• BitTorrent • TKInter
• DropBox • PyQt
• Video games • wxPython
• Civilization IV • Embedded as a scripting language
• Battlefield 2 • Amarok
• Eve Online • GIMP
• Vampire: The Masquerade – • Autodesk Maya
Bloodlines • Commercial uses
• Graphics • Google apps
• Industrial Light & Magic • Reddit
• "The Phantom Menace", "The • YouTube
Mummy Returns" and other • Government
productions as ones where • CIA.gov
Python was used. • Python implementations
• Walt Disney Feature Animation • Cpython
• Science • IronPython – Python for .NET
• NASA and Mono platforms
• National Weather Service • Jython – Python coded in Java
9. Python basics
• Indentation does matter This will work But this won’t
if True: if True:
print "True" print "Answer"
else: print "True"
print "False“ else:
print "Answer"
print "False"
• If, If.. Else, If… Elif (no Then) If Else Elif statement
• Syntax is easy statement statement
if expression: if expression: if expression1:
statement(s) statement(s) statement(s)
else: elif expression2:
statement(s) statement(s)
else:
statement(s)
• All scripts are considered Entire module Partial method
modules import sys from sys import argv
• All functions inside
module can be used or
only certain methods can
be used inside script
10. Python basics
• Help is built in Help on modules Help on methods
>>> Import sys, hashlib >>> Import sys, hashlib
>>> help(sys) >>> help(sys.argv)
>>> help(hashlib) >>> help(hashlib.sha512)
>>> pydoc sys >>> pydoc sys.argv
>>> pydoc hashlib >>> pydoc hashlib.sha512
• It can be ran interactively Via command Via IDLE or
prompt DreamPie
python • IDLE is built in to Python
installs
Python 2.72 • DreamPie is a Python
Type “help”, “copyright”.. shell (best used on Linux)
>>>
15. My approach – Post CSAW
crypto challenges
Each challenge
1. Encrypted message inside script –
Output is decrypted
2. Encrypted message can be used as
an argument when calling script –
Output is decrypted
3. Encrypted message can be read
from a file for decrypting
Overall
1. One module for all
decrypting, each decryption style is
a method
18. Answer
Welcome to the 2011 NYU Poly CSAW CTF
event. We have planned many challenges for
you and we hope you have fun solving them
all. The key for this challenge is cryptography.
19. Wolfgang’s code
private static string AsciiToString(string encodedString)
{
string[] encodedChars = encodedString.Split(' ');
char[] decodedChars = new
char[encodedChars.Length];
for (int i = 0; i < decodedChars.Length; i++)
{
// Convert the number expressed in base-10 to an
integer
int codeNum = Convert.ToInt32(encodedChars[i], 10);
// Convert the integer to a character code
decodedChars[i] = Convert.ToChar(codeNum);
}
return new string(decodedChars);
}
21. My code
Option # 1 – Encrypted message inside script – Output is decrypted
#!/usr/bin/python
Import sys
code1 =
(87,101,108,99,111,109,101,32,116,111,32,116,104,101
,32,50,48,49,49,32,78,89,85,32,80,111,108,121,32,67,83
,65,87,32,67,84,70,32,101,118,101,110,116,46,32,87,10
1,32,104,97,118,101,32,112,108,97,110,110,101,100,32,
109,97,110,121,32,99,104,97,108,108,101,110,103,101,
115,32,102,111,114,32,121,111,117,32,97,110,100,32,1
19,101,32,104,111,112,101,32,121,111,117,32,104,97,1
18,101,32,102,117,110,32,115,111,108,118,105,110,103
,32,116,104,101,109,32,97,108,108,46,32,84,104,101,32
,107,101,121,32,102,111,114,32,116,104,105,115,32,99,
104,97,108,108,101,110,103,101,32,105,115,32,99,114,
121,112,116,111,103,114,97,112,104,121,46)
for i in code1:
code1a = int(i)
codefinal = chr(code1a)
sys.stdout.write(codefinal)
22. My code
Option # 2 – Encrypted message can be used
as an argument when calling script – Output is
decrypted
#!/usr/bin/python
import sys
if len(sys.argv)<2:
sys.exit("Usage " + sys.argv[0] + " <Unicode data you wish to
decode>n")
code1 = (sys.argv[1])
code_split = code1.split(':')
for i in code_split:
code1a = int(i)
codefinal = chr(code1a)
sys.stdout.write(codefinal)
23. My code
Option # 3 - Encrypted message can be read
from a file for decrypting
#!/usr/bin/python
import binascii, sys
f = open ('unicode.txt', 'r')
file = f.read()
code_split = file.split(':')
for decode in code_split:
decode1 = int(decode)
codefinal = chr(decode1)
sys.stdout.write(codefinal)
f.close ( )
25. Answer
Last weeks meeting was a great success. We
seem to be generating a lot of buzz about the
movement. The key for next weeks meeting is
resistance. If there is anyone else you know of
that may be interested in joining bring them to
the meeting this week. It will be held same
time, same place.
26. Wolfgang’s code
private static string AsciiHexToString(string encodedString)
{
string[] encodedChars = encodedString.Split(':');
char[] decodedChars = new char[encodedChars.Length];
for (int i = 0; i < decodedChars.Length; i++)
{
// Convert the number expressed in base-16 to an
integer
int codeNum = Convert.ToInt32(encodedChars[i], 16);
// Convert the integer to a character code
decodedChars[i] = Convert.ToChar(codeNum);
}
return new string(decodedChars);
}
29. My code
Option # 2 – Encrypted message can be used as an
argument when calling script – Output is decrypted
#!/usr/bin/python
import sys, binascii
if len(sys.argv)<2:
sys.exit("Usage " + sys.argv[0] + " <Unicode data you wish to decode>n")
code1 = (sys.argv[1])
hex_split = code1.split(':')
for decode in hex_split:
hex_decode = binascii.a2b_hex(decode)
sys.stdout.write(hex_decode)
30. My code
Option # 3 - Encrypted message can be
read from a file for decrypting
#!/usr/bin/python
import binascii, sys
f = open ('hex.txt', 'r')
file = f.read()
hex_split = file.split(':')
for decode in hex_split:
hex_decode = binascii.a2b_hex(decode)
sys.stdout.write(hex_decode)
f.close ( )
32. Answer
Last weeks meeting was a great success. We
seem to be generating a lot of buzz about the
movement. The key for next weeks meeting is
resistance. If there is anyone else you know of
that may be interested in joining bring them to
the meeting this week. It will be held same time,
same place.
33. Wolfgang’s code
private static string BinaryToString(string encodedString)
{
char[] decodedChars = new char[encodedString.Length /
8];
for (int i = 0; i < decodedChars.Length; i++)
{
// Convert the number in binary (base-2) to an integer
int codeNum =
Convert.ToInt32(encodedString.Substring(i *
8, 8), 2);
// Convert the integer to a character code
decodedChars[i] = Convert.ToChar(codeNum);
}
return new string(decodedChars);
}
35. #!/usr/bin/python
import math, sys
My code
# v = value to split, l = size of each chunk
f = lambda v, l: [v[i*l:(i+1)*l] for i in range(int(math.ceil(len(v)/float(l))))]
basecode = f ('0100110001100001011100110111010000100000011101110110010101100101
0110101101110011001000000110110101100101011001010111010001101001011011100110011
1001000000111011101100001011100110010000001100001001000000110011101110010011001
0101100001011101000010000001110011011101010110001101100011011001010111001101110
0110010111000100000010101110110010100100000011100110110010101100101011011010010
0000011101000110111100100000011000100110010100100000011001110110010101101110011
0010101110010011000010111010001101001011011100110011100100000011000010010000001
1011000110111101110100001000000110111101100110001000000110001001110101011110100
1111010001000000110000101100010011011110111010101110100001000000111010001101000
0110010100100000011011010110111101110110011001010110110101100101011011100111010
0001011100010000001010100011010000110010100100000011010110110010101111001001000
0001100110011011110111001000100000011011100110010101111000011101000010000001110
1110110010101100101011010110111001100100000011011010110010101100101011101000110
1001011011100110011100100000011010010111001100100000011100100110010101110011011
0100101110011011101000110000101101110011000110110010100101110001000000100100101
1001100010000001110100011010000110010101110010011001010010000001101001011100110
0100000011000010110111001111001011011110110111001100101001000000110010101101100
0111001101100101001000000111100101101111011101010010000001101011011011100110111
1011101110010000001101111011001100010000001110100011010000110000101110100001000
0001101101011000010111100100100000011000100110010100100000011010010110111001110
1000110010101110010011001010111001101110100011001010110010000100000011010010110
1110001000000110101001101111011010010110111001101001011011100110011100100000011
0001001110010011010010110111001100111001000000111010001101000011001010110110100
1000000111010001101111001000000111010001101000011001010010000001101101011001010
1100101011101000110100101101110011001110010000001110100011010000110100101110011
0010000001110111011001010110010101101011001011100010000001001001011101000010000
0011101110110100101101100011011000010000001100010011001010010000001101000011001
0101101100011001000010000001110011011000010110110101100101001000000111010001101
0010110110101100101001011000010000001110011011000010110110101100101001000000111
00000110110001100001011000110110010100101110',8)
for code in basecode:
x = (code)
decodea = int(code,2)
decodeb = chr(decodea)
Option # 1 – Encrypted message inside
sys.stdout.write(decodeb) script – Output is decrypted
36. My code
Option # 2 – Encrypted message can be used as an
argument when calling script – Output is decrypted
import sys, math
if len(sys.argv)<2:
sys.exit("Usage " + sys.argv[0] + " <binary code you wish
to decode>n")
f = lambda v, l: [v[i*l:(i+1)*l] for i in
range(int(math.ceil(len(v)/float(l))))]
basecode = f(sys.argv[1],8)
for code in basecode:
x = (code)
decodea = int(code,2)
decodeb = chr(decodea)
sys.stdout.write(decodeb)
37. My code
Option # 3 - Encrypted message can be
read from a file for decrypting
#!/usr/bin/python
import math, sys
f = open ('binary.txt', 'r')
file = f.read()
f1 = lambda v, l: [v[i*l:(i+1)*l] for i in
range(int(math.ceil(len(v)/float(l))))]
basecode = f1(file,8)
for code in basecode:
x = (code)
decodea = int(code,2)
decodeb = chr(decodea)
sys.stdout.write(decodeb)
f.close ( )
39. Answer
That meeting was a little crazy. We have
no idea where those guys in the black
suits came from, but we are looking into
it. Use the key infiltration for next week’s
meeting. Stay with the cause and we will
succeed.
43. My code
Option # 2 – Encrypted message can be used as an
argument when calling script – Output is decrypted
#!/usr/bin/python
import sys
if len(sys.argv)<2:
sys.exit("Usage " + sys.argv[0] + " <Base64
code you wish to decode>n")
basecode = sys.argv[1]
answer=basecode.decode('base64','strict')
print "This is the encoded message : " +
sys.argv[1]
print "This is the decoded message : " +
answer
44. My code
Option # 3 - Encrypted message can be
read from a file for decrypting
#!/usr/bin/python
f = open ('base64.txt', 'r')
file = f.read()
answer=file.decode('base64','strict')
print answer
f.close ( )
45. CSAW Crypto Redux
Crypto challenge # 5
Cipher text: JR UNIR QVFPBIRERQ GUNG BHE YNFG
GUERR GENAFZVFFVBAF JR'ER RNFVYL
QRPVCURERQ. JR UNIR GNXRA PNER BS GUR CNEGL
ERFCBAFVOYR SBE GURVE RAPBQVAT NAQ NER ABJ
HFVAT N ARJ ZRGUBQ. HFR GUR VASBEZNGVBA
CEBIVQRQ NG YNFG JRRX.F ZRRGVAT GB QRPVCURE
NYY ARJ ZRFFNTRF. NAQ ERZRZORE, GUVF JRRX.F
XRL VF BOSHFPNGRQ.
46. Answer
We have discovered that our last three
transmissions we're easily deciphered. We
have taken care of the party responsible for
their encoding and are now using a new
method. Use the information provided at
last week.s meeting to decipher all new
messages. And remember, this week's key is
obfuscated.
47. Wolfgang’s code (part 1)
private static string RotToString(string
encodedString, int rotation)
{
// Boundary check because this only works
for ROT1 thru ROT26
if (rotation < 0 | rotation > 26) { throw new
Exception("RotToString only supports ROT1
thru ROT26."); }
char[] encodedChars =
encodedString.ToArray();
char[] decodedChars = new
char[encodedChars.Length];
int A = Convert.ToInt32('A'); // 65
int Z = Convert.ToInt32('Z'); // 90
int a = Convert.ToInt32('a'); // 97
int z = Convert.ToInt32('z'); // 122
48. Wolfgang’s code (part 2)
for (int i = 0; i < decodedChars.Length; i++)
{
int codeNum = Convert.ToInt32(encodedChars[i]);
// Rotate capital letters A-Z 65-90
if (codeNum >= A && codeNum <= Z)
{
codeNum = codeNum - rotation;
if (codeNum < A) { codeNum = Z - (A - codeNum) + 1; }
}
// Rotate lower-case letters a-z 97-122
if (codeNum >= a && codeNum <= z)
{
codeNum = codeNum - rotation;
if (codeNum < a) { codeNum = z - (a - codeNum) + 1; }
}
// Convert the integer to a character code
decodedChars[i] = Convert.ToChar(codeNum);
51. My code
Option # 1 – Encrypted message inside script –
Output is decrypted
#!/usr/bin/python
rot13 = ('JR UNIR QVFPBIRERQ GUNG BHE
YNFG GUERR GENAFZVFFVBAF JR ER RNFVYL
QRPVCURERQ. JR UNIR GNXRA PNER BS GUR
CNEGL ERFCBAFVOYR SBE GURVE RAPBQVAT
NAQ NER ABJ HFVAT N ARJ ZRGUBQ. HFR GUR
VASBEZNGVBA CEBIVQRQ NG YNFG JRRX.F
ZRRGVAT GB QRPVCURE NYY ARJ ZRFFNTRF.
NAQ ERZRZORE, GUVF JRRX.F XRL VF
BOSHFPNGRQ.')
answer=rot13.decode('rot13','strict')
print answer
52. My code
Option # 2 – Encrypted message can be used as an
argument when calling script – Output is
decrypted
#!/usr/bin/python
import sys
if len(sys.argv)<2:
sys.exit("Usage " + sys.argv[0] + " <ROT13 code you
wish to decode>n")
basecode = sys.argv[1]
answer=basecode.decode('rot13','strict')
print "This is the encoded message : " + sys.argv[1]
print "This is the decoded message : " + answer
53. My code
Option # 3 - Encrypted message can be
read from a file for decrypting
#!/usr/bin/python
f = open ('rot13.txt', 'r')
file = f.read()
answer=file.decode('rot13','strict')
print answer
f.close ( )
54. My final one – Encrypt/decrypt module
#!/usr/bin/python
import sys
def hexdecode(hex_key):
import binascii
hex_split = hex_key.split(':')
for decode in hex_split:
hex_decode = binascii.a2b_hex(decode)
sys.stdout.write(hex_decode)
def uni_decode(unicode_key):
unicode_split=unicode_key.split(':')
for i in unicode_split:
code1a = int(i)
codefinal = chr(code1a)
sys.stdout.write(codefinal)
def base64_decode(base64_key):
answer=base64_key.decode('base64','strict')
print answer
def binary_decode(binary_key):
import math
f = lambda v, l: [v[i*l:(i+1)*l] for i in range(int(math.ceil(len(v)/float(l))))]
basecode = f (binary_key,8)
for code in basecode:
x = (code)
decodea = int(code,2)
decodeb = chr(decodea)
sys.stdout.write(decodeb)
def rot13_decode(rot13_key):
answer=rot13_key.decode('rot13','strict')
print answer
58. Coding for Penetration Testers book Extra credit
Script Function Learned Success?
Webcheck_v1.py Monitor web server – verify it 1. Script arguments Yes
remains up 2. Connect to web server and run a GET request
Webcheck_v2.py Monitor web server – verify it 1. Alternate script arguments method No
remains up (default to port 80)
Subnetcalc.py Calculate subnet mask, broadcast 1. Parse out values programmatically Yes
address, network range, and gateway 2. Math functions with variables
from IP/CIDR 3. Displaying results
4. Using FOR loops
Pass.py Determines if users are using the 1. Use the crypt module No
original default assigned password
Robotparser.py Retrieve the paths from the robot.txt No
root_check.py Checks to see what permissions 1. Using IF and ELIF conditional statements Yes
logged in account has (normal user,
root or system account)
Readshadow.py Checks to see if you have permission 1. Tests permissions on files to see if current Yes
to read /etc/shadow credentials can read file
Network_socket. Connect to website, pull contents 1. Network socket creation Yes
py (hard coded) 2. Spaces will bite you in the ass where you least
expect it.
59. Coding for Penetration Testers book Extra credit
Script Function Learned Success?
network_socket_argum Connect to website, pull contents 1. Network socket creation Yes
ent.py (site specified by argument) 2. Spaces will bite you in the ass where you
least expect it.
Server_connect.py Once a connection is made, send 1. Network socket creation Yes
back a string 2. Allow incoming connections.
server_shell.py No
receiveICMP.py To receive a file from another 1. Python script using Scapy Yes
system via ICMP (in conjunction
with sendICMP.py)
sendICMP.py To send a file to another system 1. Python script using Scapy Yes
via ICMP (in conjunction with
receiveICMP.py)
60. All the scripts Extra credit
Category Script
CSAW Crypto
Redux –
Challenge 1 to
5
Extra credit
Coding for
Penetration
Testers – part 1
Coding for
Penetration
Testers – part 2
Coding for
Penetration
Testers – part 3
Extra extra
credit
62. Scapy Extra extra credit
• Packet creation • Classic attacks
• Read PCAP files • Malformed packets
• Create graphical dumps • Ping of death
• Must have appropriate supporting • Nestea attack
tools installed • ARP cache poisoning
• Fuzzing • Scans
• Send and receive packets • SYN scan
• TCP traceroute (can do graphical dump • ACK scan
as well) • XMAS scan
• Sniffing • IP scan
• Send and receive files through • TCP port scan
alternate data channels (ICMP) • IKE scan
• Ping • Advanced traceroute
• ARP ping • TCP SYN traceroute
• ICMP ping • UDP traceroute
• TCP ping • DNS traceroute
• UDP ping • VLAN hopping
• Wireless frame injection • Wireless sniffing
• OS Fingerprinting • Firewalking
63. Scripts I created Extra extra extra credit
Script Function
URL deobfuscator – To read the
shortened URL website and tell
you the title.
Word list creator
64. Little gems I found Extra extra credit
Description Function Site
Python-nmap It’s a Python library which helps in http://xael.org/norman/python/python-
using nmap. nmap/
Python API to the VirtualBox Allowing you to control every http://download.virtualbox.org/virtualbox
VM aspect of virtual machine /SDKRef.pdf
configuration and execution
Py2Exe py2exe is http://www.py2exe.org/
a Python Distutils extension
which converts Python scripts
into executable Windows
programs, able to run without
requiring a Python installation.
Chrome Various extensions/applications • https://chrome.google.com/webstore/
extensions/applications found in the Chrome Webstore detail/gdiimmpmdoofmahingpgabiikim
jgcia <-- Python shell (browser button)
• https://chrome.google.com/webstore/
detail/cmlchnlmkdcpelgmkebknjgjgdd
ncelc - Python shell (Chrome
application)
• https://chrome.google.com/webstore/
detail/nckbgikkpbjdliigbhgjfgfcahhona
kp <-- Online Python development
environment
65. Little gems I found Extra extra credit
Description Function Site
Tweepy It’s the best working Python http://tweepy.github.com/
library to interface with Twitter
(so far)
70. Tips, tricks, etc.
IDE (http://wiki.python.org/moin/IntegratedDevelopmentEnvironments)
• Windows
• PyScripter
• Aptana Studio
• IDLE
• Ninja
• Pycrust (it’s actually a shell)
• Part of wxPython
• Linux
• IDLE
• Geany
• Python Toolkit
• SPE
• ERIC (supposed to have auto-complete of code…)
• Pycrust (it’s actually a shell)
• Part of wxPython
• DreamPie (it’s actually a shell)
Editors (http://wiki.python.org/moin/PythonEditors)
• Windows
• Notepad++
• Linux
• Gedit
• SCiTE
71. Tips, tricks, etc.
Linux vs. Windows
Linux
• Linux scripts can be ran via terminal
• calling python <script name>
• by putting #!/usr/bin/python at the top (path
to interpreter) and typing ./<script name>
• Common problem on PyScripter
(awesome Windows Python IDE)… extra
code comments are put at the top, then
the #! /usr/bin/python
Windows
• Windows scripts don’t need the #! but need to have
.py associated with Python interepreter.
• Scripts can be double clicked or ran from
command prompt python <script name>
• If the script is double clicked, without
having raw_input("Press ENTER to exit")
you may not see the output of the script.
72. Portable Python (Windows only)
• Portable Python is a Python® programming
Tips, tricks, etc.
language preconfigured to run directly from any USB
storage device, enabling you to have, at any time, a
portable programming environment. Just download
it, extract to your portable storage device or hard
drive and in 10 minutes you are ready to create your
next Python® application.
• Portable Python 2.7.2.1 package contains
following applications/libraries:
• PyScripter v2.4.1
• NymPy 1.6.0
• SciPy 0.90
• Matplotlib 1.0.1
• PyWin32 216
• Django 1.3
• PIL 1.1.7
• Py2Exe 0.6.9
• wxPython 2.8.12.0
• Portable Python 3.2.1.1 package contains
following applications/libraries (alphabetical
order):
• NetworkX v1.4
• PySerial 2.5
• PyScripter v2.4.1
• PyWin32 v.216
• RPyC-3.0.7
73. Etc.
Antigravity
• When you open up ModulesDocs and
click on antigravity module or from IDLE
run import antigravity, a web browser
opens to the XKCD cartoon at the
beginning of this slide deck.
Zen of Python
• To start the path of finding Zen of Python,
remember these two key words…
IMPORT THIS .
• From an IDE (IDLE) or a Python shell,
run import this and the Zen of
Python will be revealed.