client.py 21 KB

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