client.py 22 KB

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