client.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import math
  4. import network
  5. import dirauth
  6. import relay
  7. class CellClient(relay.CellHandler):
  8. """The subclass of CellHandler for clients."""
  9. def __init__(self, myaddr, dirauthaddrs, perfstats):
  10. super().__init__(myaddr, dirauthaddrs, perfstats)
  11. self.guardaddr = None
  12. if network.thenetwork.womode == network.WOMode.VANILLA:
  13. self.consensus_cdf = []
  14. def get_consensus_from_fallbackrelay(self):
  15. """Download a fresh consensus from a random fallbackrelay."""
  16. fb = random.choice(network.thenetwork.getfallbackrelays())
  17. self.send_msg(relay.RelayGetConsensusMsg(), fb.netaddr)
  18. def ensure_guard_vanilla(self):
  19. """Ensure that we have a channel to a guard (Vanilla Onion
  20. Routing version)."""
  21. while True:
  22. if self.guardaddr is None:
  23. # Pick a guard from the consensus
  24. guard = self.consensus.select_weighted_relay(self.consensus_cdf)
  25. self.guardaddr = guard.descdict['addr']
  26. # Connect to the guard
  27. try:
  28. self.get_channel_to(self.guardaddr)
  29. except network.NetNoServer:
  30. # Our guard is gone
  31. self.guardaddr = None
  32. if self.guardaddr is not None:
  33. break
  34. print('chose guard=', self.guardaddr)
  35. def ensure_guard(self):
  36. """Ensure that we have a channel to a guard."""
  37. if network.thenetwork.womode == network.WOMode.VANILLA:
  38. self.ensure_guard_vanilla()
  39. def new_circuit_vanilla(self):
  40. """Create a new circuit from this client. (Vanilla Onion Routing
  41. version)"""
  42. def new_circuit(self):
  43. """Create a new circuit from this client."""
  44. if network.thenetwork.womode == network.WOMode.VANILLA:
  45. self.new_circuit_vanilla()
  46. def received_msg(self, msg, peeraddr, peer):
  47. """Callback when a NetMsg not specific to a circuit is
  48. received."""
  49. print("Client %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  50. if isinstance(msg, relay.RelayConsensusMsg):
  51. self.consensus = msg.consensus
  52. dirauth.Consensus.verify(self.consensus, \
  53. network.thenetwork.dirauthkeys(), self.perfstats)
  54. if network.thenetwork.womode == network.WOMode.VANILLA:
  55. self.consensus_cdf = self.consensus.bw_cdf()
  56. else:
  57. return super().received_msg(msg, peeraddr, peer)
  58. def received_cell(self, circid, cell, peeraddr, peer):
  59. """Callback with a circuit-specific cell is received."""
  60. print("Client %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  61. return super().received_cell(circid, cell, peeraddr, peer)
  62. class Client:
  63. """A class representing a Tor client."""
  64. def __init__(self, dirauthaddrs):
  65. # Get a network address for client-side use only (do not bind it
  66. # to the network)
  67. self.netaddr = network.NetAddr()
  68. self.perfstats = network.PerfStats(network.EntType.CLIENT)
  69. self.perfstats.name = "Client at %s" % self.netaddr
  70. self.perfstats.is_bootstrapping = True
  71. self.cellhandler = CellClient(self.netaddr, dirauthaddrs, self.perfstats)
  72. # Register for epoch tick notifications
  73. network.thenetwork.wantepochticks(self, True)
  74. def terminate(self):
  75. """Quit this client."""
  76. # Stop listening for epoch ticks
  77. network.thenetwork.wantepochticks(self, False)
  78. # Close relay connections
  79. self.cellhandler.terminate()
  80. def get_consensus(self):
  81. """Fetch a new consensus."""
  82. # We're going to want a new consensus from our guard. In order
  83. # to get that, we'll need a channel to our guard. In order to
  84. # get that, we'll need a guard address. In order to get that,
  85. # we'll need a consensus (uh, oh; in that case, fetch the
  86. # consensus from a fallback relay).
  87. self.cellhandler.get_consensus_from_fallbackrelay()
  88. print('client consensus=', self.cellhandler.consensus)
  89. def newepoch(self, epoch):
  90. """Callback that fires at the start of each epoch"""
  91. # We'll need a new consensus
  92. self.get_consensus()
  93. # If we don't have a guard, pick one and make a channel to it
  94. self.cellhandler.ensure_guard()
  95. if __name__ == '__main__':
  96. perfstats = network.PerfStats(network.EntType.NONE)
  97. totsent = 0
  98. totrecv = 0
  99. dirasent = 0
  100. dirarecv = 0
  101. relaysent = 0
  102. relayrecv = 0
  103. clisent = 0
  104. clirecv = 0
  105. # Start some dirauths
  106. numdirauths = 9
  107. dirauthaddrs = []
  108. dirauths = []
  109. for i in range(numdirauths):
  110. dira = dirauth.DirAuth(i, numdirauths)
  111. dirauths.append(dira)
  112. dirauthaddrs.append(dira.netaddr)
  113. # Start some relays
  114. numrelays = 10
  115. relays = []
  116. for i in range(numrelays):
  117. # Relay bandwidths (at least the ones fast enough to get used)
  118. # in the live Tor network (as of Dec 2019) are well approximated
  119. # by (200000-(200000-25000)/3*log10(x)) where x is a
  120. # uniform integer in [1,2500]
  121. x = random.randint(1,2500)
  122. bw = int(200000-(200000-25000)/3*math.log10(x))
  123. relays.append(relay.Relay(dirauthaddrs, bw, 0))
  124. # The fallback relays are a hardcoded list of about 5% of the
  125. # relays, used by clients for bootstrapping
  126. numfallbackrelays = int(numrelays * 0.05) + 1
  127. fallbackrelays = random.sample(relays, numfallbackrelays)
  128. for r in fallbackrelays:
  129. r.set_is_fallbackrelay()
  130. network.thenetwork.setfallbackrelays(fallbackrelays)
  131. # Tick the epoch
  132. network.thenetwork.nextepoch()
  133. dirauth.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys(), perfstats)
  134. print('ticked; epoch=', network.thenetwork.getepoch())
  135. relays[3].cellhandler.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr)
  136. # See what channels exist and do a consistency check
  137. for r in relays:
  138. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()]))
  139. raddr = r.netaddr
  140. for ad, ch in r.cellhandler.channels.items():
  141. if ch.peer.cellhandler.myaddr != ad:
  142. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  143. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  144. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  145. # Start some clients
  146. numclients = 1
  147. clients = []
  148. for i in range(numclients):
  149. clients.append(Client(dirauthaddrs))
  150. # Tick the epoch
  151. network.thenetwork.nextepoch()
  152. # See what channels exist and do a consistency check
  153. for c in clients:
  154. print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()]))
  155. caddr = c.netaddr
  156. for ad, ch in c.cellhandler.channels.items():
  157. if ch.peer.cellhandler.myaddr != ad:
  158. print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr)
  159. if ch.peer.cellhandler.channels[caddr].peer is not ch:
  160. print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)
  161. # Pick a bunch of bw-weighted random relays and look at the
  162. # distribution
  163. for i in range(100):
  164. r = clients[0].cellhandler.consensus.select_weighted_relay(clients[0].cellhandler.consensus_cdf)
  165. print("relay",r.descdict["addr"])
  166. relays[3].terminate()
  167. relaysent += relays[3].perfstats.bytes_sent
  168. relayrecv += relays[3].perfstats.bytes_received
  169. del relays[3]
  170. # Tick the epoch
  171. network.thenetwork.nextepoch()
  172. # See what channels exist and do a consistency check
  173. for c in clients:
  174. print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()]))
  175. caddr = c.netaddr
  176. for ad, ch in c.cellhandler.channels.items():
  177. if ch.peer.cellhandler.myaddr != ad:
  178. print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr)
  179. if ch.peer.cellhandler.channels[caddr].peer is not ch:
  180. print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)
  181. clients[0].cellhandler.new_circuit()
  182. for d in dirauths:
  183. print(d.perfstats)
  184. dirasent += d.perfstats.bytes_sent
  185. dirarecv += d.perfstats.bytes_received
  186. print("DirAuths sent=%d recv=%d" % (dirasent, dirarecv))
  187. totsent += dirasent
  188. totrecv += dirarecv
  189. for r in relays:
  190. print(r.perfstats)
  191. relaysent += r.perfstats.bytes_sent
  192. relayrecv += r.perfstats.bytes_received
  193. print("Relays sent=%d recv=%d" % (relaysent, relayrecv))
  194. totsent += relaysent
  195. totrecv += relayrecv
  196. for c in clients:
  197. print(c.perfstats)
  198. clisent += c.perfstats.bytes_sent
  199. clirecv += c.perfstats.bytes_received
  200. print("Client sent=%d recv=%d" % (clisent, clirecv))
  201. totsent += clisent
  202. totrecv += clirecv
  203. print("Total sent=%d recv=%d" % (totsent, totrecv))