def operation(self): restart_deferred = defer.Deferred() control_socket = '/var/run/tor/control' self.reset() def startup_callback(tor_conn): self.print_startup_error = True self.tor_conn = tor_conn self.tor_conn.protocol.on_disconnect = restart_deferred log.err('Successfully connected to Tor control port') return self.add_all_hidden_services() def startup_errback(err): if self.print_startup_error: # Print error only on first run or failure or on a failure subsequent to a success condition self.print_startup_error = False log.err('Failed to initialize Tor connection; error: %s', err) restart_deferred.callback(None) if not os.path.exists(control_socket): startup_errback(Exception('Tor control port not open on %s; waiting for Tor to become available' % control_socket)) return if not os.access(control_socket, os.R_OK): startup_errback(Exception('Unable to access %s; manual permission recheck needed' % control_socket)) return build_local_tor_connection(reactor).addCallbacks(startup_callback, startup_errback) return restart_deferred
def operation(self): restart_deferred = defer.Deferred() control_socket = '/var/run/tor/control' self.reset() def startup_callback(tor_conn): self.print_startup_error = True self.tor_conn = tor_conn self.tor_conn.protocol.on_disconnect = restart_deferred log.err('Successfully connected to Tor control port') return self.add_all_hidden_services() def startup_errback(err): if self.print_startup_error: # Print error only on first run or failure or on a failure subsequent to a success condition self.print_startup_error = False log.err('Failed to initialize Tor connection; error: %s', err) restart_deferred.callback(None) if not os.path.exists(control_socket): startup_errback(Exception('Tor control port not open on %s; waiting for Tor to become available' % control_socket)) return deferred_sleep(1) if not os.access(control_socket, os.R_OK): startup_errback(Exception('Unable to access %s; manual permission recheck needed' % control_socket)) return deferred_sleep(1) build_local_tor_connection(reactor).addCallbacks(startup_callback, startup_errback) return restart_deferred
def operation(self): restart_deferred = defer.Deferred() control_socket = '/var/run/tor/control' self.reset() @defer.inlineCallbacks def startup_callback(tor_conn): self.print_startup_error = True self.tor_conn = tor_conn self.tor_conn.protocol.on_disconnect = restart_deferred log.err('Successfully connected to Tor control port') try: version = yield self.tor_conn.protocol.queue_command( "GETINFO version") version = version.split('=')[1] if LooseVersion(version) < LooseVersion('0.3.3.9'): self.onion_service_version = 2 except: pass yield self.add_all_hidden_services() def startup_errback(err): if self.print_startup_error: # Print error only on first run or failure or on a failure subsequent to a success condition self.print_startup_error = False log.err('Failed to initialize Tor connection; error: %s', err) restart_deferred.callback(None) if not os.path.exists(control_socket): startup_errback( Exception( 'Tor control port not open on %s; waiting for Tor to become available' % control_socket)) return deferred_sleep(1) if not os.access(control_socket, os.R_OK): startup_errback( Exception( 'Unable to access %s; manual permission recheck needed' % control_socket)) return deferred_sleep(1) build_local_tor_connection(reactor).addCallbacks( startup_callback, startup_errback) return restart_deferred
def service(self, restart_deferred): hostname, key = yield get_onion_service_info() control_socket = '/var/run/tor/control' def startup_callback(tor_conn): self.print_startup_error = True self.tor_conn = tor_conn self.tor_conn.protocol.on_disconnect = restart_deferred log.debug('Successfully connected to Tor control port') hs_loc = ('80 localhost:8083') if not hostname and not key: log.info('Creating new onion service') ephs = EphemeralHiddenService(hs_loc) else: log.info('Setting up existing onion service %s', hostname) ephs = EphemeralHiddenService(hs_loc, key) @inlineCallbacks def initialization_callback(ret): log.info('Initialization of hidden-service %s completed.', ephs.hostname) if not hostname and not key: yield set_onion_service_info(ephs.hostname, ephs.private_key) yield refresh_memory_variables() d = ephs.add_to_tor(self.tor_conn.protocol) d.addCallback(initialization_callback) # pylint: disable=no-member def startup_errback(err): if self.print_startup_error: # Print error only on first run or failure or on a failure subsequent to a success condition self.print_startup_error = False log.err('Failed to initialize Tor connection; error: %s', err) restart_deferred.callback(None) if not os.path.exists(control_socket): startup_errback( Exception( 'Tor control port not open on /var/run/tor/control; waiting for Tor to become available' )) return if not os.access(control_socket, os.R_OK): startup_errback( Exception( 'Unable to access /var/run/tor/control; manual permission recheck needed' )) return d = build_local_tor_connection(reactor) d.addCallback(startup_callback) d.addErrback(startup_errback)
def main(reactor): proto = yield txtorcon.build_local_tor_connection(reactor, build_state=False) or_nickname = "moria1" print "Trying to get decriptor information about", or_nickname # If the fingerprint is used in place of nickname then, desc/id/<OR identity> # should be used. descriptor_info = yield proto.get_info('desc/name/' + or_nickname) descriptor_info = descriptor_info['desc/name/' + or_nickname] try: from stem.descriptor.server_descriptor import RelayDescriptor relay_info = RelayDescriptor(descriptor_info) print "The relay's fingerprint is:", relay_info.fingerprint print "Time in UTC when the descriptor was made:", relay_info.published except ImportError as e: print "Error:", e
def main(reactor): proto = yield txtorcon.build_local_tor_connection(reactor, build_state=False) or_nickname = "moria1" print "Trying to get decriptor information about", or_nickname # If the fingerprint is used in place of nickname then, desc/id/<OR identity> # should be used. descriptor_info = yield proto.get_info('desc/name/' + or_nickname) descriptor_info = descriptor_info['desc/name/' + or_nickname] try: from stem.descriptor.server_descriptor import RelayDescriptor relay_info = RelayDescriptor(descriptor_info) print "The relay's fingerprint is:", relay_info.fingerprint print "Time in UTC when the descriptor was made:", relay_info.published except ImportError as e: print "Error:", e
def main(): log.startLogging(sys.stdout) launch_tor = True if launch_tor: c = TorConfig() #FIXME: check these values, parametize! c.CircuitBuildTimeout = 20 c.LearnCircuitBuildTimeout = 0 c.CircuitIdleTimeout = 20 c.FetchDirInfoEarly = 1 c.FetchDirInfoExtraEarly = 1 c.FetchUselessDescriptors = 1 tor = start_tor(c) else: tor = build_local_tor_connection(reactor) tor.addCallback(setconf_fetch_all_descs) # check that each run is producing the same input set! tor.addCallback(BwScan, reactor, './logs', partitions=1, this_partition=0) tor.addCallback(lambda scanner: scanner.run_scan()) tor.addCallback(lambda _: reactor.stop()) reactor.run()
def configure_tor_hs(bind_port): hostname, key = yield get_onion_service_info() log.info('Starting up Tor connection') try: tor_conn = yield build_local_tor_connection(reactor) tor_conn.protocol.on_disconnect = Deferred() except ConnectionRefusedError as e: log.err('Tor daemon is down or misconfigured . . . starting up anyway') return log.debug('Successfully connected to Tor control port') hs_loc = ('80 localhost:%d' % bind_port) if hostname == '': log.info('Creating new onion service') ephs = EphemeralHiddenService(hs_loc) else: log.info('Setting up existing onion service %s', hostname) ephs = EphemeralHiddenService(hs_loc, key) @inlineCallbacks def shutdown_callback(): log.info('Shutting down Tor onion service %s' % ephs.hostname) if not getattr(tor_conn.protocol.on_disconnect, 'called', True): log.debug('Removing onion service') yield ephs.remove_from_tor(tor_conn.protocol) log.debug('Successfully handled Tor cleanup') @inlineCallbacks def initialization_callback(ret): log.info('Initialization of hidden-service %s completed.' % (ephs.hostname)) if hasattr(ephs, 'private_key'): yield set_onion_service_info(ephs.hostname, ephs.private_key) reactor.addSystemEventTrigger('before', 'shutdown', shutdown_callback) d = ephs.add_to_tor(tor_conn.protocol) d.addCallback(initialization_callback) # pylint: disable=no-member
def main(reactor, username, num_probes, results, verbose): state = yield txtorcon.build_local_tor_connection(reactor) if verbose: print("Connected to a Tor version", state.protocol.version) builder = CircuitBuilder(state, verbose) yield state.add_circuit_listener(builder) attacher = AttachBySourcePort(verbose) yield state.set_attacher(attacher, reactor) yield state.add_stream_listener(attacher) probe = TwitterProbe(state, builder, attacher, results, verbose) timeline_downloads = [] for x in range(num_probes): d = probe.tweets_from(reactor, username) timeline_downloads.append(d) results = yield DeferredList(timeline_downloads) print("Downloads concluded. A Fearsome Warning will be printed below if we detect discrepancies.") print("Results:\n\n") common = None for (circ, tweets) in probe._circuit_to_results.iteritems(): if common is None: common = set(tweets) else: common = set(tweets).intersection(common) print('"ID of Tor exit router used", "country code", "tweet IDs (space-delimited)"') print() for (circ, tweets) in probe._circuit_to_results.iteritems(): exit_node = circ.path[-1] print("{0}, {1}, {2}".format(exit_node.id_hex, exit_node.location.countrycode, ' '.join(tweets))) if set(tweets) != common: missing = set(tweets).difference(common) print(" *Fearsome Warning*: missing tweets: {}".format( ' '.join(missing), ))
defaults.append(k) else: print k, v if 'defaults' in sys.argv: print "Set to default value:" for k in defaults: print "# %s" % k reactor.stop() def setup_failed(arg): print "SETUP FAILED", arg reactor.stop() def bootstrap(c): conf = TorConfig(c) conf.post_bootstrap.addCallback(setup_complete).addErrback(setup_failed) print "Connection is live, bootstrapping state..." d = build_local_tor_connection(reactor, build_state=False, wait_for_proto=False) # do not use addCallbacks() here, in case bootstrap has an error d.addCallback(bootstrap).addErrback(setup_failed) reactor.run()
def test_build_local_tcp(self): reactor = FakeReactor(self) d = build_local_tor_connection(reactor, socket=None) d.addErrback(lambda _: None) return d
log.msg('Connected to a Tor version %s' % state.protocol.version) listener = StreamCircuitLogger(state) state.add_circuit_listener(listener) state.add_stream_listener(listener) state.protocol.add_event_listener('STATUS_GENERAL', log.msg) state.protocol.add_event_listener('STATUS_SERVER', log.msg) state.protocol.add_event_listener('STATUS_CLIENT', log.msg) log.msg('Existing state when we connected:') for s in state.streams.values(): logStream(s, state) log.msg('Existing circuits:') for c in state.circuits.values(): logCircuit(c) def setup_failed(arg): print "SETUP FAILED", arg log.err(arg) reactor.stop() log.startLogging(sys.stdout) d = txtorcon.build_local_tor_connection(reactor) d.addCallback(setup).addErrback(setup_failed) reactor.run()
def reactor_start(*_args): log.info('starting twisted reactor in ipython') reactor.interleave(reactor_wake) # @UndefinedVariable inputhook.set_inputhook(reactor_work) def reactor_stop(): if reactor.threadpool: # @UndefinedVariable log.info('stopping twisted threads') reactor.threadpool.stop() # @UndefinedVariable log.info('shutting down twisted reactor') reactor._mainLoopShutdown() # @UndefinedVariable ip = InteractiveShell.instance() ask_exit = ip.ask_exit def ipython_exit(): reactor_stop() return ask_exit() ip.ask_exit = ipython_exit reactor_start() return reactor reactor = __install() from txtorcon import build_local_tor_connection build_local_tor_connection(reactor).addCallback(lambda tor: globals().update(tor=tor))
print options.getUsage() sys.exit(-1) def on_shutdown(listener, *args): print '\nTo carry on where you left off, run:' print ' %s --failed %d --built %d' % ( sys.argv[0], listener.failed_circuits, listener.built_circuits), for name in listener.per_guard_built.keys(): print '--guard %s,%d,%d' % (name, listener.per_guard_built[name], listener.per_guard_failed[name]), print listener = CircuitFailureWatcher() reactor.addSystemEventTrigger('before', 'shutdown', functools.partial(on_shutdown, listener)) if options['connect']: host, port = options['connect'].split(':') port = int(port) print 'Connecting to %s:%i...' % (host, port) d = txtorcon.build_local_tor_connection(reactor, host=host, port=port) else: d = txtorcon.build_local_tor_connection(reactor) d.addCallback(functools.partial(setup, options, listener)) d.addErrback(setup_failed) reactor.run()
ns = yield info.ns.name('moria1') guards = yield info.entry_guards() print 'version:', v print '1.2.3.4 is in', ip print 'bootstrap-phase:', boot_phase print 'moria1:', ns print 'entry guards:', guards ## now we dump everything, one at a time d = recursive_dump('', info) d.addCallback(lambda x: reactor.stop()) d.addErrback(error) def setup_failed(arg): print "SETUP FAILED", arg reactor.stop() def bootstrap(c): info = TorInfo(c) info.post_bootstrap.addCallback(setup_complete).addErrback(setup_failed) d = build_local_tor_connection(reactor, build_state=False) # do not use addCallbacks() here, in case bootstrap has an error d.addCallback(bootstrap).addErrback(setup_failed) reactor.run()
def do_setup(state): print "Connected to a Tor version", state.protocol.version attacher = MyAttacher(state) state.set_attacher(attacher, reactor) state.add_circuit_listener(attacher) state.add_stream_listener(MyStreamListener()) print "Existing state when we connected:" print "Streams:" for s in state.streams.values(): print ' ', s print print "General-purpose circuits:" for c in filter(lambda x: x.purpose == 'GENERAL', state.circuits.values()): print ' ', c.id, '->'.join( map(lambda x: x.location.countrycode, c.path)) def setup_failed(arg): print "SETUP FAILED", arg reactor.stop() d = txtorcon.build_local_tor_connection(reactor) d.addCallback(do_setup).addErrback(setup_failed) reactor.run()
print options.getUsage() sys.exit(-1) def on_shutdown(listener, *args): print '\nTo carry on where you left off, run:' print ' %s --failed %d --built %d' % (sys.argv[0], listener.failed_circuits, listener.built_circuits), for name in listener.per_guard_built.keys(): print '--guard %s,%d,%d' % (name, listener.per_guard_built[name], listener.per_guard_failed[name]), print listener = CircuitFailureWatcher() reactor.addSystemEventTrigger('before', 'shutdown', functools.partial(on_shutdown, listener)) if options['connect']: host, port = options['connect'].split(':') port = int(port) print 'Connecting to %s:%i...' % (host, port) d = txtorcon.build_local_tor_connection(reactor, host=host, port=port) else: d = txtorcon.build_local_tor_connection(reactor) d.addCallback(functools.partial(setup, options, listener)) d.addErrback(setup_failed) reactor.run()
#!/usr/bin/env python ## ## Just listens for a few EVENTs from Tor (INFO NOTICE WARN ERR) and ## prints out the contents, so functions like a log monitor. ## from twisted.internet import reactor import txtorcon def log(msg): print msg def setup(proto): print "Connected to a Tor version", proto.version for event in ['INFO', 'NOTICE', 'WARN', 'ERR']: proto.add_event_listener(event, log) proto.get_info('status/version/current', 'version').addCallback(log) def setup_failed(arg): print "SETUP FAILED", arg reactor.stop() d = txtorcon.build_local_tor_connection(reactor, build_state=False) d.addCallback(setup).addErrback(setup_failed) reactor.run()
def test_build_local_tcp(self): reactor = FakeReactor(self) d = build_local_tor_connection(reactor, socket=None) d.addErrback(lambda _: None) return d