relay.py 58 KB

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