relay.py 60 KB

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