client.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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, open_circuits):
  126. super().__init__(myaddr, dirauthaddrs, perfstats)
  127. self.guardaddr = None
  128. self.guard = None
  129. self.open_circuits = open_circuits
  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. # store a reference to this new circuit.
  193. self.open_circuits[circid] = circhandler
  194. # Construct the VanillaCreateCircuitMsg
  195. ntor = relay.NTor(self.perfstats)
  196. ntor_request = ntor.request()
  197. circcreatemsg = relay.VanillaCreateCircuitMsg(circid, ntor_request)
  198. # Set up the reply handler
  199. circhandler.replace_celltype_handler(
  200. relay.VanillaCreatedCircuitCell,
  201. VanillaCreatedExtendedHandler(self, ntor, self.guard))
  202. # Send the message
  203. guardchannel.send_msg(circcreatemsg)
  204. return circhandler
  205. def new_circuit_telescoping(self):
  206. """Create a new circuit from this client. (Telescoping Walking Onions
  207. version)"""
  208. # Get our channel to the guard
  209. guardchannel = self.get_channel_to(self.guardaddr)
  210. # Allocate a new circuit id on it
  211. circid, circhandler = guardchannel.new_circuit()
  212. # store a reference to this new circuit.
  213. self.open_circuits[circid] = circhandler
  214. # Construct the VanillaCreateCircuitMsg
  215. ntor = relay.NTor(self.perfstats)
  216. ntor_request = ntor.request()
  217. circcreatemsg = relay.TelescopingCreateCircuitMsg(circid, ntor_request)
  218. # Set up the reply handler
  219. circhandler.replace_celltype_handler(
  220. relay.TelescopingCreatedCircuitCell,
  221. TelescopingCreatedHandler(self, ntor))
  222. # Send the message
  223. guardchannel.send_msg(circcreatemsg)
  224. return circhandler
  225. def new_circuit(self):
  226. """Create a new circuit from this client."""
  227. if network.thenetwork.womode == network.WOMode.VANILLA:
  228. return self.new_circuit_vanilla()
  229. elif network.thenetwork.womode == network.WOMode.TELESCOPING:
  230. return self.new_circuit_telescoping()
  231. elif network.thenetwork.womode == network.WOMode.SINGLEPASS:
  232. sys.exit("NOT YET IMPLEMENTED")
  233. def received_msg(self, msg, peeraddr, channel):
  234. """Callback when a NetMsg not specific to a circuit is
  235. received."""
  236. print("Client %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  237. if isinstance(msg, relay.RelayConsensusMsg) or \
  238. isinstance(msg, relay.RelayConsensusDiffMsg):
  239. self.relaypicker = dirauth.Consensus.verify(msg.consensus,
  240. network.thenetwork.dirauthkeys(), self.perfstats)
  241. self.consensus = msg.consensus
  242. else:
  243. return super().received_msg(msg, peeraddr, channel)
  244. def received_cell(self, circid, cell, peeraddr, channel):
  245. """Callback with a circuit-specific cell is received."""
  246. print("Client %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  247. if isinstance(msg, relay.CloseCell):
  248. print("Log: Client received close cell; closing circuit")
  249. # TODO close cell
  250. return super().received_cell(circid, cell, peeraddr, channel)
  251. class Client:
  252. """A class representing a Tor client."""
  253. def __init__(self, dirauthaddrs):
  254. # Get a network address for client-side use only (do not bind it
  255. # to the network)
  256. self.netaddr = network.NetAddr()
  257. self.perfstats = network.PerfStats(network.EntType.CLIENT)
  258. self.perfstats.name = "Client at %s" % self.netaddr
  259. self.perfstats.is_bootstrapping = True
  260. self.open_circuits = {}
  261. self.channelmgr = ClientChannelManager(self.netaddr, dirauthaddrs,
  262. self.perfstats, self.open_circuits)
  263. # Register for epoch tick notifications
  264. network.thenetwork.wantepochticks(self, True)
  265. def terminate(self):
  266. """Quit this client."""
  267. # Stop listening for epoch ticks
  268. network.thenetwork.wantepochticks(self, False)
  269. # Close relay connections
  270. self.channelmgr.terminate()
  271. def get_consensus(self):
  272. """Fetch a new consensus."""
  273. # We're going to want a new consensus from our guard. In order
  274. # to get that, we'll need a channel to our guard. In order to
  275. # get that, we'll need a guard address. In order to get that,
  276. # we'll need a consensus (uh, oh; in that case, fetch the
  277. # consensus from a fallback relay).
  278. guardaddr = self.channelmgr.guardaddr
  279. guardchannel = None
  280. if guardaddr is not None:
  281. try:
  282. guardchannel = self.channelmgr.get_channel_to(guardaddr)
  283. except network.NetNoServer:
  284. guardaddr = None
  285. if guardchannel is None:
  286. print("In bootstrapping mode")
  287. self.channelmgr.get_consensus_from_fallbackrelay()
  288. print('client consensus=', self.channelmgr.consensus)
  289. return
  290. if network.thenetwork.womode == network.WOMode.VANILLA:
  291. if self.channelmgr.consensus is not None and len(self.channelmgr.consensus.consdict['relays']) > 0:
  292. guardchannel.send_msg(relay.RelayGetConsensusDiffMsg())
  293. print('got consensus diff, client consensus=', self.channelmgr.consensus)
  294. return
  295. # At this point, we are in one of the following scenarios:
  296. # 1. This is a walking onions protocol, and the client fetches the
  297. # complete consensus each epoch
  298. # 2. This is Vanilla Onion Routing and the client doesn't have a
  299. # consensus and needs to bootstrap it.
  300. guardchannel.send_msg(relay.RelayGetConsensusMsg())
  301. print('client consensus=', self.channelmgr.consensus)
  302. def newepoch(self, epoch):
  303. """Callback that fires at the start of each epoch"""
  304. # We'll need a new consensus
  305. self.get_consensus()
  306. # If we don't have a guard, pick one and make a channel to it
  307. self.channelmgr.ensure_guard()
  308. if __name__ == '__main__':
  309. perfstats = network.PerfStats(network.EntType.NONE)
  310. totsent = 0
  311. totrecv = 0
  312. dirasent = 0
  313. dirarecv = 0
  314. relaysent = 0
  315. relayrecv = 0
  316. clisent = 0
  317. clirecv = 0
  318. if len(sys.argv) < 2:
  319. print("must pass in network mode: options are vanilla, telescoping, or single-pass.")
  320. sys.exit(0)
  321. network_mode = network.WOMode.string_to_type(sys.argv[1])
  322. if network_mode == -1:
  323. print("Not a valid network mode: " + network_mode)
  324. sys.exit(0)
  325. if network_mode == network.WOMode.VANILLA:
  326. network.thenetwork.set_wo_style(network.WOMode.VANILLA,
  327. network.SNIPAuthMode.NONE)
  328. elif network_mode == network.WOMode.TELESCOPING:
  329. network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
  330. network.SNIPAuthMode.THRESHSIG)
  331. # TODO set single-pass
  332. # Start some dirauths
  333. numdirauths = 9
  334. dirauthaddrs = []
  335. dirauths = []
  336. for i in range(numdirauths):
  337. dira = dirauth.DirAuth(i, numdirauths)
  338. dirauths.append(dira)
  339. dirauthaddrs.append(dira.netaddr)
  340. # Start some relays
  341. numrelays = 10
  342. relays = []
  343. for i in range(numrelays):
  344. # Relay bandwidths (at least the ones fast enough to get used)
  345. # in the live Tor network (as of Dec 2019) are well approximated
  346. # by (200000-(200000-25000)/3*log10(x)) where x is a
  347. # uniform integer in [1,2500]
  348. x = random.randint(1,2500)
  349. bw = int(200000-(200000-25000)/3*math.log10(x))
  350. relays.append(relay.Relay(dirauthaddrs, bw, 0))
  351. # The fallback relays are a hardcoded list of about 5% of the
  352. # relays, used by clients for bootstrapping
  353. numfallbackrelays = int(numrelays * 0.05) + 1
  354. fallbackrelays = random.sample(relays, numfallbackrelays)
  355. for r in fallbackrelays:
  356. r.set_is_fallbackrelay()
  357. network.thenetwork.setfallbackrelays(fallbackrelays)
  358. # Tick the epoch
  359. network.thenetwork.nextepoch()
  360. dirauth.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys(), perfstats)
  361. print('ticked; epoch=', network.thenetwork.getepoch())
  362. relays[3].channelmgr.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr)
  363. # See what channels exist and do a consistency check
  364. for r in relays:
  365. print("%s: %s" % (r.netaddr, [ str(k) for k in r.channelmgr.channels.keys()]))
  366. raddr = r.netaddr
  367. for ad, ch in r.channelmgr.channels.items():
  368. if ch.peer.channelmgr.myaddr != ad:
  369. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  370. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  371. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  372. # Start some clients
  373. numclients = 1
  374. clients = []
  375. for i in range(numclients):
  376. clients.append(Client(dirauthaddrs))
  377. # Tick the epoch
  378. network.thenetwork.nextepoch()
  379. # See what channels exist and do a consistency check
  380. for c in clients:
  381. print("%s: %s" % (c.netaddr, [ str(k) for k in c.channelmgr.channels.keys()]))
  382. caddr = c.netaddr
  383. for ad, ch in c.channelmgr.channels.items():
  384. if ch.peer.channelmgr.myaddr != ad:
  385. print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
  386. if ch.peer.channelmgr.channels[caddr].peer is not ch:
  387. print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
  388. # Pick a bunch of bw-weighted random relays and look at the
  389. # distribution
  390. for i in range(100):
  391. r = relays[0].channelmgr.relaypicker.pick_weighted_relay()
  392. if network.thenetwork.womode == network.WOMode.VANILLA:
  393. print("relay",r.descdict["addr"])
  394. else:
  395. print("relay",r.snipdict["addr"])
  396. relays[3].terminate()
  397. relaysent += relays[3].perfstats.bytes_sent
  398. relayrecv += relays[3].perfstats.bytes_received
  399. del relays[3]
  400. # Tick the epoch
  401. network.thenetwork.nextepoch()
  402. circs = []
  403. for i in range(20):
  404. circ = clients[0].channelmgr.new_circuit()
  405. if circ is None:
  406. sys.exit("ERR: Client unable to create circuits")
  407. circs.append(circ)
  408. circ.send_cell(relay.StringCell("hello world circuit %d" % i))
  409. # Tick the epoch
  410. network.thenetwork.nextepoch()
  411. # See what channels exist and do a consistency check
  412. for r in relays:
  413. 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()]))
  414. raddr = r.netaddr
  415. for ad, ch in r.channelmgr.channels.items():
  416. if ch.peer.channelmgr.myaddr != ad:
  417. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  418. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  419. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  420. # See what channels exist and do a consistency check
  421. for c in clients:
  422. 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()]))
  423. caddr = c.netaddr
  424. for ad, ch in c.channelmgr.channels.items():
  425. if ch.peer.channelmgr.myaddr != ad:
  426. print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
  427. if ch.peer.channelmgr.channels[caddr].peer is not ch:
  428. print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
  429. if ch.circuithandlers.keys() != \
  430. ch.peer.channelmgr.channels[caddr].circuithandlers.keys():
  431. print('circuit asymmetry:', caddr, ad, ch.peer.channelmgr.myaddr)
  432. for c in circs:
  433. c.close()
  434. for d in dirauths:
  435. print(d.perfstats)
  436. dirasent += d.perfstats.bytes_sent
  437. dirarecv += d.perfstats.bytes_received
  438. print("DirAuths sent=%s recv=%s" % (dirasent, dirarecv))
  439. totsent += dirasent
  440. totrecv += dirarecv
  441. for r in relays:
  442. print(r.perfstats)
  443. relaysent += r.perfstats.bytes_sent
  444. relayrecv += r.perfstats.bytes_received
  445. print("Relays sent=%s recv=%s" % (relaysent, relayrecv))
  446. totsent += relaysent
  447. totrecv += relayrecv
  448. for c in clients:
  449. print(c.perfstats)
  450. clisent += c.perfstats.bytes_sent
  451. clirecv += c.perfstats.bytes_received
  452. print("Client sent=%s recv=%s" % (clisent, clirecv))
  453. totsent += clisent
  454. totrecv += clirecv
  455. print("Total sent=%s recv=%s" % (totsent, totrecv))