relay.py 59 KB

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