-
Notifications
You must be signed in to change notification settings - Fork 82
/
zio.py
executable file
·2014 lines (1728 loc) · 74.3 KB
/
zio.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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#===============================================================================
# The Star And Thank Author License (SATA)
#
# Copyright (c) 2020 zTrix(i@ztrix.me)
#
# Project Url: https://github.com/zTrix/zio
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# And wait, the most important, you shall star/+1/like the project(s) in project url
# section above first, and then thank the author(s) in Copyright section.
#
# Here are some suggested ways:
#
# - Email the authors a thank-you letter, and make friends with him/her/them.
# - Report bugs or issues.
# - Tell friends what a wonderful project this is.
# - And, sure, you can just express thanks in your mind without telling the world.
#
# Contributors of this project by forking have the option to add his/her name and
# forked project url at copyright and project url sections, but shall not delete
# or modify anything else in these two sections.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#===============================================================================
from __future__ import print_function
from __future__ import division
__version__ = "2.1.3"
__project__ = "https://github.com/zTrix/zio"
import os
import sys
import re
import struct
import functools
import socket
import signal
import ast
import time
import datetime
import errno
import select
import binascii
import tempfile
# for ProcessIO below
import pty
import shlex
import fcntl
import gc
import atexit
import resource
import termios
import tty
try:
# works for python2.6 python2.7 and python3
from distutils.spawn import find_executable
except ImportError: # some stupid ubuntu
def find_executable(executable, path=None):
"""Tries to find 'executable' in the directories listed in 'path'.
A string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']. Returns the complete filename or None if not found.
"""
if os.path.isfile(executable):
return executable
if path is None:
path = os.environ.get('PATH', os.defpath)
if not path:
return None
paths = path.split(os.pathsep)
for p in paths:
f = os.path.join(p, executable)
if os.path.isfile(f):
# the file exists, we have a shot at spawn working
return f
return None
# we want to keep zio as a zero-dependency single-file easy-to-use library, and even more, work across python2/python3 boundary
# https://python-future.org/compatible_idioms.html#unicode-text-string-literals
python_version_major = sys.version_info[0] # do not use sys.version_info.major which is not available in python2.6
# python2 python3 shim
if python_version_major < 3:
input = raw_input # pylint: disable=undefined-variable
class TimeoutError(OSError): pass # from ptyprocess.py, issubclass(TimeoutError, OSError) == True
else:
unicode = str
unichr = chr
try:
from io import BytesIO
except ImportError:
from StringIO import StringIO as BytesIO
if True:
# termcolor handled using bytes instead of unicode
# since termcolor use MIT license, SATA license above should be OK
ATTRIBUTES = dict( list(zip([ 'bold', 'dark', '', 'underline', 'blink', '', 'reverse', 'concealed' ], list(range(1, 9)))))
del ATTRIBUTES['']
HIGHLIGHTS = dict( list(zip([ 'on_grey', 'on_red', 'on_green', 'on_yellow', 'on_blue', 'on_magenta', 'on_cyan', 'on_white' ], list(range(40, 48)))))
COLORS = dict(list(zip(['grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', ], list(range(30, 38)))))
RESET = b'\033[0m'
def colored(text, color=None, on_color=None, attrs=None):
fmt_str = b'\033[%dm%s'
if color is not None: text = fmt_str % (COLORS[color], text)
if on_color is not None: text = fmt_str % (HIGHLIGHTS[on_color], text)
if attrs is not None:
for attr in attrs:
text = fmt_str % (ATTRIBUTES[attr], text)
text += RESET
return text
# -------------------------------------------------
# =====> packing/unpacking related functions <=====
def convert_packing(endian, bits, arg, autopad=False, automod=True):
"""
given endian, bits spec, do the following
convert between bytes <--> int
convert between bytes <--> [int]
params:
endian: < for little endian, > for big endian
bits: bit size of packing, valid values are 8, 16, 32, 64
arg: integer or bytes
autopad: auto pad input string to required length if needed
"""
pfs = {8: 'B', 16: 'H', 32: 'I', 64: 'Q'}
if isinstance(arg, unicode):
arg = arg.encode('latin-1')
if isinstance(arg, bytearray):
arg = bytes(arg)
if isinstance(arg, bytes): # bytes -> int or [int]
c = bits // 8
r = len(arg) % c
if r != 0:
if autopad:
arg = arg[:len(arg) // c * c] + (arg[-r:].ljust(c, b'\x00') if endian == '<' else arg[-r:].rjust(c, b'\x00'))
else:
raise ValueError('bad input length, expected multiple of %d, got %d. Fix length manually or use autopad=True' % (c, len(arg)))
unpacked = struct.unpack(endian + pfs[bits] * (len(arg) // c), arg)
return list(unpacked) if len(unpacked) > 1 else unpacked[0]
else: # int or [int] -> bytes
args = list(arg) if isinstance(arg, (list, tuple)) else [arg]
if automod:
args = [i % (1<<bits) for i in args]
return struct.pack(endian + pfs[bits] * len(args), *args)
l8 = functools.partial(convert_packing, '<', 8)
b8 = functools.partial(convert_packing, '>', 8)
l16 = functools.partial(convert_packing, '<', 16)
b16 = functools.partial(convert_packing, '>', 16)
l32 = functools.partial(convert_packing, '<', 32)
b32 = functools.partial(convert_packing, '>', 32)
l64 = functools.partial(convert_packing, '<', 64)
b64 = functools.partial(convert_packing, '>', 64)
# -------------------------------------------------
# =====> utility functions <=====
def bytes2hex(s):
'''
Union{bytes, unicode} -> bytes
'''
if isinstance(s, unicode):
s = s.encode('latin-1')
return binascii.hexlify(s)
def hex2bytes(s, autopad=False):
'''
bytes -> bytes
'''
if isinstance(s, unicode):
s = s.encode('latin-1')
s = s.strip()
if len(s) % 2 == 1:
if autopad == 'left' or autopad == True:
s = b'0' + s
elif autopad == 'right':
s = s + b'0'
else:
raise ValueError('invalid length of hex bytes: %d, should be multiple of 2. Use autopad=True to fix automatically' % len(s))
return binascii.unhexlify(s)
tohex = bytes2hex
unhex = hex2bytes
if python_version_major < 3:
def xor(a, b):
'''
bytes -> bytes -> bytes
the first param a must be longer than or equal to the length of the second param
'''
return b''.join([chr(ord(c) ^ ord(b[i % len(b)])) for i, c in enumerate(a)])
else:
def xor(a, b):
'''
bytes -> bytes -> bytes
the first param a must be longer than or equal to the length of the second param
'''
return bytes([c ^ b[i % len(b)] for i, c in enumerate(a)])
def is_hostport_tuple(target):
return type(target) == tuple and len(target) == 2 and isinstance(target[1], int) and target[1] >= 0 and target[1] < 65536
def match_pattern(pattern, byte_buf):
'''
pattern -> byte_buf -> index span # (-1, -1) for not found)
pattern could be bytes or re objects or lambda function which returns index span
'''
if isinstance(pattern, unicode):
pattern = pattern.encode('latin-1')
if isinstance(pattern, bytes):
i = byte_buf.find(pattern)
if i > -1:
return (i, i + len(pattern))
else:
return (-1, -1)
elif hasattr(pattern, 'match') and hasattr(pattern, 'search'):
mo = pattern.search(byte_buf)
if not mo:
return (-1, -1)
else:
return mo.span()
elif callable(pattern):
return pattern(byte_buf)
def write_stdout(data):
if hasattr(sys.stdout, 'buffer'):
sys.stdout.buffer.write(data)
else:
if python_version_major < 3:
sys.stdout.write(data)
else:
sys.stdout.write(data.decode())
sys.stdout.flush()
def write_stderr(data):
if hasattr(sys.stderr, 'buffer'):
sys.stderr.buffer.write(data)
else:
if python_version_major < 3:
sys.stderr.write(data)
else:
sys.stderr.write(data.decode())
sys.stderr.flush()
def write_debug(f, data, show_time=True, end=b'\n'):
if not f:
return
if isinstance(data, unicode):
data = data.encode('latin-1')
if show_time:
now = datetime.datetime.now().strftime('[%Y-%m-%d_%H:%M:%S]').encode()
f.write(now)
f.write(b' ')
f.write(data)
if end:
f.write(end)
f.flush()
def ttyraw(fd, when=tty.TCSAFLUSH, echo=False, raw_in=True, raw_out=False):
mode = tty.tcgetattr(fd)[:]
if raw_in:
mode[tty.IFLAG] = mode[tty.IFLAG] & ~(tty.BRKINT | tty.ICRNL | tty.INPCK | tty.ISTRIP | tty.IXON)
mode[tty.CFLAG] = mode[tty.CFLAG] & ~(tty.CSIZE | tty.PARENB)
mode[tty.CFLAG] = mode[tty.CFLAG] | tty.CS8
if echo:
mode[tty.LFLAG] = mode[tty.LFLAG] & ~(tty.ICANON | tty.IEXTEN | tty.ISIG)
else:
mode[tty.LFLAG] = mode[tty.LFLAG] & ~(tty.ECHO | tty.ICANON | tty.IEXTEN | tty.ISIG)
if raw_out:
mode[tty.OFLAG] = mode[tty.OFLAG] & ~(tty.OPOST)
mode[tty.CC][tty.VMIN] = 1
mode[tty.CC][tty.VTIME] = 0
tty.tcsetattr(fd, when, mode)
# -------------------------------------------------
# =====> zio class modes and params <=====
PIPE = 'pipe' # io mode (process io): send all characters untouched, but use PIPE, so libc cache may apply
TTY = 'tty' # io mode (process io): normal tty behavier, support Ctrl-C to terminate, and auto \r\n to display more readable lines for human
TTY_RAW = 'ttyraw' # io mode (process io): send all characters just untouched
def COLORED(f, color='cyan', on_color=None, attrs=None):
return lambda s : colored(f(s), color, on_color, attrs)
# read/write transform functions
# bytes -> (printable) bytes
if python_version_major < 3:
def REPR(s): return b'b' + repr(s) + b'\r\n'
else:
def REPR(s): return str(s).encode() + b'\r\n'
def EVAL(s): # now you are not worried about pwning yourself, do not use ast.literal_eval because of 1. encoding issue 2. we only eval string
st = 0 # 0 for normal, 1 for escape, 2 for \xXX
ret = []
i = 0
while i < len(s):
c = s[i:i+1] # current byte, for python2/3 compatibility
if st == 0:
if c == b'\\':
st = 1
else:
ret.append(c)
elif st == 1:
if c in (b'"', b"'", b"\\", b"t", b"n", b"r"):
if c == b't':
ret.append(b'\t')
elif c == b'n':
ret.append(b'\n')
elif c == b'r':
ret.append(b'\r')
else:
ret.append(c)
st = 0
elif c == b'x':
st = 2
else:
raise ValueError('invalid repr of str %s' % s)
else:
num = int(s[i:i+2], 16)
assert 0 <= num < 256
if python_version_major < 3:
ret.append(chr(num))
else:
ret.append(bytes([num]))
st = 0
i += 1
i += 1
return b''.join(ret)
def HEX(s): return bytes2hex(s) + b'\r\n'
TOHEX = HEX
def UNHEX(s): return hex2bytes(s)
def HEXDUMP(byte_buf, width=16, indent=0):
length = len(byte_buf)
lines = (length // width) + (length % width != 0)
ret = []
printable_low = b' '
printable_high = b'~'
hexcode_width = 0
for lino in range(lines):
index_begin = lino * width
line = byte_buf[index_begin:index_begin+width]
prefix = format('%08x' % index_begin).encode()
hexcode = b''
printable = b''
for gi in range(0, len(line), 2):
gd = line[gi:gi+2]
hexcode += b' ' + binascii.hexlify(gd)
printable += gd[0:1] if printable_low <= gd[0:1] <= printable_high else b'.'
if len(gd) == 2:
printable += gd[1:2] if printable_low <= gd[1:2] <= printable_high else b'.'
if len(hexcode) > hexcode_width:
hexcode_width = len(hexcode)
elif len(hexcode) < hexcode_width:
hexcode = hexcode.ljust(hexcode_width, b' ')
ret.append(b'%s%s:%s %s\n' % (b' ' * indent, prefix, hexcode, printable))
return b''.join(ret)
HEXDUMP_INDENT4 = functools.partial(HEXDUMP, indent=4)
HEXDUMP_INDENT8 = functools.partial(HEXDUMP, indent=8)
HEXDUMP_INDENT16 = functools.partial(HEXDUMP, indent=16)
if python_version_major < 3:
def BIN(s): return b' '.join([format(ord(x),'08b') for x in str(s)]) + b'\r\n'
else:
def BIN(s): return b' '.join([format(x,'08b').encode() for x in s]) + b'\r\n'
def UNBIN(s, autopad=False):
s = bytes(filter(lambda x: x in b'01', s))
if len(s) % 8 != 0:
extra = 8 - len(s) % 8
if autopad == 'left' or autopad == True:
s = (b'0' * extra) + s
elif autopad == 'right':
s = s + (b'0' * extra)
else:
raise ValueError('invalid length of 01 bytestring: %d, should be multiple of 8. Use autopad=True to fix automatically' % len(s))
if python_version_major < 3:
return b''.join([chr(int(s[x:x+8],2)) for x in range(0, len(s), 8)])
else:
return bytes([int(s[x:x+8],2) for x in range(0, len(s), 8)])
def RAW(s): return s
def NONE(s): return b''
# -------------------------------------------------
# =====> zio helper functions <=====
def select_ignoring_useless_signal(iwtd, owtd, ewtd, timeout=None):
'''This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). '''
# if select() is interrupted by a signal (errno==EINTR) then
# we loop back and enter the select() again.
if timeout is not None:
end_time = time.time() + timeout
while True:
try:
return select.select(iwtd, owtd, ewtd, timeout)
except select.error as err:
if select.error == OSError: # python3 style
eno = err.errno
else:
err = sys.exc_info()[1] # python2 style
eno = err[0]
if eno == errno.EINTR:
# if we loop back we have to subtract the
# amount of time we already waited.
if timeout is not None:
timeout = end_time - time.time()
if timeout < 0:
return([], [], [])
else:
# something else caused the select.error, so
# this actually is an exception.
raise
# zio class here
class zio(object):
'''
zio: unified io interface for both socket io and process io
'''
def __init__(self, target,
# common params
timeout=None,
logfile=None,
print_read=True,
print_write=True,
debug=None,
# ProcessIO params
stdin=PIPE,
stdout=TTY_RAW,
cwd=None,
env=None,
sighup=signal.SIG_DFL,
write_delay=0.05,
read_echoback=True,
):
"""
zio is an easy-to-use io library for pwning development, supporting an unified interface for local process pwning and remote tcp socket io
note that zio fully operates at bytes level instead of unicode, so remember to use bytes when passing arguments to zio methods
example:
io = zio(('localhost', 80), print_read=COLORED(RAW, 'yellow'), print_write=HEX)
io = zio(socket.create_connection(('127.0.0.1', 80)))
io = zio('ls -l')
io = zio(['ls', '-l'])
params:
target(required): the target object for zio to operate with, could be socket (addr, port) tuple, or connected socket object, or cmd line for spawning process
print_read: bool | [COLORED]{NONE, RAW, REPR, HEX}, if set, transform and print all the data read from target
print_write: bool | [COLORED]{NONE, RAW, REPR, HEX}, if set, transform and print all the data sent out
timeout: int, the global timeout for this zio object
logfile: where to print traffic data in or out from target, default to sys.stderr
debug: if set to a file object(must be opened using binary mode), will provide info for debugging zio internal. leave it to None by default.
stdin(ProcessIO only): {PIPE, TTY, TTY_RAW} which mode to choose for child process stdin, PIPE is recommended for programming interface, since you will need to take care of tty control chars by hand when call write methods if stdin set to TTY mode.
stdout(ProcessIO only): {PIPE, TTY, TTY_RAW} which mode to choose for child process stdout
cwd(ProcessIO only): the working directory to spawn child process
env(ProcessIO only): env variables for child process
write_delay(ProcessIO only): write delay for child process to prevent writing too fast
"""
if not target:
raise ValueError('cmdline or socket not provided for zio, try zio("ls -l")')
self.target = target
self.print_read = print_read
self.print_write = print_write
if logfile is None:
self.logfile = sys.stderr
else:
self.logfile = logfile # must be opened using 'rb'
# zio object itself is a buffered reader/writer
self.buffer = bytearray()
self.debug = debug
if isinstance(timeout, (int, float)) and timeout > 0:
self.timeout = timeout
else:
self.timeout = 10
if is_hostport_tuple(self.target) or isinstance(self.target, socket.socket):
self.io = SocketIO(self.target, timeout=self.timeout, debug=debug)
else:
self.io = ProcessIO(self.target, timeout=self.timeout, debug=debug,
stdin=stdin,
stdout=stdout,
cwd=cwd,
env=env,
sighup=sighup,
write_delay=write_delay,
read_echoback=read_echoback,
)
def log_read(self, byte_buf):
'''
bytes -> IO bytes
'''
if self.print_read and byte_buf: # should log when byte_buf is empty bytestring
content = self.read_transform(byte_buf)
if hasattr(self.logfile, 'buffer'):
self.logfile.buffer.write(content)
else:
self.logfile.write(content)
self.logfile.flush()
def log_write(self, byte_buf):
'''
bytes -> IO bytes
'''
if self.print_write and byte_buf: # should log when byte_buf is empty bytestring
content = self.write_transform(byte_buf)
if hasattr(self.logfile, 'buffer'):
self.logfile.buffer.write(content)
else:
self.logfile.write(content)
self.logfile.flush()
@property
def print_read(self):
return self.read_transform is not None and self.read_transform is not NONE
@print_read.setter
def print_read(self, value):
if value == True:
self.read_transform = RAW
elif value == False:
self.read_transform = NONE
elif callable(value):
self.read_transform = value
else:
raise ValueError('bad print_read value')
assert callable(self.read_transform)
@property
def print_write(self):
return self.write_transform is not None and self.write_transform is not NONE
@print_write.setter
def print_write(self, value):
if value == True:
self.write_transform = RAW
elif value == False:
self.write_transform = NONE
elif callable(value):
self.write_transform = value
else:
raise ValueError('bad print_read value')
assert callable(self.write_transform)
def read(self, size=None):
'''
if size is -1 or None, then read all bytes available until EOF
if size is a positive integer, read exactly `size` bytes and return
raise EOFError if EOF occurred before full size read
raise TimeoutError if Timeout occured
'''
is_read_all = size is None or size < 0
incoming = None
# log buffer content first
if self.buffer:
if is_read_all:
self.log_read(bytes(self.buffer))
else:
self.log_read(bytes(self.buffer[:size]))
while True:
if is_read_all or len(self.buffer) < size:
incoming = self.io.recv(1536)
if incoming is None:
if is_read_all:
ret = bytes(self.buffer)
# self.buffer.clear() # note: python2 does not support bytearray.clear()
self.buffer = bytearray()
return ret
else:
raise EOFError('EOF occured before full size read, buffer = %r' % self.buffer)
self.buffer.extend(incoming)
if not is_read_all and len(self.buffer) >= size:
if incoming:
self.log_read(incoming[:len(incoming) + size - len(self.buffer)])
ret = bytes(self.buffer[:size])
self.buffer = self.buffer[size:]
return ret
else:
self.log_read(incoming)
read_exact = read
recvn = read
def read_to_end(self):
'''
read all data until EOF
'''
return self.read(size=-1)
read_all = read_to_end
recvall = read_to_end
def read_line(self, keep=True):
content = self.read_until(b'\n', keep=True)
if not keep:
content = content.rstrip(b'\r\n')
return content
readline = read_line
recvline = read_line # for pwntools compatibility
def read_until(self, pattern, keep=True):
'''
read until some bytes pattern found
patter could be one of following:
1. bytes | unicode(codepoint < 256)
2. re object(must compile using bytes rather than unicode, e.g: re.compile(b"something"))
3. callable functions return True for found and False for not found
4. lists of things above
raise EOFError if EOF occurred before pattern found
'''
if not isinstance(pattern, (list, tuple)):
pattern_list = [pattern]
else:
pattern_list = pattern
log_pos = 0
while True:
for p in pattern_list:
span = match_pattern(p, self.buffer)
if span[0] > -1: # found
end_pos = span[1]
ret = self.buffer[:end_pos] if keep == True else self.buffer[:span[0]]
self.log_read(bytes(self.buffer[log_pos:end_pos]))
self.buffer = self.buffer[end_pos:]
return bytes(ret)
self.log_read(bytes(self.buffer[log_pos:]))
log_pos = len(self.buffer)
incoming = self.io.recv(1536)
if incoming is None:
raise EOFError('EOF occured before pattern match, buffer = %r' % self.buffer)
self.buffer.extend(incoming)
readuntil = read_until
recv_until = read_until
recvuntil = read_until
def read_some(self, size=None):
'''
just read 1 or more available bytes (less than size) and return
'''
if len(self.buffer):
if size is None or size <= 0:
ret = bytes(self.buffer)
self.buffer = bytearray()
else:
ret = bytes(self.buffer[:size])
self.buffer = self.buffer[size:]
self.log_read(ret)
return ret
ret = self.io.recv(size)
self.log_read(ret)
return ret
recv = read_some
def read_until_timeout(self, timeout=1):
'''
read for some timeout, return current buffer plus whatever read
'''
end_time = time.time() + timeout
if self.buffer:
self.log_read(bytes(self.buffer))
while True:
r, _w, _e = select_ignoring_useless_signal([self.io.rfd], [], [], timeout)
data = None
if self.io.rfd in r:
data = self.io.recv(1536)
if data is None:
break
elif data:
self.buffer.extend(data)
self.log_read(data)
break
timeout = end_time - time.time()
if timeout < 0:
break
if len(self.buffer):
ret = bytes(self.buffer)
self.buffer = bytearray()
return ret
return b''
read_eager = read_until_timeout
def readable(self):
'''
tell wether we have some data to read
'''
if len(self.buffer):
return True
return select_ignoring_useless_signal([self.io.rfd], [], [], 0) == ([self.io.rfd], [], [])
def write(self, byte_buf):
'''
write/sendall bytes and flush them all
'''
if not byte_buf:
return 0
if isinstance(byte_buf, unicode):
byte_buf = byte_buf.encode('latin-1') # will raise UnicodeEncodeError if code point larger than 255
self.log_write(bytes(byte_buf))
self.io.send(byte_buf)
return len(byte_buf)
send = write # for pwntools compatibility
sendall = write # for socket compatibility
def write_line(self, byte_buf):
'''
write byte_buf and a linesep
'''
if isinstance(byte_buf, unicode):
byte_buf = byte_buf.encode('latin-1') # will raise UnicodeEncodeError if code point larger than 255
return self.write(byte_buf + os.linesep.encode())
sendline = write_line
send_line = write_line
writeline = write_line
def write_lines(self, sequence):
n = 0
for s in sequence:
n += self.write_line(s)
return n
writelines = write_lines
def write_after(self, pattern, byte_buf):
self.read_until(pattern)
self.write(byte_buf)
writeafter = write_after
sendafter = write_after
def write_line_after(self, pattern, byte_buf):
self.read_until(pattern)
self.writeline(byte_buf)
writeline_after = write_line_after # for human mistake
sendline_after = write_line_after # for human mistake
sendlineafter = write_line_after # for pwntools compatibility
def send_eof(self):
'''
notify peer that we have done writing
'''
self.io.send_eof()
sendeof = send_eof
end = send_eof # for zio 1.0 compatibility
def interact(self, **kwargs):
'''
interact with current tty stdin/stdout
'''
if self.buffer:
kwargs['buffered'] = bytes(self.buffer)
self.buffer = bytearray()
self.io.interact(**kwargs)
interactive = interact # for pwntools compatibility
def close(self):
'''
close underlying io and free all resources
'''
self.io.close()
def is_closed(self):
'''
tell whether this zio object is closed
'''
return self.io.is_closed()
def is_eof_seen(self):
'''
tell whether we have received EOF from peer end
'''
return self.io.eof_seen
def is_eof_sent(self):
'''
tell whether we have sent EOF to the peer
'''
return self.io.eof_sent
def flush(self):
'''
kept to act like a file-like object
'''
pass
def fileno(self):
'''
return underlying os fileno, act like a file-like object
'''
return self.io.rfd
def mode(self):
return self.io.mode
def exit_status(self):
return self.io.exit_status
exit_code = exit_status
def gdb_hint(self, userscript=None, breakpoints=None):
'''
script: str
breakpoints: List[Union{int, (int, keyword:str)}], example: [0x400419, (0x1009, 'libc.so')]
'''
pid = self.io.target_pid()
if not pid:
input('unable to find target pid to attach gdb')
return
gdb_cmd = ['attach %d' % pid, 'set disassembly-flavor intel']
vmmap = open('/proc/%d/maps' % pid).read()
vmmap_lines = vmmap.splitlines()
if breakpoints:
for b in breakpoints:
if isinstance(b, (tuple, list)):
found = False
for line in vmmap_lines:
if b[1].lower() in line.lower():
base = int(line.split('-')[0], 16)
gdb_cmd.append('b *' + hex(base + b[0]))
found = True
break
if not found:
print('[ WARN ] keyword not found for breakpoint base address: %r' % b)
elif isinstance(b, int):
gdb_cmd.append('b *' + hex(b))
elif isinstance(b, type('')):
gdb_cmd.append('b *' + b)
else:
print('[ WARN ] bad breakpoint: %r' % b)
if not userscript:
userscript = ''
if isinstance(userscript, bytes):
userscript = userscript.decode('utf-8')
gdb_script = '\n'.join(gdb_cmd) + '\n\n' + userscript + '\n'
tf = tempfile.NamedTemporaryFile(mode="w", suffix='.zio.gdbx')
tf.write(gdb_script)
tf.flush()
hint = "gdb -x %s" % tf.name
hint += '\nuse cmdline above to attach gdb then press enter to continue ... '
input(hint)
def __str__(self):
return '<zio target=%s, timeout=%s, io=%s, buffer=%s>' % (self.target, self.timeout, str(self.io), self.buffer)
class SocketIO(object):
mode = 'socket'
def __init__(self, target, timeout=None, debug=None):
self.timeout = timeout
self.debug = debug
if isinstance(target, socket.socket):
self.sock = target
else:
self.sock = socket.create_connection(target, self.timeout)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.eof_seen = False
self.eof_sent = False
self.exit_code = None
@property
def rfd(self):
return self.sock.fileno()
@property
def wfd(self):
return self.sock.fileno()
def recv(self, size=None):
'''
recv 1 or more available bytes then return
return None to indicate EOF
since we use b'' to indicate empty string in case of timeout, so do not return b'' for EOF
'''
if size is None: # socket.recv does not allow None or -1 as argument
size = 8192
try:
b = self.sock.recv(size)
if self.debug: write_debug(self.debug, b'SocketIO.recv(%r) -> %r' % (size, b))
if not b:
self.eof_seen = True
return None
return b
except socket.timeout:
raise TimeoutError('socket.timeout') # translate to TimeoutError
except Exception as ex:
self.exit_code = 1 # recv exception
if self.debug: write_debug(self.debug, b'SocketIO.recv(%r) exception: %r' % (size, ex))
raise
def send(self, buf):
try:
return self.sock.sendall(buf)
except Exception as ex:
self.exit_code = 2 # send exception
if self.debug: write_debug(self.debug, b'SocketIO.send(%r) exception: %r' % (buf, ex))
raise
def send_eof(self):
self.eof_sent = True
self.sock.shutdown(socket.SHUT_WR)
if self.debug: write_debug(self.debug, b'SocketIO.send_eof()')
def interact(self, buffered=None, read_transform=None, write_transform=None, show_input=None, show_output=None, raw_mode=False):
if show_input is None:
show_input = not os.isatty(pty.STDIN_FILENO) # if pty, itself will echo; if pipe, we do echo
if show_output is None:
show_output = True
parent_tty_mode = None
if os.isatty(pty.STDIN_FILENO) and raw_mode:
parent_tty_mode = tty.tcgetattr(pty.STDIN_FILENO) # save mode and restore after interact
ttyraw(pty.STDIN_FILENO) # set to raw mode to pass all input thru, supporting remote apps as htop/vim