client.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. def get_consensus_from_fallbackrelay(self):
  13. """Download a fresh consensus from a random fallbackrelay."""
  14. fb = random.choice(network.thenetwork.getfallbackrelays())
  15. self.send_msg(relay.RelayGetConsensusMsg(), fb.netaddr)
  16. def received_msg(self, msg, peeraddr, peer):
  17. """Callback when a NetMsg not specific to a circuit is
  18. received."""
  19. print("Client %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  20. if isinstance(msg, relay.RelayConsensusMsg):
  21. self.consensus = msg.consensus
  22. dirauth.verify_consensus(self.consensus, network.thenetwork.dirauthkeys())
  23. else:
  24. return super().received_msg(msg, peeraddr, peer)
  25. def received_cell(self, circid, cell, peeraddr, peer):
  26. """Callback with a circuit-specific cell is received."""
  27. print("Client %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  28. return super().received_cell(circid, cell, peeraddr, peer)
  29. class Client:
  30. """A class representing a Tor client."""
  31. def __init__(self, dirauthaddrs):
  32. # Get a network address for client-side use only (do not bind it
  33. # to the network)
  34. self.netaddr = network.NetAddr()
  35. self.cellhandler = CellClient(self.netaddr, dirauthaddrs)
  36. # Register for epoch tick notifications
  37. network.thenetwork.wantepochticks(self, True)
  38. def terminate(self):
  39. """Quit this client."""
  40. # Stop listening for epoch ticks
  41. network.thenetwork.wantepochticks(self, False)
  42. # Close relay connections
  43. self.cellhandler.terminate()
  44. def get_consensus(self):
  45. """Fetch a new consensus."""
  46. # We're going to want a new consensus from our guard. In order
  47. # to get that, we'll need a channel to our guard. In order to
  48. # get that, we'll need a guard address. In order to get that,
  49. # we'll need a consensus (uh, oh; in that case, fetch the
  50. # consensus from a fallback relay).
  51. self.cellhandler.get_consensus_from_fallbackrelay()
  52. print('client consensus=', self.cellhandler.consensus)
  53. def newepoch(self, epoch):
  54. """Callback that fires at the start of each epoch"""
  55. if self.cellhandler.consensus is None or \
  56. self.cellhandler.consensus.consdict['epoch'] != \
  57. network.thenetwork.getepoch():
  58. # We'll need a new consensus
  59. self.get_consensus()
  60. if __name__ == '__main__':
  61. # Start some dirauths
  62. numdirauths = 9
  63. dirauthaddrs = []
  64. for i in range(numdirauths):
  65. dira = dirauth.DirAuth(i, numdirauths)
  66. dirauthaddrs.append(network.thenetwork.bind(dira))
  67. # Start some relays
  68. numrelays = 10
  69. relays = []
  70. for i in range(numrelays):
  71. # Relay bandwidths (at least the ones fast enough to get used)
  72. # in the live Tor network (as of Dec 2019) are well approximated
  73. # by (200000-(200000-25000)/3*log10(x)) where x is a
  74. # uniform integer in [1,2500]
  75. x = random.randint(1,2500)
  76. bw = int(200000-(200000-25000)/3*math.log10(x))
  77. relays.append(relay.Relay(dirauthaddrs, bw, 0))
  78. # The fallback relays are a hardcoded list of about 5% of the
  79. # relays, used by clients for bootstrapping
  80. numfallbackrelays = int(numrelays * 0.05) + 1
  81. fallbackrelays = random.sample(relays, numfallbackrelays)
  82. for r in fallbackrelays:
  83. r.set_is_fallbackrelay()
  84. network.thenetwork.setfallbackrelays(fallbackrelays)
  85. # Tick the epoch
  86. network.thenetwork.nextepoch()
  87. dirauth.verify_consensus(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys())
  88. print('ticked; epoch=', network.thenetwork.getepoch())
  89. relays[3].cellhandler.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr)
  90. # See what channels exist and do a consistency check
  91. for r in relays:
  92. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()]))
  93. raddr = r.netaddr
  94. for ad, ch in r.cellhandler.channels.items():
  95. if ch.peer.cellhandler.myaddr != ad:
  96. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  97. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  98. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  99. # Start some clients
  100. numclients = 1
  101. clients = []
  102. for i in range(numclients):
  103. clients.append(Client(dirauthaddrs))
  104. # Tick the epoch
  105. network.thenetwork.nextepoch()
  106. # See what channels exist and do a consistency check
  107. for c in clients:
  108. print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()]))
  109. caddr = c.netaddr
  110. for ad, ch in c.cellhandler.channels.items():
  111. if ch.peer.cellhandler.myaddr != ad:
  112. print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr)
  113. if ch.peer.cellhandler.channels[caddr].peer is not ch:
  114. print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)