client.py 14 KB

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