/
http.py
3665 lines (3156 loc) · 122 KB
/
http.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
import StringIO
import base64
import bs4
import crochet
import datetime
import gzip
import json
import pygments
import re
import time
import urlparse
import zlib
import weakref
import Queue
from .util import PappyException, printable_data, short_data, PappyStringTransport, sha1, print_traceback
from .requestcache import RequestCache
from .colors import Colors, host_color, path_formatter
from .proxy import ProtocolProxy, make_proxied_connection, get_http_proxy_addr, start_maybe_tls
from pygments.formatters import TerminalFormatter
from pygments.lexers import get_lexer_for_mimetype, HttpLexer
from twisted.internet import defer
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketClientFactory, WebSocketServerProtocol, WebSocketClientProtocol
from autobahn.websocket.protocol import WebSocketProtocol
from autobahn.websocket.compress import PERMESSAGE_COMPRESSION_EXTENSION
ENCODE_NONE = 0
ENCODE_DEFLATE = 1
ENCODE_GZIP = 2
PATH_RELATIVE = 0
PATH_ABSOLUTE = 1
PATH_HOST = 2
dbpool = None
web_server = None
def init(pool):
"""
Initialize the http module.
:param pool: The ConnectionPool to use to store the request/response objects
:type pool: SQLite ConnectionPool
"""
from .site import PappyWebServer
global dbpool
global web_server
if dbpool is None:
dbpool = pool
web_server = PappyWebServer()
assert(dbpool)
def destruct():
assert(dbpool)
dbpool.close()
def _decode_encoded(data, encoding):
if encoding == ENCODE_NONE:
return data
if encoding == ENCODE_DEFLATE:
dec_data = zlib.decompress(data, -15)
else:
dec_data = gzip.GzipFile('', 'rb', 9, StringIO.StringIO(data))
dec_data = dec_data.read()
return dec_data
def _strip_leading_newlines(string):
while (len(string) > 1 and string[0:2] == '\r\n') or \
(len(string) > 0 and string[0] == '\n'):
if len(string) > 1 and string[0:2] == '\r\n':
string = string[2:]
elif len(string) > 0 and string[0] == '\n':
string = string[1:]
return string
def _consume_line(instr):
# returns (line, rest)
l = []
pos = 0
while pos < len(instr):
if instr[pos] == '\n':
if l and l[-1] == '\r':
l = l[:-1]
return (''.join(l), instr[pos+1:])
l.append(instr[pos])
pos += 1
return (instr, '')
###################
## Functions to use
def get_request(url='', url_params={}):
"""
get_request(url='', url_params={})
Create a request object that makes a GET request to the given url with the
given url params.
"""
r = Request()
r.start_line = 'GET / HTTP/1.1'
r.url = url
r.headers['Host'] = r.host
if url_params:
r.url_params.from_dict(url_params)
return r
def post_request(url, post_params={}, url_params={}):
"""
post_request(url, post_params={}, url_params={})
Create a request object that makes a POST request to the given url with the
given post and url params.
"""
r = Request()
r.start_line = 'POST / HTTP/1.1'
r.url = url
r.headers['Host'] = r.host
if url_params:
r.url_params.from_dict(url_params)
if post_params:
r.post_params.from_dict(post_params)
return r
def repeatable_parse_qs(s):
pairs = s.split('&')
ret_dict = RepeatableDict()
for pair in pairs:
if '=' in pair:
t = tuple(pair.split('=', 1))
ret_dict.append(t[0], t[1])
else:
ret_dict.append(pair, None)
return ret_dict
@crochet.wait_for(timeout=180.0)
@defer.inlineCallbacks
def request_by_id(reqid):
req = yield Request.load_request(str(reqid))
defer.returnValue(req)
@defer.inlineCallbacks
def async_submit_requests(reqs, mangle=False, save=False, save_in_mem=False, unique_paths=False,
unique_path_and_args=False, use_cookie_jar=False, tag=None):
"""
async_submit_requests(reqs, mangle=False)
:param mangle: Whether to pass the requests through intercepting macros
:type mangle: Bool
:rtype: DeferredList
Copies and submits a list of requests at the same time asynchronously.
Responses/unmangled versions will be attached to the request objects in the list.
Prints progress to stdout.
Returns list of submitted requests
"""
import sys
from pappyproxy.plugin import add_to_history
if unique_paths and unique_path_and_args:
raise PappyException("Cannot use both unique_paths and unique_paths_and_argts")
if save and save_in_mem:
raise PappyException("Cannot use both save and save_in_mem")
to_submit = [r.copy() for r in reqs]
if unique_paths or unique_path_and_args:
endpoints = set()
new_reqs = []
for r in reqs:
if unique_path_and_args:
s = r.url
else:
s = r.path
if not s in endpoints:
new_reqs.append(r)
endpoints.add(s)
to_submit = new_reqs
print 'Submitting %d request(s)' % len(to_submit)
sys.stdout.flush()
dones = 0
errors = 0
list_deferred = defer.Deferred()
deferreds = []
for r in to_submit:
if tag is not None:
r.tags.add(tag)
d = r.async_submit(mangle=mangle)
deferreds.append(d)
# Really not the best way to do this. If one request hangs forever the whole thing will
# just hang in the middle
for d in deferreds:
try:
yield d
dones += 1
except Exception as e:
errors += 1
print e
finished = dones+errors
if finished % 30 == 0 or finished == len(to_submit):
if errors > 0:
print '{0}/{1} complete with {3} errors ({2:.2f}%)'.format(finished, len(to_submit), (float(finished)/len(to_submit))*100, errors)
else:
print '{0}/{1} complete ({2:.2f}%)'.format(finished, len(to_submit), (float(finished)/len(to_submit))*100)
sys.stdout.flush()
if finished == len(to_submit):
list_deferred.callback(None)
if save:
for r in to_submit:
yield r.async_deep_save()
elif save_in_mem:
for r in to_submit:
add_to_history(r)
@crochet.wait_for(timeout=180.0)
@defer.inlineCallbacks
def submit_requests(*args, **kwargs):
ret = yield async_submit_requests(*args, **kwargs)
defer.returnValue(ret)
def apply_http_proxy_creds(req):
from pappyproxy import pappy
if not pappy.session.config.http_proxy:
return
if 'username' in pappy.session.config.http_proxy and \
'password' in pappy.session.config.http_proxy:
req.proxy_creds = (pappy.session.config.http_proxy['username'],
pappy.session.config.http_proxy['password'])
@defer.inlineCallbacks
def handle_webserver_request(req):
global web_server
yield web_server.handle_request(req)
##########
## Classes
class RepeatableDict:
"""
A dict that retains the order of items inserted and keeps track of
duplicate values. Can optionally treat keys as case insensitive.
Custom made for the proxy, so it has strange features
"""
def __init__(self, from_pairs=None, case_insensitive=False):
# If efficiency becomes a problem, add a dict that keeps a list by key
# and use that for getting data. But until then, this stays.
self._pairs = []
self._keys = set()
self._modify_callback = None
self.case_insensitive = case_insensitive
if from_pairs:
for k, v in from_pairs:
self.append(k, v)
def _ef_key(self, key):
# "effective key", returns key.lower() if we're case insensitive,
# otherwise it returns the same key
if self.case_insensitive:
return key.lower()
return key
def _mod_callback(self):
# Calls the modify callback if we have one
if self._modify_callback:
self._modify_callback()
def __contains__(self, val):
return self._ef_key(val) in self._keys
def __getitem__(self, key):
for p in reversed(self._pairs):
if self._ef_key(p[0]) == self._ef_key(key):
return p[1]
raise KeyError
def __setitem__(self, key, val):
# Replaces first instance of `key` and deletes the rest
self.set_val(key, val)
def __delitem__(self, key):
self._remove_key(key)
self._pairs = [p for p in self._pairs if self._ef_key(p[0]) != self._ef_key(key)]
self._mod_callback()
def __nonzero__(self):
if self._pairs:
return True
else:
return False
def _add_key(self, key):
self._keys.add(self._ef_key(key))
def _remove_key(self, key):
self._keys.remove(self._ef_key(key))
def all_pairs(self):
"""
A list of all the key/value pairs stored in the dictionary
"""
return self._pairs[:]
def append(self, key, val, do_callback=True):
"""
append(key, val)
Append a pair to the end of the dictionary. Will add a duplicate if the key already exists.
"""
# Add a duplicate entry for key
self._add_key(key)
self._pairs.append((key, val))
if do_callback:
self._mod_callback()
def set_val(self, key, val, do_callback=True):
"""
set_val(key, val)
Set a value in the dictionary. Will replace the first instance of the
key with the value. If multiple values of the keys are already in the
dictionary, the duplicates of the key will be removed and the first instance
of the key will be replaced with the value. If the dictionary is case
insensitive, it will maintain the original capitalization. This is the same
behavior as assigning a value via ``d[key] = val``. If the key is not
present, it will be added to the end of the dict.
"""
new_pairs = []
added = False
self._add_key(key)
for p in self._pairs:
if self._ef_key(p[0]) == self._ef_key(key):
if not added:
# only add the first instance
new_pairs.append((key, val))
added = True
else:
new_pairs.append(p)
if not added:
new_pairs.append((key, val))
self._pairs = new_pairs
if do_callback:
self._mod_callback()
def update(self, key, val, do_callback=True):
# If key is already in the dict, replace that value with the new value
if key in self:
for k, v in self.all_pairs():
if self._ef_key(k) == self._ef_key(key):
self.set_val(k, val, do_callback=do_callback)
break
else:
self.set_val(key, val, do_callback=do_callback)
def clear(self, do_callback=True):
"""
clear()
Remove all key/value pairs from the dictionary
"""
self._pairs = []
if do_callback:
self._mod_callback()
def all_vals(self, key):
"""
all_vals(key)
Return all the values associated with a given key
"""
return [p[1] for p in self._pairs if self._ef_key(p[0]) == self._ef_key(key)]
def add_pairs(self, pairs, do_callback=True):
"""
add_pairs(pairs)
Add a list of pairs to the dictionary.
:param pairs: The list of key/value pairs to add
:type pairs: List of tuples of length 2
"""
for pair in pairs:
self._add_key(pair[0])
self._pairs += pairs
if do_callback:
self._mod_callback()
def from_dict(self, d, do_callback=True):
"""
from_dict(d)
Set the RepeatableDict to contain the same items as a normal dictionary.
:param d: The dictionary to use
:type d: dict
"""
self._pairs = list(d.items())
if do_callback:
self._mod_callback()
def sort(self):
"""
sort()
Sort the dictionary by the key. Requires that all keys can be compared
to each other
"""
# Sorts pairs by key alphabetaclly
self._pairs = sorted(self._pairs, key=lambda x: x[0])
def set_modify_callback(self, callback):
# Add a function to be called whenever an element is added, changed, or
# deleted. Set to None to remove
self._modify_callback = callback
class LengthData:
def __init__(self, length=None):
self.body = ''
self.complete = False
self.length = length or 0
if self.length == 0 or self.length == -1:
self.complete = True
def add_data(self, data):
if self.complete and self.length != -1:
raise PappyException("Data already complete!")
remaining_length = self.length-len(self.body)
if self.length == -1:
self.body += data
complete = True
else:
if len(data) >= remaining_length:
self.body += data[:remaining_length]
assert(len(self.body) == self.length)
self.complete = True
else:
self.body += data
class ChunkedData:
def __init__(self):
self.body = ''
self._pos = 0
self._state = 0 # 0=reading length, 1=reading data, 2=going over known string
self._len_str = ''
self._chunk_remaining = 0
self._known_str = ''
self._known_str_pos = 0
self._next_state = 0
self._body = []
self.complete = False
self.unchunked_data = []
def add_data(self, data):
for c in data:
self._body.append(c)
self.scan_forward()
def scan_forward(self):
# Don't add more data if we're already done
if self.complete:
return
while self._pos < len(self._body):
curchar = self._body[self._pos]
if self._state == 0:
if curchar.lower() in '0123456789abcdef':
# Read the next char of the length
self._len_str += curchar
# Move to the next char
self._pos += 1
elif curchar == '\r':
# Save how much chunk to read
self._chunk_remaining = int(self._len_str, 16)
# If the length is 0, chunked encoding is done!
if self._chunk_remaining == 0:
self.complete = True
self.body = ''.join(self.unchunked_data)
return
# There should be a newline after the \r
self._known_str = '\n'
self._state = 2
self._next_state = 1
# Reset the length str
self._len_str = ''
# Move to the next char
self._pos += 1
else:
raise Exception("Malformed chunked encoding!")
elif self._state == 1:
if self._chunk_remaining > 0:
# Read next byte of data
self.unchunked_data.append(curchar)
self._chunk_remaining -= 1
self._pos += 1
else:
# Read newline then read a new chunk
self._known_str = '\r\n'
self._next_state = 0 # Read len after newlines
self._state = 2 # Read newlines
# Don't move to the next char because we didn't do anything
elif self._state == 2:
# Read a char of an expected string
# If the expected char doesn't match, throw an error
if self._known_str[self._known_str_pos] != curchar:
raise Exception("Unexpected data")
# Move to the next char in the raw data and in our known string
self._known_str_pos += 1
self._pos += 1
# If we've reached the end of the known string, go to the next state
if self._known_str_pos == len(self._known_str):
self._known_str_pos = 0
self._state = self._next_state
class ResponseCookie(object):
"""
A cookie representing a cookie set by a response
:ivar key: The key of the cookie
:type key: string
:ivar val: The value of the cookie
:type val: string
:ivar expires: The value of the "expires" attribute
:type expires: string
:ivar max_age: The max age of the cookie
:type max_age: int
:ivar domain: The domain of the cookie
:type domain: string
:ivar path: The path of the cookie
:type path: string
:ivar secure: The secure flag of the cookie
:type secure: Bool
:ivar http_only: The httponly flag of the cookie
:type http_only: Bool
"""
def __init__(self, set_cookie_string=None):
self.key = None
self.val = None
self.expires = None
self.max_age = None
self.domain = None
self.path = None
self.secure = False
self.http_only = False
if set_cookie_string:
self._from_cookie(set_cookie_string)
@property
def cookie_str(self):
"""
Returns the full string of the cookie. ie ``foo=bar; secure; path=/``
:getter: Returns the full string of the cookie.
:setter: Set the metadata from a cookie string. ie from a ``Set-Cookie`` header
"""
av = '%s=%s' % (self.key, self.val)
to_add = [av]
if self.expires:
to_add.append('expires=%s'%self.expires)
if self.max_age:
to_add.append('Max-Age=%d'%self.max_age)
if self.domain:
to_add.append('Domain=%s'%self.domain)
if self.path:
to_add.append('Path=%s'%self.path)
if self.secure:
to_add.append('secure')
if self.http_only:
to_add.append('httponly')
return '; '.join(to_add)
@cookie_str.setter
def cookie_str(self, val):
self._from_cookie(val)
def _parse_cookie_av(self, cookie_av):
if '=' in cookie_av:
key, val = cookie_av.split('=', 1)
key = key.lstrip()
if key.lower() == 'expires':
self.expires = val
if key.lower() == 'max-age':
self.max_age = int(val)
if key.lower() == 'domain':
self.domain = val
if key.lower() == 'path':
self.path = val
elif cookie_av.lstrip().lower() == 'secure':
self.secure = True
elif cookie_av.lstrip().lower() == 'httponly':
self.http_only = True
def _from_cookie(self, set_cookie_string):
self.key = None
self.val = None
self.expires = None
self.max_age = None
self.domain = None
self.path = None
self.secure = False
self.http_only = False
if ';' in set_cookie_string:
cookie_pair, rest = set_cookie_string.split(';', 1)
if '=' in cookie_pair:
self.key, self.val = cookie_pair.split('=',1)
elif cookie_pair == '' or re.match('\s+', cookie_pair):
self.key = ''
self.val = ''
else:
self.key = cookie_pair
self.val = ''
cookie_avs = rest.split(';')
for cookie_av in cookie_avs:
cookie_av.lstrip()
self._parse_cookie_av(cookie_av)
else:
self.key, self.val = set_cookie_string.split('=',1)
class WebSocketMessage(object):
"""
A class representing a websocket message
"""
DIRECTION_OUTGOING = 0
DIRECTION_INCOMING = 1
TYPE_MESSAGE = 0
def __init__(self, direction=None, contents=None, message_type=None, time_sent=None, is_binary=None):
self.direction = None
self.contents = None
self.message_type = WebSocketMessage.TYPE_MESSAGE
self.time_sent = None
self.unmangled = None
self.parent_request = None
self.is_unmangled_version = False
self.is_binary = False
self.msgid = '--'
def __eq__(self, other):
if self.contents != other.contents:
return False
if self.is_binary != other.is_binary:
return False
return True
def __copy__(self):
new_msg = WebSocketMessage()
new_msg.direction = self.direction
new_msg.contents = self.contents
new_msg.message_type = self.message_type
new_msg.is_binary = self.is_binary
return new_msg
def copy(self):
return self.__copy__()
def duplicate(self):
m = self.copy()
m.msgid = self.msgid
m.time_sent = self.time_sent
if self.unmangled:
m.unmangled = self.unmangled.duplicate()
return m
@defer.inlineCallbacks
def async_save(self, cust_dbpool=None):
from .pappy import main_context
global dbpool
if cust_dbpool:
use_dbpool = cust_dbpool
else:
use_dbpool = dbpool
assert(use_dbpool)
if not self.msgid:
self.msgid = '--'
try:
# Check for intyness
_ = int(self.msgid)
# If we have msgid, we're updating
yield use_dbpool.runInteraction(self._update)
assert(self.msgid is not None)
except (ValueError, TypeError):
# Either no id or in-memory
yield use_dbpool.runInteraction(self._insert)
assert(self.msgid is not None)
main_context.cache_reset()
@defer.inlineCallbacks
def async_deep_save(self):
if self.unmangled:
yield self.unmangled.async_deep_save()
yield self.async_save()
def _update(self, txn):
setnames = ['is_binary=?', 'contents=?']
queryargs = [self.is_binary, self.contents]
# Direction
if self.direction == 'OUTGOING':
setnames.append('direction=?')
queryargs.append(0)
elif self.direction == 'INCOMING':
setnames.append('direction=?')
queryargs.append(1)
else:
setnames.append('direction=?')
queryargs.append(-1)
# Unmangled
if self.unmangled:
setnames.append('unmangled_id=?')
assert(self.unmangled.msgid is not None) # should be saved first
queryargs.append(self.unmangled.msgid)
# Message time
if self.time_sent:
setnames.append('time_sent=?')
queryargs.append((self.time_sent-datetime.datetime(1970,1,1)).total_seconds())
# Parent request
if self.parent_request:
assert(self.parent_request.reqid)
setnames.append('parent_request=?')
queryargs.append(self.parent_request.reqid)
queryargs.append(self.msgid)
txn.execute(
"""
UPDATE websocket_messages SET %s WHERE id=?;
""" % ','.join(setnames),
tuple(queryargs)
)
def _insert(self, txn):
colnames = ['is_binary', 'contents']
colvals = [self.is_binary, self.contents]
# Direction
if self.direction == 'OUTGOING':
colnames.append('direction')
colvals.append(0)
elif self.direction == 'INCOMING':
colnames.append('direction')
colvals.append(1)
else:
colnames.append('direction')
colvals.append(-1)
# Unmangled
if self.unmangled:
colnames.append('unmangled_id')
assert(self.unmangled.msgid is not None) # should be saved first
colvals.append(self.unmangled.msgid)
# Message time
if self.time_sent:
colnames.append('time_sent')
colvals.append((self.time_sent-datetime.datetime(1970,1,1)).total_seconds())
# Parent request
if self.parent_request:
assert(self.parent_request.reqid)
colnames.append('parent_request')
colvals.append(self.parent_request.reqid)
txn.execute(
"""
INSERT INTO websocket_messages (%s) VALUES (%s);
""" % (','.join(colnames), ','.join(['?']*len(colvals))),
tuple(colvals)
)
self.msgid = str(txn.lastrowid)
class WebSocketProxy(object):
def __init__(self, server_transport, client_transport, client_handshake, server_handshake, parent_proxy, log_id=None):
self.message_callback = None
self.close_callback = None
self.log_id = log_id
self.intercepting_macros = None
self.parent_http_proxy = parent_proxy
# The raw http messages from the handshake
self.client_handshake = client_handshake
self.server_handshake = server_handshake
self.server_factory = WebSocketServerFactory()
self.server_factory.protocol = WebSocketServerProtocol
self.server_transport = server_transport
self.client_factory = WebSocketClientFactory()
self.client_factory.protocol = WebSocketClientProtocol
self.client_transport = client_transport
self._fake_handshake()
def log(self, message, symbol='*', verbosity_level=3):
from pappyproxy.proxy import log
if self.log_id:
log(message, id=log_id, symbol=symbol, verbosity_level=verbosity_level)
else:
log(message, symbol=symbol, verbosity_level=verbosity_level)
def _build_server_protocol(self):
self.server_protocol = self.server_factory.buildProtocol(None)
self.server_protocol.makeConnection(self.server_transport)
self._patch_server_protocol()
def _build_client_protocol(self):
"""
Builds the client protocol then returns the bytes written to the
transport after creation
"""
self.client_protocol = self.client_factory.buildProtocol(None)
tr = PappyStringTransport()
self.client_protocol.makeConnection(tr)
tval = tr.pop_value()
self.client_protocol.transport = self.client_transport
self._patch_client_protocol()
return tval
def _patch_server_protocol(self):
self.log("Patching server protocol")
self._add_hook(self.server_protocol, 'onMessage', '_on_server_message')
def _patch_client_protocol(self):
self.log("Patching client protocol")
self._add_hook(self.client_protocol, 'onMessage', '_on_client_message')
def _add_hook(self, c, their_method, my_method):
"""
Make it so that c.their_method(*args, **kwargs) calls self.my_method(*args, **kwargs)
before calling their method
"""
old = getattr(c, their_method)
def patched(*args, **kwargs):
getattr(self, my_method)(*args, **kwargs)
old(*args, **kwargs)
setattr(c, their_method, patched)
@staticmethod
def _gen_sec_websocket_accept(token):
MAGIC_STRING = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
concatenated = token + MAGIC_STRING
hashed = sha1(concatenated)
reencoded = base64.b64encode(hashed)
return reencoded
def _parse_extension_header(self, hd):
"""
Parses the extension header and returns a list of offers
"""
offers = []
extensions = self.server_protocol._parseExtensionsHeader(hd)
for (extension, params) in extensions:
if extension in PERMESSAGE_COMPRESSION_EXTENSION:
PMCE = PERMESSAGE_COMPRESSION_EXTENSION[extension]
try:
offer = PMCE['Offer'].parse(params)
offers.append(offer)
except Exception as e:
raise PappyException(str(e))
else:
self.log("Bad extension: %s" % extension)
return offers
def _set_up_ws_client(self, ws_server_factory, ws_client_factory, hs_req, hs_rsp):
"""
Sets up a WebSocketClientProtocolFactory from a WebSocketServerProtocolFactory
"""
self.log("Setting up websocket client")
client_settings = {}
# Common attributes
skip_attrs = ('logFrames','trackTimings','logOctets')
for attr in WebSocketProtocol.CONFIG_ATTRS_COMMON:
if attr not in skip_attrs:
client_settings[attr] = getattr(ws_server_factory, attr)
def accept(response):
from autobahn.websocket.compress import PerMessageDeflateResponse, \
PerMessageDeflateResponseAccept, \
PerMessageBzip2Response, \
PerMessageBzip2ResponseAccept, \
PerMessageSnappyResponse, \
PerMessageSnappyResponseAccept
if isinstance(response, PerMessageDeflateResponse):
return PerMessageDeflateResponseAccept(response)
elif isinstance(response, PerMessageBzip2Response):
return PerMessageBzip2ResponseAccept(response)
elif isinstance(response, PerMessageSnappyResponse):
return PerMessageSnappyResponseAccept(response)
# Client specific attributes
client_settings['version'] = int(hs_req.headers['Sec-WebSocket-Version'])
client_settings['acceptMaskedServerFrames'] = True
client_settings['maskClientFrames'] = True
#client_settings['serverConnectionDropTimeout'] = None
offers = self._parse_extension_header(hs_req.headers['Sec-WebSocket-Extensions'])
client_settings['perMessageCompressionOffers'] = offers
client_settings['perMessageCompressionAccept'] = accept
# debug
client_settings['openHandshakeTimeout'] = 8
self.log("Setting client options: %s" % client_settings)
ws_client_factory.setProtocolOptions(**client_settings)
def _fake_handshake(self):
self.log("Performing fake handshake")
# Set up our server listener
self._build_server_protocol()
old_server_transport = self.server_protocol.transport
self.server_protocol.transport = PappyStringTransport()
self.log("Sending fake handshake response to server protocol:")
self.log("pf> %s" % printable_data(self.server_handshake.full_message))
self.server_protocol.dataReceived(self.server_handshake.full_message)
tval = self.server_protocol.transport.pop_value()
self.log("<fp %s" % printable_data(tval))
assert tval
self.server_protocol.transport = old_server_transport
# Set up our client
self._set_up_ws_client(self.server_factory,
self.client_factory,
self.server_handshake,
self.client_handshake)
# Perform rest of client handshake
tval = self._build_client_protocol()
self.log("Getting handshake request start from client protocol")
self.log("<fp %s" % printable_data(tval))
# Revert transport handshake so that any data sent after our response is
# sent to the real transport
self.log("Reverting client transport")
self.log("Sending fake handshake response to client protocol:")
handshake_req = Request(tval)
handshake_rsp = self.client_handshake.copy()
sec_ws_key = handshake_req.headers['Sec-WebSocket-Key']
self.log("Generating Sec-WebSocket-Accept for %s" % sec_ws_key)
sec_ws_accept = WebSocketProxy._gen_sec_websocket_accept(sec_ws_key)
self.log("Sec-WebSocket-Accept = %s" % sec_ws_accept)
handshake_rsp.headers['Sec-WebSocket-Accept'] = sec_ws_accept
self.log("pf> %s" % printable_data(handshake_rsp.full_message))
self.client_protocol.dataReceived(handshake_rsp.full_message) # Tell it whatever the remote server told us
self.log("Compressed after handshake? %s" % self.client_protocol._perMessageCompress)
self.log("Fake handshake complete")
def _on_server_message(self, payload, is_binary):
"""
Wrapper to convert arguments to onMessage into an object and call on_server_message
"""
# Turn into object
m = WebSocketMessage()
m.direction = 'OUTGOING'
m.contents = payload
m.time_sent = datetime.datetime.utcnow()
m.is_binary = is_binary
self.log("rp< (websocket, binary=%s) %s" % (m.is_binary, m.contents))
self.on_server_message(m)
def _on_client_message(self, payload, is_binary):
"""
Wrapper function for when the client protocol gets a data frame
"""
# Turn into object
m = WebSocketMessage()
m.direction = 'INCOMING'
m.contents = payload
m.time_sent = datetime.datetime.utcnow()
m.is_binary = is_binary
self.log("cp> (websocket, binary=%s) %s" % (m.is_binary, m.contents))