123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384 |
- #!/usr/bin/env python3
- import random # For simulation, not cryptography!
- import math
- import network
- import dirauth
- import relay
- import nacl.hash
- class VanillaCreatedExtendedHandler:
- """A handler for VanillaCreatedCircuitCell and
- VanillaExtendedCircuitCell cells."""
- def __init__(self, channelmgr, ntor, expecteddesc):
- self.channelmgr = channelmgr
- self.ntor = ntor
- self.expecteddesc = expecteddesc
- self.onionkey = expecteddesc.descdict['onionkey']
- self.idkey = expecteddesc.descdict['idkey']
- def received_cell(self, circhandler, cell):
- secret = self.ntor.verify(cell.ntor_reply, self.onionkey, self.idkey)
- enckey = nacl.hash.sha256(secret + b'upstream')
- deckey = nacl.hash.sha256(secret + b'downstream')
- circhandler.add_crypt_layer(enckey, deckey)
- if len(circhandler.circuit_descs) == 0:
- # This was a VanillaCreatedCircuitCell
- circhandler.replace_celltype_handler(
- relay.VanillaCreatedCircuitCell, None)
- else:
- # This was a VanillaExtendedCircuitCell
- circhandler.replace_celltype_handler(
- relay.VanillaExtendedCircuitCell, None)
- circhandler.circuit_descs.append(self.expecteddesc)
- # Are we done building the circuit?
- if len(circhandler.circuit_descs) == 3:
- # Yes!
- return
- nexthop = None
- while nexthop is None:
- nexthop = self.channelmgr.relaypicker.pick_weighted_relay()
- if nexthop.descdict['addr'] in \
- [ desc.descdict['addr'] \
- for desc in circhandler.circuit_descs ]:
- nexthop = None
- # Construct the VanillaExtendCircuitCell
- ntor = relay.NTor(self.channelmgr.perfstats)
- ntor_request = ntor.request()
- circextendmsg = relay.VanillaExtendCircuitCell(
- nexthop.descdict['addr'], ntor_request)
- # Set up the reply handler
- circhandler.replace_celltype_handler(
- relay.VanillaExtendedCircuitCell,
- VanillaCreatedExtendedHandler(self.channelmgr, ntor, nexthop))
- # Send the cell
- circhandler.send_cell(circextendmsg)
- class ClientChannelManager(relay.ChannelManager):
- """The subclass of ChannelManager for clients."""
- def __init__(self, myaddr, dirauthaddrs, perfstats):
- super().__init__(myaddr, dirauthaddrs, perfstats)
- self.guardaddr = None
- self.guard = None
- def get_consensus_from_fallbackrelay(self):
- """Download a fresh consensus from a random fallbackrelay."""
- fb = random.choice(network.thenetwork.getfallbackrelays())
- if network.thenetwork.womode == network.WOMode.VANILLA:
- if self.consensus is not None and \
- len(self.consensus.consdict['relays']) > 0:
- self.send_msg(relay.RelayGetConsensusDiffMsg(), fb.netaddr)
- else:
- self.send_msg(relay.RelayGetConsensusMsg(), fb.netaddr)
- else:
- 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
- self.guard = self.relaypicker.pick_weighted_relay()
- self.guardaddr = self.guard.descdict['addr']
- # Connect to the guard
- try:
- self.get_channel_to(self.guardaddr)
- except network.NetNoServer:
- # Our guard is gone
- self.guardaddr = None
- self.guard = 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)"""
- # Get our channel to the guard
- guardchannel = self.get_channel_to(self.guardaddr)
- # Allocate a new circuit id on it
- circid, circhandler = guardchannel.new_circuit()
- # Construct the VanillaCreateCircuitMsg
- ntor = relay.NTor(self.perfstats)
- ntor_request = ntor.request()
- circcreatemsg = relay.VanillaCreateCircuitMsg(circid, ntor_request)
- # Set up the reply handler
- circhandler.replace_celltype_handler(
- relay.VanillaCreatedCircuitCell,
- VanillaCreatedExtendedHandler(self, ntor, self.guard))
- # Send the message
- guardchannel.send_msg(circcreatemsg)
- return circhandler
- def new_circuit(self):
- """Create a new circuit from this client."""
- if network.thenetwork.womode == network.WOMode.VANILLA:
- return self.new_circuit_vanilla()
- def received_msg(self, msg, peeraddr, channel):
- """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) or \
- isinstance(msg, relay.RelayConsensusDiffMsg):
- self.relaypicker = dirauth.Consensus.verify(msg.consensus,
- network.thenetwork.dirauthkeys(), self.perfstats)
- self.consensus = msg.consensus
- else:
- return super().received_msg(msg, peeraddr, channel)
- def received_cell(self, circid, cell, peeraddr, channel):
- """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, channel)
- 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.channelmgr = ClientChannelManager(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.channelmgr.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).
- guardaddr = self.channelmgr.guardaddr
- guardchannel = None
- if guardaddr is not None:
- try:
- guardchannel = self.channelmgr.get_channel_to(guardaddr)
- except network.NetNoServer:
- guardaddr = None
- if guardchannel is None:
- self.channelmgr.get_consensus_from_fallbackrelay()
- else:
- if self.channelmgr.consensus is not None and \
- len(self.channelmgr.consensus.consdict['relays']) > 0:
- guardchannel.send_msg(relay.RelayGetConsensusDiffMsg())
- else:
- guardchannel.send_msg(relay.RelayGetConsensusMsg())
- print('client consensus=', self.channelmgr.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.channelmgr.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
- network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
- network.SNIPAuthMode.THRESHSIG)
- # 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].channelmgr.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.channelmgr.channels.keys()]))
- raddr = r.netaddr
- for ad, ch in r.channelmgr.channels.items():
- if ch.peer.channelmgr.myaddr != ad:
- print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
- if ch.peer.channelmgr.channels[raddr].peer is not ch:
- print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.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.channelmgr.channels.keys()]))
- caddr = c.netaddr
- for ad, ch in c.channelmgr.channels.items():
- if ch.peer.channelmgr.myaddr != ad:
- print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
- if ch.peer.channelmgr.channels[caddr].peer is not ch:
- print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
- # Pick a bunch of bw-weighted random relays and look at the
- # distribution
- for i in range(100):
- r = relays[0].channelmgr.relaypicker.pick_weighted_relay()
- if network.thenetwork.womode == network.WOMode.VANILLA:
- print("relay",r.descdict["addr"])
- else:
- print("relay",r.snipdict["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()
- circs = []
- for i in range(20):
- circ = clients[0].channelmgr.new_circuit()
- circs.append(circ)
- circ.send_cell(relay.StringCell("hello world circuit %d" % i))
- # Tick the epoch
- network.thenetwork.nextepoch()
- # See what channels exist and do a consistency check
- for r in relays:
- print("%s: %s" % (r.netaddr, [ str(k) + str([ck for ck in r.channelmgr.channels[k].circuithandlers.keys()]) for k in r.channelmgr.channels.keys()]))
- raddr = r.netaddr
- for ad, ch in r.channelmgr.channels.items():
- if ch.peer.channelmgr.myaddr != ad:
- print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
- if ch.peer.channelmgr.channels[raddr].peer is not ch:
- print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
- # See what channels exist and do a consistency check
- for c in clients:
- print("%s: %s" % (c.netaddr, [ str(k) + str([ck for ck in c.channelmgr.channels[k].circuithandlers.keys()]) for k in c.channelmgr.channels.keys()]))
- caddr = c.netaddr
- for ad, ch in c.channelmgr.channels.items():
- if ch.peer.channelmgr.myaddr != ad:
- print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
- if ch.peer.channelmgr.channels[caddr].peer is not ch:
- print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
- if ch.circuithandlers.keys() != \
- ch.peer.channelmgr.channels[caddr].circuithandlers.keys():
- print('circuit asymmetry:', caddr, ad, ch.peer.channelmgr.myaddr)
- for c in circs:
- c.close()
- for d in dirauths:
- print(d.perfstats)
- dirasent += d.perfstats.bytes_sent
- dirarecv += d.perfstats.bytes_received
- print("DirAuths sent=%s recv=%s" % (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=%s recv=%s" % (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=%s recv=%s" % (clisent, clirecv))
- totsent += clisent
- totrecv += clirecv
- print("Total sent=%s recv=%s" % (totsent, totrecv))
|