client.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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):
  10. super().__init__(myaddr, dirauthaddrs)
  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 create_circuit_vanilla(self):
  40. """Create a new circuit from this client. (Vanilla Onion Routing
  41. version)"""
  42. def create_circuit(self):
  43. """Create a new circuit from this client."""
  44. if network.thenetwork.womode == network.WOMode.VANILLA:
  45. self.create_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, network.thenetwork.dirauthkeys())
  53. if network.thenetwork.womode == network.WOMode.VANILLA:
  54. self.consensus_cdf = self.consensus.bw_cdf()
  55. else:
  56. return super().received_msg(msg, peeraddr, peer)
  57. def received_cell(self, circid, cell, peeraddr, peer):
  58. """Callback with a circuit-specific cell is received."""
  59. print("Client %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  60. return super().received_cell(circid, cell, peeraddr, peer)
  61. class Client:
  62. """A class representing a Tor client."""
  63. def __init__(self, dirauthaddrs):
  64. # Get a network address for client-side use only (do not bind it
  65. # to the network)
  66. self.netaddr = network.NetAddr()
  67. self.cellhandler = CellClient(self.netaddr, dirauthaddrs)
  68. # Register for epoch tick notifications
  69. network.thenetwork.wantepochticks(self, True)
  70. def terminate(self):
  71. """Quit this client."""
  72. # Stop listening for epoch ticks
  73. network.thenetwork.wantepochticks(self, False)
  74. # Close relay connections
  75. self.cellhandler.terminate()
  76. def get_consensus(self):
  77. """Fetch a new consensus."""
  78. # We're going to want a new consensus from our guard. In order
  79. # to get that, we'll need a channel to our guard. In order to
  80. # get that, we'll need a guard address. In order to get that,
  81. # we'll need a consensus (uh, oh; in that case, fetch the
  82. # consensus from a fallback relay).
  83. self.cellhandler.get_consensus_from_fallbackrelay()
  84. print('client consensus=', self.cellhandler.consensus)
  85. def newepoch(self, epoch):
  86. """Callback that fires at the start of each epoch"""
  87. # We'll need a new consensus
  88. self.get_consensus()
  89. # If we don't have a guard, pick one and make a channel to it
  90. self.cellhandler.ensure_guard()
  91. if __name__ == '__main__':
  92. # Start some dirauths
  93. numdirauths = 9
  94. dirauthaddrs = []
  95. for i in range(numdirauths):
  96. dira = dirauth.DirAuth(i, numdirauths)
  97. dirauthaddrs.append(network.thenetwork.bind(dira))
  98. # Start some relays
  99. numrelays = 10
  100. relays = []
  101. for i in range(numrelays):
  102. # Relay bandwidths (at least the ones fast enough to get used)
  103. # in the live Tor network (as of Dec 2019) are well approximated
  104. # by (200000-(200000-25000)/3*log10(x)) where x is a
  105. # uniform integer in [1,2500]
  106. x = random.randint(1,2500)
  107. bw = int(200000-(200000-25000)/3*math.log10(x))
  108. relays.append(relay.Relay(dirauthaddrs, bw, 0))
  109. # The fallback relays are a hardcoded list of about 5% of the
  110. # relays, used by clients for bootstrapping
  111. numfallbackrelays = int(numrelays * 0.05) + 1
  112. fallbackrelays = random.sample(relays, numfallbackrelays)
  113. for r in fallbackrelays:
  114. r.set_is_fallbackrelay()
  115. network.thenetwork.setfallbackrelays(fallbackrelays)
  116. # Tick the epoch
  117. network.thenetwork.nextepoch()
  118. dirauth.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys())
  119. print('ticked; epoch=', network.thenetwork.getepoch())
  120. relays[3].cellhandler.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr)
  121. # See what channels exist and do a consistency check
  122. for r in relays:
  123. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()]))
  124. raddr = r.netaddr
  125. for ad, ch in r.cellhandler.channels.items():
  126. if ch.peer.cellhandler.myaddr != ad:
  127. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  128. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  129. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  130. # Start some clients
  131. numclients = 1
  132. clients = []
  133. for i in range(numclients):
  134. clients.append(Client(dirauthaddrs))
  135. # Tick the epoch
  136. network.thenetwork.nextepoch()
  137. # See what channels exist and do a consistency check
  138. for c in clients:
  139. print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()]))
  140. caddr = c.netaddr
  141. for ad, ch in c.cellhandler.channels.items():
  142. if ch.peer.cellhandler.myaddr != ad:
  143. print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr)
  144. if ch.peer.cellhandler.channels[caddr].peer is not ch:
  145. print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)
  146. # Pick a bunch of bw-weighted random relays and look at the
  147. # distribution
  148. for i in range(100):
  149. r = clients[0].cellhandler.consensus.select_weighted_relay(clients[0].cellhandler.consensus_cdf)
  150. print("relay",r.descdict["addr"])
  151. relays[3].terminate()
  152. del relays[3]
  153. # Tick the epoch
  154. network.thenetwork.nextepoch()
  155. # See what channels exist and do a consistency check
  156. for c in clients:
  157. print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()]))
  158. caddr = c.netaddr
  159. for ad, ch in c.cellhandler.channels.items():
  160. if ch.peer.cellhandler.myaddr != ad:
  161. print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr)
  162. if ch.peer.cellhandler.channels[caddr].peer is not ch:
  163. print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)