client.py 18 KB

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