client.py 7.1 KB

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