relay.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import math
  4. import sys
  5. import logging
  6. import nacl.utils
  7. import nacl.signing
  8. import nacl.public
  9. import nacl.hash
  10. import nacl.bindings
  11. import hashlib
  12. from collections import namedtuple
  13. import network
  14. import dirauth
  15. VRFOutput = namedtuple('VRFOutput', 'output proof')
  16. class VRF():
  17. def __init__(self, private_key, relaypicker):
  18. self.private_key = private_key
  19. self.relaypicker = relaypicker
  20. def get_output(self, vrf_input):
  21. output = self.relaypicker.pick_weighted_relay_index()
  22. m = hashlib.sha256()
  23. m.update(str(output).encode())
  24. return VRFOutput(output, m.digest())
  25. class RelayNetMsg(network.NetMsg):
  26. """The subclass of NetMsg for messages between relays and either
  27. relays or clients."""
  28. class RelayGetConsensusMsg(RelayNetMsg):
  29. """The subclass of RelayNetMsg for fetching the consensus. Sent by
  30. clients to relays."""
  31. class RelayConsensusMsg(RelayNetMsg):
  32. """The subclass of RelayNetMsg for returning the consensus from
  33. relays to clients, in response to RelayGetConsensusMsg."""
  34. def __init__(self, consensus):
  35. self.consensus = consensus
  36. class RelayGetConsensusDiffMsg(RelayNetMsg):
  37. """The subclass of RelayNetMsg for fetching the consensus, if the
  38. requestor already has the previous consensus. Sent by clients to
  39. relays."""
  40. class RelayConsensusDiffMsg(RelayNetMsg):
  41. """The subclass of RelayNetMsg for returning the consensus, if the
  42. requestor already has the previous consensus. We don't _actually_
  43. produce the diff at this time; we just charge fewer bytes for this
  44. message. Sent by relays to clients in response to
  45. RelayGetConsensusDiffMsg."""
  46. def __init__(self, consensus):
  47. self.consensus = consensus
  48. def size(self):
  49. if network.symbolic_byte_counters:
  50. return super().size()
  51. return math.ceil(RelayConsensusMsg(self.consensus).size() \
  52. * network.P_Delta)
  53. class RelayRandomHopMsg(RelayNetMsg):
  54. """A message used for testing, that hops from relay to relay
  55. randomly until its TTL expires."""
  56. def __init__(self, ttl):
  57. self.ttl = ttl
  58. def __str__(self):
  59. return "RandomHop TTL=%d" % self.ttl
  60. class CircuitCellMsg(RelayNetMsg):
  61. """Send a message tagged with a circuit id. This is the container
  62. class for all RelayCell messages."""
  63. def __init__(self, circuitid, cell):
  64. self.circid = circuitid
  65. self.cell = cell
  66. def __str__(self):
  67. return "C%d:%s" % (self.circid, self.cell)
  68. def size(self):
  69. # circuitids are 4 bytes
  70. return 4 + self.cell.size()
  71. class RelayCell(RelayNetMsg):
  72. """All cells (which are sent inside a CircuitCellMsg, and so do not
  73. need their own circuitid) should be a subclass of this class."""
  74. class StringCell(RelayCell):
  75. """Send an arbitrary string as a cell."""
  76. def __init__(self, str):
  77. self.data = str
  78. def __str__(self):
  79. return self.data.__str__()
  80. class CloseCell(RelayCell):
  81. """Close the circuit this cell was sent on. It should be sent
  82. _unencrypted_ (not within an EncryptedCell), and relays that receive
  83. one should forward it along the adjacent circuit, then close both
  84. the circuit it was received on and the adjacent one."""
  85. # It is intentional that VanillaCreateCircuitMsg is a RelayNetMsg and
  86. # not a RelayCell. This is the message that _creates_ the circuit, so
  87. # it can't be sent as a cell _within_ the circuit.
  88. class VanillaCreateCircuitMsg(RelayNetMsg):
  89. """The message for requesting circuit creation in Vanilla Onion
  90. Routing."""
  91. def __init__(self, circid, ntor_request):
  92. self.circid = circid
  93. self.ntor_request = ntor_request
  94. class VanillaCreatedCircuitCell(RelayCell):
  95. """The message for responding to circuit creation in Vanilla Onion
  96. Routing."""
  97. def __init__(self, ntor_reply):
  98. self.ntor_reply = ntor_reply
  99. class VanillaExtendCircuitCell(RelayCell):
  100. """The message for requesting circuit extension in Vanilla Onion
  101. Routing."""
  102. def __init__(self, hopaddr, ntor_request):
  103. self.hopaddr = hopaddr
  104. self.ntor_request = ntor_request
  105. class VanillaExtendedCircuitCell(RelayCell):
  106. """The message for responding to circuit extension in Vanilla Onion
  107. Routing."""
  108. def __init__(self, ntor_reply):
  109. self.ntor_reply = ntor_reply
  110. # It is intentional that TelescopingCreateCircuitMsg is a RelayNetMsg and
  111. # not a RelayCell. This is the message that _creates_ the circuit, so
  112. # it can't be sent as a cell _within_ the circuit.
  113. class TelescopingCreateCircuitMsg(RelayNetMsg):
  114. """The message for requesting circuit creation in Telescoping Onion
  115. Routing."""
  116. def __init__(self, circid, ntor_request):
  117. self.circid = circid
  118. self.ntor_request = ntor_request
  119. class TelescopingCreatedCircuitCell(RelayCell):
  120. """The message for responding to circuit creation in Telescoping Walking
  121. Onions."""
  122. def __init__(self, ntor_reply):
  123. self.ntor_reply = ntor_reply
  124. class TelescopingExtendCircuitCell(RelayCell):
  125. """The message for requesting circuit extension in Telescoping Walking
  126. Onions."""
  127. def __init__(self, idx, ntor_request):
  128. self.idx = idx
  129. self.ntor_request = ntor_request
  130. class TelescopingExtendedCircuitCell(RelayCell):
  131. """The message for responding to circuit extension in Telescoping Walking
  132. Onions."""
  133. def __init__(self, ntor_reply, snip):
  134. self.ntor_reply = ntor_reply
  135. self.snip = snip
  136. class SinglePassCreateCircuitMsg(RelayNetMsg):
  137. """The message for requesting circuit creation in Single Pass Onion
  138. Routing. This is used to extend a Single-Pass circuit by clients."""
  139. def __init__(self, circid, ntor_request, client_path_selection_key,
  140. ttl=2):
  141. self.circid = circid
  142. self.ntor_request = ntor_request
  143. self.clipathselkey = bytes(client_path_selection_key)
  144. self.ttl = ttl
  145. class SinglePassCreatedCircuitCell(RelayCell):
  146. """The message for responding to circuit creation in Single-Pass Walking
  147. Onions."""
  148. def __init__(self, ntor_reply, encrypted_cell):
  149. self.ntor_reply = ntor_reply
  150. # The above field is sent in plaintext; the below is an
  151. # SinglePassCreatedEnc, or None if this is the last layer
  152. self.enc = encrypted_cell
  153. class EncryptedCell(RelayCell):
  154. """Send a message encrypted with a symmetric key. In this
  155. implementation, the encryption is not really done. A hash of the
  156. key is stored with the message so that it can be checked at
  157. decryption time."""
  158. def __init__(self, key, msg):
  159. self.keyhash = nacl.hash.sha256(key)
  160. self.plaintext = msg
  161. def decrypt(self, key):
  162. keyhash = nacl.hash.sha256(key)
  163. if keyhash != self.keyhash:
  164. raise ValueError("EncryptedCell key mismatch")
  165. return self.plaintext
  166. def size(self):
  167. # Current Tor actually has no overhead for encryption
  168. return self.plaintext.size()
  169. class SinglePassCreatedEnc(EncryptedCell):
  170. """The nested encrypted informaion inside a
  171. SinglePassCreatedCircuitCell. nextlayer is itself a
  172. SinglePassCreatedCircuitCell."""
  173. def __init__(self, key, snip, vrf_output, nextlayer):
  174. super().__init__(key, (snip, vrf_output, nextlayer))
  175. class RelayFallbackTerminationError(Exception):
  176. """An exception raised when someone tries to terminate a fallback
  177. relay."""
  178. class Sphinx:
  179. """Implement the public-key reblinding technique based on Sphinx.
  180. This does a few more public-key operations than it would strictly
  181. need to if we were using a group implementation that (unlike nacl)
  182. supported the operations we needed directly. The biggest issue is
  183. that nacl insists the high bit is set on private keys, which means
  184. we can't just multiply private keys together to get a new private
  185. key, and do a single DH operation with that resulting key; we have
  186. to perform a linear number of DH operations instead, per node in the
  187. circuit, so a quadratic number of DH operations total."""
  188. @staticmethod
  189. def makeblindkey(shared_secret, domain_separator, perfstats):
  190. """Create a Sphinx reblinding key (a PrivateKey) out of a shared
  191. secret and a domain separator (both bytestrings). The domain
  192. separator is just a constant bytestring like b'data' or
  193. b'circuit' for the data-protecting and circuit-protecting
  194. public-key elements respectively."""
  195. rawkey = nacl.hash.sha256(domain_separator + shared_secret,
  196. encoder=nacl.encoding.RawEncoder)
  197. perfstats.keygens += 1
  198. # The PrivateKey constructor does the Curve25519 pinning of
  199. # certain bits of the key to 0 and 1
  200. return nacl.public.PrivateKey(rawkey)
  201. @staticmethod
  202. def reblindpubkey(blindkey, pubkey, perfstats):
  203. """Create a Sphinx reblinded PublicKey out of a reblinding key
  204. (output by makeblindkey) and a (possibly already reblinded)
  205. PublicKey."""
  206. new_pubkey = nacl.bindings.crypto_scalarmult(bytes(blindkey),
  207. bytes(pubkey))
  208. perfstats.dhs += 1
  209. return nacl.public.PublicKey(new_pubkey)
  210. @staticmethod
  211. def client(client_privkey, blindkey_list, server_pubkey,
  212. domain_separator, is_last, perfstats):
  213. """Given the client's PrivateKey, a (possibly empty) list of
  214. reblinding keys, and the server's PublicKey, produce the shared
  215. secret and the new blinding key (to add to the list). The
  216. domain separator is as above. If is_last is true, don't bother
  217. creating the new blinding key, since this is the last iteration,
  218. and we won't be using it."""
  219. reblinded_server_pubkey = server_pubkey
  220. for blindkey in blindkey_list:
  221. reblinded_server_pubkey = Sphinx.reblindpubkey(blindkey,
  222. reblinded_server_pubkey, perfstats)
  223. sharedsecret = nacl.public.Box(client_privkey,
  224. reblinded_server_pubkey).shared_key()
  225. perfstats.dhs += 1
  226. if is_last:
  227. blindkey = None
  228. else:
  229. blindkey = Sphinx.makeblindkey(sharedsecret,
  230. domain_separator, perfstats)
  231. return sharedsecret, blindkey
  232. @staticmethod
  233. def server(client_pubkey, server_privkey, domain_separator, is_last,
  234. perfstats):
  235. """Given the client's PublicKey and the server's PrivateKey,
  236. produce the shared secret and the new reblinded client
  237. PublicKey. The domain separator is as above. If is_last is
  238. True, don't bother generating the new PublicKey, since we're the
  239. last server in the chain, and won't be using it."""
  240. sharedsecret = nacl.public.Box(server_privkey,
  241. client_pubkey).shared_key()
  242. perfstats.dhs += 1
  243. if is_last:
  244. blinded_pubkey = None
  245. else:
  246. blindkey = Sphinx.makeblindkey(sharedsecret, domain_separator,
  247. perfstats)
  248. blinded_pubkey = Sphinx.reblindpubkey(blindkey, client_pubkey,
  249. perfstats)
  250. return sharedsecret, blinded_pubkey
  251. class NTor:
  252. """A class implementing the ntor one-way authenticated key agreement
  253. scheme. The details are not exactly the same as either the ntor
  254. paper or Tor's implementation, but it will agree on keys and have
  255. the same number of public key operations."""
  256. def __init__(self, perfstats):
  257. self.perfstats = perfstats
  258. # Only used for Single-Pass Walking Onions; it is the sequence
  259. # of blinding keys used by Sphinx
  260. self.blinding_keys = []
  261. def request(self):
  262. """Create the ntor request message: X = g^x."""
  263. self.client_ephem_key = nacl.public.PrivateKey.generate()
  264. self.perfstats.keygens += 1
  265. return bytes(self.client_ephem_key.public_key)
  266. @staticmethod
  267. def reply(onion_privkey, idpubkey, client_pubkey, perfstats,
  268. sphinx_domainsep=None):
  269. """The server calls this static method to produce the ntor reply
  270. message: (Y = g^y, B = g^b, A = H(M, "verify")) and the shared
  271. secret S = H(M, "secret") for M = (X^y,X^b,ID,B,X,Y). If
  272. sphinx_domainsep is not None, also compute and return the Sphinx
  273. reblinded client request to pass to the next server."""
  274. if type(idpubkey) is not bytes:
  275. idpubkey = bytes(idpubkey)
  276. if type(client_pubkey) is bytes:
  277. client_pubkey = nacl.public.PublicKey(client_pubkey)
  278. server_ephem_key = nacl.public.PrivateKey.generate()
  279. perfstats.keygens += 1
  280. xykey = nacl.public.Box(server_ephem_key, client_pubkey).shared_key()
  281. xbkey = nacl.public.Box(onion_privkey, client_pubkey).shared_key()
  282. perfstats.dhs += 2
  283. M = xykey + xbkey + \
  284. idpubkey + \
  285. onion_privkey.public_key.encode(encoder=nacl.encoding.RawEncoder) + \
  286. server_ephem_key.public_key.encode(encoder=nacl.encoding.RawEncoder)
  287. A = nacl.hash.sha256(M + b'verify', encoder=nacl.encoding.RawEncoder)
  288. S = nacl.hash.sha256(M + b'secret', encoder=nacl.encoding.RawEncoder)
  289. if sphinx_domainsep is not None:
  290. blindkey = Sphinx.makeblindkey(S, sphinx_domainsep, perfstats)
  291. blinded_client_pubkey = Sphinx.reblindpubkey(blindkey,
  292. client_pubkey, perfstats)
  293. return ((bytes(server_ephem_key.public_key),
  294. bytes(onion_privkey.public_key), A),
  295. S), blinded_client_pubkey
  296. else:
  297. return ((bytes(server_ephem_key.public_key),
  298. bytes(onion_privkey.public_key), A), S)
  299. def verify(self, reply, onion_pubkey, idpubkey, sphinx_domainsep=None):
  300. """The client calls this method to verify the ntor reply
  301. message, passing the onion and id public keys for the server
  302. it's expecting to be talking to. If sphinx_domainsep is not
  303. None, also compute the reblinding key so that the client can
  304. reuse this same NTor object for the next server. Returns the
  305. shared secret on success, or raises ValueError on failure."""
  306. server_ephem_pubkey, server_onion_pubkey, authtag = reply
  307. if type(idpubkey) is not bytes:
  308. idpubkey = bytes(idpubkey)
  309. if type(server_ephem_pubkey) is bytes:
  310. server_ephem_pubkey = nacl.public.PublicKey(server_ephem_pubkey)
  311. if type(server_onion_pubkey) is bytes:
  312. server_onion_pubkey = nacl.public.PublicKey(server_onion_pubkey)
  313. if type(onion_pubkey) is bytes:
  314. onion_pubkey = nacl.public.PublicKey(onion_pubkey)
  315. if onion_pubkey != server_onion_pubkey:
  316. raise ValueError("NTor onion pubkey mismatch")
  317. # We use the blinding keys if present; if they're not present
  318. # (because we're not in Single-Pass Walking Onions), the loops
  319. # are just empty anyway, so everything will work in the usual
  320. # unblinded way.
  321. reblinded_server_ephem_pubkey = server_ephem_pubkey
  322. for blindkey in self.blinding_keys:
  323. reblinded_server_ephem_pubkey = Sphinx.reblindpubkey(blindkey,
  324. reblinded_server_ephem_pubkey, self.perfstats)
  325. xykey = nacl.public.Box(self.client_ephem_key,
  326. reblinded_server_ephem_pubkey).shared_key()
  327. reblinded_onion_pubkey = onion_pubkey
  328. for blindkey in self.blinding_keys:
  329. reblinded_onion_pubkey = Sphinx.reblindpubkey(blindkey,
  330. reblinded_onion_pubkey, self.perfstats)
  331. xbkey = nacl.public.Box(self.client_ephem_key,
  332. reblinded_onion_pubkey).shared_key()
  333. self.perfstats.dhs += 2
  334. M = xykey + xbkey + \
  335. idpubkey + \
  336. onion_pubkey.encode(encoder=nacl.encoding.RawEncoder) + \
  337. server_ephem_pubkey.encode(encoder=nacl.encoding.RawEncoder)
  338. Acheck = nacl.hash.sha256(M + b'verify', encoder=nacl.encoding.RawEncoder)
  339. S = nacl.hash.sha256(M + b'secret', encoder=nacl.encoding.RawEncoder)
  340. if Acheck != authtag:
  341. raise ValueError("NTor auth mismatch")
  342. if sphinx_domainsep is not None:
  343. blindkey = Sphinx.makeblindkey(S, sphinx_domainsep,
  344. self.perfstats)
  345. self.blinding_keys.append(blindkey)
  346. return S
  347. class VanillaExtendCircuitHandler:
  348. """A handler for VanillaExtendCircuitCell cells. It allocates a new
  349. circuit id on the Channel to the requested next hop, connects the
  350. existing and new circuits together, and forwards a
  351. VanillaCreateCircuitMsg to the next hop."""
  352. def received_cell(self, circhandler, cell):
  353. # Remove ourselves from handling a second
  354. # VanillaExtendCircuitCell on this circuit
  355. circhandler.replace_celltype_handler(VanillaExtendCircuitCell, None)
  356. # Allocate a new circuit id to the requested next hop
  357. channelmgr = circhandler.channel.channelmgr
  358. nexthopchannel = channelmgr.get_channel_to(cell.hopaddr)
  359. newcircid, newcirchandler = nexthopchannel.new_circuit()
  360. # Connect the existing and new circuits together
  361. circhandler.adjacent_circuit_handler = newcirchandler
  362. newcirchandler.adjacent_circuit_handler = circhandler
  363. # Set up a handler for when the VanillaCreatedCircuitCell comes
  364. # back
  365. newcirchandler.replace_celltype_handler(
  366. VanillaCreatedCircuitCell,
  367. VanillaCreatedRelayHandler())
  368. # Forward a VanillaCreateCircuitMsg to the next hop
  369. nexthopchannel.send_msg(
  370. VanillaCreateCircuitMsg(newcircid, cell.ntor_request))
  371. class TelescopingExtendCircuitHandler:
  372. """A handler for TelescopingExtendCircuitCell cells. It allocates a new
  373. circuit id on the Channel to the requested next hop, connects the
  374. existing and new circuits together, and forwards a
  375. TelescopingCreateCircuitMsg to the next hop."""
  376. def __init__(self, relaypicker, current_relay_idkey):
  377. self.relaypicker = relaypicker
  378. self.current_relay_idkey = bytes(current_relay_idkey)
  379. def received_cell(self, circhandler, cell):
  380. # Remove ourselves from handling a second
  381. # TelescopingExtendCircuitCell on this circuit
  382. circhandler.replace_celltype_handler(TelescopingExtendCircuitCell, None)
  383. # Find the SNIP corresponding to the index sent by the client
  384. next_snip = self.relaypicker.pick_relay_by_uniform_index(cell.idx)
  385. # Check to make sure that we aren't extending to ourselves. If we are,
  386. # close the circuit.
  387. if next_snip.snipdict["idkey"] == self.current_relay_idkey:
  388. logging.debug("Client requested extending the circuit to a relay already in the path; aborting. my circid: %s", str(circhandler.circid))
  389. circhandler.close()
  390. return
  391. # Allocate a new circuit id to the requested next hop
  392. channelmgr = circhandler.channel.channelmgr
  393. nexthopchannel = channelmgr.get_channel_to(next_snip.snipdict["addr"])
  394. newcircid, newcirchandler = nexthopchannel.new_circuit()
  395. # Connect the existing and new circuits together
  396. circhandler.adjacent_circuit_handler = newcirchandler
  397. newcirchandler.adjacent_circuit_handler = circhandler
  398. # Set up a handler for when the TelescopingCreatedCircuitCell comes
  399. # back
  400. newcirchandler.replace_celltype_handler(
  401. TelescopingCreatedCircuitCell,
  402. TelescopingCreatedRelayHandler(next_snip))
  403. # Forward a TelescopingCreateCircuitMsg to the next hop
  404. nexthopchannel.send_msg(
  405. TelescopingCreateCircuitMsg(newcircid, cell.ntor_request))
  406. class VanillaCreatedRelayHandler:
  407. """Handle a VanillaCreatedCircuitCell received by a _relay_ that
  408. recently received a VanillaExtendCircuitCell from a client, and so
  409. forwarded a VanillaCreateCircuitCell to the next hop."""
  410. def received_cell(self, circhandler, cell):
  411. # Remove ourselves from handling a second
  412. # VanillaCreatedCircuitCell on this circuit
  413. circhandler.replace_celltype_handler(VanillaCreatedCircuitCell, None)
  414. # Just forward a VanillaExtendedCircuitCell back towards the
  415. # client
  416. circhandler.adjacent_circuit_handler.send_cell(
  417. VanillaExtendedCircuitCell(cell.ntor_reply))
  418. class TelescopingCreatedRelayHandler:
  419. """Handle a TelescopingCreatedCircuitCell received by a _relay_ that
  420. recently received a TelescopingExtendCircuitCell from a client, and so
  421. forwarded a TelescopingCreateCircuitCell to the next hop."""
  422. def __init__(self, next_snip):
  423. self.next_snip = next_snip
  424. def received_cell(self, circhandler, cell):
  425. logging.debug("Handle a TelescopingCreatedCircuit received by a relay")
  426. # Remove ourselves from handling a second
  427. # TelescopingCreatedCircuitCell on this circuit
  428. circhandler.replace_celltype_handler(TelescopingCreatedCircuitCell, None)
  429. # Just forward a TelescopingExtendedCircuitCell back towards the
  430. # client
  431. circhandler.adjacent_circuit_handler.send_cell(
  432. TelescopingExtendedCircuitCell(cell.ntor_reply, self.next_snip))
  433. class SinglePassCreatedRelayHandler:
  434. """Handle a SinglePassCreatedCircuitCell received by a _relay_ that
  435. recently received a SinglePassCreateCircuitMsg from this relay."""
  436. def __init__(self, ntorreply, next_snip, vrf_output, enckey):
  437. self.ntorreply = ntorreply
  438. self.next_snip = next_snip
  439. self.vrf_output = vrf_output
  440. self.enckey = enckey
  441. def received_cell(self, circhandler, cell):
  442. logging.debug("Handle a SinglePassCreatedCircuitCell received by a relay")
  443. # Remove ourselves from handling a second
  444. # SinglePassCreatedCircuitCell on this circuit
  445. circhandler.replace_celltype_handler(SinglePassCreatedCircuitCell, None)
  446. logging.debug("Sending a SinglePassCreatedCell after receiving one from %s", self.next_snip.snipdict['addr'])
  447. # Forward a SinglePassCreatedCircuitCell back towards the client
  448. circhandler.adjacent_circuit_handler.channel_send_cell(
  449. SinglePassCreatedCircuitCell(cell.ntor_reply,
  450. SinglePassCreatedEnc(self.enckey, self.next_snip,
  451. self.vrf_output, cell)))
  452. class CircuitHandler:
  453. """A class for managing sending and receiving encrypted cells on a
  454. particular circuit."""
  455. class NoCryptLayer:
  456. def encrypt_msg(self, msg): return msg
  457. def decrypt_msg(self, msg): return msg
  458. class CryptLayer:
  459. def __init__(self, enckey, deckey, next_layer):
  460. self.enckey = enckey
  461. self.deckey = deckey
  462. self.next_layer = next_layer
  463. def encrypt_msg(self, msg):
  464. return self.next_layer.encrypt_msg(EncryptedCell(self.enckey, msg))
  465. def decrypt_msg(self, msg):
  466. return self.next_layer.decrypt_msg(msg).decrypt(self.deckey)
  467. def __init__(self, channel, circid):
  468. self.channel = channel
  469. self.circid = circid
  470. # The list of relay descriptors that form the circuit so far
  471. # (client side only)
  472. self.circuit_descs = []
  473. # The dispatch table is indexed by type, and the values are
  474. # objects with received_cell(circhandler, cell) methods.
  475. self.cell_dispatch_table = dict()
  476. # The topmost crypt layer. This is an object with
  477. # encrypt_msg(msg) and decrypt_msg(msg) methods that returns the
  478. # en/decrypted messages respectively. Messages are encrypted
  479. # starting with the last layer that was added (the keys for the
  480. # furthest away relay in the circuit) and are decrypted starting
  481. # with the first layer that was added (the keys for the guard).
  482. self.crypt_layer = self.NoCryptLayer()
  483. # The adjacent CircuitHandler that's connected to this one. If
  484. # we get a cell on one, we forward it to the other (if it's not
  485. # meant for us to handle directly)
  486. self.adjacent_circuit_handler = None
  487. # The function to call when this circuit closes
  488. self.closer = lambda: self.channel.circuithandlers.pop(circid)
  489. def close(self):
  490. """Close the circuit. Sends a CloseCell on the circuit (and its
  491. adjacent circuit, if present) and closes both."""
  492. adjcirchandler = self.adjacent_circuit_handler
  493. self.adjacent_circuit_handler = None
  494. logging.debug("Closing circuit. circid: %s", str(self.circid))
  495. if adjcirchandler is not None:
  496. adjcirchandler.adjacent_circuit_handler = None
  497. self.closer()
  498. self.channel_send_cell(CloseCell())
  499. if adjcirchandler is not None:
  500. adjcirchandler.closer()
  501. adjcirchandler.channel_send_cell(CloseCell())
  502. def send_cell(self, cell):
  503. """Send a cell on this circuit, encrypting as needed."""
  504. self.channel_send_cell(self.crypt_layer.encrypt_msg(cell))
  505. def channel_send_cell(self, cell):
  506. """Send a cell on this circuit directly without encrypting it
  507. first."""
  508. self.channel.send_msg(CircuitCellMsg(self.circid, cell))
  509. def received_cell(self, cell):
  510. """A cell has been received on this circuit. Dispatch it
  511. according to its type."""
  512. if isinstance(cell, EncryptedCell):
  513. cell = self.crypt_layer.decrypt_msg(cell)
  514. logging.debug("CircuitHandler: %s received cell %s on circuit %d from %s" % (self.channel.channelmgr.myaddr, cell, self.circid, self.channel.peer.channelmgr.myaddr))
  515. # If it's still encrypted, it's for sure meant for forwarding to
  516. # our adjacent hop, which had better exist.
  517. if isinstance(cell, EncryptedCell):
  518. self.adjacent_circuit_handler.send_cell(cell)
  519. else:
  520. # This is a plaintext cell meant for us. Handle it
  521. # according to the table.
  522. celltype = type(cell)
  523. if celltype in self.cell_dispatch_table:
  524. self.cell_dispatch_table[celltype].received_cell(self, cell)
  525. elif isinstance(cell, StringCell):
  526. # Default handler; just print the message in the cell
  527. logging.debug("CircuitHandler: %s received '%s' on circuit %d from %s" \
  528. % (self.channel.channelmgr.myaddr, cell,
  529. self.circid, self.channel.peer.channelmgr.myaddr))
  530. elif isinstance(cell, CloseCell):
  531. logging.debug("Received CloseCell on circuit %s", str(self.circid))
  532. # Forward the CloseCell (without encryption) to the
  533. # adjacent circuit, if any, and close both this and the
  534. # adjacent circuit
  535. adjcirchandler = self.adjacent_circuit_handler
  536. self.adjacent_circuit_handler = None
  537. if adjcirchandler is not None:
  538. adjcirchandler.adjacent_circuit_handler = None
  539. self.closer()
  540. if adjcirchandler is not None:
  541. adjcirchandler.closer()
  542. adjcirchandler.channel_send_cell(cell)
  543. else:
  544. # I don't know how to handle this cell?
  545. raise ValueError("CircuitHandler: %s received unknown cell type %s on circuit %d from %s" \
  546. % (self.channel.channelmgr.myaddr, cell,
  547. self.circid, self.channel.peer.channelmgr.myaddr))
  548. def replace_celltype_handler(self, celltype, handler):
  549. """Add an object with a received_cell(circhandler, cell) method
  550. to the cell dispatch table. It replaces anything that's already
  551. there. Passing None as the handler removes the dispatcher for
  552. that cell type."""
  553. if handler is None:
  554. del self.cell_dispatch_table[celltype]
  555. else:
  556. self.cell_dispatch_table[celltype] = handler
  557. def add_crypt_layer(self, enckey, deckey):
  558. """Add a processing layer to this CircuitHandler so that cells
  559. we send will get encrypted with the first given key, and cells
  560. we receive will be decrypted with the other given key."""
  561. current_crypt_layer = self.crypt_layer
  562. self.crypt_layer = self.CryptLayer(enckey, deckey, current_crypt_layer)
  563. class Channel(network.Connection):
  564. """A class representing a channel between a relay and either a
  565. client or a relay, transporting cells from various circuits."""
  566. def __init__(self):
  567. super().__init__()
  568. # The RelayChannelManager managing this Channel
  569. self.channelmgr = None
  570. # The Channel at the other end
  571. self.peer = None
  572. # The function to call when the connection closes
  573. self.closer = lambda: None
  574. # The next circuit id to use on this channel. The party that
  575. # opened the channel uses even numbers; the receiving party uses
  576. # odd numbers.
  577. self.next_circid = None
  578. # A map for CircuitHandlers to use for each open circuit on the
  579. # channel
  580. self.circuithandlers = dict()
  581. def closed(self):
  582. # Close each circuithandler we're managing
  583. while self.circuithandlers:
  584. chitems = iter(self.circuithandlers.items())
  585. circid, circhandler = next(chitems)
  586. logging.debug('closing circuit %s', circid)
  587. circhandler.close()
  588. self.closer()
  589. self.peer = None
  590. def close(self):
  591. peer = self.peer
  592. self.closed()
  593. if peer is not None and peer is not self:
  594. peer.closed()
  595. def new_circuit(self):
  596. """Allocate a new circuit on this channel, returning the new
  597. circuit's id and the new CircuitHandler."""
  598. circid = self.next_circid
  599. self.next_circid += 2
  600. circuithandler = CircuitHandler(self, circid)
  601. self.circuithandlers[circid] = circuithandler
  602. return circid, circuithandler
  603. def is_circuit_open(self, circid):
  604. is_open = (circid in self.circuithandlers) and (self.circuithandlers[circid] is not None)
  605. return is_open
  606. def new_circuit_with_circid(self, circid):
  607. """Allocate a new circuit on this channel, with the circuit id
  608. received from our peer. Return the new CircuitHandler"""
  609. circuithandler = CircuitHandler(self, circid)
  610. self.circuithandlers[circid] = circuithandler
  611. return circuithandler
  612. def send_cell(self, circid, cell):
  613. """Send the given message on the given circuit, encrypting or
  614. decrypting as needed."""
  615. self.circuithandlers[circid].send_cell(cell)
  616. def send_raw_cell(self, circid, cell):
  617. """Send the given message, tagged for the given circuit id. No
  618. encryption or decryption is done."""
  619. self.send_msg(CircuitCellMsg(self.circid, self.cell))
  620. def send_msg(self, msg):
  621. """Send the given NetMsg on the channel."""
  622. self.channelmgr.perfstats.bytes_sent += msg.size()
  623. self.peer.received(self.channelmgr.myaddr, msg)
  624. def received(self, peeraddr, msg):
  625. """Callback when a message is received from the network."""
  626. logging.debug('Channel: %s received %s from %s' % (self.channelmgr.myaddr, msg, peeraddr))
  627. self.channelmgr.perfstats.bytes_received += msg.size()
  628. if isinstance(msg, CircuitCellMsg):
  629. circid, cell = msg.circid, msg.cell
  630. self.circuithandlers[circid].received_cell(cell)
  631. else:
  632. self.channelmgr.received_msg(msg, peeraddr, self)
  633. class ChannelManager:
  634. """The class that manages the channels to other relays and clients.
  635. Relays and clients both use subclasses of this class to both create
  636. on-demand channels to relays, to gracefully handle the closing of
  637. channels, and to handle commands received over the channels."""
  638. def __init__(self, myaddr, dirauthaddrs, perfstats):
  639. # A dictionary of Channels to other hosts, indexed by NetAddr
  640. self.channels = dict()
  641. self.myaddr = myaddr
  642. self.dirauthaddrs = dirauthaddrs
  643. self.consensus = None
  644. self.relaypicker = None
  645. self.perfstats = perfstats
  646. def terminate(self):
  647. """Close all connections we're managing."""
  648. while self.channels:
  649. channelitems = iter(self.channels.items())
  650. addr, channel = next(channelitems)
  651. logging.debug('closing channel %s %s', addr, channel)
  652. channel.close()
  653. def add_channel(self, channel, peeraddr):
  654. """Add the given channel to the list of channels we are
  655. managing. If we are already managing a channel to the same
  656. peer, close it first."""
  657. if peeraddr in self.channels:
  658. self.channels[peeraddr].close()
  659. channel.channelmgr = self
  660. self.channels[peeraddr] = channel
  661. channel.closer = lambda: self.channels.pop(peeraddr)
  662. def get_channel_to(self, addr):
  663. """Get the Channel connected to the given NetAddr, creating one
  664. if none exists right now."""
  665. if addr in self.channels:
  666. return self.channels[addr]
  667. # Create the new channel
  668. logging.debug('getting channel from %s to %s',self.myaddr,addr)
  669. newchannel = network.thenetwork.connect(self.myaddr, addr,
  670. self.perfstats)
  671. logging.debug('got channel from %s to %s',self.myaddr,addr)
  672. self.channels[addr] = newchannel
  673. newchannel.closer = lambda: self.channels.pop(addr)
  674. newchannel.channelmgr = self
  675. return newchannel
  676. def received_msg(self, msg, peeraddr, channel):
  677. """Callback when a NetMsg not specific to a circuit is
  678. received."""
  679. logging.debug("ChannelManager: Node %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  680. def received_cell(self, circid, cell, peeraddr, channel):
  681. """Callback with a circuit-specific cell is received."""
  682. logging.debug("ChannelManager: Node %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  683. def send_msg(self, msg, peeraddr):
  684. """Send a message to the peer with the given address."""
  685. channel = self.get_channel_to(peeraddr)
  686. channel.send_msg(msg)
  687. def send_cell(self, circid, cell, peeraddr):
  688. """Send a cell on the given circuit to the peer with the given
  689. address."""
  690. channel = self.get_channel_to(peeraddr)
  691. channel.send_cell(circid, cell)
  692. class RelayChannelManager(ChannelManager):
  693. """The subclass of ChannelManager for relays."""
  694. def __init__(self, myaddr, dirauthaddrs, onionprivkey, idpubkey,
  695. path_selection_key, perfstats):
  696. super().__init__(myaddr, dirauthaddrs, perfstats)
  697. self.onionkey = onionprivkey
  698. self.idpubkey = idpubkey
  699. if network.thenetwork.womode != network.WOMode.VANILLA:
  700. self.endive = None
  701. if network.thenetwork.womode == network.WOMode.SINGLEPASS:
  702. self.path_selection_key = path_selection_key
  703. def get_consensus(self):
  704. """Download a fresh consensus (and ENDIVE if using Walking
  705. Onions) from a random dirauth."""
  706. a = random.choice(self.dirauthaddrs)
  707. c = network.thenetwork.connect(self, a, self.perfstats)
  708. if network.thenetwork.womode == network.WOMode.VANILLA:
  709. if self.consensus is not None and \
  710. len(self.consensus.consdict['relays']) > 0:
  711. self.consensus = c.getconsensusdiff()
  712. else:
  713. self.consensus = c.getconsensus()
  714. self.relaypicker = dirauth.Consensus.verify(self.consensus,
  715. network.thenetwork.dirauthkeys(), self.perfstats)
  716. else:
  717. self.consensus = c.getconsensus()
  718. if self.endive is not None and \
  719. len(self.endive.enddict['snips']) > 0:
  720. self.endive = c.getendivediff()
  721. else:
  722. self.endive = c.getendive()
  723. self.relaypicker = dirauth.ENDIVE.verify(self.endive,
  724. self.consensus, network.thenetwork.dirauthkeys(),
  725. self.perfstats)
  726. c.close()
  727. def received_msg(self, msg, peeraddr, channel):
  728. """Callback when a NetMsg not specific to a circuit is
  729. received."""
  730. logging.debug("RelayChannelManager: Node %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  731. if isinstance(msg, RelayRandomHopMsg):
  732. if msg.ttl > 0:
  733. # Pick a random next hop from the consensus
  734. nexthop = self.relaypicker.pick_weighted_relay()
  735. if network.thenetwork.womode == network.WOMode.VANILLA:
  736. nextaddr = nexthop.descdict["addr"]
  737. else:
  738. nextaddr = nexthop.snipdict["addr"]
  739. self.send_msg(RelayRandomHopMsg(msg.ttl-1), nextaddr)
  740. elif isinstance(msg, RelayGetConsensusMsg):
  741. self.send_msg(RelayConsensusMsg(self.consensus), peeraddr)
  742. elif isinstance(msg, RelayGetConsensusDiffMsg):
  743. self.send_msg(RelayConsensusDiffMsg(self.consensus), peeraddr)
  744. elif isinstance(msg, VanillaCreateCircuitMsg):
  745. # A new circuit has arrived
  746. circhandler = channel.new_circuit_with_circid(msg.circid)
  747. # Create the ntor reply
  748. reply, secret = NTor.reply(self.onionkey, self.idpubkey,
  749. msg.ntor_request, self.perfstats)
  750. # Set up the circuit to use the shared secret
  751. enckey = nacl.hash.sha256(secret + b'downstream')
  752. deckey = nacl.hash.sha256(secret + b'upstream')
  753. circhandler.add_crypt_layer(enckey, deckey)
  754. # Add a handler for if an Extend Cell arrives (there should
  755. # be at most one on this circuit).
  756. circhandler.replace_celltype_handler(
  757. VanillaExtendCircuitCell, VanillaExtendCircuitHandler())
  758. # Send the ntor reply
  759. self.send_msg(CircuitCellMsg(msg.circid,
  760. VanillaCreatedCircuitCell(reply)), peeraddr)
  761. elif isinstance(msg, TelescopingCreateCircuitMsg):
  762. # A new circuit has arrived
  763. circhandler = channel.new_circuit_with_circid(msg.circid)
  764. # Create the ntor reply
  765. reply, secret = NTor.reply(self.onionkey, self.idpubkey,
  766. msg.ntor_request, self.perfstats)
  767. # Set up the circuit to use the shared secret
  768. enckey = nacl.hash.sha256(secret + b'downstream')
  769. deckey = nacl.hash.sha256(secret + b'upstream')
  770. circhandler.add_crypt_layer(enckey, deckey)
  771. # Add a handler for if an Extend Cell arrives (there should
  772. # be at most one on this circuit).
  773. circhandler.replace_celltype_handler(
  774. TelescopingExtendCircuitCell,
  775. TelescopingExtendCircuitHandler(self.relaypicker,
  776. self.idpubkey))
  777. # Send the ntor reply
  778. self.send_msg(CircuitCellMsg(msg.circid,
  779. TelescopingCreatedCircuitCell(reply)), peeraddr)
  780. elif isinstance(msg, SinglePassCreateCircuitMsg) and msg.ttl == 0:
  781. # we are the end of the circuit, just establish a shared key and
  782. # return
  783. logging.debug("RelayChannelManager: Single-Pass TTL is 0, replying without extending")
  784. # A new circuit has arrived
  785. circhandler = channel.new_circuit_with_circid(msg.circid)
  786. # Create the ntor reply
  787. reply, secret = NTor.reply(self.onionkey, self.idpubkey,
  788. msg.ntor_request, self.perfstats)
  789. # Set up the circuit to use the shared secret
  790. enckey = nacl.hash.sha256(secret + b'downstream')
  791. deckey = nacl.hash.sha256(secret + b'upstream')
  792. circhandler.add_crypt_layer(enckey, deckey)
  793. # Send the ntor reply, but no need to send the snip for the next
  794. # relay or vrf proof, as this is the last relay in the circuit.
  795. self.send_msg(CircuitCellMsg(msg.circid,
  796. SinglePassCreatedCircuitCell(reply, None)), peeraddr)
  797. elif isinstance(msg, SinglePassCreateCircuitMsg) and msg.ttl > 0:
  798. logging.debug("RelayChannelManager: Single-Pass TTL is greater than 0; extending")
  799. # A new circuit has arrived
  800. circhandler = channel.new_circuit_with_circid(msg.circid)
  801. # Create the ntor reply for the circuit-extension key, and derive
  802. # the client's next blinded key
  803. (ntorreply, secret), blinded_client_encr_key = NTor.reply(self.onionkey, self.idpubkey,
  804. msg.ntor_request, self.perfstats, b'circuit')
  805. # Set up the circuit to use the shared secret established from the
  806. # circuit extension key
  807. enckey = nacl.hash.sha256(secret + b'downstream')
  808. deckey = nacl.hash.sha256(secret + b'upstream')
  809. # here, we will directly extend the circuit ourselves, after
  810. # determining the next relay using the client's path selection
  811. # key in conjunction with our own
  812. idx_as_hex, blinded_client_path_selection_key = \
  813. Sphinx.server(nacl.public.PublicKey(msg.clipathselkey),
  814. self.path_selection_key, b'circuit', False, self.perfstats)
  815. logging.debug("RelayChannelManager: Unimplemented! need to translate idx into endive index")
  816. logging.debug("RelayChannelManager: Unimplemented! need to pick the next relay using the shared secret between the client and the relay.")
  817. # simpulate the VRF output for now
  818. vrf_output = VRF(self.path_selection_key,
  819. self.relaypicker).get_output(idx_as_hex)
  820. next_hop = self.relaypicker.pick_relay_by_uniform_index(vrf_output.output)
  821. if next_hop == None:
  822. logging.debug("Client requested extending the circuit to a relay index that results in None, aborting. my circid: %s", str(circhandler.circid))
  823. circhandler.close()
  824. elif next_hop.snipdict["idkey"] == bytes(self.idpubkey) or next_hop.snipdict["addr"] == peeraddr:
  825. logging.debug("Client requested extending the circuit to a relay already in the path; aborting. my circid: %s", str(circhandler.circid))
  826. circhandler.close()
  827. # Allocate a new circuit id to the requested next hop
  828. channelmgr = circhandler.channel.channelmgr
  829. nexthopchannel = channelmgr.get_channel_to(next_hop.snipdict["addr"])
  830. newcircid, newcirchandler = nexthopchannel.new_circuit()
  831. # Connect the existing and new circuits together
  832. circhandler.adjacent_circuit_handler = newcirchandler
  833. newcirchandler.adjacent_circuit_handler = circhandler
  834. # Add a handler for once the next relay replies to say that the
  835. # circuit has been created
  836. newcirchandler.replace_celltype_handler(
  837. SinglePassCreatedCircuitCell,
  838. SinglePassCreatedRelayHandler(ntorreply, next_hop,
  839. vrf_output, enckey))
  840. # Send the next create message to the next hop
  841. nexthopchannel.send_msg(SinglePassCreateCircuitMsg(newcircid,
  842. blinded_client_encr_key, blinded_client_path_selection_key,
  843. msg.ttl-1))
  844. # Now set up the crypto
  845. circhandler.add_crypt_layer(enckey, deckey)
  846. else:
  847. return super().received_msg(msg, peeraddr, channel)
  848. def received_cell(self, circid, cell, peeraddr, channel):
  849. """Callback with a circuit-specific cell is received."""
  850. logging.debug("RelayChannelManager: Node %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  851. return super().received_cell(circid, cell, peeraddr, channel)
  852. class Relay(network.Server):
  853. """The class representing an onion relay."""
  854. def __init__(self, dirauthaddrs, bw, flags):
  855. # Gather performance statistics
  856. self.perfstats = network.PerfStats(network.EntType.RELAY, bw)
  857. self.perfstats.is_bootstrapping = True
  858. # Create the identity and onion keys
  859. self.idkey = nacl.signing.SigningKey.generate()
  860. self.onionkey = nacl.public.PrivateKey.generate()
  861. self.perfstats.keygens += 2
  862. self.name = self.idkey.verify_key.encode(encoder=nacl.encoding.HexEncoder).decode("ascii")
  863. # Bind to the network to get a network address
  864. self.netaddr = network.thenetwork.bind(self)
  865. self.perfstats.name = "Relay at %s" % self.netaddr
  866. # Our bandwidth and flags
  867. self.bw = bw
  868. self.flags = flags
  869. # Register for epoch change notification
  870. network.thenetwork.wantepochticks(self, True, end=True)
  871. network.thenetwork.wantepochticks(self, True)
  872. # Create the path selection key for Single-Pass Walking Onions
  873. if network.thenetwork.womode == network.WOMode.SINGLEPASS:
  874. self.path_selection_key = nacl.public.PrivateKey.generate()
  875. self.perfstats.keygens += 1
  876. else:
  877. self.path_selection_key = None
  878. # Create the RelayChannelManager connection manager
  879. self.channelmgr = RelayChannelManager(self.netaddr, dirauthaddrs,
  880. self.onionkey, self.idkey.verify_key, self.path_selection_key, self.perfstats)
  881. # Initially, we're not a fallback relay
  882. self.is_fallbackrelay = False
  883. self.uploaddesc()
  884. def terminate(self):
  885. """Stop this relay."""
  886. if self.is_fallbackrelay:
  887. # Fallback relays must not (for now) terminate
  888. raise RelayFallbackTerminationError(self)
  889. # Stop listening for epoch ticks
  890. network.thenetwork.wantepochticks(self, False, end=True)
  891. network.thenetwork.wantepochticks(self, False)
  892. # Tell the dirauths we're going away
  893. self.uploaddesc(False)
  894. # Close connections to other relays
  895. self.channelmgr.terminate()
  896. # Stop listening to our own bound port
  897. self.close()
  898. def set_is_fallbackrelay(self, isfallback = True):
  899. """Set this relay to be a fallback relay (or unset if passed
  900. False)."""
  901. self.is_fallbackrelay = isfallback
  902. def epoch_ending(self, epoch):
  903. # Download the new consensus, which will have been created
  904. # already since the dirauths' epoch_ending callbacks happened
  905. # before the relays'.
  906. self.channelmgr.get_consensus()
  907. def newepoch(self, epoch):
  908. # Rotate the path selection key for Single-Pass Walking Onions
  909. if network.thenetwork.womode == network.WOMode.SINGLEPASS:
  910. self.path_selection_key = nacl.public.PrivateKey.generate()
  911. self.perfstats.keygens += 1
  912. self.uploaddesc()
  913. def uploaddesc(self, upload=True):
  914. # Upload the descriptor for the epoch to come, or delete a
  915. # previous upload if upload=False
  916. descdict = dict();
  917. descdict["epoch"] = network.thenetwork.getepoch() + 1
  918. descdict["idkey"] = bytes(self.idkey.verify_key)
  919. descdict["onionkey"] = bytes(self.onionkey.public_key)
  920. descdict["addr"] = self.netaddr
  921. descdict["bw"] = self.bw
  922. descdict["flags"] = self.flags
  923. if network.thenetwork.womode == network.WOMode.SINGLEPASS:
  924. descdict["pathselkey"] = bytes(self.path_selection_key)
  925. desc = dirauth.RelayDescriptor(descdict)
  926. desc.sign(self.idkey, self.perfstats)
  927. dirauth.RelayDescriptor.verify(desc, self.perfstats)
  928. if upload:
  929. descmsg = dirauth.DirAuthUploadDescMsg(desc)
  930. else:
  931. # Note that this relies on signatures being deterministic;
  932. # otherwise we'd need to save the descriptor we uploaded
  933. # before so we could tell the airauths to delete the exact
  934. # one
  935. descmsg = dirauth.DirAuthDelDescMsg(desc)
  936. # Upload them
  937. for a in self.channelmgr.dirauthaddrs:
  938. c = network.thenetwork.connect(self, a, self.perfstats)
  939. c.sendmsg(descmsg)
  940. c.close()
  941. def connected(self, peer):
  942. """Callback invoked when someone (client or relay) connects to
  943. us. Create a pair of linked Channels and return the peer half
  944. to the peer."""
  945. # Create the linked pair
  946. if peer is self.netaddr:
  947. # A self-loop? We'll allow it.
  948. peerchannel = Channel()
  949. peerchannel.peer = peerchannel
  950. peerchannel.next_circid = 2
  951. return peerchannel
  952. peerchannel = Channel()
  953. ourchannel = Channel()
  954. peerchannel.peer = ourchannel
  955. peerchannel.next_circid = 2
  956. ourchannel.peer = peerchannel
  957. ourchannel.next_circid = 1
  958. # Add our channel to the RelayChannelManager
  959. self.channelmgr.add_channel(ourchannel, peer)
  960. return peerchannel
  961. if __name__ == '__main__':
  962. perfstats = network.PerfStats(network.EntType.NONE)
  963. # Initialize the (non-cryptographic) random seed
  964. random.seed(1)
  965. if len(sys.argv) < 3:
  966. print("Must pass in network mode and snip auth mode!")
  967. print("Network options are vanilla, telescoping, or single-pass.")
  968. print("SNIP auth options are merkle or threshold.")
  969. sys.exit(0)
  970. network_mode = network.WOMode.string_to_type(sys.argv[1])
  971. if network_mode == -1:
  972. print("Not a valid network mode: " + network_mode)
  973. sys.exit(0)
  974. snipauth_mode = network.SNIPAuthMode.string_to_type(sys.argv[2])
  975. if network_mode == -1:
  976. print("Not a valid SNIP authentication mode: " + snipauth_mode)
  977. sys.exit(0)
  978. if network_mode == network.WOMode.VANILLA:
  979. network.thenetwork.set_wo_style(network.WOMode.VANILLA,
  980. network.SNIPAuthMode.NONE)
  981. elif network_mode == network.WOMode.TELESCOPING:
  982. if snipauth_mode == network.SNIPAuthMode.MERKLE:
  983. network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
  984. network.SNIPAuthMode.MERKLE)
  985. else:
  986. network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
  987. network.SNIPAuthMode.THRESHSIG)
  988. elif network_mode == network.WOMode.SINGLEPASS:
  989. if snipauth_mode == network.SNIPAuthMode.MERKLE:
  990. network.thenetwork.set_wo_style(network.WOMode.SINGLEPASS,
  991. network.SNIPAuthMode.MERKLE)
  992. else:
  993. network.thenetwork.set_wo_style(network.WOMode.SINGLEPASS,
  994. network.SNIPAuthMode.THRESHSIG)
  995. else:
  996. sys.exit("Received unsupported network mode, exiting.")
  997. # Start some dirauths
  998. numdirauths = 9
  999. dirauthaddrs = []
  1000. for i in range(numdirauths):
  1001. dira = dirauth.DirAuth(i, numdirauths)
  1002. dirauthaddrs.append(dira.netaddr)
  1003. # Start some relays
  1004. numrelays = 10
  1005. relays = []
  1006. for i in range(numrelays):
  1007. # Relay bandwidths (at least the ones fast enough to get used)
  1008. # in the live Tor network (as of Dec 2019) are well approximated
  1009. # by (200000-(200000-25000)/3*log10(x)) where x is a
  1010. # uniform integer in [1,2500]
  1011. x = random.randint(1,2500)
  1012. bw = int(200000-(200000-25000)/3*math.log10(x))
  1013. relays.append(Relay(dirauthaddrs, bw, 0))
  1014. # The fallback relays are a hardcoded list of about 5% of the
  1015. # relays, used by clients for bootstrapping
  1016. numfallbackrelays = int(numrelays * 0.05) + 1
  1017. fallbackrelays = random.sample(relays, numfallbackrelays)
  1018. for r in fallbackrelays:
  1019. r.set_is_fallbackrelay()
  1020. network.thenetwork.setfallbackrelays(fallbackrelays)
  1021. # Tick the epoch
  1022. network.thenetwork.nextepoch()
  1023. print(dirauth.DirAuth.consensus)
  1024. print(dirauth.DirAuth.endive)
  1025. if network.thenetwork.womode == network.WOMode.VANILLA:
  1026. relaypicker = dirauth.Consensus.verify(dirauth.DirAuth.consensus,
  1027. network.thenetwork.dirauthkeys(), perfstats)
  1028. else:
  1029. relaypicker = dirauth.ENDIVE.verify(dirauth.DirAuth.endive,
  1030. dirauth.DirAuth.consensus,
  1031. network.thenetwork.dirauthkeys(), perfstats)
  1032. if network.thenetwork.snipauthmode == \
  1033. network.SNIPAuthMode.THRESHSIG:
  1034. for s in dirauth.DirAuth.endive.enddict['snips']:
  1035. dirauth.SNIP.verify(s, dirauth.DirAuth.consensus,
  1036. network.thenetwork.dirauthkeys()[0], perfstats)
  1037. print('ticked; epoch=', network.thenetwork.getepoch())
  1038. relays[3].channelmgr.send_msg(RelayRandomHopMsg(30), relays[5].netaddr)
  1039. # See what channels exist and do a consistency check
  1040. for r in relays:
  1041. print("%s: %s" % (r.netaddr, [ str(k) for k in r.channelmgr.channels.keys()]))
  1042. raddr = r.netaddr
  1043. for ad, ch in r.channelmgr.channels.items():
  1044. if ch.peer.channelmgr.myaddr != ad:
  1045. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  1046. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  1047. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  1048. # Stop some relays
  1049. relays[3].terminate()
  1050. del relays[3]
  1051. relays[5].terminate()
  1052. del relays[5]
  1053. relays[7].terminate()
  1054. del relays[7]
  1055. # Tick the epoch
  1056. network.thenetwork.nextepoch()
  1057. print(dirauth.DirAuth.consensus)
  1058. print(dirauth.DirAuth.endive)
  1059. # See what channels exist and do a consistency check
  1060. for r in relays:
  1061. print("%s: %s" % (r.netaddr, [ str(k) for k in r.channelmgr.channels.keys()]))
  1062. raddr = r.netaddr
  1063. for ad, ch in r.channelmgr.channels.items():
  1064. if ch.peer.channelmgr.myaddr != ad:
  1065. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  1066. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  1067. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  1068. channel = relays[3].channelmgr.get_channel_to(relays[5].netaddr)
  1069. circid, circhandler = channel.new_circuit()
  1070. peerchannel = relays[5].channelmgr.get_channel_to(relays[3].netaddr)
  1071. peerchannel.new_circuit_with_circid(circid)
  1072. relays[3].channelmgr.send_cell(circid, StringCell("test"), relays[5].netaddr)
  1073. idpubkey = relays[1].idkey.verify_key
  1074. onionpubkey = relays[1].onionkey.public_key
  1075. nt = NTor(perfstats)
  1076. req = nt.request()
  1077. R, S = NTor.reply(relays[1].onionkey, idpubkey, req, perfstats)
  1078. S2 = nt.verify(R, onionpubkey, idpubkey)
  1079. print(S == S2)
  1080. # Test the Sphinx class: DH version (for the path selection keys)
  1081. server1_key = nacl.public.PrivateKey.generate()
  1082. server2_key = nacl.public.PrivateKey.generate()
  1083. server3_key = nacl.public.PrivateKey.generate()
  1084. client_key = nacl.public.PrivateKey.generate()
  1085. # Check that normal DH is working
  1086. ckey = nacl.public.Box(client_key, server1_key.public_key).shared_key()
  1087. skey = nacl.public.Box(server1_key, client_key.public_key).shared_key()
  1088. assert(ckey == skey)
  1089. # Transform the client pubkey with Sphinx as it passes through the
  1090. # servers and record the resulting shared secrets
  1091. blinded_client_pubkey = client_key.public_key
  1092. s1secret, blinded_client_pubkey = Sphinx.server(blinded_client_pubkey,
  1093. server1_key, b'circuit', False, perfstats)
  1094. s2secret, blinded_client_pubkey = Sphinx.server(blinded_client_pubkey,
  1095. server2_key, b'circuit', False, perfstats)
  1096. s3secret, _ = Sphinx.server(blinded_client_pubkey,
  1097. server3_key, b'circuit', True, perfstats)
  1098. # Hopefully matching keys on the client side
  1099. blinding_keys = []
  1100. c1secret, blind_key = Sphinx.client(client_key, blinding_keys,
  1101. server1_key.public_key, b'circuit', False, perfstats)
  1102. blinding_keys.append(blind_key)
  1103. c2secret, blind_key = Sphinx.client(client_key, blinding_keys,
  1104. server2_key.public_key, b'circuit', False, perfstats)
  1105. blinding_keys.append(blind_key)
  1106. c3secret, _ = Sphinx.client(client_key, blinding_keys,
  1107. server3_key.public_key, b'circuit', True, perfstats)
  1108. assert(s1secret == c1secret)
  1109. assert(s2secret == c2secret)
  1110. assert(s3secret == c3secret)
  1111. print('Sphinx DH test successful')
  1112. # End test of Sphinx (DH version)
  1113. # Test the Sphinx class: NTor version (for the path selection keys)
  1114. server1_idkey = nacl.signing.SigningKey.generate().verify_key
  1115. server2_idkey = nacl.signing.SigningKey.generate().verify_key
  1116. server3_idkey = nacl.signing.SigningKey.generate().verify_key
  1117. server1_onionkey = nacl.public.PrivateKey.generate()
  1118. server2_onionkey = nacl.public.PrivateKey.generate()
  1119. server3_onionkey = nacl.public.PrivateKey.generate()
  1120. client_ntor = NTor(perfstats)
  1121. # Client's initial message
  1122. client_pubkey = client_ntor.request()
  1123. # Transform the client pubkey with Sphinx as it passes through the
  1124. # servers and record the resulting shared secrets
  1125. blinded_client_pubkey = client_pubkey
  1126. (s1reply, s1secret), blinded_client_pubkey = NTor.reply(
  1127. server1_onionkey, server1_idkey, blinded_client_pubkey,
  1128. perfstats, b'data')
  1129. (s2reply, s2secret), blinded_client_pubkey = NTor.reply(
  1130. server2_onionkey, server2_idkey, blinded_client_pubkey,
  1131. perfstats, b'data')
  1132. (s3reply, s3secret) = NTor.reply(
  1133. server3_onionkey, server3_idkey, blinded_client_pubkey,
  1134. perfstats)
  1135. # Hopefully matching keys on the client side
  1136. c1secret = client_ntor.verify(s1reply, server1_onionkey.public_key,
  1137. server1_idkey, b'data')
  1138. c2secret = client_ntor.verify(s2reply, server2_onionkey.public_key,
  1139. server2_idkey, b'data')
  1140. c3secret = client_ntor.verify(s3reply, server3_onionkey.public_key,
  1141. server3_idkey)
  1142. assert(s1secret == c1secret)
  1143. assert(s2secret == c2secret)
  1144. assert(s3secret == c3secret)
  1145. print('Sphinx NTor test successful')
  1146. # End test of Sphinx (NTor version)