#!/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, perfstats): super().__init__(myaddr, dirauthaddrs, perfstats) self.guardaddr = None if network.thenetwork.womode == network.WOMode.VANILLA: self.consensus_cdf = [] 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 new_circuit_vanilla(self): """Create a new circuit from this client. (Vanilla Onion Routing version)""" def new_circuit(self): """Create a new circuit from this client.""" if network.thenetwork.womode == network.WOMode.VANILLA: self.new_circuit_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.Consensus.verify(self.consensus, \ network.thenetwork.dirauthkeys(), self.perfstats) if network.thenetwork.womode == network.WOMode.VANILLA: 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.perfstats = network.PerfStats(network.EntType.CLIENT) self.perfstats.name = "Client at %s" % self.netaddr self.perfstats.is_bootstrapping = True self.cellhandler = CellClient(self.netaddr, dirauthaddrs, self.perfstats) # 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__': perfstats = network.PerfStats(network.EntType.NONE) totsent = 0 totrecv = 0 dirasent = 0 dirarecv = 0 relaysent = 0 relayrecv = 0 clisent = 0 clirecv = 0 # Start some dirauths numdirauths = 9 dirauthaddrs = [] dirauths = [] for i in range(numdirauths): dira = dirauth.DirAuth(i, numdirauths) dirauths.append(dira) dirauthaddrs.append(dira.netaddr) # 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.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys(), perfstats) 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) # Pick a bunch of bw-weighted random relays and look at the # distribution for i in range(100): r = clients[0].cellhandler.consensus.select_weighted_relay(clients[0].cellhandler.consensus_cdf) print("relay",r.descdict["addr"]) relays[3].terminate() relaysent += relays[3].perfstats.bytes_sent relayrecv += relays[3].perfstats.bytes_received 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) clients[0].cellhandler.new_circuit() for d in dirauths: print(d.perfstats) dirasent += d.perfstats.bytes_sent dirarecv += d.perfstats.bytes_received print("DirAuths sent=%d recv=%d" % (dirasent, dirarecv)) totsent += dirasent totrecv += dirarecv for r in relays: print(r.perfstats) relaysent += r.perfstats.bytes_sent relayrecv += r.perfstats.bytes_received print("Relays sent=%d recv=%d" % (relaysent, relayrecv)) totsent += relaysent totrecv += relayrecv for c in clients: print(c.perfstats) clisent += c.perfstats.bytes_sent clirecv += c.perfstats.bytes_received print("Client sent=%d recv=%d" % (clisent, clirecv)) totsent += clisent totrecv += clirecv print("Total sent=%d recv=%d" % (totsent, totrecv))