forked from pagekite/PyPagekite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pagekite.py
executable file
·5316 lines (4534 loc) · 185 KB
/
pagekite.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/python -u
#
# pagekite.py, Copyright 2010, 2011, the Beanstalks Project ehf.
# and Bjarni Runar Einarsson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
##[ Maybe TODO: ]##############################################################
#
# Optimization:
# - Implement epoll() support.
# - Stress test this thing: when do we need a C rewrite?
# - Make multi-process, use the FD-over-socket trick? Threads=>GIL=>bleh
# - Add QoS and bandwidth shaping
# - Add a scheduler for deferred/periodic processing.
# - Create a derivative BaseHTTPServer which doesn't actually listen()
# on a real socket, but instead communicates with the tunnel directly.
# - Replace string concatenation ops with lists of buffers.
#
# Protocols:
# - Make tunnel creation more stubborn (try multiple ports etc.)
# - Add XMPP and incoming SMTP support.
# - Tor entry point support? Is current SSL enough?
# - Replace current tunnel auth scheme with SSL certificates.
#
# User interface:
# - Enable (re)configuration from within HTTP UI.
# - More human readable console output?
#
# Security:
# - Add same-origin cookie enforcement to front-end. Or is that pointless
# due to Javascript side-channels?
#
# Bugs?
# - Front-ends should time-out dead back-ends.
# - Gzip-related memory issues.
#
#
##[ Hacking guide! ]###########################################################
#
# Hello! Welcome to my source code.
#
# Here's a brief intro to how the program is structured, to encourage people
# to hack and improve.
#
# * The PageKite object contains the master configuration and some related
# routines. It takes care of parsing configuration files and implements
# things like the authentication protocol. It also contains the main event
# loop, which is select() or epoll() based. In short, it's the boss.
#
# * The Connections object keeps track of which tunnels and user connections
# are open at any given time and which protocol/domain pairs they belong to.
# It gets passed around as an argument quite a lot - not too elegant.
#
# * The Selectable and it's *Parser subclasses incrementally build up basic
# parsers for the supported protocols. Note that none of the protocols
# are fully implemented, we only implement the bare minimum required to
# figure out which back-end should handle a given request, and then forward
# the bytes unmodified over that channel. As a result, the current HTTP
# proxy code is not HTTP 1.1 compliant - but if you put it behind Varnish
# or some other decent reverse-proxy, then *the combination* should be!
#
# * The UserConn object represents connections on behalf of users. It can
# be created as a FrontEnd, which will find the right tunnel and send
# traffic to the back-end PageKite process, where a BackEnd UserConn
# will be created to connect to the actual HTTP server.
#
# * The Tunnel object represents one end of a PageKite tunnel and is also
# created either as a FrontEnd or BackEnd, depending on which end it is.
# Tunnels handle multiplexing and demultiplexing all the traffic for
# a given back-end so multiple requests can share a single TCP/IP
# connection.
#
# Although most of the work done by pagekite.py happens in an event-loop
# on a single thread, there are some exceptions:
#
# * The AuthThread handles checking whether an incoming tunnel request is
# allowed or not; authentication requests may end up blocking and waiting
# for each other, but the main work of proxying data back and forth won't
# be blocked.
#
# * The HttpUiThread implements a basic HTTP (or HTTPS) server, for basic
# monitoring and static file serving.
#
# WARNING: The UI threading code assumes it is running in CPython, where the
# GIL makes snooping across the thread-boundary relatively safe, even
# without explicit locking. Beware!
#
###############################################################################
#
PROTOVER = '0.8'
APPVER = '0.4.1+github'
AUTHOR = 'Bjarni Runar Einarsson, http://bre.klaki.net/'
WWWHOME = 'http://pagekite.net/'
LICENSE_URL = 'http://www.gnu.org/licenses/agpl.html'
EXAMPLES = ("""\
To make public a webserver running on localhost:
$ pagekite.py NAME.pagekite.me # local port 80
$ pagekite.py NAME.pagekite.me:3000 # local port 3000
$ pagekite.py NAME.pagekite.me:built-in # built-in HTTPD
$ pagekite.py NAME.pagekite.me:/path/to/webroot # built-in HTTPD
To make public HTTP and SSH servers:
$ pagekite.py http:NAME.pagekite.me ssh:NAME.pagekite.me
$ pagekite.py http,ssh:NAME.pagekite.me # The same thing!
""")
MINIDOC = ("""\
>>> Welcome to pagekite.py v%s!
%s
To sign up with PageKite.net or get advanced instructions:
$ pagekite.py --signup
$ pagekite.py --help
If you request a kite which does not exist in your configuration file,
the program will offer to help you sign up with http://pagekite.net/ and
create it. Just choose whatever name you like and if it's available, it
will be granted.
""") % (APPVER, EXAMPLES)
DOC = ("""\
pagekite.py is Copyright 2010, 2011, the Beanstalks Project ehf.
v%s http://pagekite.net/
This the reference implementation of the PageKite tunneling protocol,
both the front- and back-end. This following protocols are supported:
HTTP - HTTP 1.1 only, requires a valid HTTP Host: header
HTTPS - Recent versions of TLS only, requires the SNI extension.
WEBSOCKET - Using the proposed Upgrade: WebSocket method.
Other protocols may be proxied by using "raw" back-ends and HTTP CONNECT.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License. For the full text of the
license, see: http://www.gnu.org/licenses/agpl-3.0.html
Usage:
pagekite.py [options] [shortcuts]
Common Options:
--clean Skip loading the default configuration file.
--signup Interactively sign up for PageKite.net service.
--defaults Set defaults for use with PageKite.net service.
--optfile=X -o X Read settings from file X. Default is ~/.pagekite.rc.
--savefile=X -S X Saved settings will be written to file X.
--autosave Enable auto-saving.
--noautosave Disable auto-saving.
--save Save this configuration.
--settings Dump the current settings to STDOUT, formatted as
an options file would be.
--httpd=X:P -H X:P Enable the HTTP user interface on hostname X, port P.
--webroot=X Directory to serve as root of built-in HTTPD.
--pemfile=X -P X Use X as a PEM key for the HTTPS UI.
--httppass=X -X X Require password X to access the UI.
--nozchunks Disable zlib tunnel compression.
--sslzlib Enable zlib compression in OpenSSL.
--buffers N Buffer at most N kB of back-end data before blocking.
--logfile=F -L F Log to file F.
--daemonize -Z Run as a daemon.
--runas -U U:G Set UID:GID after opening our listening sockets.
--pidfile=P -I P Write PID to the named file.
--nocrashreport Don't send anonymous crash reports to PageKite.net.
--tls_default=N Default name to use for SSL, if SNI and tracking fail.
--tls_endpoint=N:F Terminate SSL/TLS for name N, using key/cert from F.
--errorurl=U -E U URL to redirect to when back-ends are not found.
Front-end Options:
--isfrontend -f Enable front-end mode.
--authdomain=X -A X Use X as a remote authentication domain.
--host=H -h H Listen on H (hostname).
--ports=A,B,C -p A,B Listen on ports A, B, C, ...
--portalias=A:B Report port A as port B to backends.
--protos=A,B,C Accept the listed protocols for tunneling.
--rawports=A,B,C Listen on ports A, B, C, ... (raw/timed connections)
--domain=proto,proto2,pN:domain:secret
Accept tunneling requests for the named protocols and
specified domain, using the given secret. A * may be
used as a wildcard for subdomains or protocols.
Back-end Options:
--backend=proto:kitename:host:port:secret
Configure a back-end service on host:port, using protocol
proto and the given kite name as the public domain. As a
special case, if host is 'localhost' and the word 'built-in'
is used as a port number, pagekite.py's HTTP server will be used.
--define_backend=... Same as --backend, except not enabled by default.
--frontends=N:X:P Choose N front-ends from X (a DNS domain name), port P.
--frontend=host:port Connect to the named front-end server.
--fe_certname=N Connect using SSL, accepting valid certs for domain N.
--ca_certs=PATH Path to your trusted root SSL certificates file.
--dyndns=X -D X Register changes with DynDNS provider X. X can either
be simply the name of one of the 'built-in' providers,
or a URL format string for ad-hoc updating.
--all -a Terminate early if any tunnels fail to register.
--new -N Don't attempt to connect to the domain's old front-end.
--noprobes Reject all probes for back-end liveness.
--socksify=S:P Connect via SOCKS server S, port P (requires socks.py)
--torify=S:P Same as socksify, but more paranoid.
About the configuration file:
The configuration file contains the same options as are available to the
command line, with the restriction that there be exactly one "option"
per line.
The leading '--' may also be omitted for readability, and for the same
reason it is recommended to use the long form of the options in the
configuration file (also, the short form may not always parse correctly).
Blank lines and lines beginning with # (comments) are treated as comments
and are ignored. It is perfectly acceptable to have multiple configuration
files, and configuration files can include other configuration files.
NOTE: When using -o or --optfile on the command line, it is almost always
advisable to use --clean as well, to suppress the default configuration.
Examples:
Create a configuration file with default options, and then edit it.
$ pagekite.py --defaults --settings > ~/.pagekite.rc
$ vim ~/.pagekite.rc
Run the built-in HTTPD.
$ pagekite.py --defaults --httpd=localhost:9999
$ firefox http://localhost:9999/
Fly a PageKite on pagekite.net for somedomain.com, and register the
new front-ends with the No-IP Dynamic DNS provider.
$ pagekite.py \\
--defaults \\
--dyndns=user:pass@no-ip.com \\
--backend=http:kitename.com:localhost:80:mygreatsecret
Shortcuts:
A shortcut is simply the name of a kite, optionally prefixed by a
protocol specification, followed by a local port number, or followed
by a path to a folder for serving static files from. Protocols,
kite names and ports (or folders) are separated by the ':' character
(see examples below).
When shortcuts are used, all defined back-ends are disabled except for
those matching the list of shortcuts.
If no match is found and the program is run interactively, the user
will be prompted and given the option of signing up and/or creating a
new kite using the PageKite.net service.
Shortcut examples:
"""+EXAMPLES) % APPVER
MAGIC_PREFIX = '/~:PageKite:~/'
MAGIC_PATH = '%sv%s' % (MAGIC_PREFIX, PROTOVER)
MAGIC_PATHS = (MAGIC_PATH, '/Beanstalk~Magic~Beans/0.2')
SERVICE_PROVIDER = 'PageKite.net'
SERVICE_DOMAINS = ('pagekite.me', )
SERVICE_XMLRPC = 'pk:http://pagekite.net/xmlrpc/'
SERVICE_TOS_URL = 'https://pagekite.net/support/terms/'
SERVICE_XMLRPC = 'pk:http://pagekite.net/xmlrpc/'
OPT_FLAGS = 'o:S:H:P:X:L:ZI:fA:R:h:p:aD:U:NE:'
OPT_ARGS = ['noloop', 'clean', 'nopyopenssl', 'nocrashreport',
'signup', 'nullui', 'help',
'optfile=', 'savefile=', 'autosave', 'noautosave',
'save',' settings',
'service_xmlrpc=', 'controlpanel', 'controlpass',
'httpd=', 'pemfile=', 'httppass=', 'errorurl=', 'webroot=',
'logfile=', 'daemonize', 'nodaemonize', 'runas=', 'pidfile=',
'isfrontend', 'noisfrontend', 'defaults', 'domain=',
'authdomain=', 'register=', 'host=',
'ports=', 'protos=', 'portalias=', 'rawports=',
'tls_default=', 'tls_endpoint=', 'fe_certname=', 'ca_certs=',
'backend=', 'define_backend=',
'frontend=', 'frontends=', 'torify=', 'socksify=',
'new', 'all', 'noall', 'dyndns=', 'nozchunks', 'sslzlib',
'buffers=', 'noprobes']
AUTH_ERRORS = '255.255.255.'
AUTH_ERR_USER_UNKNOWN = '.0'
AUTH_ERR_INVALID = '.1'
AUTH_QUOTA_MAX = '255.255.254.255'
VIRTUAL_PN = 'virtual'
CATCHALL_HN = 'unknown'
LOOPBACK_HN = 'loopback'
LOOPBACK_FE = LOOPBACK_HN + ':1'
LOOPBACK_BE = LOOPBACK_HN + ':2'
LOOPBACK = {'FE': LOOPBACK_FE, 'BE': LOOPBACK_BE}
BE_PROTO = 0
BE_PORT = 1
BE_DOMAIN = 2
BE_BHOST = 3
BE_BPORT = 4
BE_SECRET = 5
BE_STATUS = 6
BE_STATUS_OK = 100
BE_STATUS_BE_FAIL = 2
BE_STATUS_NO_TUNNEL = 1
BE_STATUS_DISABLED = -1
BE_STATUS_UNKNOWN = -2
BE_NONE = ('', '', None, None, None, '', BE_STATUS_UNKNOWN)
DYNDNS = {
'pagekite.net': ('http://up.pagekite.net/'
'?hostname=%(domain)s&myip=%(ips)s&sign=%(sign)s'),
'beanstalks.net': ('http://up.b5p.us/'
'?hostname=%(domain)s&myip=%(ips)s&sign=%(sign)s'),
'dyndns.org': ('https://%(user)s:%(pass)s@members.dyndns.org'
'/nic/update?wildcard=NOCHG&backmx=NOCHG'
'&hostname=%(domain)s&myip=%(ip)s'),
'no-ip.com': ('https://%(user)s:%(pass)s@dynupdate.no-ip.com'
'/nic/update?hostname=%(domain)s&myip=%(ip)s'),
}
##[ Standard imports ]########################################################
import base64
import cgi
from cgi import escape as escape_html
import errno
import getopt
import os
import random
import re
import select
import socket
rawsocket = socket.socket
import struct
import sys
import threading
import time
import traceback
import urllib
import xmlrpclib
import zlib
import SocketServer
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
import Cookie
##[ Conditional imports & compatibility magic! ]###############################
# Create our service-domain matching regexp
SERVICE_DOMAIN_RE = re.compile('\.(' + '|'.join(SERVICE_DOMAINS) + ')$')
SERVICE_SUBKITE_RE = re.compile(r'^[A-Za-z0-9_]+$')
# System logging on Unix
try:
import syslog
except ImportError:
pass
# Backwards compatibility for old Pythons.
if not 'SHUT_RD' in dir(socket):
socket.SHUT_RD = 0
socket.SHUT_WR = 1
socket.SHUT_RDWR = 2
try:
sorted([1, 2, 3])
except:
def sorted(l):
tmp = l[:]
tmp.sort()
return tmp
# SSL/TLS strategy: prefer pyOpenSSL, as it comes with built-in Context
# objects. If that fails, look for Python 2.6+ native ssl support and
# create a compatibility wrapper. If both fail, bomb with a ConfigError
# when the user tries to enable anything SSL-related.
SEND_MAX_BYTES = 16 * 1024
SEND_ALWAYS_BUFFERS = False
HAVE_SSL = False
try:
if '--nopyopenssl' in sys.argv:
raise ImportError('pyOpenSSL disabled')
from OpenSSL import SSL
HAVE_SSL = True
def SSL_Connect(ctx, sock,
server_side=False, accepted=False, connected=False,
verify_names=None):
LogInfo('TLS is provided by pyOpenSSL')
if verify_names:
def vcb(conn, x509, errno, depth, rc):
# FIXME: No ALT names, no wildcards ...
if errno != 0: return False
if depth != 0: return True
commonName = x509.get_subject().commonName.lower()
cNameDigest = '%s/%s' % (commonName, x509.digest('sha1').replace(':','').lower())
if (commonName in verify_names) or (cNameDigest in verify_names):
LogDebug('Cert OK: %s' % (cNameDigest))
return True
return False
ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, vcb)
else:
def vcb(conn, x509, errno, depth, rc): return (errno == 0)
ctx.set_verify(SSL.VERIFY_NONE, vcb)
nsock = SSL.Connection(ctx, sock)
if accepted: nsock.set_accept_state()
if connected: nsock.set_connect_state()
if verify_names: nsock.do_handshake()
return nsock
except ImportError:
try:
import ssl
# Because the native Python ssl module does not expose WantWriteError,
# we need this to keep tunnels from shutting down when busy.
SEND_ALWAYS_BUFFERS = True
SEND_MAX_BYTES = 4 * 1024
HAVE_SSL = True
class SSL(object):
SSLv23_METHOD = ssl.PROTOCOL_SSLv23
TLSv1_METHOD = ssl.PROTOCOL_TLSv1
WantReadError = ssl.SSLError
class Error(Exception): pass
class SysCallError(Exception): pass
class WantWriteError(Exception): pass
class ZeroReturnError(Exception): pass
class Context(object):
def __init__(self, method):
self.method = method
self.privatekey_file = None
self.certchain_file = None
self.ca_certs = None
def use_privatekey_file(self, fn): self.privatekey_file = fn
def use_certificate_chain_file(self, fn): self.certchain_file = fn
def load_verify_locations(self, pemfile, capath=None): self.ca_certs = pemfile
def SSL_CheckPeerName(fd, names):
cert = fd.getpeercert()
certhash = sha1hex(fd.getpeercert(binary_form=True))
if not cert: return None
for field in cert['subject']:
if field[0][0].lower() == 'commonname':
name = field[0][1].lower()
namehash = '%s/%s' % (name, certhash)
if name in names or namehash in names:
LogDebug('Cert OK: %s' % (namehash))
return name
if 'subjectAltName' in cert:
for field in cert['subjectAltName']:
if field[0].lower() == 'dns':
name = field[1].lower()
namehash = '%s/%s' % (name, certhash)
if name in names or namehash in names:
LogDebug('Cert OK: %s' % (namehash))
return name
return None
def SSL_Connect(ctx, sock,
server_side=False, accepted=False, connected=False,
verify_names=None):
LogInfo('TLS is provided by native Python ssl')
reqs = (verify_names and ssl.CERT_REQUIRED or ssl.CERT_NONE)
fd = ssl.wrap_socket(sock, keyfile=ctx.privatekey_file,
certfile=ctx.certchain_file,
cert_reqs=reqs,
ca_certs=ctx.ca_certs,
do_handshake_on_connect=False,
ssl_version=ctx.method,
server_side=server_side)
if verify_names:
fd.do_handshake()
if not SSL_CheckPeerName(fd, verify_names):
raise SSL.Error('Cert not in %s (%s)' % (verify_names, reqs))
return fd
except ImportError:
class SSL(object):
SSLv23_METHOD = 0
TLSv1_METHOD = 0
class Error(Exception): pass
class SysCallError(Exception): pass
class WantReadError(Exception): pass
class WantWriteError(Exception): pass
class ZeroReturnError(Exception): pass
class Context(object):
def __init__(self, method):
raise ConfigError('Neither pyOpenSSL nor python 2.6+ ssl modules found!')
if HAVE_SSL:
class PageKiteXmlRpcTransport(xmlrpclib.SafeTransport):
"""Treat the XML-RPC host as a HTTP proxy for itself (SNI workaround)"""
def make_connection(self, host):
# FIXME: This is insecure by default, certs are unchecked.
conn = xmlrpclib.SafeTransport.make_connection(self, host)
try:
# FIXME: This stuff will probably fail or be a no-op before Python 2.6,
# making our connections unreliable. :-( We need a more robust hack.
host, extra_headers, x509 = self.get_host_info(host)
conn._conn._tunnel_host = host
conn._conn._tunnel_port = 443
conn._conn._tunnel_headers = {}
except:
LogError('Warning, failed to configure HTTP tunnel for %s' % host)
return conn
else:
class PageKiteXmlRpcTransport(xmlrpclib.Transport): pass
def DisableSSLCompression():
# Hack to disable compression in OpenSSL and reduce memory usage *lots*.
# Source:
# http://journal.paul.querna.org/articles/2011/04/05/openssl-memory-use/
try:
import ctypes
import glob
openssl = ctypes.CDLL(None, ctypes.RTLD_GLOBAL)
try:
f = openssl.SSL_COMP_get_compression_methods
except AttributeError:
ssllib = sorted(glob.glob("/usr/lib/libssl.so.*"))[0]
openssl = ctypes.CDLL(ssllib, ctypes.RTLD_GLOBAL)
openssl.SSL_COMP_get_compression_methods.restype = ctypes.c_void_p
openssl.sk_zero.argtypes = [ctypes.c_void_p]
openssl.sk_zero(openssl.SSL_COMP_get_compression_methods())
except Exception, e:
LogError('disableSSLCompression: Failed: %s' % e)
# Different Python 2.x versions complain about deprecation depending on
# where we pull these from.
try:
from urlparse import parse_qs, urlparse
except ImportError, e:
from cgi import parse_qs
from urlparse import urlparse
try:
import hashlib
def sha1hex(data):
hl = hashlib.sha1()
hl.update(data)
return hl.hexdigest().lower()
except ImportError:
import sha
def sha1hex(data):
return sha.new(data).hexdigest().lower()
# YamonD is a part of PageKite.net's internal monitoring systems. It's not
# required, so if you don't have it, the mock makes things Just Work.
class MockYamonD(object):
def __init__(self, sspec, server=None, handler=None): pass
def vmax(self, var, value): pass
def vscale(self, var, ratio, add=0): pass
def vset(self, var, value): pass
def vadd(self, var, value, wrap=None): pass
def vmin(self, var, value): pass
def vdel(self, var): pass
def lcreate(self, listn, elems): pass
def ladd(self, listn, value): pass
def render_vars_text(self): return ''
def quit(self): pass
def run(self): pass
gYamon = MockYamonD(())
try:
import yamond
YamonD=yamond.YamonD
except Exception:
YamonD=MockYamonD
##[ PageKite.py code starts here! ]############################################
gSecret = None
def globalSecret():
global gSecret
if not gSecret:
# This always works...
gSecret = '%8.8x%8.8x%8.8x' % (random.randint(0, 0x7FFFFFFE),
time.time(),
random.randint(0, 0x7FFFFFFE))
# Next, see if we can augment that with some real randomness.
try:
newSecret = sha1hex(open('/dev/random').read(16) + gSecret)
gSecret = newSecret
LogDebug('Seeded signatures using /dev/random, hooray!')
except:
try:
newSecret = sha1hex(os.urandom(64) + gSecret)
gSecret = newSecret
LogDebug('Seeded signatures using os.urandom(), hooray!')
except:
LogInfo('WARNING: Seeding signatures with time.time() and random.randint()')
return gSecret
TOKEN_LENGTH=36
def signToken(token=None, secret=None, payload='', timestamp=None,
length=TOKEN_LENGTH):
"""
This will generate a random token with a signature which could only have come
from this server. If a token is provided, it is re-signed so the original
can be compared with what we would have generated, for verification purposes.
If a timestamp is provided it will be embedded in the signature to a
resolution of 10 minutes, and the signature will begin with the letter 't'
Note: This is only as secure as random.randint() is random.
"""
if not secret: secret = globalSecret()
if not token: token = sha1hex('%s%8.8x' % (globalSecret(),
random.randint(0, 0x7FFFFFFD)+1))
if timestamp:
tok = 't' + token[1:]
ts = '%x' % int(timestamp/600)
return tok[0:8] + sha1hex(secret + payload + ts + tok[0:8])[0:length-8]
else:
return token[0:8] + sha1hex(secret + payload + token[0:8])[0:length-8]
def checkSignature(sign='', secret='', payload=''):
"""
Check a signature for validity. When using timestamped signatures, we only
accept signatures from the current and previous windows.
"""
if sign[0] == 't':
ts = int(time.time())
for window in (0, 1):
valid = signToken(token=sign, secret=secret, payload=payload,
timestamp=(ts-(window*600)))
if sign == valid: return True
return False
else:
valid = signToken(token=sign, secret=secret, payload=payload)
return sign == valid
class ConfigError(Exception):
pass
class ConnectError(Exception):
pass
class AuthError(Exception):
pass
def HTTP_PageKiteRequest(server, backends, tokens=None, nozchunks=False,
tls=False, testtoken=None, replace=None):
req = ['CONNECT PageKite:1 HTTP/1.0\r\n']
if not nozchunks: req.append('X-PageKite-Features: ZChunks\r\n')
if replace: req.append('X-PageKite-Replace: %s\r\n' % replace)
if tls: req.append('X-PageKite-Features: TLS\r\n')
tokens = tokens or {}
for d in backends.keys():
if (backends[d][BE_BHOST] and
backends[d][BE_STATUS] != BE_STATUS_DISABLED):
# A stable (for replay on challenge) but unguessable salt.
my_token = sha1hex(globalSecret() + server + backends[d][BE_SECRET]
)[:TOKEN_LENGTH]
# This is the challenge (salt) from the front-end, if any.
server_token = d in tokens and tokens[d] or ''
# Our payload is the (proto, name) combined with both salts
data = '%s:%s:%s' % (d, my_token, server_token)
# Sign the payload with the shared secret (random salt).
sign = signToken(secret=backends[d][BE_SECRET],
payload=data,
token=testtoken)
req.append('X-PageKite: %s:%s\r\n' % (data, sign))
req.append('\r\n')
return ''.join(req)
def HTTP_ResponseHeader(code, title, mimetype='text/html'):
return ('HTTP/1.1 %s %s\r\nContent-Type: %s\r\nPragma: no-cache\r\n'
'Expires: 0\r\nCache-Control: no-store\r\nConnection: close'
'\r\n') % (code, title, mimetype)
def HTTP_Header(name, value):
return '%s: %s\r\n' % (name, value)
def HTTP_StartBody():
return '\r\n'
def HTTP_ConnectOK():
return 'HTTP/1.0 200 Connection Established\r\n\r\n'
def HTTP_ConnectBad():
return 'HTTP/1.0 503 Sorry\r\n\r\n'
def HTTP_Response(code, title, body, mimetype='text/html', headers=None):
data = [HTTP_ResponseHeader(code, title, mimetype)]
if headers: data.extend(headers)
data.extend([HTTP_StartBody(), ''.join(body)])
return ''.join(data)
def HTTP_NoFeConnection():
return HTTP_Response(200, 'OK', base64.decodestring(
'R0lGODlhCgAKAMQCAN4hIf/+/v///+EzM+AuLvGkpORISPW+vudgYOhiYvKpqeZY'
'WPbAwOdaWup1dfOurvW7u++Rkepycu6PjwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAACH5BAEAAAIALAAAAAAKAAoAAAUtoCAcyEA0jyhEQOs6AuPO'
'QJHQrjEAQe+3O98PcMMBDAdjTTDBSVSQEmGhEIUAADs='),
headers=[HTTP_Header('X-PageKite-Status', 'Down-FE')],
mimetype='image/gif')
def HTTP_NoBeConnection():
return HTTP_Response(200, 'OK', base64.decodestring(
'R0lGODlhCgAKAPcAAI9hE6t2Fv/GAf/NH//RMf/hd7u6uv/mj/ntq8XExMbFxc7N'
'zc/Ozv/xwfj31+jn5+vq6v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAAKAAoAAAhDACUIlBAgwMCDARo4MHiQ'
'4IEGDAcGKAAAAESEBCoiiBhgQEYABzYK7OiRQIEDBgMIEDCgokmUKlcOKFkgZcGb'
'BSUEBAA7'),
headers=[HTTP_Header('X-PageKite-Status', 'Down-BE')],
mimetype='image/gif')
def HTTP_GoodBeConnection():
return HTTP_Response(200, 'OK', base64.decodestring(
'R0lGODlhCgAKANUCAEKtP0StQf8AAG2/a97w3qbYpd/x3mu/aajZp/b79vT69Mnn'
'yK7crXTDcqraqcfmxtLr0VG0T0ivRpbRlF24Wr7jveHy4Pv9+53UnPn8+cjnx4LI'
'gNfu1v///37HfKfZpq/crmG6XgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAACH5BAEAAAIALAAAAAAKAAoAAAZIQIGAUDgMEASh4BEANAGA'
'xRAaaHoYAAPCCZUoOIDPAdCAQhIRgJGiAG0uE+igAMB0MhYoAFmtJEJcBgILVU8B'
'GkpEAwMOggJBADs='),
headers=[HTTP_Header('X-PageKite-Status', 'OK')],
mimetype='image/gif')
def HTTP_Unavailable(where, proto, domain, comment='', frame_url=None):
code, status = 503, 'Unavailable'
message = ''.join(['<h1>Sorry! (', where, ')</h1>',
'<p>The ', proto.upper(),' <a href="', WWWHOME, '">',
'<i>PageKite</i></a> for <b>', domain,
'</b> is unavailable at the moment.</p>',
'<p>Please try again later.</p><!-- ', comment, ' -->'])
if frame_url:
if '?' in frame_url:
frame_url += '&where=%s&proto=%s&domain=%s' % (where.upper(), proto, domain)
return HTTP_Response(code, status,
['<html><frameset cols="*">',
'<frame target="_top" src="', frame_url, '" />',
'<noframes>', message, '</noframes>',
'</frameset></html>'])
else:
return HTTP_Response(code, status,
['<html><body>', message, '</body></html>'])
LOG = []
LOG_LINE = 0
LOG_LENGTH = 300
LOG_THRESHOLD = 256 * 1024
def LogValues(values, testtime=None):
global LOG_LINE
words = [('ts', '%x' % (testtime or time.time())), ('ll', '%x' % LOG_LINE)]
words.extend([(kv[0], ('%s' % kv[1]).replace('\t', ' ')
.replace('\r', ' ')
.replace('\n', ' ')
.replace('; ', ', ')
.strip()) for kv in values])
wdict = dict(words)
LOG_LINE += 1
LOG.append(wdict)
while len(LOG) > LOG_LENGTH: LOG.pop(0)
return (words, wdict)
def LogSyslog(values, wdict=None, words=None):
if values:
words, wdict = LogValues(values)
if 'err' in wdict:
syslog.syslog(syslog.LOG_ERR, '; '.join(['='.join(x) for x in words]))
elif 'debug' in wdict:
syslog.syslog(syslog.LOG_DEBUG, '; '.join(['='.join(x) for x in words]))
else:
syslog.syslog(syslog.LOG_INFO, '; '.join(['='.join(x) for x in words]))
LogFile = sys.stdout
def LogToFile(values, wdict=None, words=None):
if values:
words, wdict = LogValues(values)
LogFile.write('; '.join(['='.join(x) for x in words]))
LogFile.write('\n')
def LogToMemory(values, wdict=None, words=None):
if values: LogValues(values)
def FlushLogMemory():
for l in LOG:
Log(None, wdict=l, words=[(w, l[w]) for w in l])
Log = LogToMemory
def LogError(msg, parms=None):
emsg = [('err', msg)]
if parms: emsg.extend(parms)
Log(emsg)
global gYamon
gYamon.vadd('errors', 1, wrap=1000000)
def LogDebug(msg, parms=None):
emsg = [('debug', msg)]
if parms: emsg.extend(parms)
Log(emsg)
def LogInfo(msg, parms=None):
emsg = [('info', msg)]
if parms: emsg.extend(parms)
Log(emsg)
# FIXME: This could easily be a pool of threads to let us handle more
# than one incoming request at a time.
class AuthThread(threading.Thread):
"""Handle authentication work in a separate thread."""
def __init__(self, conns):
threading.Thread.__init__(self)
self.qc = threading.Condition()
self.jobs = []
self.conns = conns
def check(self, requests, conn, callback):
self.qc.acquire()
self.jobs.append((requests, conn, callback))
self.qc.notify()
self.qc.release()
def quit(self):
self.qc.acquire()
self.keep_running = False
self.qc.notify()
self.qc.release()
def run(self):
self.keep_running = True
self.qc.acquire()
while self.keep_running:
now = int(time.time())
if self.jobs:
(requests, conn, callback) = self.jobs.pop(0)
self.qc.release()
quotas = []
results = []
session = '%x:%s:' % (now, globalSecret())
for request in requests:
try:
proto, domain, srand, token, sign, prefix = request
except:
LogError('Invalid request: %s' % (request, ))
continue
what = '%s:%s:%s' % (proto, domain, srand)
session += what
if not token or not sign:
# Send a challenge. Our challenges are time-stamped, so we can
# put stict bounds on possible replay attacks (20 minutes atm).
results.append(('%s-SignThis' % prefix,
'%s:%s' % (what, signToken(payload=what,
timestamp=now))))
else:
# This is a bit lame, but we only check the token if the quota
# for this connection has never been verified.
quota = self.conns.config.GetDomainQuota(proto, domain, srand,
token, sign,
check_token=(conn.quota is None))
if not quota:
results.append(('%s-Invalid' % prefix, what))
elif self.conns.Tunnel(proto, domain):
# FIXME: Allow multiple backends?
results.append(('%s-Duplicate' % prefix, what))
else:
results.append(('%s-OK' % prefix, what))
quotas.append(quota)
results.append(('%s-SessionID' % prefix,
'%x:%s' % (now, sha1hex(session))))
if quotas:
nz_quotas = [q for q in quotas if q and q > 0]
if nz_quotas:
quota = min(nz_quotas)
if quota is not None:
conn.quota = [quota, requests[quotas.index(quota)], time.time()]
results.append(('%s-Quota' % prefix, quota))
elif requests:
if not conn.quota:
conn.quota = [None, requests[0], time.time()]
else:
conn.quota[2] = time.time()
callback(results)
self.qc.acquire()
else:
self.qc.wait()
self.buffering = 0
self.qc.release()
def fmt_size(count):
if count > 2*(1024*1024*1024):
return '%dGB' % (count / (1024*1024*1024))
if count > 2*(1024*1024):
return '%dMB' % (count / (1024*1024))
if count > 2*(1024):
return '%dKB' % (count / 1024)
return '%dB' % count
class UiRequestHandler(SimpleXMLRPCRequestHandler):
# Make all paths/endpoints legal, we interpret them below.
rpc_paths = ( )
MIME_TYPES = {
'txt': 'text/plain',
'shtml': 'text/html',
'html': 'text/html',
'htm': 'text/html',
'css': 'text/css',
'js': 'application/javascript',
'jsonp': 'application/javascript',
'png': 'image/png',
'gif': 'image/gif',
'jpg': 'image/jpeg',
'jepg': 'image/jpeg',
'DEFAULT': 'application/octet-stream'
}
TEMPLATE_RAW = ('%(body)s')
TEMPLATE_JSONP = ('window.pkData = %s;')
TEMPLATE_HTML = ('<html><head>\n'
'<link rel="stylesheet" media="screen, screen"'
' href="http://pagekite.net/css/pagekite.css"'
' type="text/css" title="Default stylesheet" />\n'
'<title>%(title)s - %(prog)s v%(ver)s</title>\n'
'</head><body>\n'
'<h1>%(title)s</h1>\n'
'<div id=body>%(body)s</div>\n'
'<div id=footer><hr><i>Powered by <b>pagekite.py'
' v%(ver)s</b> and'