client.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. import nacl.hash
  8. class VanillaCreatedExtendedHandler:
  9. """A handler for VanillaCreatedCircuitMsg and
  10. VanillaExtendedCircuitMsg cells."""
  11. def __init__(self, cellhandler, ntor, expecteddesc):
  12. self.cellhandler = cellhandler
  13. self.ntor = ntor
  14. self.expecteddesc = expecteddesc
  15. self.onionkey = expecteddesc.descdict['onionkey']
  16. self.idkey = expecteddesc.descdict['idkey']
  17. def received_cell(self, circhandler, cell):
  18. secret = self.ntor.verify(cell.ntor_reply, self.onionkey, self.idkey)
  19. enckey = nacl.hash.sha256(secret + b'upstream')
  20. deckey = nacl.hash.sha256(secret + b'downstream')
  21. circhandler.add_crypt_layer(enckey, deckey)
  22. if len(circhandler.circuit_descs) == 0:
  23. # This was a VanillaCreatedCircuitMsg
  24. del circhandler.cell_dispatch_table[relay.VanillaCreatedCircuitMsg]
  25. else:
  26. # This was a VanillaExtendedCircuitMsg
  27. del circhandler.cell_dispatch_table[relay.VanillaExtendedCircuitMsg]
  28. circhandler.circuit_descs.append(self.expecteddesc)
  29. # Are we done building the circuit?
  30. if len(circhandler.circuit_descs) == 3:
  31. # Yes!
  32. return
  33. nexthop = None
  34. while nexthop is None:
  35. nexthop = self.cellhandler.consensus.select_weighted_relay( \
  36. self.cellhandler.consensus_cdf)
  37. if nexthop.descdict['addr'] in circhandler.circuit_descs:
  38. nexthop = None
  39. # Construct the VanillaExtendCircuitMsg cell
  40. ntor = relay.NTor(self.cellhandler.perfstats)
  41. ntor_request = ntor.request()
  42. circextendmsg = relay.VanillaExtendCircuitMsg( \
  43. nexthop.descdict['addr'], ntor_request)
  44. # Set up the reply handler
  45. circhandler.cell_dispatch_table[relay.VanillaExtendedCircuitMsg] = \
  46. VanillaCreatedExtendedHandler(self, ntor, nexthop)
  47. # Send the cell
  48. circhandler.send_cell(circextendmsg)
  49. class CellClient(relay.CellHandler):
  50. """The subclass of CellHandler for clients."""
  51. def __init__(self, myaddr, dirauthaddrs, perfstats):
  52. super().__init__(myaddr, dirauthaddrs, perfstats)
  53. self.guardaddr = None
  54. self.guard = None
  55. if network.thenetwork.womode == network.WOMode.VANILLA:
  56. self.consensus_cdf = []
  57. def get_consensus_from_fallbackrelay(self):
  58. """Download a fresh consensus from a random fallbackrelay."""
  59. fb = random.choice(network.thenetwork.getfallbackrelays())
  60. self.send_msg(relay.RelayGetConsensusMsg(), fb.netaddr)
  61. def ensure_guard_vanilla(self):
  62. """Ensure that we have a channel to a guard (Vanilla Onion
  63. Routing version)."""
  64. while True:
  65. if self.guardaddr is None:
  66. # Pick a guard from the consensus
  67. self.guard = self.consensus.select_weighted_relay(self.consensus_cdf)
  68. self.guardaddr = self.guard.descdict['addr']
  69. # Connect to the guard
  70. try:
  71. self.get_channel_to(self.guardaddr)
  72. except network.NetNoServer:
  73. # Our guard is gone
  74. self.guardaddr = None
  75. self.guard = None
  76. if self.guardaddr is not None:
  77. break
  78. print('chose guard=', self.guardaddr)
  79. def ensure_guard(self):
  80. """Ensure that we have a channel to a guard."""
  81. if network.thenetwork.womode == network.WOMode.VANILLA:
  82. self.ensure_guard_vanilla()
  83. def new_circuit_vanilla(self):
  84. """Create a new circuit from this client. (Vanilla Onion Routing
  85. version)"""
  86. # Get our channel to the guard
  87. guardchannel = self.get_channel_to(self.guardaddr)
  88. # Allocate a new circuit id on it
  89. circid, circhandler = guardchannel.new_circuit()
  90. # Construct the VanillaCreateCircuitMsg
  91. ntor = relay.NTor(self.perfstats)
  92. ntor_request = ntor.request()
  93. circcreatemsg = relay.VanillaCreateCircuitMsg(circid, ntor_request)
  94. # Set up the reply handler
  95. circhandler.cell_dispatch_table[relay.VanillaCreatedCircuitMsg] = \
  96. VanillaCreatedExtendedHandler(self, ntor, self.guard)
  97. # Send the message
  98. guardchannel.send_msg(circcreatemsg)
  99. def new_circuit(self):
  100. """Create a new circuit from this client."""
  101. if network.thenetwork.womode == network.WOMode.VANILLA:
  102. self.new_circuit_vanilla()
  103. def received_msg(self, msg, peeraddr, channel):
  104. """Callback when a NetMsg not specific to a circuit is
  105. received."""
  106. print("Client %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  107. if isinstance(msg, relay.RelayConsensusMsg):
  108. dirauth.Consensus.verify(msg.consensus, \
  109. network.thenetwork.dirauthkeys(), self.perfstats)
  110. self.consensus = msg.consensus
  111. if network.thenetwork.womode == network.WOMode.VANILLA:
  112. self.consensus_cdf = self.consensus.bw_cdf()
  113. else:
  114. return super().received_msg(msg, peeraddr, channel)
  115. def received_cell(self, circid, cell, peeraddr, channel):
  116. """Callback with a circuit-specific cell is received."""
  117. print("Client %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  118. return super().received_cell(circid, cell, peeraddr, channel)
  119. class Client:
  120. """A class representing a Tor client."""
  121. def __init__(self, dirauthaddrs):
  122. # Get a network address for client-side use only (do not bind it
  123. # to the network)
  124. self.netaddr = network.NetAddr()
  125. self.perfstats = network.PerfStats(network.EntType.CLIENT)
  126. self.perfstats.name = "Client at %s" % self.netaddr
  127. self.perfstats.is_bootstrapping = True
  128. self.cellhandler = CellClient(self.netaddr, dirauthaddrs, self.perfstats)
  129. # Register for epoch tick notifications
  130. network.thenetwork.wantepochticks(self, True)
  131. def terminate(self):
  132. """Quit this client."""
  133. # Stop listening for epoch ticks
  134. network.thenetwork.wantepochticks(self, False)
  135. # Close relay connections
  136. self.cellhandler.terminate()
  137. def get_consensus(self):
  138. """Fetch a new consensus."""
  139. # We're going to want a new consensus from our guard. In order
  140. # to get that, we'll need a channel to our guard. In order to
  141. # get that, we'll need a guard address. In order to get that,
  142. # we'll need a consensus (uh, oh; in that case, fetch the
  143. # consensus from a fallback relay).
  144. self.cellhandler.get_consensus_from_fallbackrelay()
  145. print('client consensus=', self.cellhandler.consensus)
  146. def newepoch(self, epoch):
  147. """Callback that fires at the start of each epoch"""
  148. # We'll need a new consensus
  149. self.get_consensus()
  150. # If we don't have a guard, pick one and make a channel to it
  151. self.cellhandler.ensure_guard()
  152. if __name__ == '__main__':
  153. perfstats = network.PerfStats(network.EntType.NONE)
  154. totsent = 0
  155. totrecv = 0
  156. dirasent = 0
  157. dirarecv = 0
  158. relaysent = 0
  159. relayrecv = 0
  160. clisent = 0
  161. clirecv = 0
  162. # Start some dirauths
  163. numdirauths = 9
  164. dirauthaddrs = []
  165. dirauths = []
  166. for i in range(numdirauths):
  167. dira = dirauth.DirAuth(i, numdirauths)
  168. dirauths.append(dira)
  169. dirauthaddrs.append(dira.netaddr)
  170. # Start some relays
  171. numrelays = 10
  172. relays = []
  173. for i in range(numrelays):
  174. # Relay bandwidths (at least the ones fast enough to get used)
  175. # in the live Tor network (as of Dec 2019) are well approximated
  176. # by (200000-(200000-25000)/3*log10(x)) where x is a
  177. # uniform integer in [1,2500]
  178. x = random.randint(1,2500)
  179. bw = int(200000-(200000-25000)/3*math.log10(x))
  180. relays.append(relay.Relay(dirauthaddrs, bw, 0))
  181. # The fallback relays are a hardcoded list of about 5% of the
  182. # relays, used by clients for bootstrapping
  183. numfallbackrelays = int(numrelays * 0.05) + 1
  184. fallbackrelays = random.sample(relays, numfallbackrelays)
  185. for r in fallbackrelays:
  186. r.set_is_fallbackrelay()
  187. network.thenetwork.setfallbackrelays(fallbackrelays)
  188. # Tick the epoch
  189. network.thenetwork.nextepoch()
  190. dirauth.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys(), perfstats)
  191. print('ticked; epoch=', network.thenetwork.getepoch())
  192. relays[3].cellhandler.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr)
  193. # See what channels exist and do a consistency check
  194. for r in relays:
  195. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()]))
  196. raddr = r.netaddr
  197. for ad, ch in r.cellhandler.channels.items():
  198. if ch.peer.cellhandler.myaddr != ad:
  199. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  200. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  201. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  202. # Start some clients
  203. numclients = 1
  204. clients = []
  205. for i in range(numclients):
  206. clients.append(Client(dirauthaddrs))
  207. # Tick the epoch
  208. network.thenetwork.nextepoch()
  209. # See what channels exist and do a consistency check
  210. for c in clients:
  211. print("%s: %s" % (c.netaddr, [ str(k) for k in c.cellhandler.channels.keys()]))
  212. caddr = c.netaddr
  213. for ad, ch in c.cellhandler.channels.items():
  214. if ch.peer.cellhandler.myaddr != ad:
  215. print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr)
  216. if ch.peer.cellhandler.channels[caddr].peer is not ch:
  217. print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)
  218. # Pick a bunch of bw-weighted random relays and look at the
  219. # distribution
  220. for i in range(100):
  221. r = clients[0].cellhandler.consensus.select_weighted_relay(clients[0].cellhandler.consensus_cdf)
  222. print("relay",r.descdict["addr"])
  223. relays[3].terminate()
  224. relaysent += relays[3].perfstats.bytes_sent
  225. relayrecv += relays[3].perfstats.bytes_received
  226. del relays[3]
  227. # Tick the epoch
  228. network.thenetwork.nextepoch()
  229. clients[0].cellhandler.new_circuit()
  230. circhandler = clients[0].cellhandler.channels[clients[0].cellhandler.guardaddr].circuithandlers[2]
  231. circhandler.send_cell(network.StringNetMsg("hello world"))
  232. # See what channels exist and do a consistency check
  233. for r in relays:
  234. print("%s: %s" % (r.netaddr, [ str(k) + str([ck for ck in r.cellhandler.channels[k].circuithandlers.keys()]) for k in r.cellhandler.channels.keys()]))
  235. raddr = r.netaddr
  236. for ad, ch in r.cellhandler.channels.items():
  237. if ch.peer.cellhandler.myaddr != ad:
  238. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  239. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  240. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  241. # See what channels exist and do a consistency check
  242. for c in clients:
  243. print("%s: %s" % (c.netaddr, [ str(k) + str([ck for ck in c.cellhandler.channels[k].circuithandlers.keys()]) for k in c.cellhandler.channels.keys()]))
  244. caddr = c.netaddr
  245. for ad, ch in c.cellhandler.channels.items():
  246. if ch.peer.cellhandler.myaddr != ad:
  247. print('address mismatch:', caddr, ad, ch.peer.cellhandler.myaddr)
  248. if ch.peer.cellhandler.channels[caddr].peer is not ch:
  249. print('asymmetry:', caddr, ad, ch, ch.peer.cellhandler.channels[caddr].peer)
  250. if ch.circuithandlers.keys() != \
  251. ch.peer.cellhandler.channels[caddr].circuithandlers.keys():
  252. print('circuit asymmetry:', caddr, ad, ch.peer.cellhandler.myaddr)
  253. for d in dirauths:
  254. print(d.perfstats)
  255. dirasent += d.perfstats.bytes_sent
  256. dirarecv += d.perfstats.bytes_received
  257. print("DirAuths sent=%s recv=%s" % (dirasent, dirarecv))
  258. totsent += dirasent
  259. totrecv += dirarecv
  260. for r in relays:
  261. print(r.perfstats)
  262. relaysent += r.perfstats.bytes_sent
  263. relayrecv += r.perfstats.bytes_received
  264. print("Relays sent=%s recv=%s" % (relaysent, relayrecv))
  265. totsent += relaysent
  266. totrecv += relayrecv
  267. for c in clients:
  268. print(c.perfstats)
  269. clisent += c.perfstats.bytes_sent
  270. clirecv += c.perfstats.bytes_received
  271. print("Client sent=%s recv=%s" % (clisent, clirecv))
  272. totsent += clisent
  273. totrecv += clirecv
  274. print("Total sent=%s recv=%s" % (totsent, totrecv))