client.py 21 KB

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