client.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. self.test_guard_connection()
  80. if self.guardaddr is not None:
  81. break
  82. print('chose guard=', self.guardaddr)
  83. def test_guard_connection(self):
  84. # Connect to the guard
  85. try:
  86. self.get_channel_to(self.guardaddr)
  87. except network.NetNoServer:
  88. # Our guard is gone
  89. self.guardaddr = None
  90. self.guard = None
  91. def ensure_guard_walking_onions(self):
  92. """Ensure we have a channel to a guard (Walking Onions version).
  93. For the first implementation, we assume an out-of-band mechanism
  94. that just simply hands us a guard; we don't count the number of
  95. operations or bandwidth as this operation in practice occurs
  96. infrequently."""
  97. while True:
  98. if self.guardaddr is None:
  99. #randomly-sample a guard
  100. print("WARNING: Unimplemented! guard should be selected from any relays.")
  101. self.guard = self.relaypicker.pick_weighted_relay()
  102. # here, we have a SNIP instead of a relay descriptor
  103. self.guardaddr = self.guard.snipdict['addr']
  104. self.test_guard_connection()
  105. if self.guardaddr is not None:
  106. break
  107. print('chose guard=', self.guardaddr)
  108. def ensure_guard(self):
  109. """Ensure that we have a channel to a guard."""
  110. if network.thenetwork.womode == network.WOMode.VANILLA:
  111. self.ensure_guard_vanilla()
  112. return
  113. # At this point, we are either in Telescoping or Single-Pass mode
  114. self.ensure_guard_walking_onions()
  115. def new_circuit_vanilla(self):
  116. """Create a new circuit from this client. (Vanilla Onion Routing
  117. version)"""
  118. # Get our channel to the guard
  119. guardchannel = self.get_channel_to(self.guardaddr)
  120. # Allocate a new circuit id on it
  121. circid, circhandler = guardchannel.new_circuit()
  122. # Construct the VanillaCreateCircuitMsg
  123. ntor = relay.NTor(self.perfstats)
  124. ntor_request = ntor.request()
  125. circcreatemsg = relay.VanillaCreateCircuitMsg(circid, ntor_request)
  126. # Set up the reply handler
  127. circhandler.replace_celltype_handler(
  128. relay.VanillaCreatedCircuitCell,
  129. VanillaCreatedExtendedHandler(self, ntor, self.guard))
  130. # Send the message
  131. guardchannel.send_msg(circcreatemsg)
  132. return circhandler
  133. def new_circuit_telescoping(self):
  134. """Create a new circuit from this client. (Telescoping Walking Onions
  135. version)"""
  136. print("WARNING: Unimplemented! Need to implement building circuits via telescoping.")
  137. def new_circuit(self):
  138. """Create a new circuit from this client."""
  139. if network.thenetwork.womode == network.WOMode.VANILLA:
  140. return self.new_circuit_vanilla()
  141. elif network.thenetwork.womode == network.WOMode.TELESCOPING:
  142. return self.new_circuit_telescoping()
  143. elif network.thenetwork.womode == network.WOMode.SINGLEPASS:
  144. sys.exit("NOT YET IMPLEMENTED")
  145. def received_msg(self, msg, peeraddr, channel):
  146. """Callback when a NetMsg not specific to a circuit is
  147. received."""
  148. print("Client %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  149. if isinstance(msg, relay.RelayConsensusMsg) or \
  150. isinstance(msg, relay.RelayConsensusDiffMsg):
  151. self.relaypicker = dirauth.Consensus.verify(msg.consensus,
  152. network.thenetwork.dirauthkeys(), self.perfstats)
  153. self.consensus = msg.consensus
  154. else:
  155. return super().received_msg(msg, peeraddr, channel)
  156. def received_cell(self, circid, cell, peeraddr, channel):
  157. """Callback with a circuit-specific cell is received."""
  158. print("Client %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  159. return super().received_cell(circid, cell, peeraddr, channel)
  160. class Client:
  161. """A class representing a Tor client."""
  162. def __init__(self, dirauthaddrs):
  163. # Get a network address for client-side use only (do not bind it
  164. # to the network)
  165. self.netaddr = network.NetAddr()
  166. self.perfstats = network.PerfStats(network.EntType.CLIENT)
  167. self.perfstats.name = "Client at %s" % self.netaddr
  168. self.perfstats.is_bootstrapping = True
  169. self.channelmgr = ClientChannelManager(self.netaddr, dirauthaddrs, self.perfstats)
  170. # Register for epoch tick notifications
  171. network.thenetwork.wantepochticks(self, True)
  172. def terminate(self):
  173. """Quit this client."""
  174. # Stop listening for epoch ticks
  175. network.thenetwork.wantepochticks(self, False)
  176. # Close relay connections
  177. self.channelmgr.terminate()
  178. def get_consensus(self):
  179. """Fetch a new consensus."""
  180. # We're going to want a new consensus from our guard. In order
  181. # to get that, we'll need a channel to our guard. In order to
  182. # get that, we'll need a guard address. In order to get that,
  183. # we'll need a consensus (uh, oh; in that case, fetch the
  184. # consensus from a fallback relay).
  185. guardaddr = self.channelmgr.guardaddr
  186. guardchannel = None
  187. if guardaddr is not None:
  188. try:
  189. guardchannel = self.channelmgr.get_channel_to(guardaddr)
  190. except network.NetNoServer:
  191. guardaddr = None
  192. if guardchannel is None:
  193. print("In bootstrapping mode")
  194. self.channelmgr.get_consensus_from_fallbackrelay()
  195. print('client consensus=', self.channelmgr.consensus)
  196. return
  197. if network.thenetwork.womode == network.WOMode.VANILLA:
  198. if self.channelmgr.consensus is not None and len(self.channelmgr.consensus.consdict['relays']) > 0:
  199. guardchannel.send_msg(relay.RelayGetConsensusDiffMsg())
  200. print('got consensus diff, client consensus=', self.channelmgr.consensus)
  201. return
  202. # At this point, we are in one of the following scenarios:
  203. # 1. This is a walking onions protocol, and the client fetches the
  204. # complete consensus each epoch
  205. # 2. This is Vanilla Onion Routing and the client doesn't have a
  206. # consensus and needs to bootstrap it.
  207. guardchannel.send_msg(relay.RelayGetConsensusMsg())
  208. print('client consensus=', self.channelmgr.consensus)
  209. def newepoch(self, epoch):
  210. """Callback that fires at the start of each epoch"""
  211. # We'll need a new consensus
  212. self.get_consensus()
  213. # If we don't have a guard, pick one and make a channel to it
  214. self.channelmgr.ensure_guard()
  215. if __name__ == '__main__':
  216. perfstats = network.PerfStats(network.EntType.NONE)
  217. totsent = 0
  218. totrecv = 0
  219. dirasent = 0
  220. dirarecv = 0
  221. relaysent = 0
  222. relayrecv = 0
  223. clisent = 0
  224. clirecv = 0
  225. if len(sys.argv) < 2:
  226. print("must pass in network mode: options are vanilla, telescoping, or single-pass.")
  227. sys.exit(0)
  228. network_mode = network.WOMode.string_to_type(sys.argv[1])
  229. if network_mode == -1:
  230. print("Not a valid network mode: " + network_mode)
  231. sys.exit(0)
  232. if network_mode == network.WOMode.VANILLA:
  233. network.thenetwork.set_wo_style(network.WOMode.VANILLA,
  234. network.SNIPAuthMode.NONE)
  235. elif network_mode == network.WOMode.TELESCOPING:
  236. network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
  237. network.SNIPAuthMode.THRESHSIG)
  238. # TODO set single-pass
  239. # Start some dirauths
  240. numdirauths = 9
  241. dirauthaddrs = []
  242. dirauths = []
  243. for i in range(numdirauths):
  244. dira = dirauth.DirAuth(i, numdirauths)
  245. dirauths.append(dira)
  246. dirauthaddrs.append(dira.netaddr)
  247. # Start some relays
  248. numrelays = 10
  249. relays = []
  250. for i in range(numrelays):
  251. # Relay bandwidths (at least the ones fast enough to get used)
  252. # in the live Tor network (as of Dec 2019) are well approximated
  253. # by (200000-(200000-25000)/3*log10(x)) where x is a
  254. # uniform integer in [1,2500]
  255. x = random.randint(1,2500)
  256. bw = int(200000-(200000-25000)/3*math.log10(x))
  257. relays.append(relay.Relay(dirauthaddrs, bw, 0))
  258. # The fallback relays are a hardcoded list of about 5% of the
  259. # relays, used by clients for bootstrapping
  260. numfallbackrelays = int(numrelays * 0.05) + 1
  261. fallbackrelays = random.sample(relays, numfallbackrelays)
  262. for r in fallbackrelays:
  263. r.set_is_fallbackrelay()
  264. network.thenetwork.setfallbackrelays(fallbackrelays)
  265. # Tick the epoch
  266. network.thenetwork.nextepoch()
  267. dirauth.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys(), perfstats)
  268. print('ticked; epoch=', network.thenetwork.getepoch())
  269. relays[3].channelmgr.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr)
  270. # See what channels exist and do a consistency check
  271. for r in relays:
  272. print("%s: %s" % (r.netaddr, [ str(k) for k in r.channelmgr.channels.keys()]))
  273. raddr = r.netaddr
  274. for ad, ch in r.channelmgr.channels.items():
  275. if ch.peer.channelmgr.myaddr != ad:
  276. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  277. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  278. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  279. # Start some clients
  280. numclients = 1
  281. clients = []
  282. for i in range(numclients):
  283. clients.append(Client(dirauthaddrs))
  284. # Tick the epoch
  285. network.thenetwork.nextepoch()
  286. # See what channels exist and do a consistency check
  287. for c in clients:
  288. print("%s: %s" % (c.netaddr, [ str(k) for k in c.channelmgr.channels.keys()]))
  289. caddr = c.netaddr
  290. for ad, ch in c.channelmgr.channels.items():
  291. if ch.peer.channelmgr.myaddr != ad:
  292. print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
  293. if ch.peer.channelmgr.channels[caddr].peer is not ch:
  294. print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
  295. # Pick a bunch of bw-weighted random relays and look at the
  296. # distribution
  297. for i in range(100):
  298. r = relays[0].channelmgr.relaypicker.pick_weighted_relay()
  299. if network.thenetwork.womode == network.WOMode.VANILLA:
  300. print("relay",r.descdict["addr"])
  301. else:
  302. print("relay",r.snipdict["addr"])
  303. relays[3].terminate()
  304. relaysent += relays[3].perfstats.bytes_sent
  305. relayrecv += relays[3].perfstats.bytes_received
  306. del relays[3]
  307. # Tick the epoch
  308. network.thenetwork.nextepoch()
  309. circs = []
  310. for i in range(20):
  311. circ = clients[0].channelmgr.new_circuit()
  312. if circ is None:
  313. sys.exit("ERR: Client unable to create circuits")
  314. circs.append(circ)
  315. circ.send_cell(relay.StringCell("hello world circuit %d" % i))
  316. # Tick the epoch
  317. network.thenetwork.nextepoch()
  318. # See what channels exist and do a consistency check
  319. for r in relays:
  320. 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()]))
  321. raddr = r.netaddr
  322. for ad, ch in r.channelmgr.channels.items():
  323. if ch.peer.channelmgr.myaddr != ad:
  324. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  325. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  326. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  327. # See what channels exist and do a consistency check
  328. for c in clients:
  329. 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()]))
  330. caddr = c.netaddr
  331. for ad, ch in c.channelmgr.channels.items():
  332. if ch.peer.channelmgr.myaddr != ad:
  333. print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
  334. if ch.peer.channelmgr.channels[caddr].peer is not ch:
  335. print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
  336. if ch.circuithandlers.keys() != \
  337. ch.peer.channelmgr.channels[caddr].circuithandlers.keys():
  338. print('circuit asymmetry:', caddr, ad, ch.peer.channelmgr.myaddr)
  339. for c in circs:
  340. c.close()
  341. for d in dirauths:
  342. print(d.perfstats)
  343. dirasent += d.perfstats.bytes_sent
  344. dirarecv += d.perfstats.bytes_received
  345. print("DirAuths sent=%s recv=%s" % (dirasent, dirarecv))
  346. totsent += dirasent
  347. totrecv += dirarecv
  348. for r in relays:
  349. print(r.perfstats)
  350. relaysent += r.perfstats.bytes_sent
  351. relayrecv += r.perfstats.bytes_received
  352. print("Relays sent=%s recv=%s" % (relaysent, relayrecv))
  353. totsent += relaysent
  354. totrecv += relayrecv
  355. for c in clients:
  356. print(c.perfstats)
  357. clisent += c.perfstats.bytes_sent
  358. clirecv += c.perfstats.bytes_received
  359. print("Client sent=%s recv=%s" % (clisent, clirecv))
  360. totsent += clisent
  361. totrecv += clirecv
  362. print("Total sent=%s recv=%s" % (totsent, totrecv))