client.py 20 KB

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