relay.py 58 KB

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