client.py 13 KB

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