client.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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 = dirauth.PerfStats(dirauth.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 = dirauth.PerfStats(dirauth.EntType.NONE)
  97. # Start some dirauths
  98. numdirauths = 9
  99. dirauthaddrs = []
  100. dirauths = []
  101. for i in range(numdirauths):
  102. dira = dirauth.DirAuth(i, numdirauths)
  103. dirauths.append(dira)
  104. dirauthaddrs.append(dira.netaddr)
  105. # Start some relays
  106. numrelays = 10
  107. relays = []
  108. for i in range(numrelays):
  109. # Relay bandwidths (at least the ones fast enough to get used)
  110. # in the live Tor network (as of Dec 2019) are well approximated
  111. # by (200000-(200000-25000)/3*log10(x)) where x is a
  112. # uniform integer in [1,2500]
  113. x = random.randint(1,2500)
  114. bw = int(200000-(200000-25000)/3*math.log10(x))
  115. relays.append(relay.Relay(dirauthaddrs, bw, 0))
  116. # The fallback relays are a hardcoded list of about 5% of the
  117. # relays, used by clients for bootstrapping
  118. numfallbackrelays = int(numrelays * 0.05) + 1
  119. fallbackrelays = random.sample(relays, numfallbackrelays)
  120. for r in fallbackrelays:
  121. r.set_is_fallbackrelay()
  122. network.thenetwork.setfallbackrelays(fallbackrelays)
  123. # Tick the epoch
  124. network.thenetwork.nextepoch()
  125. dirauth.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys(), perfstats)
  126. print('ticked; epoch=', network.thenetwork.getepoch())
  127. relays[3].cellhandler.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr)
  128. # See what channels exist and do a consistency check
  129. for r in relays:
  130. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()]))
  131. raddr = r.netaddr
  132. for ad, ch in r.cellhandler.channels.items():
  133. if ch.peer.cellhandler.myaddr != ad:
  134. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  135. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  136. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  137. # Start some clients
  138. numclients = 1
  139. clients = []
  140. for i in range(numclients):
  141. clients.append(Client(dirauthaddrs))
  142. # Tick the epoch
  143. network.thenetwork.nextepoch()
  144. # See what channels exist and do a consistency check
  145. for c in clients:
  146. print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()]))
  147. caddr = c.netaddr
  148. for ad, ch in c.cellhandler.channels.items():
  149. if ch.peer.cellhandler.myaddr != ad:
  150. print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr)
  151. if ch.peer.cellhandler.channels[caddr].peer is not ch:
  152. print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)
  153. # Pick a bunch of bw-weighted random relays and look at the
  154. # distribution
  155. for i in range(100):
  156. r = clients[0].cellhandler.consensus.select_weighted_relay(clients[0].cellhandler.consensus_cdf)
  157. print("relay",r.descdict["addr"])
  158. relays[3].terminate()
  159. del relays[3]
  160. # Tick the epoch
  161. network.thenetwork.nextepoch()
  162. # See what channels exist and do a consistency check
  163. for c in clients:
  164. print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()]))
  165. caddr = c.netaddr
  166. for ad, ch in c.cellhandler.channels.items():
  167. if ch.peer.cellhandler.myaddr != ad:
  168. print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr)
  169. if ch.peer.cellhandler.channels[caddr].peer is not ch:
  170. print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)
  171. clients[0].cellhandler.new_circuit()
  172. totsent = 0
  173. totrecv = 0
  174. for d in dirauths:
  175. print(d.perfstats)
  176. totsent += d.perfstats.bytes_sent
  177. totrecv += d.perfstats.bytes_received
  178. for r in relays:
  179. print(r.perfstats)
  180. totsent += r.perfstats.bytes_sent
  181. totrecv += r.perfstats.bytes_received
  182. for c in clients:
  183. print(c.perfstats)
  184. totsent += c.perfstats.bytes_sent
  185. totrecv += c.perfstats.bytes_received
  186. print("Total sent=%d recv=%d" % (totsent, totrecv))