forked from sensepost/birp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbirp.py
executable file
·548 lines (508 loc) · 18.1 KB
/
birp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
#!/usr/bin/env python
from py3270wrapper import WrappedEmulator
import tn3270
import sys
import argparse
import re
import platform
from time import sleep
from os import path
from colorama import Fore,Back,Style,init
from IPython import embed
from getch import getch
import pickle
from pprint import pprint
from encodings import utf_8
# Big Iron Recon & Pwnage (BIRP) is a TN3270 z/OS application assessment tool.
# Written by Dominic White (@singe) at SensePost
# It's homepage is available at https://github.com/sensepost/birp
# Big Iron Recon & Pwnage by SensePost is licensed under a Creative Commons
# Attribution-ShareAlike 4.0 International License. Permissions beyond the
# scope of this license may be available at http://sensepost.com/contact us/.
# todo allow field marker edits
# todo build replay
# todo intruder functionality
# Menus are here because folds don't like them
menu_list = "\nBIRP Menu\n\
=========\n\n\
1 - Interactive Mode\n\
2 - View History\n\
3 - Find Transaction\n\
4 - Python Console\n\
5 - Save History\n\
X - Quit\n\n\
Selection: "
interactive_help = "\nInteractive mode help\n\
=====================\n\n\
Hit ESC to exit interactive mode.\n\n\
Most keys will be passed directly to x3270. Except:\n\
Ctrl-c - Clear\n\
Ctrl-q/w/e - PA1, PA2, PA3\n\
Ctrl-r - Re-print the markedup view of the current screen\n\
Ctrl-u - Manually push the last interaction as a transaction\n\
Ctrl-p - Drop to Python interactive shell\n\
Ctrl-s - Create timestampe'd HTML file of the current screen\n\
Ctrl-k - Color key\n\
Ctrl-h - This help\n\
Alt-F8-11 - PF13-16\n\
Alt-F12 - PF24\n\n\
Hitting Enter, any of the PF/PA keys, or Ctrl-u will record a transaction."
color_key = u"\nColor Key\n\
=========\n\n\
\u2219\t\t\t- Start of field marker" + Style.RESET_ALL + "\n\
Hidden Fields\t\t- " + Back.RED + "Red background" + Style.RESET_ALL + "\n\
Modified Fields\t\t- " + Fore.YELLOW + "Yellow text" + Style.RESET_ALL + "\n\
Input Fields\t\t- " + Back.GREEN + "Green background" + Style.RESET_ALL + "\n\
"
#Intensified Fields\t- " + Style.BRIGHT + "Bright text" + Style.RESET_ALL + "\n\
# Print output that can be surpressed by a CLI opt
def logger(text, kind='clear', level=0):
if results.quiet and (kind == 'warn' or kind == 'info'):
return
else:
typdisp = ''
lvldisp = ''
if kind == 'warn': typdisp = '[!] '
elif kind == 'info': typdisp = '[+] '
elif kind == 'err': typdisp = '[#] '
elif kind == 'good': typdisp = '[*] '
if level == 1: lvldisp = "\t"
elif level == 2: lvldisp = "\t\t"
elif level == 3: lvldisp = "\t\t\t"
print lvldisp+typdisp+text
# Update a screen object with the latest x3270 screen
def update_screen(em,screen):
screen = tn3270.Screen(em.exec_command('ReadBuffer(Ascii)').data)
return screen
# Record the current screen, hit enter, and record the response
def exec_trans(em,history,key='enter'):
request = tn3270.Screen
response = tn3270.Screen
check = tn3270.Screen
request = update_screen(em,request)
keypress = ''
hostinfo = em.exec_command('Query(Host)').data[0].split(' ')
host = hostinfo[1]+':'+hostinfo[2]
data = request.modified_fields
if key == 'enter':
em.send_enter()
keypress = key
# PF1=1, PF24=24, PA1=25, PA3=27
elif key > 0 and key < 25:
keypress = 'PF(' + str(key) + ')'
em.exec_command(keypress)
elif key > 25 and key < 28:
keypress = 'PA(' + str(key - 24) + ')'
em.exec_command(keypress)
em.exec_command('Wait(1,3270Mode)') #Capture the whole 3270 screen
response = update_screen(em,response)
trans = tn3270.Transaction(request,response,data,keypress,host)
history.append(trans)
return trans
# Compare two screens, allow a "fuzzy" match to account for time/terminal fields
def compare_screen(screen1,screen2,exact=False):
diffcount = 0
linecount = 0
for line in screen1.rawbuffer:
if screen1.rawbuffer[linecount] != screen2.rawbuffer[linecount]:
diffcount += 1
if exact:
return 0
elif diffcount > 2:
return 0 # More than two lines different they're different
return True # screens are the same
# Currently unused
def find_first(history,text):
transid = 0
row = 0
rr = 0
col = 0
for trans in history:
row = 0
# Check the request
for line in trans.request.stringbuffer:
rr = 0
col = line.find(text)
if col >= 0:
return (transid,rr,row,col)
row += 1
row = 0
# Check the response
for line in trans.response.stringbuffer:
rr = 1
col = line.find(text)
if col >= 0:
return (transid,rr,row,col)
row += 1
transid += 1
return (-1,-1,-1,-1) # Not found
# Find text within the transaction history
def find_all(history,text):
result = list()
transid = 0
row = 0
rr = 0
col = 0
for trans in history:
row = 0
# Check the request
for line in trans.request.stringbuffer:
rr = 0
col = line.find(text)
if col >= 0:
result.append((transid,rr,row,col))
row += 1
row = 0
# Check the response
for line in trans.response.stringbuffer:
rr = 1
col = line.find(text)
if col >= 0:
result.append((transid,rr,row,col))
row += 1
transid += 1
return result
# Interactive mode, will record transactions, and display hacker view companion
def interactive(em,history):
key = ''
trans = ''
screen = ''
data = ''
logger("Interactive mode started! Hit ESC to exit",kind="info")
logger("Hit Ctrl-h for help. Start typing ...",kind="info")
while key != getch.KEY_ESC:
if not em.is_connected():
logger(Fore.RED+"Emulator not connected, interactive mode prevented."+Fore.RESET,kind="err")
return
key = getch()
if key == getch.KEY_UP: # Up
em.exec_command('Up()')
elif key == getch.KEY_DOWN: # Down
em.exec_command('Down()')
elif key == getch.KEY_LEFT: # Left
em.exec_command('Left()')
elif key == getch.KEY_RIGHT: # Right
em.exec_command('Right()')
elif key == getch.KEY_ENTER: # Enter
trans = exec_trans(em,history,'enter')
print trans.response.colorbuffer
logger('Enter entered',kind='info')
elif key == getch.KEY_CTRLr: # Ctrl-r print screen
screen = update_screen(em,screen)
print screen.colorbuffer
logger('Screen refreshed',kind='info')
elif key == getch.KEY_CTRLu: # Ctrl-u manually push transaction
screen = update_screen(em,screen)
data = screen.modified_fields
hostinfo = em.exec_command('Query(Host)').data[0].split(' ')
host = hostinfo[1]+':'+hostinfo[2]
trans = tn3270.Transaction(history.last().response,screen,data,'manual',host)
history.append(trans)
print screen.colorbuffer
logger('Transaction added',kind='info')
elif key == getch.KEY_CTRLh: # Ctrl-h help
print interactive_help
elif key == getch.KEY_CTRLk: # Ctrl-k color key
print color_key
elif key == getch.KEY_CTRLp: # Ctrl-p python shell
embed()
elif key == getch.KEY_CTRLs: # Ctrl-s screenshot
em.save_screen(str(trans.timestamp.date())+'_'+str(trans.timestamp.time())+'.html')
logger('Screenshot saved',kind='info')
elif key == getch.KEY_TAB: # Tab 9
em.exec_command('Tab()')
elif key == getch.KEY_BACKSPACE: # Backspace
em.exec_command('BackSpace()')
elif key == getch.KEY_DELETE: # Delete
em.exec_command('Delete()')
elif key == getch.KEY_CTRLc: # Ctrl-c Clear
em.exec_command('Clear()')
elif key == getch.KEY_CTRLq: # Ctrl-q PA1
trans = exec_trans(em,history,25)
print trans.response.colorbuffer
elif key == getch.KEY_CTRLw: # Ctrl-w PA2
trans = exec_trans(em,history,26)
print trans.response.colorbuffer
elif key == getch.KEY_CTRLe: # Ctrl-e PA3
trans = exec_trans(em,history,27)
print trans.response.colorbuffer
elif key > 31 and key < 127: # Alphanumeric
em.safe_send(chr(key))
elif key == getch.KEY_F1:
trans = exec_trans(em,history,1)
print trans.response.colorbuffer
elif key == getch.KEY_F2:
trans = exec_trans(em,history,2)
print trans.response.colorbuffer
elif key == getch.KEY_F3:
trans = exec_trans(em,history,3)
print trans.response.colorbuffer
elif key == getch.KEY_F4:
trans = exec_trans(em,history,4)
print trans.response.colorbuffer
elif key == getch.KEY_F5:
trans = exec_trans(em,history,5)
print trans.response.colorbuffer
elif key == getch.KEY_F6:
trans = exec_trans(em,history,6)
print trans.response.colorbuffer
elif key == getch.KEY_F7:
trans = exec_trans(em,history,7)
print trans.response.colorbuffer
elif key == getch.KEY_F8:
trans = exec_trans(em,history,8)
print trans.response.colorbuffer
elif key == getch.KEY_F9:
trans = exec_trans(em,history,9)
print trans.response.colorbuffer
elif key == getch.KEY_F10:
trans = exec_trans(em,history,10)
print trans.response.colorbuffer
elif key == getch.KEY_F11:
trans = exec_trans(em,history,11)
print trans.response.colorbuffer
elif key == getch.KEY_F12:
trans = exec_trans(em,history,12)
print trans.response.colorbuffer
elif key == getch.KEY_AltF8:
trans = exec_trans(em,history,13)
print trans.response.colorbuffer
elif key == getch.KEY_AltF9:
trans = exec_trans(em,history,14)
print trans.response.colorbuffer
elif key == getch.KEY_AltF10:
trans = exec_trans(em,history,15)
print trans.response.colorbuffer
elif key == getch.KEY_AltF11:
trans = exec_trans(em,history,16)
print trans.response.colorbuffer
elif key == getch.KEY_AltF12:
trans = exec_trans(em,history,24)
print trans.response.colorbuffer
def save_history(history,savefile):
if path.exists(savefile):
logger('Savefile exists, I won\'t overwrite yet',kind='err')
return False # Don't overwrite existing saves just yet
try:
sav = open(savefile,'w')
pickle.dump(history, sav)
sav.close()
except IOError:
logger('Saving didn\'t work.',kind='err')
return False
return True
def load_history(loadfile):
if not path.exists(loadfile):
logger("Couldn't find the history file" + loadfile + " bailing.",kind='err')
sys.exit(1)
try:
lod = open(loadfile,'r')
hist = pickle.load(lod)
lod.close()
except KeyError:
logger("That doesn't look like a BIRP file",kind='err')
sys.exit(1)
return hist
def print_trans(history,num,header):
trans = history[num]
if header:
print "\n",Fore.BLUE,"View Transaction",Fore.RESET
print Fore.BLUE,"================",Fore.RESET
print "\n",Fore.YELLOW,num,Fore.BLUE,trans.timestamp,Fore.CYAN,trans.key,\
"\t",Fore.BLUE,trans.host,trans.comment,Fore.RESET
print " Req : ",trans.request.stringbuffer[0]
for field in trans.data:
print " Data: row:",field.row,"col:",field.col,"str:",Fore.RED,field.contents,Fore.RESET
print " Resp: ",trans.response.stringbuffer[0],'\n'
# todo have print_history call print_trans rather
def print_history(history):
print "\n",Fore.BLUE,"Transaction List",Fore.RESET
print Fore.BLUE,"================",Fore.RESET,"\n"
count = 0
for trans in history:
print Fore.YELLOW,count,Fore.BLUE,trans.timestamp,Fore.CYAN,trans.key,\
"\t",Fore.BLUE,trans.host,trans.comment,Fore.RESET
print " Req : ",trans.request.stringbuffer[0]
for field in trans.data:
fieldtxt = field.contents.strip()
if len(fieldtxt) > 0:
print " Data: row:",field.row,"col:",field.col,"str:",Fore.RED,fieldtxt,Fore.RESET
print " Resp: ",trans.response.stringbuffer[0],"\n"
count += 1
def menu_save(history):
savefile = ''
logger(''.join([Fore.CYAN,'What file should I save to (must not exist): ',Fore.RESET]),kind='info')
savefile = sys.stdin.readline().strip()
if save_history(history,savefile):
logger(''.join([Fore.CYAN,'History saved to ',savefile,Fore.RESET]),kind='info')
def print_seq(history,start,stop):
print '\n' * 100
for trans in history[start:stop+1]:
print '\n' * 101
print trans.request
sleep(1)
print '\n' * 100
print Fore.RED,trans.key,Fore.RESET
print trans.response
sleep(1)
# this will print two copies of the individual screen
def screentofile(screen,path):
f = open(path+'.emu','w')
g = open(path+'.brp','w')
f.write(utf_8.encode(screen.emubuffer)[0])
g.write(utf_8.encode(screen.colorbuffer)[0])
f.close()
g.close()
def menu_screen(transaction, reqres):
#If reqres is True, we show the request, if False, we show the response
if reqres: screen = transaction.request
else: screen = transaction.response
key = ''
print screen.colorbuffer
while key != getch.KEY_x:
logger(''.join([Fore.CYAN,"Type 'f' to view the screen's fields or 'p' to view the un-markedup screen, 'e' to view the screen as an emulator would, 'r' to switch between the Request/Response, or 's' to export a copy to a text file (.brp/.emu). Type 'x' to go back.",Fore.RESET]),kind='info')
key = getch()
if key == getch.KEY_f or key == getch.KEY_F:
print Fore.BLUE,"View Fields",Fore.RESET
print Fore.BLUE,"===========",Fore.RESET,"\n"
pprint(screen.fields)
logger(''.join([Fore.RED,"Dropping into shell, check the",Fore.BLUE," screen ",Fore.RED,"object. Type quit() to return here.",Fore.RESET,"\n\n"]),kind='info')
embed()
elif key == getch.KEY_p or key == getch.KEY_p:
print '\n',screen
elif key == getch.KEY_e or key == getch.KEY_e:
print '\n',screen.emubuffer
elif key == getch.KEY_r or key == getch.KEY_r:
reqres = not reqres
if reqres:
screen = transaction.request
print Fore.BLUE,'REQUEST',Fore.RESET
else:
screen = transaction.response
print Fore.BLUE,'RESPONSE',Fore.RESET
print screen.colorbuffer
elif key == getch.KEY_s or key == getch.KEY_s:
filename = transaction.host+'_'+str(transaction.timestamp.date())+'_'+str(transaction.timestamp.time())
screentofile(screen, filename)
def menu_trans(history,num):
if num >= len(history) or num < 0:
logger(''.join([Fore.CYAN,"Whoops, that transaction doesn't exist.",Fore.RESET]),kind='info')
return 1
trans = history[num]
key = ''
while key != getch.KEY_x:
print_trans(history,num,True)
logger(''.join([Fore.CYAN,"Choose '1' to view the Request, and '2' to view the Response. Type 'j' to move to the next transaction, and 'k' to the previous. Type 'x' to go back.",Fore.RESET]),kind='info')
key = getch()
if key == getch.KEY_1:
menu_screen(trans, reqres=True) #reqres True shows request, False shows response
elif key == getch.KEY_2:
menu_screen(trans, reqres=False)
elif key == getch.KEY_j:
return menu_trans(history,num+1)
elif key == getch.KEY_k:
return menu_trans(history,num-1)
return 0
def menu_history(history):
choice = ''
while choice.lower() != 'x':
print_history(history)
logger(''.join([Fore.CYAN,'Choose a transaction to view with the appropriate numeric key. Hit x, then enter to go back.',Fore.RESET]),kind='info')
# We'll have more than just single digits here, so readline
choice = sys.stdin.readline().strip()
if choice.isdigit():
key = int(choice)
if key >= 0 and key < len(history):
menu_trans(history,key)
def menu_find(history):
choice = ''
while choice.lower() != 'x':
logger(''.join([Fore.CYAN,'Type the text you would like to search for and hit enter. Hit x, then enter to go back.',Fore.RESET]),kind='info')
# We'll have more than just single digits here, so readline
choice = sys.stdin.readline().strip()
if choice.lower() == 'x': break
results = find_all(history,choice) # execute the search
for result in results: # print out the results, suppressing the header
print_trans(history,result[0],False)
logger(''.join([Fore.CYAN,'Choose a transaction to view with the appropriate numeric key. Hit x, then enter to go back.',Fore.RESET]),kind='info')
choice = sys.stdin.readline().strip()
if choice.isdigit():
key = int(choice)
if key >= 0 and key < len(history):
return menu_trans(history,key)
def menu(em, history):
key = ''
while key != getch.KEY_CTRLc:
print menu_list
key = getch()
if key == getch.KEY_1:
interactive(em,history)
elif key == getch.KEY_2:
menu_history(history)
elif key == getch.KEY_3:
menu_find(history)
elif key == getch.KEY_4:
embed()
elif key == getch.KEY_5:
menu_save(history)
elif key == getch.KEY_X or key == getch.KEY_x:
logger('Do big irons dream of electric paddocks? Goodnight.',kind='info')
sys.exit(0)
# Just an excuse to wrap this away in a fold
def prestartup():
init() # initialise coloured output from colorama
# Define and fetch commandline arguments
parser = argparse.ArgumentParser(\
description = 'Big Iron Recon & Pwnage (BIRP) by @singe',\
epilog = "It's easier than you think" )
parser.add_argument('-t', '--target',\
help='Target IP address or hostname & port: TARGET[:PORT]. The default port is 23. If you don\'t specify a target, you can manually specify it in the emulator',\
required = False, dest = 'target', default = "")
parser.add_argument('-s', '--sleep',\
help='Seconds to sleep between actions (increase on slower systems). The default is 0 seconds.',\
default = 0, type = float, dest = 'sleep')
parser.add_argument('-l', '--load', help='Load a previously saved history file', default='',\
dest = 'loadfile', type = str)
parser.add_argument('-q', '--quiet', help="Ssssh! Don't print info text.",\
default = False, dest = 'quiet', action = 'store_true')
results = parser.parse_args()
return results
# Just an excuse to wrap this away in a fold
def startup():
# Parse commandline arguments
logger('Big Iron Recon & Pwnage (BIRP) by @singe',kind='info')
if not results.target:
logger('Manual target selection chosen.',kind='info')
else:
logger('Target Acquired\t\t: ' + results.target,kind='info')
logger('Slowdown is\t\t\t: ' + str(results.sleep),kind='info')
logger('Attack platform\t\t: ' + platform.system(),kind='info')
if not platform.system() == 'Windows':
em = WrappedEmulator(visible=True,delay=results.sleep)
elif platform.system() == 'Windows':
logger('x3270 not supported on Windows',kind='err')
sys.exit(1)
if results.quiet:
logger('Quiet Mode Enabled\t: Shhhhhhhhh!',kind='warn')
history = tn3270.History()
if results.loadfile:
logger('Load history from\t\t: ' + results.loadfile,kind='info')
history = load_history(results.loadfile)
return (em,history)
results = prestartup()
(em,history) = startup()
if results.target:
logger('Connecting to ' + results.target,kind='info')
try:
em.connect(results.target)
except:
logger('Connection failure',kind='err')
sys.exit(1)
if not em.is_connected():
logger('Could not connect to ' + results.target + '. Aborting.',kind='err')
sys.exit(1)
hostinfo = em.get_hostinfo()
host = hostinfo[1]+':'+hostinfo[2]
menu(em, history)
# And we're done. Close the connection
em.terminate()