#!/usr/bin/env python3 import random # For simulation, not cryptography! import math import network import dirauth import relay class CellClient(relay.CellHandler): """The subclass of CellHandler for clients.""" def __init__(self, myaddr, dirauthaddrs): super().__init__(myaddr, dirauthaddrs) self.guardaddr = None self.consensus_cdf = [0] def get_consensus_from_fallbackrelay(self): """Download a fresh consensus from a random fallbackrelay.""" fb = random.choice(network.thenetwork.getfallbackrelays()) self.send_msg(relay.RelayGetConsensusMsg(), fb.netaddr) def ensure_guard_vanilla(self): """Ensure that we have a channel to a guard (Vanilla Onion Routing version).""" while True: if self.guardaddr is None: # Pick a guard from the consensus guard = self.consensus.select_weighted_relay(self.consensus_cdf) self.guardaddr = guard.descdict['addr'] # Connect to the guard try: self.get_channel_to(self.guardaddr) except network.NetNoServer: # Our guard is gone self.guardaddr = None if self.guardaddr is not None: break print('chose guard=', self.guardaddr) def ensure_guard(self): """Ensure that we have a channel to a guard.""" if network.thenetwork.womode == network.WOMode.VANILLA: self.ensure_guard_vanilla() def received_msg(self, msg, peeraddr, peer): """Callback when a NetMsg not specific to a circuit is received.""" print("Client %s received msg %s from %s" % (self.myaddr, msg, peeraddr)) if isinstance(msg, relay.RelayConsensusMsg): self.consensus = msg.consensus dirauth.verify_consensus(self.consensus, network.thenetwork.dirauthkeys()) self.consensus_cdf = self.consensus.bw_cdf() else: return super().received_msg(msg, peeraddr, peer) def received_cell(self, circid, cell, peeraddr, peer): """Callback with a circuit-specific cell is received.""" print("Client %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr)) return super().received_cell(circid, cell, peeraddr, peer) class Client: """A class representing a Tor client.""" def __init__(self, dirauthaddrs): # Get a network address for client-side use only (do not bind it # to the network) self.netaddr = network.NetAddr() self.cellhandler = CellClient(self.netaddr, dirauthaddrs) # Register for epoch tick notifications network.thenetwork.wantepochticks(self, True) def terminate(self): """Quit this client.""" # Stop listening for epoch ticks network.thenetwork.wantepochticks(self, False) # Close relay connections self.cellhandler.terminate() def get_consensus(self): """Fetch a new consensus.""" # We're going to want a new consensus from our guard. In order # to get that, we'll need a channel to our guard. In order to # get that, we'll need a guard address. In order to get that, # we'll need a consensus (uh, oh; in that case, fetch the # consensus from a fallback relay). self.cellhandler.get_consensus_from_fallbackrelay() print('client consensus=', self.cellhandler.consensus) def newepoch(self, epoch): """Callback that fires at the start of each epoch""" # We'll need a new consensus self.get_consensus() # If we don't have a guard, pick one and make a channel to it self.cellhandler.ensure_guard() if __name__ == '__main__': # Start some dirauths numdirauths = 9 dirauthaddrs = [] for i in range(numdirauths): dira = dirauth.DirAuth(i, numdirauths) dirauthaddrs.append(network.thenetwork.bind(dira)) # Start some relays numrelays = 10 relays = [] for i in range(numrelays): # Relay bandwidths (at least the ones fast enough to get used) # in the live Tor network (as of Dec 2019) are well approximated # by (200000-(200000-25000)/3*log10(x)) where x is a # uniform integer in [1,2500] x = random.randint(1,2500) bw = int(200000-(200000-25000)/3*math.log10(x)) relays.append(relay.Relay(dirauthaddrs, bw, 0)) # The fallback relays are a hardcoded list of about 5% of the # relays, used by clients for bootstrapping numfallbackrelays = int(numrelays * 0.05) + 1 fallbackrelays = random.sample(relays, numfallbackrelays) for r in fallbackrelays: r.set_is_fallbackrelay() network.thenetwork.setfallbackrelays(fallbackrelays) # Tick the epoch network.thenetwork.nextepoch() dirauth.verify_consensus(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys()) print('ticked; epoch=', network.thenetwork.getepoch()) relays[3].cellhandler.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr) # See what channels exist and do a consistency check for r in relays: print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()])) raddr = r.netaddr for ad, ch in r.cellhandler.channels.items(): if ch.peer.cellhandler.myaddr != ad: print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr) if ch.peer.cellhandler.channels[raddr].peer is not ch: print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer) # Start some clients numclients = 1 clients = [] for i in range(numclients): clients.append(Client(dirauthaddrs)) # Tick the epoch network.thenetwork.nextepoch() # See what channels exist and do a consistency check for c in clients: print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()])) caddr = c.netaddr for ad, ch in c.cellhandler.channels.items(): if ch.peer.cellhandler.myaddr != ad: print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr) if ch.peer.cellhandler.channels[caddr].peer is not ch: print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer) relays[3].terminate() del relays[3] # Tick the epoch network.thenetwork.nextepoch() # See what channels exist and do a consistency check for c in clients: print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()])) caddr = c.netaddr for ad, ch in c.cellhandler.channels.items(): if ch.peer.cellhandler.myaddr != ad: print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr) if ch.peer.cellhandler.channels[caddr].peer is not ch: print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)