forked from br0ns/poek
-
Notifications
You must be signed in to change notification settings - Fork 0
/
poke
executable file
·329 lines (294 loc) · 9.4 KB
/
poke
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
#!/usr/bin/env python2
import argparse
import errno
import os
import pwnlib
import select
import socket
import struct
import sys
import tarfile
import tempfile
import time
import traceback
PORT = 1337
parser = argparse.ArgumentParser(
description = "Poke",
)
parser.add_argument(
'--verbose', '-v',
action='store_true',
help='Verbose output',
)
parser.add_argument(
'--port', '-p',
type=int,
default=PORT,
help='Port to listen on for file list requests',
)
parser.add_argument(
'--watch', '-w',
metavar='<dir>',
help='Watch directory and serve everything added to it',
)
parser.add_argument(
'paths',
metavar='<path>',
nargs='+',
)
args = parser.parse_args()
def _log(emblem, msg):
t = time.strftime('%T', time.localtime())
print >>sys.stderr, '%s %s %s' % \
(pwnlib.term.text.magenta(t),
emblem, msg)
def debug(s):
if args.verbose:
_log(pwnlib.term.text.cyan('D'), s)
def info(s):
_log(pwnlib.term.text.blue('I'), s)
def warn(s):
_log(pwnlib.term.text.yellow('W'), s)
def err(s):
_log(pwnlib.term.text.red('E'), s)
class EventLoop:
def __init__(self):
self.rfds = {}
self.wfds = {}
def watch_read(self, fd, cb):
self.rfds[fd] = cb
def watch_write(self, fd, cb):
self.wfds[fd] = cb
def unwatch_read(self, fd):
if fd in self.rfds:
del self.rfds[fd]
def unwatch_write(self, fd):
if fd in self.wfds:
del self.wfds[fd]
def unwatch(self, fd):
self.unwatch_read(fd)
self.unwatch_write(fd)
def run(self):
while True:
try:
self._loop()
except KeyboardInterrupt:
info('Interrupted')
break
except Exception as e:
err('An exception occurred: %r' % e)
for line in traceback.format_exc().splitlines():
debug(line)
def _loop(self):
rfds = self.rfds.keys()
wfds = self.wfds.keys()
try:
rfds, wfds, _ = select.select(rfds, wfds, [], 1)
except select.error as e:
if e[0] != errno.EINTR:
raise
return
for fd in rfds:
self.rfds[fd](fd)
for fd in wfds:
self.wfds[fd](fd)
event_loop = EventLoop()
class Selectable:
def fileno(self):
return self.sock.fileno()
def watch_read(self, cb):
event_loop.watch_read(self, cb)
def watch_write(self, cb):
event_loop.watch_write(self, cb)
def unwatch_read(self):
event_loop.unwatch_read(self)
def unwatch_write(self):
event_loop.unwatch_write(self)
def unwatch(self):
event_loop.unwatch(self)
class TCPConnect(Selectable):
def __init__(self, addr, port):
self.sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
self.sock.setblocking(False)
assert errno.EINPROGRESS == self.sock.connect_ex((addr, port))
def cb(self):
self.unwatch()
if 0 == self.sock.connect_ex((self.addr, self.port)):
self.on_connected()
else:
self.on_refused()
self.watch_write(cb)
self.addr = addr
self.port = port
def bind_first_free(sock, port):
while True:
try:
sock.bind(('', port))
except socket.error as e:
if e.errno == errno.EADDRINUSE:
port += 1
continue
raise
break
class TCPListen(Selectable):
def __init__(self, port = 0, backlog = 10):
self.sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.setblocking(False)
bind_first_free(self.sock, port)
self.port = self.sock.getsockname()[1]
self.sock.listen(backlog)
def cb(self):
try:
sock, (addr, _) = self.sock.accept()
except socket.error as e:
if e.errno == errno.EWOULDBLOCK:
return
raise
self.on_connection(sock, addr)
self.watch_read(cb)
class UDPListen(Selectable):
def __init__(self, port = 0):
self.sock = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM,
socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
self.sock.setblocking(False)
bind_first_free(self.sock, port)
self.port = self.sock.getsockname()[1]
def cb(self):
data, (addr, _) = self.sock.recvfrom(4096)
self.on_data(data, addr)
self.watch_read(cb)
def ip4_addresses():
ip_list = []
for interface in netifaces.interfaces():
if interface == 'lo':
continue
addresses = netifaces.ifaddresses(interface)
if socket.AF_INET in addresses:
for link in addresses[socket.AF_INET]:
ip_list.append(link['addr'])
return ip_list
self_addrs = []
for _iface, addrs in pwnlib.util.net.interfaces4().items():
self_addrs += addrs
items = []
class Directory(TCPConnect):
def __init__(self, addr, port):
TCPConnect.__init__(self, addr, port)
def on_connected(self):
debug('Connected to %s:%d, sending file list' % \
(self.addr, self.port))
for i in items:
self.sock.send(struct.pack('!H', i.port) + \
i.path + '\x00')
self.sock.send('\x00\x00')
self.sock.close()
def on_refused(self):
warn('%s refused connection on port %d' % \
(self.addr, self.port))
class PeekHandler(UDPListen):
def __init__(self, port):
UDPListen.__init__(self, port)
info('Listening on port %d' % self.port)
def on_data(self, data, addr):
if len(data) != 8 or data[:6] != 'POKEME':
debug('Ignoring bogus request from %s' % addr)
return
if addr in self_addrs:
debug('Ignoring request from self (%s)' % addr)
return
port = struct.unpack('!H', data[6:8])[0]
debug('%s wants file list' % addr)
Directory(addr, port)
class Transfer(Selectable):
def __init__(self, sock, addr, item):
self.numb = 0
self.sock = sock
self.addr = addr
self.path = item.path
self.start = time.time()
self.last_update = 0
try:
if self.path[-1] == '/':
self.fd = tempfile.TemporaryFile(prefix='poke')
name = os.path.basename(self.path[:-1])
tar = tarfile.open(fileobj=self.fd, mode='w')
tar.add(self.path, arcname=name)
tar.close()
self.fd.seek(0)
else:
self.fd = open(self.path, 'r')
except IOError as e:
if e.errno == errno.ENOENT:
warn('Could not open "%s" for reading' % self.path)
return
raise
prefix = pwnlib.term.text.magenta('[Active]') + \
pwnlib.term.text.blue(' I ') + \
'"%s" => %s (' % (self.path, self.addr)
self.h_prefix = pwnlib.term.output(prefix, float=True)
self.h_progress = pwnlib.term.output('', float=True)
self.h_suffix = pwnlib.term.output(')\n', float=True)
def cb(self):
# time.sleep(0.1)
# data = self.fd.read(200)
data = self.fd.read(4096)
if data:
try:
self.sock.send(data)
except socket.error as e:
if e.errno in (errno.ECONNRESET, errno.EPIPE):
self.finish()
warn('%s closed connection' % self.addr)
return
raise
self.numb += len(data)
self.update()
else:
self.finish()
info('"%s" => %s completed' % (self.path, self.addr))
self.watch_write(cb)
def finish(self):
self.h_prefix.delete()
self.h_progress.delete()
self.h_suffix.delete()
self.sock.close()
self.unwatch()
def update(self):
now = time.time()
if now - self.last_update > 0.1:
bps = self.numb / (now - self.start)
progress = '%s, %s/s' % \
(pwnlib.util.misc.size(self.numb),
pwnlib.util.misc.size(bps))
self.h_progress.update(progress)
self.last_update = now
class Item(TCPListen):
def __init__(self, path, port=0):
if not os.path.isdir(path) and not os.path.isfile(path):
raise IOError('No such file or directory: %s' % path)
path = path.rstrip('/')
if os.path.isdir(path):
path += '/'
self.path = path
TCPListen.__init__(self, port)
items.append(self)
info('Port %5d: "%s"' % (self.port, self.path))
def __str__(self):
return self.path
def on_connection(self, sock, addr):
info('%s wants "%s"' % \
(addr, self.path))
Transfer(sock, addr, self)
pwnlib.term.init()
PeekHandler(args.port)
for p in args.paths:
try:
Item(p, port=args.port)
except IOError as e:
err(e)
event_loop.run()