relay.py 56 KB

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