-
Notifications
You must be signed in to change notification settings - Fork 71
/
torconfig.py
1507 lines (1216 loc) · 52.2 KB
/
torconfig.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
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import with_statement
import os
import sys
import types
import functools
import tempfile
import warnings
from io import StringIO
import shlex
if sys.platform in ('linux2', 'darwin'):
import pwd
from twisted.python import log
from twisted.python.failure import Failure
from twisted.internet import defer, error, protocol
from twisted.internet.interfaces import IReactorTime
from twisted.internet.endpoints import TCP4ClientEndpoint
from txtorcon.torcontrolprotocol import parse_keywords, TorProtocolFactory, DEFAULT_VALUE
from txtorcon.util import delete_file_or_tree, find_keywords, find_tor_binary
from txtorcon.log import txtorlog
from txtorcon.interface import ITorControlProtocol
class TorNotFound(RuntimeError):
"""
Raised by launch_tor() in case the tor binary was unspecified and could
not be found by consulting the shell.
"""
class TorProcessProtocol(protocol.ProcessProtocol):
def __init__(self, connection_creator, progress_updates=None, config=None,
ireactortime=None, timeout=None, kill_on_stderr=True,
stdout=None, stderr=None):
"""
This will read the output from a Tor process and attempt a
connection to its control port when it sees any 'Bootstrapped'
message on stdout. You probably don't need to use this
directly except as the return value from the
:func:`txtorcon.launch_tor` method. tor_protocol contains a
valid :class:`txtorcon.TorControlProtocol` instance by that
point.
connection_creator is a callable that should return a Deferred
that callbacks with a :class:`txtorcon.TorControlProtocol`;
see :func:`txtorcon.launch_tor` for the default one which is a
functools.partial that will call
``connect(TorProtocolFactory())`` on an appropriate
:api:`twisted.internet.endpoints.TCP4ClientEndpoint`
:param connection_creator: A no-parameter callable which
returns a Deferred which promises a
:api:`twisted.internet.interfaces.IStreamClientEndpoint
<IStreamClientEndpoint>`. If this is None, we do NOT
attempt to connect to the underlying Tor process.
:param progress_updates: A callback which received progress
updates with three args: percent, tag, summary
:param config: a TorConfig object to connect to the
TorControlProtocl from the launched tor (should it succeed)
:param ireactortime:
An object implementing IReactorTime (i.e. a reactor) which
needs to be supplied if you pass a timeout.
:param timeout:
An int representing the timeout in seconds. If we are
unable to reach 100% by this time we will consider the
setting up of Tor to have failed. Must supply ireactortime
if you supply this.
:param kill_on_stderr:
When True, kill subprocess if we receive anything on stderr
:param stdout:
Anything subprocess writes to stdout is sent to .write() on this
:param stderr:
Anything subprocess writes to stderr is sent to .write() on this
:ivar tor_protocol: The TorControlProtocol instance connected
to the Tor this :api:`twisted.internet.protocol.ProcessProtocol
<ProcessProtocol>`` is speaking to. Will be valid
when the `connected_cb` callback runs.
:ivar connected_cb: Triggered when the Tor process we
represent is fully bootstrapped
"""
self.config = config
self.tor_protocol = None
self.progress_updates = progress_updates
if connection_creator:
self.connection_creator = connection_creator
self.connected_cb = defer.Deferred()
else:
self.connection_creator = None
self.connected_cb = None
self.attempted_connect = False
self.to_delete = []
self.kill_on_stderr = kill_on_stderr
self.stderr = stderr
self.stdout = stdout
self.collected_stdout = StringIO()
self._setup_complete = False
self._did_timeout = False
self._timeout_delayed_call = None
if timeout:
if not ireactortime:
raise RuntimeError(
'Must supply an IReactorTime object when supplying a '
'timeout')
ireactortime = IReactorTime(ireactortime)
self._timeout_delayed_call = ireactortime.callLater(
timeout, self.timeout_expired)
def outReceived(self, data):
"""
:api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API
"""
if self.stdout:
self.stdout.write(data)
# minor hack: we can't try this in connectionMade because
# that's when the process first starts up so Tor hasn't
# opened any ports properly yet. So, we presume that after
# its first output we're good-to-go. If this fails, we'll
# reset and try again at the next output (see this class'
# tor_connection_failed)
txtorlog.msg(data)
if not self.attempted_connect and self.connection_creator \
and 'Bootstrap' in data:
self.attempted_connect = True
d = self.connection_creator()
d.addCallback(self.tor_connected)
d.addErrback(self.tor_connection_failed)
def timeout_expired(self):
"""
A timeout was supplied during setup, and the time has run out.
"""
try:
self.transport.signalProcess('TERM')
except error.ProcessExitedAlready:
self.transport.loseConnection()
self._did_timeout = True
def errReceived(self, data):
"""
:api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API
"""
if self.stderr:
self.stderr.write(data)
if self.kill_on_stderr:
self.transport.loseConnection()
raise RuntimeError(
"Received stderr output from slave Tor process: " + data)
def cleanup(self):
"""
Clean up my temporary files.
"""
all([delete_file_or_tree(f) for f in self.to_delete])
self.to_delete = []
def processEnded(self, status):
"""
:api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API
"""
self.cleanup()
if status.value.exitCode is None:
if self._did_timeout:
err = RuntimeError("Timeout waiting for Tor launch..")
else:
err = RuntimeError(
"Tor was killed (%s)." % status.value.signal)
else:
err = RuntimeError(
"Tor exited with error-code %d" % status.value.exitCode)
log.err(err)
if self.connected_cb:
self.connected_cb.errback(err)
self.connected_cb = None
def progress(self, percent, tag, summary):
"""
Can be overridden or monkey-patched if you want to get
progress updates yourself.
"""
if self.progress_updates:
self.progress_updates(percent, tag, summary)
# the below are all callbacks
def tor_connection_failed(self, failure):
# FIXME more robust error-handling please, like a timeout so
# we don't just wait forever after 100% bootstrapped (that
# is, we're ignoring these errors, but shouldn't do so after
# we'll stop trying)
self.attempted_connect = False
def status_client(self, arg):
args = shlex.split(arg)
if args[1] != 'BOOTSTRAP':
return
kw = find_keywords(args)
prog = int(kw['PROGRESS'])
tag = kw['TAG']
summary = kw['SUMMARY']
self.progress(prog, tag, summary)
if prog == 100:
if self._timeout_delayed_call:
self._timeout_delayed_call.cancel()
self._timeout_delayed_call = None
if self.connected_cb:
self.connected_cb.callback(self)
self.connected_cb = None
def tor_connected(self, proto):
txtorlog.msg("tor_connected %s" % proto)
self.tor_protocol = proto
if self.config is not None:
self.config._update_proto(proto)
self.tor_protocol.is_owned = self.transport.pid
self.tor_protocol.post_bootstrap.addCallback(
self.protocol_bootstrapped).addErrback(
self.tor_connection_failed)
def protocol_bootstrapped(self, proto):
txtorlog.msg("Protocol is bootstrapped")
self.tor_protocol.add_event_listener(
'STATUS_CLIENT', self.status_client)
# FIXME: should really listen for these to complete as well
# as bootstrap etc. For now, we'll be optimistic.
self.tor_protocol.queue_command('TAKEOWNERSHIP')
self.tor_protocol.queue_command('RESETCONF __OwningControllerProcess')
def launch_tor(config, reactor,
tor_binary=None,
progress_updates=None,
connection_creator=None,
timeout=None,
kill_on_stderr=True,
stdout=None, stderr=None):
"""launches a new Tor process with the given config.
There may seem to be a ton of options, but don't panic: this
method should be easy to use and most options can be ignored
except for advanced use-cases. Calling with a completely empty
TorConfig should Just Work::
config = TorConfig()
d = launch_tor(config, reactor)
d.addCallback(...)
Note that the incoming TorConfig instance is examined and several
config options are acted upon appropriately:
``DataDirectory``: if supplied, a tempdir is not created, and the
one supplied is not deleted.
``ControlPort``: if 0 (zero), a control connection is NOT
established (and ``connection_creator`` is ignored). In this case
we can't wait for Tor to bootstrap, and **you must kill the tor**
yourself.
``User``: if this exists, we attempt to set ownership of the tempdir
to this user (but only if our effective UID is 0).
This method may set the following options on the supplied
TorConfig object: ``DataDirectory, ControlPort,
CookieAuthentication, __OwningControllerProcess`` and WILL call
:meth:`txtorcon.TorConfig.save`
:param config:
an instance of :class:`txtorcon.TorConfig` with any
configuration values you want. If ``ControlPort`` isn't set,
9052 is used; if ``DataDirectory`` isn't set, tempdir is used
to create one (in this case, it will be deleted upon exit).
:param reactor: a Twisted IReactorCore implementation (usually
twisted.internet.reactor)
:param tor_binary: path to the Tor binary to run. Tries to find the tor
binary if unset.
:param progress_updates: a callback which gets progress updates; gets as
args: percent, tag, summary (FIXME make an interface for this).
:param kill_on_stderr:
When True (the default), if Tor prints anything on stderr we
kill off the process, close the TorControlProtocol and raise
an exception.
:param stdout: a file-like object to which we write anything that
Tor prints on stdout (just needs to support write()).
:param stderr: a file-like object to which we write anything that
Tor prints on stderr (just needs .write()). Note that we kill Tor
off by default if anything appears on stderr; pass "no_kill=True"
if you don't like the behavior.
:param connection_creator: is mostly available to ease testing, so
you probably don't want to supply this. If supplied, it is a
callable that should return a Deferred that delivers an
:api:`twisted.internet.interfaces.IProtocol <IProtocol>` or
ConnectError.
See :api:`twisted.internet.interfaces.IStreamClientEndpoint`.connect
Note that this parameter is ignored if config.ControlPort == 0
:return: a Deferred which callbacks with a TorProcessProtocol
connected to the fully-bootstrapped Tor; this has a
:class:`txtorcon.TorControlProtocol` instance as `.tor_protocol`. In
Tor, ``__OwningControllerProcess`` will be set and TAKEOWNERSHIP will
have been called, so if you close the TorControlProtocol the Tor should
exit also (see `control-spec
<https://gitweb.torproject.org/torspec.git/blob/HEAD:/control-spec.txt>`_
3.23). Note that if ControlPort was 0, we don't connect at all
and therefore don't wait for Tor to be bootstrapped. In this case, it's
up to you to kill off the Tor you created.
HACKS:
1. It's hard to know when Tor has both (completely!) written its
authentication cookie file AND is listening on the control
port. It seems that waiting for the first 'bootstrap' message on
stdout is sufficient. Seems fragile...and doesn't work 100% of
the time, so FIXME look at Tor source.
"""
# We have a slight problem with the approach: we need to pass a
# few minimum values to a torrc file so that Tor will start up
# enough that we may connect to it. Ideally, we'd be able to
# start a Tor up which doesn't really do anything except provide
# "AUTHENTICATE" and "GETINFO config/names" so we can do our
# config validation.
# the other option here is to simply write a torrc version of our
# config and get Tor to load that...which might be the best
# option anyway.
# actually, can't we pass them all as command-line arguments?
# could be pushing some limits for giant configs...
if tor_binary is None:
tor_binary = find_tor_binary()
if tor_binary is None:
# We fail right here instead of waiting for the reactor to start
raise TorNotFound('Tor binary could not be found')
# make sure we got things that have write() for stderr, stdout
# kwargs
for arg in [stderr, stdout]:
if arg and not getattr(arg, "write", None):
raise RuntimeError(
'File-like object needed for stdout or stderr args.')
try:
data_directory = config.DataDirectory
user_set_data_directory = True
except KeyError:
user_set_data_directory = False
data_directory = tempfile.mkdtemp(prefix='tortmp')
config.DataDirectory = data_directory
# Set ownership on the temp-dir to the user tor will drop privileges to
# when executing as root.
try:
user = config.User
except KeyError:
pass
else:
if sys.platform in ('linux2', 'darwin') and os.geteuid() == 0:
os.chown(data_directory, pwd.getpwnam(user).pw_uid, -1)
try:
control_port = config.ControlPort
except KeyError:
control_port = 9052 # FIXME choose a random, unoccupied one?
config.ControlPort = control_port
# so, we support passing in ControlPort=0 -- not really sure if
# this is a good idea (since then the caller has to kill the tor
# off, etc), but at least one person has requested it :/
if control_port != 0:
config.CookieAuthentication = 1
config.__OwningControllerProcess = os.getpid()
if connection_creator is None:
connection_creator = functools.partial(
TCP4ClientEndpoint(reactor, 'localhost', control_port).connect,
TorProtocolFactory()
)
else:
connection_creator = None
# NOTE well, that if we don't pass "-f" then Tor will merrily load
# it's default torrc, and apply our options over top... :/
config_args = ['-f', '/non-existant', '--ignore-missing-torrc']
# ...now add all our config options on the command-line. This
# avoids writing a temporary torrc.
for (k, v) in config.config_args():
config_args.append(k)
config_args.append(v)
# txtorlog.msg('Running with config:\n', ' '.join(config_args))
process_protocol = TorProcessProtocol(
connection_creator,
progress_updates,
config, reactor,
timeout,
kill_on_stderr,
stdout,
stderr
)
# we set both to_delete and the shutdown events because this
# process might be shut down way before the reactor, but if the
# reactor bombs out without the subprocess getting closed cleanly,
# we'll want the system shutdown events triggered so the temporary
# files get cleaned up either way
# we don't want to delete the user's directories, just temporary
# ones this method created.
if not user_set_data_directory:
process_protocol.to_delete = [data_directory]
reactor.addSystemEventTrigger(
'before', 'shutdown',
functools.partial(delete_file_or_tree, data_directory)
)
try:
log.msg('Spawning tor process with DataDirectory', data_directory)
args = [tor_binary] + config_args
transport = reactor.spawnProcess(
process_protocol,
tor_binary,
args=args,
env={'HOME': data_directory},
path=data_directory
)
# FIXME? don't need rest of the args: uid, gid, usePTY, childFDs)
transport.closeStdin()
except RuntimeError as e:
return defer.fail(e)
if process_protocol.connected_cb:
return process_protocol.connected_cb
return defer.succeed(process_protocol)
class TorConfigType(object):
"""
Base class for all configuration types, which function as parsers
and un-parsers.
"""
def parse(self, s):
"""
Given the string s, this should return a parsed representation
of it.
"""
return s
def validate(self, s, instance, name):
"""
If s is not a valid type for this object, an exception should
be thrown. The validated object should be returned.
"""
return s
class Boolean(TorConfigType):
def parse(self, s):
if int(s):
return True
return False
class Boolean_Auto(TorConfigType):
"""
weird class-name, but see the parser for these which is *mostly*
just the classname <==> string from Tor, except for something
called Boolean+Auto which is replace()d to be Boolean_Auto
"""
def parse(self, s):
if s == 'auto' or int(s) < 0:
return -1
if int(s):
return 1
return 0
class Integer(TorConfigType):
def parse(self, s):
return int(s)
class SignedInteger(Integer):
pass
class Port(Integer):
pass
class TimeInterval(Integer):
pass
# not actually used?
class TimeMsecInterval(TorConfigType):
pass
class DataSize(Integer):
pass
class Float(TorConfigType):
def parse(self, s):
return float(s)
# unused also?
class Time(TorConfigType):
pass
class CommaList(TorConfigType):
def parse(self, s):
return [x.strip() for x in s.split(',')]
# FIXME: in latest master; what is it?
# Tor source says "A list of strings, separated by commas and optional
# whitespace, representing intervals in seconds, with optional units"
class TimeIntervalCommaList(CommaList):
pass
# FIXME: is this really a comma-list?
class RouterList(CommaList):
pass
class String(TorConfigType):
pass
class Filename(String):
pass
class LineList(TorConfigType):
def parse(self, s):
if isinstance(s, list):
return [str(x).strip() for x in s]
return [x.strip() for x in s.split('\n')]
def validate(self, obj, instance, name):
if not isinstance(obj, list):
raise ValueError("Not valid for %s: %s" % (self.__class__, obj))
return _ListWrapper(
obj, functools.partial(instance.mark_unsaved, name))
config_types = [Boolean, Boolean_Auto, LineList, Integer, SignedInteger, Port,
TimeInterval, TimeMsecInterval,
DataSize, Float, Time, CommaList, String, LineList, Filename,
RouterList, TimeIntervalCommaList]
def is_list_config_type(klass):
return 'List' in klass.__name__ or klass.__name__ in ['HiddenServices']
def _wrapture(orig):
"""
Returns a new method that wraps orig (the original method) with
something that first calls on_modify from the
instance. _ListWrapper uses this to wrap all methods that modify
the list.
"""
# @functools.wraps(orig)
def foo(*args):
obj = args[0]
obj.on_modify()
return orig(*args)
return foo
class _ListWrapper(list):
"""
Do some voodoo to wrap lists so that if you do anything to modify
it, we mark the config as needing saving.
FIXME: really worth it to preserve attribute-style access? seems
to be okay from an exterior API perspective....
"""
def __init__(self, thelist, on_modify_cb):
list.__init__(self, thelist)
self.on_modify = on_modify_cb
__setitem__ = _wrapture(list.__setitem__)
__setslice__ = _wrapture(list.__setslice__)
append = _wrapture(list.append)
extend = _wrapture(list.extend)
insert = _wrapture(list.insert)
remove = _wrapture(list.remove)
pop = _wrapture(list.pop)
def __repr__(self):
return '_ListWrapper' + super(_ListWrapper, self).__repr__()
class HiddenServiceClientAuth(object):
"""
Encapsulates a single client-authorization, as parsed from a
HiddenServiceDir's "client_keys" file if you have stealth or basic
authentication turned on.
:param name: the name you gave it in the HiddenServiceAuthorizeClient line
:param cookie: random password
:param key: RSA private key, or None if this was basic auth
"""
def __init__(self, name, cookie, key=None):
self.name = name
self.cookie = cookie
self.key = parse_rsa_blob(key) if key else None
class HiddenService(object):
"""
Because hidden service configuration is handled specially by Tor,
we wrap the config in this class. This corresponds to the
HiddenServiceDir, HiddenServicePort, HiddenServiceVersion and
HiddenServiceAuthorizeClient lines from the config. If you want
multiple HiddenServicePort lines, simply append more strings to
the ports member.
To create an additional hidden service, append a new instance of
this class to the config (ignore the conf argument)::
state.hiddenservices.append(HiddenService('/path/to/dir', ['80
127.0.0.1:1234']))
"""
def __init__(self, config, thedir, ports,
auth=[], ver=2, group_readable=0):
"""
config is the TorConfig to which this will belong, thedir
corresponds to 'HiddenServiceDir' and will ultimately contain
a 'hostname' and 'private_key' file, ports is a list of lines
corresponding to HiddenServicePort (like '80 127.0.0.1:1234'
to advertise a hidden service at port 80 and redirect it
internally on 127.0.0.1:1234). auth corresponds to the
HiddenServiceAuthenticateClient lines and can be either a
string or a list of strings (like 'basic client0,client1' or
'stealth client5,client6') and ver corresponds to
HiddenServiceVersion and is always 2 right now.
XXX FIXME can we avoid having to pass the config object
somehow? Like provide a factory-function on TorConfig for
users instead?
"""
self.conf = config
self.dir = thedir
self.version = ver
self.group_readable = group_readable
# HiddenServiceAuthorizeClient is a list
# in case people are passing '' for the auth
if not auth:
auth = []
elif not isinstance(auth, list):
auth = [auth]
self.authorize_client = _ListWrapper(
auth, functools.partial(
self.conf.mark_unsaved, 'HiddenServices'
)
)
# there are three magic attributes, "hostname" and
# "private_key" are gotten from the dir if they're still None
# when accessed. "client_keys" parses out any client
# authorizations. Note that after a SETCONF has returned '250
# OK' it seems from tor code that the keys will always have
# been created on disk by that point
if not isinstance(ports, list):
ports = [ports]
self.ports = _ListWrapper(ports, functools.partial(
self.conf.mark_unsaved, 'HiddenServices'))
def __setattr__(self, name, value):
"""
We override the default behavior so that we can mark
HiddenServices as unsaved in our TorConfig object if anything
is changed.
"""
watched_params = ['dir', 'version', 'authorize_client', 'ports']
if name in watched_params and self.conf:
self.conf.mark_unsaved('HiddenServices')
if isinstance(value, list):
value = _ListWrapper(value, functools.partial(
self.conf.mark_unsaved, 'HiddenServices'))
self.__dict__[name] = value
def __getattr__(self, name):
'''
FIXME can't we just move this to @property decorated methods
instead?
'''
# For stealth authentication, the .onion is per-client. So in
# that case, we really have no choice here -- we can't have
# "a" hostname. So we just barf; it's an error to access to
# hostname this way. Instead, use .clients.{hostname, cookie}
if name == 'private_key':
with open(os.path.join(self.dir, name)) as f:
data = f.read().strip()
self.__dict__[name] = data
elif name == 'clients':
clients = []
try:
with open(os.path.join(self.dir, 'hostname')) as f:
for line in f.readlines():
args = line.split()
# XXX should be a dict?
if len(args) > 1:
# tag, onion-uri?
clients.append((args[0], args[1]))
else:
clients.append(('default', args[0]))
except IOError:
pass
self.__dict__[name] = clients
elif name == 'hostname':
with open(os.path.join(self.dir, name)) as f:
data = f.read().strip()
host = None
for line in data.split('\n'):
h = line.split(' ')[0]
if host is None:
host = h
elif h != host:
raise RuntimeError(
".hostname accessed on stealth-auth'd hidden-service "
"with multiple onion addresses."
)
self.__dict__[name] = h
elif name == 'client_keys':
fname = os.path.join(self.dir, name)
keys = []
if os.path.exists(fname):
with open(fname) as f:
keys = parse_client_keys(f)
self.__dict__[name] = keys
return self.__dict__[name]
def config_attributes(self):
"""
Helper method used by TorConfig when generating a torrc file.
"""
rtn = [('HiddenServiceDir', str(self.dir))]
if self.conf._supports['HiddenServiceDirGroupReadable'] \
and self.group_readable:
rtn.append(('HiddenServiceDirGroupReadable', str(1)))
for x in self.ports:
rtn.append(('HiddenServicePort', str(x)))
if self.version:
rtn.append(('HiddenServiceVersion', str(self.version)))
for authline in self.authorize_client:
rtn.append(('HiddenServiceAuthorizeClient', str(authline)))
return rtn
class EphemeralHiddenService(object):
'''
This uses the ephemeral hidden-service APIs (in comparison to
torrc or SETCONF). This means your hidden-service private-key is
never in a file. It also means that when the process exits, that
HS goes away. See documentation for ADD_ONION in torspec:
https://gitweb.torproject.org/torspec.git/tree/control-spec.txt#n1295
'''
# XXX the "ports" stuff is still kind of an awkward API, especialy
# making the actual list public (since it'll have
# "80,127.0.0.1:80" instead of with a space
# XXX descriptor upload stuff needs more features from Tor (the
# actual uploaded key; the event always says UNKNOWN)
# XXX "auth" is unused (also, no Tor support I don't think?)
def __init__(self, ports, key_blob_or_type='NEW:BEST', auth=[], ver=2):
if not isinstance(ports, types.ListType):
ports = [ports]
# for "normal" HSes the port-config bit looks like "80
# 127.0.0.1:1234" whereas this one wants a comma, so we leave
# the public API the same and fix up the space. Or of course
# you can just use the "real" comma-syntax if you wanted.
self._ports = map(lambda x: x.replace(' ', ','), ports)
self._key_blob = key_blob_or_type
self.auth = auth # FIXME ununsed
# FIXME nicer than assert, plz
assert ' ' not in self._key_blob
assert isinstance(ports, types.ListType)
if not key_blob_or_type.startswith('NEW:') \
and (len(key_blob_or_type) > 825 or len(key_blob_or_type) < 820):
raise RuntimeError('Wrong size key-blob')
@defer.inlineCallbacks
def add_to_tor(self, protocol):
'''
Returns a Deferred which fires with 'self' after at least one
descriptor has been uploaded. Errback if no descriptor upload
succeeds.
'''
ports = ' '.join(map(lambda x: 'Port=' + x.strip(), self._ports))
cmd = 'ADD_ONION %s %s' % (self._key_blob, ports)
ans = yield protocol.queue_command(cmd)
ans = find_keywords(ans.split('\n'))
self.hostname = ans['ServiceID'] + '.onion'
if self._key_blob == 'NEW:BEST':
self.private_key = ans['PrivateKey']
log.msg('Created hidden-service at', self.hostname)
# Now we want to wait for the descriptor uploads. This doesn't
# quite work, as the UPLOADED events always say "UNKNOWN" for
# the HSAddress so we can't correlate it to *this* onion for
# sure :/ "yet", though. Yawning says on IRC this is coming.
# XXX Hmm, still UPLOADED always says UNKNOWN, but the UPLOAD
# events do say the address -- so we save all those, and
# correlate to the target nodes. Not sure if this will really
# even work, but better than nothing.
uploaded = defer.Deferred()
attempted_uploads = set()
confirmed_uploads = set()
failed_uploads = set()
def hs_desc(evt):
"""
From control-spec:
"650" SP "HS_DESC" SP Action SP HSAddress SP AuthType SP HsDir
[SP DescriptorID] [SP "REASON=" Reason] [SP "REPLICA=" Replica]
"""
args = evt.split()
subtype = args[0]
if subtype == 'UPLOAD':
if args[1] == self.hostname[:-6]:
attempted_uploads.add(args[3])
elif subtype == 'UPLOADED':
# we only need ONE successful upload to happen for the
# HS to be reachable.
addr = args[1]
if args[3] in attempted_uploads:
confirmed_uploads.add(args[3])
log.msg("Uploaded '{}' to '{}'".format(self.hostname, args[3]))
uploaded.callback(self)
elif subtype == 'FAILED':
if args[1] == self.hostname[:-6]:
failed_uploads.add(args[3])
if failed_uploads == attempted_uploads:
msg = "Failed to upload '{}' to: {}".format(
self.hostname,
', '.join(failed_uploads),
)
uploaded.errback(RuntimeError(msg))
log.msg("Created '{}', waiting for descriptor uploads.".format(self.hostname))
yield protocol.add_event_listener('HS_DESC', hs_desc)
yield uploaded
yield protocol.remove_event_listener('HS_DESC', hs_desc)
@defer.inlineCallbacks
def remove_from_tor(self, protocol):
'''
Returns a Deferred which fires with None
'''
r = yield protocol.queue_command('DEL_ONION %s' % self.hostname[:-6])
if r.strip() != 'OK':
raise RuntimeError('Failed to remove hidden service: "%s".' % r)
def parse_rsa_blob(lines):
return 'RSA1024:' + ''.join(lines[1:-1])
def parse_client_keys(stream):
'''
This parses a hidden-service "client_keys" file, either stealth or
basic (they're the same, except "stealth" includes a
"client-key"). Returns a list of HiddenServiceClientAuth() instances.
Note that the key does NOT include the "----BEGIN ---" markers,
nor *any* embedded whitespace. It is *just* the key blob.
'''
def parse_error(data):
raise RuntimeError("Parse error at: " + data)
class ParserState(object):
def __init__(self):
self.keys = []
self.reset()
def reset(self):
self.name = None
self.cookie = None
self.key = []
def create_key(self):
if self.name is not None:
self.keys.append(HiddenServiceClientAuth(self.name, self.cookie, self.key))
self.reset()
def set_name(self, name):
self.create_key()
self.name = name.split()[1]
def set_cookie(self, cookie):
self.cookie = cookie.split()[1]
if self.cookie.endswith('=='):
self.cookie = self.cookie[:-2]
def add_key_line(self, line):
self.key.append(line)
from txtorcon.spaghetti import FSM, State, Transition
init = State('init')
got_name = State('got_name')
got_cookie = State('got_cookie')
reading_key = State('got_key')
parser_state = ParserState()
# initial state; we want "client-name" or it's an error
init.add_transitions([
Transition(got_name, lambda line: line.startswith('client-name '), parser_state.set_name),
Transition(init, lambda line: not line.startswith('client-name '), parse_error),
])
# next up is "descriptor-cookie" or it's an error
got_name.add_transitions([
Transition(got_cookie, lambda line: line.startswith('descriptor-cookie '), parser_state.set_cookie),
Transition(init, lambda line: not line.startswith('descriptor-cookie '), parse_error),
])
# the "interesting bit": there's either a client-name if we're a
# "basic" file, or an RSA key (with "client-key" before it)
got_cookie.add_transitions([
Transition(reading_key, lambda line: line.startswith('client-key'), None),