Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_build_with_answers(self):
p = FakeEndpointAnswers(['', # ns/all
'', # circuit-status
'', # stream-status
'', # address-mappings/all
'', # entry-guards
'1234' # PID
])
d = build_tor_connection(p, build_state=True)
d.addCallback(self.confirm_state).addErrback(self.fail)
d.addCallback(self.confirm_pid).addErrback(self.fail)
p.proto.post_bootstrap.callback(p.proto)
return d
def test_build(self):
p = FakeEndpoint()
d = build_tor_connection(p, build_state=False)
d.addCallback(self.confirm_proto)
p.proto.post_bootstrap.callback(p.proto)
return d
def test_build_with_answers_guards_unfound_entry(self):
p = FakeEndpointAnswers(['', # ns/all
'', # circuit-status
'', # stream-status
'', # address-mappings/all
'\n\nkerblam up\nOK\n' # entry-guards
])
d = build_tor_connection(p, build_state=True)
d.addCallback(self.confirm_state)
d.addCallback(self.confirm_no_pid)
p.proto.post_bootstrap.callback(p.proto)
return d
fake_consensus = '\n'.join([
'r fake YkkmgCNRV1/35OPWDvo7+1bmfoo tanLV/4ZfzpYQW0xtGFqAa46foo 2011-12-12 16:29:16 11.11.11.11 443 80',
's Exit Fast Guard HSDir Named Running Stable V2Dir Valid FutureProof',
'r ekaf foooooooooooooooooooooooooo barbarbarbarbarbarbarbarbar 2011-11-11 16:30:00 22.22.22.22 443 80',
's Exit Fast Guard HSDir Named Running Stable V2Dir Valid FutureProof',
'',
])
p = FakeEndpointAnswers([fake_consensus, # ns/all
'', # circuit-status
'', # stream-status
'', # address-mappings/all
'', # entry-guards
'1234' # PID
])
d = build_tor_connection(p, build_state=True)
d.addCallback(self.confirm_state).addErrback(self.fail)
d.addCallback(self.confirm_pid).addErrback(self.fail)
d.addCallback(self.confirm_consensus).addErrback(self.fail)
p.proto.post_bootstrap.callback(p.proto)
return d
try:
options = Options()
options.parseOptions(sys.argv[1:])
if options['launch']:
print "Launching new Tor instance:"
config = txtorcon.TorConfig()
# FIXME could make this better (e.g. random, and/or check if it's taken first)
config.SOCKSPort = 9999
config.ControlPort = 1234
d = txtorcon.launch_tor(config, reactor, progress_updates=update)
d.addCallback(setup, options).addErrback(setup_failed)
else:
host, port = options['address'].split(':')
d = txtorcon.build_tor_connection(TCP4ClientEndpoint(reactor, host, int(port)))
d.addCallback(really_setup, options).addErrback(setup_failed)
reactor.run()
except usage.UsageError:
print options.getUsage()
sys.exit(-1)
except Exception, e:
print options.getUsage()
print "ERROR:",e
sys.exit(-2)
@defer.inlineCallbacks
def main(reactor):
ep = TCP4ClientEndpoint(reactor, "localhost", 9251)
tor_protocol = yield txtorcon.build_tor_connection(ep, build_state=False)
print "Connected to Tor"
hs_public_port = 80
hs_port = yield txtorcon.util.available_tcp_port(reactor)
hs_string = '%s 127.0.0.1:%d' % (hs_public_port, hs_port)
print "Adding ephemeral service", hs_string
print "(this can take some time; please be patient)"
hs = txtorcon.EphemeralHiddenService([hs_string])
yield hs.add_to_tor(tor_protocol)
print "Added ephemeral HS to Tor:", hs.hostname
print "Starting site"
site = server.Site(Simple())
hs_endpoint = TCP4ServerEndpoint(reactor, hs_port, interface='127.0.0.1')
yield hs_endpoint.listen(site)
log.startLogging(sys.stdout)
if options.launch_tor:
config = txtorcon.TorConfig()
config.ControlPort = options.control_port
config.SocksPort = 0
d = txtorcon.launch_tor(config, reactor, progress_updates=progress)
# launch_tor returns a TorProcessProtocol
# ...so we grab out the TorControlProtocol instance in order
# to simply use the same callback on "d" below
d.addCallback(lambda pp: pp.tor_protocol)
else:
# if build_state=True, then we get a TorState() object back
d = txtorcon.build_tor_connection((reactor, '127.0.0.1',
options.control_port),
build_state=False)
d.addCallback(setup_complete).addErrback(an_error)
try:
reactor.run()
except KeyboardInterrupt:
pass # ctrl+c
def _connect(self, reactor, update_status):
maker = self._tor_control_endpoint_maker
with add_context(update_status, "making Tor control endpoint"):
tor_control_endpoint = yield maker(reactor, update_status)
assert IStreamClientEndpoint.providedBy(tor_control_endpoint)
with add_context(update_status, "connecting to Tor"):
tproto = yield txtorcon.build_tor_connection(tor_control_endpoint,
build_state=False)
with add_context(update_status, "waiting for Tor bootstrap"):
config = yield txtorcon.TorConfig.from_protocol(tproto)
ports = list(config.SocksPort)
# I've seen "9050", and "unix:/var/run/tor/socks WorldWritable"
# and recently [["9050", "unix:.."]] which is weird
try:
(socks_endpoint, socks_desc) = next(find_port(reactor, ports))
self._socks_desc = socks_desc # stash for tests
returnValue(socks_endpoint)
except StopIteration:
raise ValueError("could not use config.SocksPort: %r" % (ports,))
def main(reactor):
# change the port to 9151 for Tor Browser Bundle
tor_ep = TCP4ClientEndpoint(reactor, "localhost", 9051)
connection = yield txtorcon.build_tor_connection(tor_ep, build_state=False)
version = yield connection.get_info('version', 'events/names')
print("Connected to Tor {version}".format(**version))
print("Events:", version['events/names'])
print("Building state.")
state = yield txtorcon.TorState.from_protocol(connection)
print("listening for circuit events")
state.add_circuit_listener(MyCircuitListener())
print("Issuing NEWNYM.")
yield connection.signal('NEWNYM')
print("OK.")
print("Existing circuits:")
for c in state.circuits.values():
def change_torrc(result):
config.UseEntryGuards=0
d2 = config.save()
d2.addCallback(lambda ign: result)
return d2
d.addCallback(change_torrc)
d.addCallback(lambda protocol: TorState.from_protocol(protocol))
return d
if tor_control is None:
print "launching tor..."
d = start_tor()
else:
print "using tor control port..."
endpoint = clientFromString(reactor, tor_control.encode('utf-8'))
d = txtorcon.build_tor_connection(endpoint, build_state=True)
secret_hash = hashlib.sha256(secret).digest()
def start_probe(tor_state):
if consensus is not None:
routers = get_router_list_from_consensus(tor_state, consensus)
elif relay_list is not None:
routers = get_router_list_from_file(tor_state, relay_list)
else:
pass # XXX todo: print usage
probe = ProbeAll2HopCircuits(tor_state, reactor, log_dir, reactor.stop, routers, secret_hash,
partitions, this_partition, build_duration, circuit_timeout, prometheus_port, prometheus_interface)
print "starting scan"
probe.start()
def signal_handler(signal, frame):
print "signal caught, stopping probe"