forked from uyjco0/flashproxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflashproxy-client
executable file
·1177 lines (1044 loc) · 40.7 KB
/
flashproxy-client
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
import BaseHTTPServer
import array
import base64
import cStringIO
import getopt
import httplib
import os
import os.path
import re
import select
import socket
import struct
import subprocess
import sys
import threading
import time
import traceback
import urllib
import xml.sax.saxutils
try:
from hashlib import sha1
except ImportError:
# Python 2.4 uses this name.
from sha import sha as sha1
try:
import numpy
except ImportError:
numpy = None
# Default local port in managed mode (choose one arbitrarily).
DEFAULT_LOCAL_PORT_MANAGED = 0
# Default local port in external mode.
DEFAULT_LOCAL_PORT_EXTERNAL = 9001
DEFAULT_REMOTE_PORT = 9000
DEFAULT_REGISTER_METHODS = ["email", "http"]
# We will re-register if we have fewer than this many waiting proxies. The
# facilitator may choose to ignore our requests.
DESIRED_NUMBER_OF_PROXIES = 3
LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
class options(object):
local_addrs = []
remote_addrs = []
register_addr = None
facilitator_url = None
managed = True
log_filename = None
log_file = sys.stdout
daemonize = False
register = False
register_commands = []
pid_filename = None
safe_logging = True
address_family = socket.AF_UNSPEC
# We accept up to this many bytes from a socket not yet matched with a partner
# before disconnecting it.
UNCONNECTED_BUFFER_LIMIT = 10240
def usage(f = sys.stdout):
print >> f, """\
Usage: %(progname)s --register [LOCAL][:PORT] [REMOTE][:PORT]
Wait for connections on a local and a remote port. When any pair of connections
exists, data is ferried between them until one side is closed. By default
LOCAL is localhost addresses on port %(local_port)d and REMOTE is all addresses
on port %(remote_port)d.
The local connection acts as a SOCKS4a proxy, but the host and port in the SOCKS
request are ignored and the local connection is always linked to a remote
connection.
By default, runs as a managed proxy: informs a parent Tor project of support for
the "websocket" pluggable transport. In managed mode, the LOCAL port is chosen
arbitrarily instead of defaulting to %(local_port)d; however this can be
overridden by including a LOCAL port in the command. This is the way the
program should be invoked in a torrc ClientTransportPlugin "exec" line.
Use the --external option to run as an external proxy that does not
interact with Tor.
If any of the --register, --register-addr, or --register-methods options are
used, then your IP address will be sent to the facilitator so that proxies can
connect to you. You need to register in some way in order to get any service.
The --facilitator option allows controlling which facilitator is used; if
omitted, it uses a public default.
-4 registration helpers use IPv4.
-6 registration helpers use IPv6.
--daemon daemonize (Unix only).
--external be an external proxy (don't interact with Tor using
environment variables and stdout).
-f, --facilitator=URL advertise willingness to receive connections to URL.
-h, --help show this help.
-l, --log FILENAME write log to FILENAME (default stdout).
--pidfile FILENAME write PID to FILENAME after daemonizing.
-r, --register register with the facilitator.
--register-addr=ADDR register the given address (in case it differs from
REMOTE). Implies --register.
--register-methods=METHOD[,METHOD...]
register using the given comma-separated list of
methods. Implies --register. Possible methods are
email http
Default is "%(reg_methods)s".
--unsafe-logging don't scrub IP addresses from logs.\
""" % {
"progname": sys.argv[0],
"local_port": DEFAULT_LOCAL_PORT_EXTERNAL,
"remote_port": DEFAULT_REMOTE_PORT,
"reg_methods": ",".join(DEFAULT_REGISTER_METHODS),
}
def safe_str(s):
"""Return s if options.safe_logging is true, and "[scrubbed]" otherwise."""
if options.safe_logging:
return "[scrubbed]"
else:
return s
log_lock = threading.Lock()
def log(msg):
log_lock.acquire()
try:
print >> options.log_file, (u"%s %s" % (time.strftime(LOG_DATE_FORMAT), msg)).encode("UTF-8")
options.log_file.flush()
finally:
log_lock.release()
def parse_addr_spec(spec, defhost = None, defport = None):
host = None
port = None
af = 0
m = None
# IPv6 syntax.
if not m:
m = re.match(ur'^\[(.+)\]:(\d*)$', spec)
if m:
host, port = m.groups()
af = socket.AF_INET6
if not m:
m = re.match(ur'^\[(.+)\]$', spec)
if m:
host, = m.groups()
af = socket.AF_INET6
# IPv4/hostname/port-only syntax.
if not m:
try:
host, port = spec.split(":", 1)
except ValueError:
host = spec
if re.match(ur'^[\d.]+$', host):
af = socket.AF_INET
else:
af = 0
host = host or defhost
port = port or defport
if port is not None:
port = int(port)
return host, port
def format_addr(addr):
host, port = addr
if not host:
return u":%d" % port
# Numeric IPv6 address?
try:
addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_NUMERICHOST)
af = addrs[0][0]
except socket.gaierror, e:
af = 0
if af == socket.AF_INET6:
result = u"[%s]" % host
else:
result = "%s" % host
if port is not None:
result += u":%d" % port
return result
def safe_format_addr(addr):
return safe_str(format_addr(addr))
def format_sockaddr(sockaddr):
host, port = socket.getnameinfo(sockaddr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)
port = int(port)
return format_addr((host, port))
def safe_format_sockaddr(sockaddr):
return safe_str(format_sockaddr(sockaddr))
def safe_format_peername(s):
try:
return safe_format_sockaddr(s.getpeername())
except socket.error, e:
return "<unconnected>"
def apply_mask_numpy(payload, mask_key):
if len(payload) == 0:
return ""
payload_a = numpy.frombuffer(payload, dtype="|u4", count=len(payload)//4)
m, = numpy.frombuffer(mask_key, dtype="|u4", count=1)
result = numpy.bitwise_xor(payload_a, m).tostring()
i = len(payload) // 4 * 4
if i < len(payload):
remainder = []
while i < len(payload):
remainder.append(chr(ord(payload[i]) ^ ord(mask_key[i % 4])))
i += 1
result = result + "".join(remainder)
return result
def apply_mask_py(payload, mask_key):
result = array.array("B", payload)
m = array.array("B", mask_key)
i = 0
while i < len(result) - 7:
result[i] ^= m[0]
result[i+1] ^= m[1]
result[i+2] ^= m[2]
result[i+3] ^= m[3]
result[i+4] ^= m[0]
result[i+5] ^= m[1]
result[i+6] ^= m[2]
result[i+7] ^= m[3]
i += 8
while i < len(result):
result[i] ^= m[i%4]
i += 1
return result.tostring()
if numpy is not None:
apply_mask = apply_mask_numpy
else:
apply_mask = apply_mask_py
class WebSocketFrame(object):
def __init__(self):
self.fin = False
self.opcode = None
self.payload = None
def is_control(self):
return (self.opcode & 0x08) != 0
class WebSocketMessage(object):
def __init__(self):
self.opcode = None
self.payload = None
def is_control(self):
return (self.opcode & 0x08) != 0
class WebSocketDecoder(object):
"""RFC 6455 section 5 is about the WebSocket framing format."""
# Raise an exception rather than buffer anything larger than this.
MAX_MESSAGE_LENGTH = 1024 * 1024
class MaskingError(ValueError):
pass
def __init__(self, use_mask = False):
"""use_mask should be True for server-to-client sockets, and False for
client-to-server sockets."""
self.use_mask = use_mask
# Per-frame state.
self.buf = ""
# Per-message state.
self.message_buf = ""
self.message_opcode = None
def feed(self, data):
self.buf += data
def read_frame(self):
"""Read a frame from the internal buffer, if one is available. Returns a
WebSocketFrame object, or None if there are no complete frames to
read."""
# RFC 6255 section 5.2.
if len(self.buf) < 2:
return None
offset = 0
b0, b1 = struct.unpack_from(">BB", self.buf, offset)
offset += 2
fin = (b0 & 0x80) != 0
opcode = b0 & 0x0f
frame_masked = (b1 & 0x80) != 0
payload_len = b1 & 0x7f
if payload_len == 126:
if len(self.buf) < offset + 2:
return None
payload_len, = struct.unpack_from(">H", self.buf, offset)
offset += 2
elif payload_len == 127:
if len(self.buf) < offset + 8:
return None
payload_len, = struct.unpack_from(">Q", self.buf, offset)
offset += 8
if frame_masked:
if not self.use_mask:
# "A client MUST close a connection if it detects a masked
# frame."
raise self.MaskingError("Got masked payload from server")
if len(self.buf) < offset + 4:
return None
mask_key = self.buf[offset:offset+4]
offset += 4
else:
if self.use_mask:
# "The server MUST close the connection upon receiving a frame
# that is not masked."
raise self.MaskingError("Got unmasked payload from client")
mask_key = None
if payload_len > self.MAX_MESSAGE_LENGTH:
raise ValueError("Refusing to buffer payload of %d bytes" % payload_len)
if len(self.buf) < offset + payload_len:
return None
if mask_key:
payload = apply_mask(self.buf[offset:offset+payload_len], mask_key)
else:
payload = self.buf[offset:offset+payload_len]
self.buf = self.buf[offset+payload_len:]
frame = WebSocketFrame()
frame.fin = fin
frame.opcode = opcode
frame.payload = payload
return frame
def read_message(self):
"""Read a complete message. If the opcode is 1, the payload is decoded
from a UTF-8 binary string to a unicode string. If a control frame is
read while another fragmented message is in progress, the control frame
is returned as a new message immediately. Returns None if there is no
complete frame to be read."""
# RFC 6455 section 5.4 is about fragmentation.
while True:
frame = self.read_frame()
if frame is None:
return None
# "Control frames (see Section 5.5) MAY be injected in the middle of
# a fragmented message. Control frames themselves MUST NOT be
# fragmented."
if frame.is_control():
if not frame.fin:
raise ValueError("Control frame (opcode %d) has FIN bit clear" % frame.opcode)
message = WebSocketMessage()
message.opcode = frame.opcode
message.payload = frame.payload
return message
if self.message_opcode is None:
if frame.opcode == 0:
raise ValueError("First frame has opcode 0")
self.message_opcode = frame.opcode
else:
if frame.opcode != 0:
raise ValueError("Non-first frame has nonzero opcode %d" % frame.opcode)
if len(self.message_buf) + len(frame.payload) > self.MAX_MESSAGE_LENGTH:
raise ValueError("Refusing to buffer payload of %d bytes" % (len(self.message_buf) + len(frame.payload)))
self.message_buf += frame.payload
if frame.fin:
break
message = WebSocketMessage()
message.opcode = self.message_opcode
message.payload = self.message_buf
self.postprocess_message(message)
self.message_opcode = None
self.message_buf = ""
return message
def postprocess_message(self, message):
if message.opcode == 1:
message.payload = message.payload.decode("utf-8")
return message
class WebSocketEncoder(object):
def __init__(self, use_mask = False):
self.use_mask = use_mask
def encode_frame(self, opcode, payload):
if opcode >= 16:
raise ValueError("Opcode of %d is >= 16" % opcode)
length = len(payload)
if self.use_mask:
mask_key = os.urandom(4)
payload = apply_mask(payload, mask_key)
mask_bit = 0x80
else:
mask_key = ""
mask_bit = 0x00
if length < 126:
len_b, len_ext = length, ""
elif length < 0x10000:
len_b, len_ext = 126, struct.pack(">H", length)
elif length < 0x10000000000000000:
len_b, len_ext = 127, struct.pack(">Q", length)
else:
raise ValueError("payload length of %d is too long" % length)
return chr(0x80 | opcode) + chr(mask_bit | len_b) + len_ext + mask_key + payload
def encode_message(self, opcode, payload):
if opcode == 1:
payload = payload.encode("utf-8")
return self.encode_frame(opcode, payload)
# WebSocket implementations generally support text (opcode 1) messages, which
# are UTF-8-encoded text. Not all support binary (opcode 2) messages. During the
# WebSocket handshake, we use the "base64" value of the Sec-WebSocket-Protocol
# header field to indicate that text frames should encoded UTF-8-encoded
# base64-encoded binary data. Binary messages are always interpreted verbatim,
# but text messages are rejected if "base64" was not negotiated.
#
# The idea here is that browsers that know they don't support binary messages
# can negotiate "base64" with both endpoints and still reliably transport binary
# data. Those that know they can support binary messages can just use binary
# messages in the straightforward way.
class WebSocketBinaryDecoder(object):
def __init__(self, protocols, use_mask = False):
self.dec = WebSocketDecoder(use_mask)
self.base64 = "base64" in protocols
def feed(self, data):
self.dec.feed(data)
def read(self):
"""Returns None when there are currently no data to be read. Returns ""
when a close message is received."""
while True:
message = self.dec.read_message()
if message is None:
return None
elif message.opcode == 1:
if not self.base64:
raise ValueError("Received text message on decoder incapable of base64")
payload = base64.b64decode(message.payload)
if payload:
return payload
elif message.opcode == 2:
if message.payload:
return message.payload
elif message.opcode == 8:
return ""
# Ignore all other opcodes.
return None
class WebSocketBinaryEncoder(object):
def __init__(self, protocols, use_mask = False):
self.enc = WebSocketEncoder(use_mask)
self.base64 = "base64" in protocols
def encode(self, data):
if self.base64:
return self.enc.encode_message(1, base64.b64encode(data))
else:
return self.enc.encode_message(2, data)
def listen_socket(addr):
"""Return a socket listening on the given address."""
addrinfo = socket.getaddrinfo(addr[0], addr[1], 0, socket.SOCK_STREAM, socket.IPPROTO_TCP)[0]
s = socket.socket(addrinfo[0], addrinfo[1], addrinfo[2])
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if addrinfo[0] == socket.AF_INET6 and socket.has_ipv6:
# Set the IPV6_V6ONLY socket option, otherwise some operating systems
# will listen on an IPv4 address as well as IPv6 by default. For
# example, "::" will listen on both "::" and "0.0.0.0", and "::1" will
# listen on both "::1" and "127.0.0.1". See
# https://trac.torproject.org/projects/tor/ticket/4760.
try:
s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
except AttributeError:
# Python 2.7.3 on Windows does not define IPPROTO_IPV6; see
# http://bugs.python.org/issue6926. IPV6_V6ONLY is the default
# behavior on Windows anyway, so we can skip the setsockopt.
pass
s.bind(addr)
s.listen(10)
return s
# How long to wait for a WebSocket request on the remote socket. It is limited
# to avoid Slowloris-like attacks.
WEBSOCKET_REQUEST_TIMEOUT = 2.0
# This subclass of BaseHTTPRequestHandler is essentially a means of parsing an
# HTTP request.
class WebSocketRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, request_text, fd):
self.rfile = cStringIO.StringIO(request_text)
self.wfile = fd.makefile()
self.error = False
self.raw_requestline = self.rfile.readline()
self.parse_request()
def log_message(self, *args):
pass
def send_error(self, code, message = None):
BaseHTTPServer.BaseHTTPRequestHandler.send_error(self, code, message)
self.error = True
MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
def handle_websocket_request(fd):
try:
request_text = fd.recv(10 * 1024)
except socket.error, e:
log(u"Socket error while receiving WebSocket request: %s" % repr(str(e)))
return None
handler = WebSocketRequestHandler(request_text, fd)
if handler.error or not hasattr(handler, "path"):
return None
method = handler.command
path = handler.path
headers = handler.headers
# See RFC 6455 section 4.2.1 for this sequence of checks.
#
# 1. An HTTP/1.1 or higher GET request, including a "Request-URI"...
if method != "GET":
handler.send_error(405)
return None
if path != "/":
handler.send_error(404)
return None
# 2. A |Host| header field containing the server's authority.
# We deliberately skip this test.
# 3. An |Upgrade| header field containing the value "websocket", treated as
# an ASCII case-insensitive value.
upgrade = headers.get("upgrade")
if upgrade is None:
handler.send_error(400)
return None
if "websocket" not in [x.strip().lower() for x in upgrade.split(",")]:
handler.send_error(400)
return None
# 4. A |Connection| header field that includes the token "Upgrade", treated
# as an ASCII case-insensitive value.
connection = headers.get("connection")
if connection is None:
handler.send_error(400)
return None
if "upgrade" not in [x.strip().lower() for x in connection.split(",")]:
handler.send_error(400)
return None
# 5. A |Sec-WebSocket-Key| header field with a base64-encoded value that,
# when decoded, is 16 bytes in length.
try:
key = headers.get("sec-websocket-key")
if len(base64.b64decode(key)) != 16:
raise TypeError("Sec-WebSocket-Key must be 16 bytes")
except TypeError:
handler.send_error(400)
return None
# 6. A |Sec-WebSocket-Version| header field, with a value of 13. We also
# allow 8 from draft-ietf-hybi-thewebsocketprotocol-10.
version = headers.get("sec-websocket-version")
KNOWN_VERSIONS = ["8", "13"]
if version not in KNOWN_VERSIONS:
# "If this version does not match a version understood by the server,
# the server MUST abort the WebSocket handshake described in this
# section and instead send an appropriate HTTP error code (such as 426
# Upgrade Required) and a |Sec-WebSocket-Version| header field
# indicating the version(s) the server is capable of understanding."
handler.send_response(426)
handler.send_header("Sec-WebSocket-Version", ", ".join(KNOWN_VERSIONS))
handler.end_headers()
return None
# 7. Optionally, an |Origin| header field.
# 8. Optionally, a |Sec-WebSocket-Protocol| header field, with a list of
# values indicating which protocols the client would like to speak, ordered
# by preference.
protocols_str = headers.get("sec-websocket-protocol")
if protocols_str is None:
protocols = []
else:
protocols = [x.strip().lower() for x in protocols_str.split(",")]
# 9. Optionally, a |Sec-WebSocket-Extensions| header field...
# 10. Optionally, other header fields...
# See RFC 6455 section 4.2.2, item 5 for these steps.
# 1. A Status-Line with a 101 response code as per RFC 2616.
handler.send_response(101)
# 2. An |Upgrade| header field with value "websocket" as per RFC 2616.
handler.send_header("Upgrade", "websocket")
# 3. A |Connection| header field with value "Upgrade".
handler.send_header("Connection", "Upgrade")
# 4. A |Sec-WebSocket-Accept| header field. The value of this header field
# is constructed by concatenating /key/, defined above in step 4 in Section
# 4.2.2, with the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", taking the
# SHA-1 hash of this concatenated value to obtain a 20-byte value and
# base64-encoding (see Section 4 of [RFC4648]) this 20-byte hash.
accept_key = base64.b64encode(sha1(key + MAGIC_GUID).digest())
handler.send_header("Sec-WebSocket-Accept", accept_key)
# 5. Optionally, a |Sec-WebSocket-Protocol| header field, with a value
# /subprotocol/ as defined in step 4 in Section 4.2.2.
if "base64" in protocols:
handler.send_header("Sec-WebSocket-Protocol", "base64")
# 6. Optionally, a |Sec-WebSocket-Extensions| header field...
handler.end_headers()
return protocols
def grab_string(s, pos):
"""Grab a NUL-terminated string from the given string, starting at the given
offset. Return (pos, str) tuple, or (pos, None) on error."""
i = pos
while i < len(s):
if s[i] == '\0':
return (i + 1, s[pos:i])
i += 1
return pos, None
# http://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4.protocol
# https://en.wikipedia.org/wiki/SOCKS#SOCKS4a
def parse_socks_request(data):
"""Parse the 8-byte SOCKS header at the beginning of data. Returns a
(dest, port) tuple. Raises ValueError on error."""
try:
ver, cmd, dport, o1, o2, o3, o4 = struct.unpack(">BBHBBBB", data[:8])
except struct.error:
raise ValueError("Couldn't unpack SOCKS4 header")
if ver != 4:
raise ValueError("Wrong SOCKS version (%d)" % ver)
if cmd != 1:
raise ValueError("Wrong SOCKS command (%d)" % cmd)
pos, userid = grab_string(data, 8)
if userid is None:
raise ValueError("Couldn't read userid")
if o1 == 0 and o2 == 0 and o3 == 0 and o4 != 0:
pos, dest = grab_string(data, pos)
if dest is None:
raise ValueError("Couldn't read destination")
else:
dest = "%d.%d.%d.%d" % (o1, o2, o3, o4)
return dest, dport
def handle_socks_request(fd):
try:
addr = fd.getpeername()
data = fd.recv(100)
except socket.error, e:
log(u"Socket error from SOCKS-pending: %s" % repr(str(e)))
return False
try:
dest_addr = parse_socks_request(data)
except ValueError, e:
log(u"Error parsing SOCKS request: %s." % str(e))
# Error reply.
fd.sendall(struct.pack(">BBHBBBB", 0, 91, 0, 0, 0, 0, 0))
return False
log(u"Got SOCKS request for %s." % safe_format_addr(dest_addr))
fd.sendall(struct.pack(">BBHBBBB", 0, 90, dest_addr[1], 127, 0, 0, 1))
# Note we throw away the requested address and port.
return True
def report_pending():
log(u"locals (%d): %s" % (len(locals), [safe_format_peername(x) for x in locals]))
log(u"remotes (%d): %s" % (len(remotes), [safe_format_peername(x) for x in remotes]))
register_condvar = threading.Condition()
def register():
if not options.register:
return
register_condvar.acquire()
register_condvar.notify()
register_condvar.release()
def register_using_command(command):
basename = os.path.basename(command[0])
try:
log(u"Running command: %s" % " ".join(command))
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
except OSError, e:
log(u"Error running %s: %s" % (basename, str(e)))
return False
for line in stdout.splitlines():
log(u"%s: %s" % (basename, line))
for line in stderr.splitlines():
log(u"%s: %s" % (basename, line))
if p.returncode != 0:
log("%s exited with status %d." % (basename, p.returncode))
return False
return True
def register_one():
spec = format_addr(options.register_addr)
log(u"Trying to register \"%s\"." % spec)
for command in options.register_commands:
if register_using_command(command + [spec]):
break
else:
log(u"All registration commands failed.")
def registration_thread_func():
while True:
register_condvar.acquire()
register_condvar.wait()
register_condvar.release()
if len(unlinked_remotes) < DESIRED_NUMBER_OF_PROXIES:
register_one()
def proxy_chunk_local_to_remote(local, remote, data = None):
if data is None:
try:
data = local.recv(65536)
except socket.error, e: # Can be "Connection reset by peer".
log(u"Socket error from local: %s" % repr(str(e)))
remote.close()
return False
if not data:
log(u"EOF from local %s." % safe_format_peername(local))
local.close()
remote.close()
return False
else:
try:
remote.send_chunk(data)
except socket.error, e:
log(u"Socket error writing to remote: %s" % repr(str(e)))
local.close()
return False
return True
def proxy_chunk_remote_to_local(remote, local, data = None):
if data is None:
try:
data = remote.recv(65536)
except socket.error, e: # Can be "Connection reset by peer".
log(u"Socket error from remote: %s" % repr(str(e)))
local.close()
return False
if not data:
log(u"EOF from remote %s." % safe_format_peername(remote))
remote.close()
local.close()
return False
else:
remote.dec.feed(data)
while True:
try:
data = remote.dec.read()
except (WebSocketDecoder.MaskingError, ValueError), e:
log(u"WebSocket decode error from remote: %s" % repr(str(e)))
remote.close()
local.close()
return False
if data is None:
break
elif not data:
log(u"WebSocket close from remote %s." % safe_format_peername(remote))
remote.close()
local.close()
return False
try:
local.send_chunk(data)
except socket.error, e:
log(u"Socket error writing to local: %s" % repr(str(e)))
remote.close()
return False
return True
def receive_unlinked(fd, label):
"""Receive and buffer data on a socket that has not been linked yet. Returns
True iff there was no error and the socket may still be used; otherwise, the
socket will be closed before returning."""
try:
data = fd.recv(1024)
except socket.error, e:
log(u"Socket error from %s: %s" % (label, repr(str(e))))
fd.close()
return False
if not data:
log(u"EOF from unlinked %s %s with %d bytes buffered." % (label, safe_format_peername(fd), len(fd.buf)))
fd.close()
return False
else:
log(u"Data from unlinked %s %s (%d bytes)." % (label, safe_format_peername(fd), len(data)))
fd.buf += data
if len(fd.buf) >= UNCONNECTED_BUFFER_LIMIT:
log(u"Refusing to buffer more than %d bytes from %s %s." % (UNCONNECTED_BUFFER_LIMIT, label, safe_format_peername(fd)))
fd.close()
return False
return True
def match_proxies():
while unlinked_remotes and unlinked_locals:
remote = unlinked_remotes.pop(0)
local = unlinked_locals.pop(0)
log(u"Linking %s and %s." % (safe_format_peername(local), safe_format_peername(remote)))
remote.partner = local
local.partner = remote
if remote.buf:
if not proxy_chunk_remote_to_local(remote, local, remote.buf):
remotes.remove(remote)
locals.remove(local)
register()
return
if local.buf:
if not proxy_chunk_local_to_remote(local, remote, local.buf):
remotes.remove(remote)
locals.remove(local)
return
class TimeoutSocket(object):
def __init__(self, fd):
self.fd = fd
self.birthday = time.time()
def age(self):
return time.time() - self.birthday
def __getattr__(self, name):
return getattr(self.fd, name)
class RemoteSocket(object):
def __init__(self, fd, protocols):
self.fd = fd
self.buf = ""
self.partner = None
self.dec = WebSocketBinaryDecoder(protocols, use_mask = True)
self.enc = WebSocketBinaryEncoder(protocols, use_mask = False)
def send_chunk(self, data):
self.sendall(self.enc.encode(data))
def __getattr__(self, name):
return getattr(self.fd, name)
class LocalSocket(object):
def __init__(self, fd):
self.fd = fd
self.buf = ""
self.partner = None
def send_chunk(self, data):
self.sendall(data)
def __getattr__(self, name):
return getattr(self.fd, name)
def proxy_loop():
while True:
rset = remote_listen + local_listen + websocket_pending + socks_pending + locals + remotes
rset, _, _ = select.select(rset, [], [], WEBSOCKET_REQUEST_TIMEOUT)
for fd in rset:
if fd in remote_listen:
remote_c, addr = fd.accept()
log(u"Remote connection from %s." % safe_format_sockaddr(addr))
websocket_pending.append(TimeoutSocket(remote_c))
elif fd in local_listen:
local_c, addr = fd.accept()
log(u"Local connection from %s." % safe_format_sockaddr(addr))
socks_pending.append(local_c)
register()
elif fd in websocket_pending:
log(u"Data from WebSocket-pending %s." % safe_format_peername(fd))
protocols = handle_websocket_request(fd)
if protocols is not None:
wrapped = RemoteSocket(fd, protocols)
remotes.append(wrapped)
unlinked_remotes.append(wrapped)
else:
fd.close()
register()
websocket_pending.remove(fd)
report_pending()
elif fd in socks_pending:
log(u"SOCKS request from %s." % safe_format_peername(fd))
if handle_socks_request(fd):
wrapped = LocalSocket(fd)
locals.append(wrapped)
unlinked_locals.append(wrapped)
else:
fd.close()
socks_pending.remove(fd)
report_pending()
elif fd in remotes:
local = fd.partner
if local:
if not proxy_chunk_remote_to_local(fd, local):
remotes.remove(fd)
locals.remove(local)
register()
else:
if not receive_unlinked(fd, "remote"):
remotes.remove(fd)
unlinked_remotes.remove(fd)
register()
report_pending()
elif fd in locals:
remote = fd.partner
if remote:
if not proxy_chunk_local_to_remote(fd, remote):
remotes.remove(remote)
locals.remove(fd)
else:
if not receive_unlinked(fd, "local"):
locals.remove(fd)
unlinked_locals.remove(fd)
report_pending()
match_proxies()
while websocket_pending:
pending = websocket_pending[0]
if pending.age() < WEBSOCKET_REQUEST_TIMEOUT:
break
log(u"Expired remote connection from %s." % safe_format_peername(pending))
pending.close()
websocket_pending.pop(0)
report_pending()
def build_register_command(method):
# sys.path[0] is initialized to the directory containing the Python script file.
script_dir = sys.path[0]
if not script_dir:
# Maybe the script was read from stdin; in any case don't guess at the directory.
raise ValueError("Can't find executable directory for registration helpers")
af = []
if options.address_family == socket.AF_INET:
af = ["-4"]
elif options.address_family == socket.AF_INET6:
af = ["-6"]
if method == "email":
command = [os.path.join(script_dir, "flashproxy-reg-email")] + af
return command
elif method == "http":
command = [os.path.join(script_dir, "flashproxy-reg-http")] + af
if options.facilitator_url is not None:
command += ["-f", options.facilitator_url]
return command
else:
raise ValueError("Unknown registration method \"%s\"" % method)
def pt_escape(s):
result = []
for c in s:
if c == "\n":
result.append("\\n")
elif c == "\\":
result.append("\\\\")
elif 0 < ord(c) < 128:
result.append(c)
else:
result.append("\\x%02x" % ord(c))
return "".join(result)
def pt_line(keyword, *args):
log(keyword + " " + " ".join(pt_escape(x) for x in args))
print keyword, " ".join(pt_escape(x) for x in args)
sys.stdout.flush()
def pt_enverror(msg):
pt_line("ENV-ERROR", msg)
sys.exit(1)
def pt_smethoderror(msg):
pt_line("SMETHOD-ERROR", msg)
sys.exit(1)
def pt_get_client_transports(known):
result = []
if os.environ.get("TOR_PT_CLIENT_TRANSPORTS") == "*":
return known
for method in os.environ.get("TOR_PT_CLIENT_TRANSPORTS", "").split(","):
if method in known:
result.append(method)
return result
def pt_setup_managed():