relay.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import math
  4. import sys
  5. import nacl.utils
  6. import nacl.signing
  7. import nacl.public
  8. import nacl.hash
  9. import network
  10. import dirauth
  11. class RelayNetMsg(network.NetMsg):
  12. """The subclass of NetMsg for messages between relays and either
  13. relays or clients."""
  14. class RelayGetConsensusMsg(RelayNetMsg):
  15. """The subclass of RelayNetMsg for fetching the consensus. Sent by
  16. clients to relays."""
  17. class RelayConsensusMsg(RelayNetMsg):
  18. """The subclass of RelayNetMsg for returning the consensus from
  19. relays to clients, in response to RelayGetConsensusMsg."""
  20. def __init__(self, consensus):
  21. self.consensus = consensus
  22. class RelayGetConsensusDiffMsg(RelayNetMsg):
  23. """The subclass of RelayNetMsg for fetching the consensus, if the
  24. requestor already has the previous consensus. Sent by clients to
  25. relays."""
  26. class RelayConsensusDiffMsg(RelayNetMsg):
  27. """The subclass of RelayNetMsg for returning the consensus, if the
  28. requestor already has the previous consensus. We don't _actually_
  29. produce the diff at this time; we just charge fewer bytes for this
  30. message. Sent by relays to clients in response to
  31. RelayGetConsensusDiffMsg."""
  32. def __init__(self, consensus):
  33. self.consensus = consensus
  34. def size(self):
  35. if network.symbolic_byte_counters:
  36. return super().size()
  37. return math.ceil(RelayConsensusMsg(self.consensus).size() \
  38. * network.P_Delta)
  39. class RelayRandomHopMsg(RelayNetMsg):
  40. """A message used for testing, that hops from relay to relay
  41. randomly until its TTL expires."""
  42. def __init__(self, ttl):
  43. self.ttl = ttl
  44. def __str__(self):
  45. return "RandomHop TTL=%d" % self.ttl
  46. class CircuitCellMsg(RelayNetMsg):
  47. """Send a message tagged with a circuit id. This is the container
  48. class for all RelayCell messages."""
  49. def __init__(self, circuitid, cell):
  50. self.circid = circuitid
  51. self.cell = cell
  52. def __str__(self):
  53. return "C%d:%s" % (self.circid, self.cell)
  54. def size(self):
  55. # circuitids are 4 bytes
  56. return 4 + self.cell.size()
  57. class RelayCell(RelayNetMsg):
  58. """All cells (which are sent inside a CircuitCellMsg, and so do not
  59. need their own circuitid) should be a subclass of this class."""
  60. class StringCell(RelayCell):
  61. """Send an arbitrary string as a cell."""
  62. def __init__(self, str):
  63. self.data = str
  64. def __str__(self):
  65. return self.data.__str__()
  66. class CloseCell(RelayCell):
  67. """Close the circuit this cell was sent on. It should be sent
  68. _unencrypted_ (not within an EncryptedCell), and relays that receive
  69. one should forward it along the adjacent circuit, then close both
  70. the circuit it was received on and the adjacent one."""
  71. # It is intentional that VanillaCreateCircuitMsg is a RelayNetMsg and
  72. # not a RelayCell. This is the message that _creates_ the circuit, so
  73. # it can't be sent as a cell _within_ the circuit.
  74. class VanillaCreateCircuitMsg(RelayNetMsg):
  75. """The message for requesting circuit creation in Vanilla Onion
  76. Routing."""
  77. def __init__(self, circid, ntor_request):
  78. self.circid = circid
  79. self.ntor_request = ntor_request
  80. class VanillaCreatedCircuitCell(RelayCell):
  81. """The message for responding to circuit creation in Vanilla Onion
  82. Routing."""
  83. def __init__(self, ntor_reply):
  84. self.ntor_reply = ntor_reply
  85. class VanillaExtendCircuitCell(RelayCell):
  86. """The message for requesting circuit extension in Vanilla Onion
  87. Routing."""
  88. def __init__(self, hopaddr, ntor_request):
  89. self.hopaddr = hopaddr
  90. self.ntor_request = ntor_request
  91. class VanillaExtendedCircuitCell(RelayCell):
  92. """The message for responding to circuit extension in Vanilla Onion
  93. Routing."""
  94. def __init__(self, ntor_reply):
  95. self.ntor_reply = ntor_reply
  96. # It is intentional that TelescopingCreateCircuitMsg is a RelayNetMsg and
  97. # not a RelayCell. This is the message that _creates_ the circuit, so
  98. # it can't be sent as a cell _within_ the circuit.
  99. class TelescopingCreateCircuitMsg(RelayNetMsg):
  100. """The message for requesting circuit creation in Telescoping Onion
  101. Routing."""
  102. def __init__(self, circid, ntor_request):
  103. self.circid = circid
  104. self.ntor_request = ntor_request
  105. class TelescopingCreatedCircuitCell(RelayCell):
  106. """The message for responding to circuit creation in Telescoping Walking
  107. Onions."""
  108. def __init__(self, ntor_reply):
  109. self.ntor_reply = ntor_reply
  110. class TelescopingExtendCircuitCell(RelayCell):
  111. """The message for requesting circuit extension in Telescoping Walking
  112. Onionss."""
  113. def __init__(self, idx, ntor_request):
  114. self.idx = idx
  115. self.ntor_request = ntor_request
  116. class TelescopingExtendedCircuitCell(RelayCell):
  117. """The message for responding to circuit extension in Telescoping Walking
  118. Onions."""
  119. def __init__(self, ntor_reply, snip):
  120. self.ntor_reply = ntor_reply
  121. self.snip = snip
  122. class EncryptedCell(RelayCell):
  123. """Send a message encrypted with a symmetric key. In this
  124. implementation, the encryption is not really done. A hash of the
  125. key is stored with the message so that it can be checked at
  126. decryption time."""
  127. def __init__(self, key, msg):
  128. self.keyhash = nacl.hash.sha256(key)
  129. self.plaintext = msg
  130. def decrypt(self, key):
  131. keyhash = nacl.hash.sha256(key)
  132. if keyhash != self.keyhash:
  133. raise ValueError("EncryptedCell key mismatch")
  134. return self.plaintext
  135. def size(self):
  136. # Current Tor actually has no overhead for encryption
  137. return self.plaintext.size()
  138. class RelayFallbackTerminationError(Exception):
  139. """An exception raised when someone tries to terminate a fallback
  140. relay."""
  141. class NTor:
  142. """A class implementing the ntor one-way authenticated key agreement
  143. scheme. The details are not exactly the same as either the ntor
  144. paper or Tor's implementation, but it will agree on keys and have
  145. the same number of public key operations."""
  146. def __init__(self, perfstats):
  147. self.perfstats = perfstats
  148. def request(self):
  149. """Create the ntor request message: X = g^x."""
  150. self.client_ephem_key = nacl.public.PrivateKey.generate()
  151. self.perfstats.keygens += 1
  152. return self.client_ephem_key.public_key
  153. @staticmethod
  154. def reply(onion_privkey, idpubkey, client_pubkey, perfstats):
  155. """The server calls this static method to produce the ntor reply
  156. message: (Y = g^y, B = g^b, A = H(M, "verify")) and the shared
  157. secret S = H(M, "secret") for M = (X^y,X^b,ID,B,X,Y)."""
  158. server_ephem_key = nacl.public.PrivateKey.generate()
  159. perfstats.keygens += 1
  160. xykey = nacl.public.Box(server_ephem_key, client_pubkey).shared_key()
  161. xbkey = nacl.public.Box(onion_privkey, client_pubkey).shared_key()
  162. perfstats.dhs += 2
  163. M = xykey + xbkey + \
  164. idpubkey.encode(encoder=nacl.encoding.RawEncoder) + \
  165. onion_privkey.public_key.encode(encoder=nacl.encoding.RawEncoder) + \
  166. server_ephem_key.public_key.encode(encoder=nacl.encoding.RawEncoder)
  167. A = nacl.hash.sha256(M + b'verify', encoder=nacl.encoding.RawEncoder)
  168. S = nacl.hash.sha256(M + b'secret', encoder=nacl.encoding.RawEncoder)
  169. return ((server_ephem_key.public_key, onion_privkey.public_key, A), S)
  170. def verify(self, reply, onion_pubkey, idpubkey):
  171. """The client calls this method to verify the ntor reply
  172. message, passing the onion and id public keys for the server
  173. it's expecting to be talking to . Returns the shared secret on
  174. success, or raises ValueError on failure."""
  175. server_ephem_pubkey, server_onion_pubkey, authtag = reply
  176. if onion_pubkey != server_onion_pubkey:
  177. raise ValueError("NTor onion pubkey mismatch")
  178. xykey = nacl.public.Box(self.client_ephem_key, server_ephem_pubkey).shared_key()
  179. xbkey = nacl.public.Box(self.client_ephem_key, onion_pubkey).shared_key()
  180. self.perfstats.dhs += 2
  181. M = xykey + xbkey + \
  182. idpubkey.encode(encoder=nacl.encoding.RawEncoder) + \
  183. onion_pubkey.encode(encoder=nacl.encoding.RawEncoder) + \
  184. server_ephem_pubkey.encode(encoder=nacl.encoding.RawEncoder)
  185. Acheck = nacl.hash.sha256(M + b'verify', encoder=nacl.encoding.RawEncoder)
  186. S = nacl.hash.sha256(M + b'secret', encoder=nacl.encoding.RawEncoder)
  187. if Acheck != authtag:
  188. raise ValueError("NTor auth mismatch")
  189. return S
  190. class VanillaExtendCircuitHandler:
  191. """A handler for VanillaExtendCircuitCell cells. It allocates a new
  192. circuit id on the Channel to the requested next hop, connects the
  193. existing and new circuits together, and forwards a
  194. VanillaCreateCircuitMsg to the next hop."""
  195. def received_cell(self, circhandler, cell):
  196. # Remove ourselves from handling a second
  197. # VanillaExtendCircuitCell on this circuit
  198. circhandler.replace_celltype_handler(VanillaExtendCircuitCell, None)
  199. # Allocate a new circuit id to the requested next hop
  200. channelmgr = circhandler.channel.channelmgr
  201. nexthopchannel = channelmgr.get_channel_to(cell.hopaddr)
  202. newcircid, newcirchandler = nexthopchannel.new_circuit()
  203. # Connect the existing and new circuits together
  204. circhandler.adjacent_circuit_handler = newcirchandler
  205. newcirchandler.adjacent_circuit_handler = circhandler
  206. # Set up a handler for when the VanillaCreatedCircuitCell comes
  207. # back
  208. #TODO shouldn't these be extended?
  209. newcirchandler.replace_celltype_handler(
  210. VanillaCreatedCircuitCell,
  211. VanillaCreatedRelayHandler())
  212. # Forward a VanillaCreateCircuitMsg to the next hop
  213. nexthopchannel.send_msg(
  214. VanillaCreateCircuitMsg(newcircid, cell.ntor_request))
  215. class TelescopingExtendCircuitHandler:
  216. """A handler for TelescopingExtendCircuitCell cells. It allocates a new
  217. circuit id on the Channel to the requested next hop, connects the
  218. existing and new circuits together, and forwards a
  219. TelescopingCreateCircuitMsg to the next hop."""
  220. def __init__(self, relaypicker):
  221. self.relaypicker = relaypicker
  222. def received_cell(self, circhandler, cell):
  223. # Remove ourselves from handling a second
  224. # TelescopingExtendCircuitCell on this circuit
  225. print("Log: Received TelescopingExtendCircuitHandler cell")
  226. circhandler.replace_celltype_handler(TelescopingExtendCircuitCell, None)
  227. # Find the SNIP corresponding to the index sent by the client
  228. next_snip = self.relaypicker.pick_relay_by_uniform_index(cell.idx)
  229. # Allocate a new circuit id to the requested next hop
  230. channelmgr = circhandler.channel.channelmgr
  231. nexthopchannel = channelmgr.get_channel_to(next_snip.snipdict["addr"])
  232. newcircid, newcirchandler = nexthopchannel.new_circuit()
  233. # Connect the existing and new circuits together
  234. circhandler.adjacent_circuit_handler = newcirchandler
  235. newcirchandler.adjacent_circuit_handler = circhandler
  236. # Set up a handler for when the TelescopingCreatedCircuitCell comes
  237. # back
  238. newcirchandler.replace_celltype_handler(
  239. TelescopingCreatedCircuitCell,
  240. TelescopingCreatedRelayHandler(next_snip))
  241. # Forward a TelescopingCreateCircuitMsg to the next hop
  242. nexthopchannel.send_msg(
  243. TelescopingCreateCircuitMsg(newcircid, cell.ntor_request))
  244. class VanillaCreatedRelayHandler:
  245. """Handle a VanillaCreatedCircuitCell received by a _relay_ that
  246. recently received a VanillaExtendCircuitCell from a client, and so
  247. forwarded a VanillaCreateCircuitCell to the next hop."""
  248. def received_cell(self, circhandler, cell):
  249. # Remove ourselves from handling a second
  250. # VanillaCreatedCircuitCell on this circuit
  251. circhandler.replace_celltype_handler(VanillaCreatedCircuitCell, None)
  252. # Just forward a VanillaExtendedCircuitCell back towards the
  253. # client
  254. circhandler.adjacent_circuit_handler.send_cell(
  255. VanillaExtendedCircuitCell(cell.ntor_reply))
  256. class TelescopingCreatedRelayHandler:
  257. """Handle a TelescopingCreatedCircuitCell received by a _relay_ that
  258. recently received a TelescopingExtendCircuitCell from a client, and so
  259. forwarded a TelescopingCreateCircuitCell to the next hop."""
  260. def __init__(self, next_snip):
  261. self.next_snip = next_snip
  262. def received_cell(self, circhandler, cell):
  263. print("LOG: Handle a TelescopingCreatedCircui received by a relay")
  264. # Remove ourselves from handling a second
  265. # VanillaCreatedCircuitCell on this circuit
  266. circhandler.replace_celltype_handler(TelescopingCreatedCircuitCell, None)
  267. # Just forward a TelescopingExtendedCircuitCell back towards the
  268. # client
  269. circhandler.adjacent_circuit_handler.send_cell(
  270. TelescopingExtendedCircuitCell(cell.ntor_reply, self.next_snip))
  271. class CircuitHandler:
  272. """A class for managing sending and receiving encrypted cells on a
  273. particular circuit."""
  274. class NoCryptLayer:
  275. def encrypt_msg(self, msg): return msg
  276. def decrypt_msg(self, msg): return msg
  277. class CryptLayer:
  278. def __init__(self, enckey, deckey, next_layer):
  279. self.enckey = enckey
  280. self.deckey = deckey
  281. self.next_layer = next_layer
  282. def encrypt_msg(self, msg):
  283. return self.next_layer.encrypt_msg(EncryptedCell(self.enckey, msg))
  284. def decrypt_msg(self, msg):
  285. return self.next_layer.decrypt_msg(msg).decrypt(self.deckey)
  286. def __init__(self, channel, circid):
  287. self.channel = channel
  288. self.circid = circid
  289. # The list of relay descriptors that form the circuit so far
  290. # (client side only)
  291. self.circuit_descs = []
  292. # The dispatch table is indexed by type, and the values are
  293. # objects with received_cell(circhandler, cell) methods.
  294. self.cell_dispatch_table = dict()
  295. # The topmost crypt layer. This is an object with
  296. # encrypt_msg(msg) and decrypt_msg(msg) methods that returns the
  297. # en/decrypted messages respectively. Messages are encrypted
  298. # starting with the last layer that was added (the keys for the
  299. # furthest away relay in the circuit) and are decrypted starting
  300. # with the first layer that was added (the keys for the guard).
  301. self.crypt_layer = self.NoCryptLayer()
  302. # The adjacent CircuitHandler that's connected to this one. If
  303. # we get a cell on one, we forward it to the other (if it's not
  304. # meant for us to handle directly)
  305. self.adjacent_circuit_handler = None
  306. # The function to call when this circuit closes
  307. self.closer = lambda: self.channel.circuithandlers.pop(circid)
  308. def close(self):
  309. """Close the circuit. Sends a CloseCell on the circuit (and its
  310. adjacent circuit, if present) and closes both."""
  311. adjcirchandler = self.adjacent_circuit_handler
  312. self.adjacent_circuit_handler = None
  313. if adjcirchandler is not None:
  314. adjcirchandler.adjacent_circuit_handler = None
  315. self.closer()
  316. self.channel_send_cell(CloseCell())
  317. if adjcirchandler is not None:
  318. adjcirchandler.closer()
  319. adjcirchandler.channel_send_cell(CloseCell())
  320. def send_cell(self, cell):
  321. """Send a cell on this circuit, encrypting as needed."""
  322. self.channel_send_cell(self.crypt_layer.encrypt_msg(cell))
  323. def channel_send_cell(self, cell):
  324. """Send a cell on this circuit directly without encrypting it
  325. first."""
  326. self.channel.send_msg(CircuitCellMsg(self.circid, cell))
  327. def received_cell(self, cell):
  328. """A cell has been received on this circuit. Dispatch it
  329. according to its type."""
  330. if isinstance(cell, EncryptedCell):
  331. cell = self.crypt_layer.decrypt_msg(cell)
  332. print("CircuitHandler: %s received cell %s on circuit %d from %s" % (self.channel.channelmgr.myaddr, cell, self.circid, self.channel.peer.channelmgr.myaddr))
  333. # If it's still encrypted, it's for sure meant for forwarding to
  334. # our adjacent hop, which had better exist.
  335. if isinstance(cell, EncryptedCell):
  336. self.adjacent_circuit_handler.send_cell(cell)
  337. else:
  338. # This is a plaintext cell meant for us. Handle it
  339. # according to the table.
  340. celltype = type(cell)
  341. if celltype in self.cell_dispatch_table:
  342. self.cell_dispatch_table[celltype].received_cell(self, cell)
  343. elif isinstance(cell, StringCell):
  344. # Default handler; just print the message in the cell
  345. print("CircuitHandler: %s received '%s' on circuit %d from %s" \
  346. % (self.channel.channelmgr.myaddr, cell,
  347. self.circid, self.channel.peer.channelmgr.myaddr))
  348. elif isinstance(cell, CloseCell):
  349. # Forward the CloseCell (without encryption) to the
  350. # adjacent circuit, if any, and close both this and the
  351. # adjacent circuit
  352. adjcirchandler = self.adjacent_circuit_handler
  353. self.adjacent_circuit_handler = None
  354. if adjcirchandler is not None:
  355. adjcirchandler.adjacent_circuit_handler = None
  356. self.closer()
  357. if adjcirchandler is not None:
  358. adjcirchandler.closer()
  359. adjcirchandler.channel_send_cell(cell)
  360. else:
  361. # I don't know how to handle this cell?
  362. raise ValueError("CircuitHandler: %s received unknown cell type %s on circuit %d from %s" \
  363. % (self.channel.channelmgr.myaddr, cell,
  364. self.circid, self.channel.peer.channelmgr.myaddr))
  365. def replace_celltype_handler(self, celltype, handler):
  366. """Add an object with a received_cell(circhandler, cell) method
  367. to the cell dispatch table. It replaces anything that's already
  368. there. Passing None as the handler removes the dispatcher for
  369. that cell type."""
  370. if handler is None:
  371. del self.cell_dispatch_table[celltype]
  372. else:
  373. self.cell_dispatch_table[celltype] = handler
  374. def add_crypt_layer(self, enckey, deckey):
  375. """Add a processing layer to this CircuitHandler so that cells
  376. we send will get encrypted with the first given key, and cells
  377. we receive will be decrypted with the other given key."""
  378. current_crypt_layer = self.crypt_layer
  379. self.crypt_layer = self.CryptLayer(enckey, deckey, current_crypt_layer)
  380. class Channel(network.Connection):
  381. """A class representing a channel between a relay and either a
  382. client or a relay, transporting cells from various circuits."""
  383. def __init__(self):
  384. super().__init__()
  385. # The RelayChannelManager managing this Channel
  386. self.channelmgr = None
  387. # The Channel at the other end
  388. self.peer = None
  389. # The function to call when the connection closes
  390. self.closer = lambda: None
  391. # The next circuit id to use on this channel. The party that
  392. # opened the channel uses even numbers; the receiving party uses
  393. # odd numbers.
  394. self.next_circid = None
  395. # A map for CircuitHandlers to use for each open circuit on the
  396. # channel
  397. self.circuithandlers = dict()
  398. def closed(self):
  399. # Close each circuithandler we're managing
  400. while self.circuithandlers:
  401. chitems = iter(self.circuithandlers.items())
  402. circid, circhandler = next(chitems)
  403. print('closing circuit', circid)
  404. circhandler.close()
  405. self.closer()
  406. self.peer = None
  407. def close(self):
  408. peer = self.peer
  409. self.closed()
  410. if peer is not None and peer is not self:
  411. peer.closed()
  412. def new_circuit(self):
  413. """Allocate a new circuit on this channel, returning the new
  414. circuit's id and the new CircuitHandler."""
  415. circid = self.next_circid
  416. self.next_circid += 2
  417. circuithandler = CircuitHandler(self, circid)
  418. self.circuithandlers[circid] = circuithandler
  419. return circid, circuithandler
  420. def new_circuit_with_circid(self, circid):
  421. """Allocate a new circuit on this channel, with the circuit id
  422. received from our peer. Return the new CircuitHandler"""
  423. circuithandler = CircuitHandler(self, circid)
  424. self.circuithandlers[circid] = circuithandler
  425. return circuithandler
  426. def send_cell(self, circid, cell):
  427. """Send the given message on the given circuit, encrypting or
  428. decrypting as needed."""
  429. self.circuithandlers[circid].send_cell(cell)
  430. def send_raw_cell(self, circid, cell):
  431. """Send the given message, tagged for the given circuit id. No
  432. encryption or decryption is done."""
  433. self.send_msg(CircuitCellMsg(self.circid, self.cell))
  434. def send_msg(self, msg):
  435. """Send the given NetMsg on the channel."""
  436. self.channelmgr.perfstats.bytes_sent += msg.size()
  437. self.peer.received(self.channelmgr.myaddr, msg)
  438. def received(self, peeraddr, msg):
  439. """Callback when a message is received from the network."""
  440. print('Channel: %s received %s from %s' % (self.channelmgr.myaddr, msg, peeraddr))
  441. self.channelmgr.perfstats.bytes_received += msg.size()
  442. if isinstance(msg, CircuitCellMsg):
  443. circid, cell = msg.circid, msg.cell
  444. self.circuithandlers[circid].received_cell(cell)
  445. else:
  446. self.channelmgr.received_msg(msg, peeraddr, self)
  447. class ChannelManager:
  448. """The class that manages the channels to other relays and clients.
  449. Relays and clients both use subclasses of this class to both create
  450. on-demand channels to relays, to gracefully handle the closing of
  451. channels, and to handle commands received over the channels."""
  452. def __init__(self, myaddr, dirauthaddrs, perfstats):
  453. # A dictionary of Channels to other hosts, indexed by NetAddr
  454. self.channels = dict()
  455. self.myaddr = myaddr
  456. self.dirauthaddrs = dirauthaddrs
  457. self.consensus = None
  458. self.relaypicker = None
  459. self.perfstats = perfstats
  460. def terminate(self):
  461. """Close all connections we're managing."""
  462. while self.channels:
  463. channelitems = iter(self.channels.items())
  464. addr, channel = next(channelitems)
  465. print('closing channel', addr, channel)
  466. channel.close()
  467. def add_channel(self, channel, peeraddr):
  468. """Add the given channel to the list of channels we are
  469. managing. If we are already managing a channel to the same
  470. peer, close it first."""
  471. if peeraddr in self.channels:
  472. self.channels[peeraddr].close()
  473. channel.channelmgr = self
  474. self.channels[peeraddr] = channel
  475. channel.closer = lambda: self.channels.pop(peeraddr)
  476. def get_channel_to(self, addr):
  477. """Get the Channel connected to the given NetAddr, creating one
  478. if none exists right now."""
  479. if addr in self.channels:
  480. return self.channels[addr]
  481. # Create the new channel
  482. print('getting channel from',self.myaddr,'to',addr)
  483. newchannel = network.thenetwork.connect(self.myaddr, addr,
  484. self.perfstats)
  485. print('got channel from',self.myaddr,'to',addr)
  486. self.channels[addr] = newchannel
  487. newchannel.closer = lambda: self.channels.pop(addr)
  488. newchannel.channelmgr = self
  489. return newchannel
  490. def received_msg(self, msg, peeraddr, channel):
  491. """Callback when a NetMsg not specific to a circuit is
  492. received."""
  493. print("ChannelManager: Node %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  494. def received_cell(self, circid, cell, peeraddr, channel):
  495. """Callback with a circuit-specific cell is received."""
  496. print("ChannelManager: Node %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  497. def send_msg(self, msg, peeraddr):
  498. """Send a message to the peer with the given address."""
  499. channel = self.get_channel_to(peeraddr)
  500. channel.send_msg(msg)
  501. def send_cell(self, circid, cell, peeraddr):
  502. """Send a cell on the given circuit to the peer with the given
  503. address."""
  504. channel = self.get_channel_to(peeraddr)
  505. channel.send_cell(circid, cell)
  506. class RelayChannelManager(ChannelManager):
  507. """The subclass of ChannelManager for relays."""
  508. def __init__(self, myaddr, dirauthaddrs, onionprivkey, idpubkey, perfstats):
  509. super().__init__(myaddr, dirauthaddrs, perfstats)
  510. self.onionkey = onionprivkey
  511. self.idpubkey = idpubkey
  512. if network.thenetwork.womode != network.WOMode.VANILLA:
  513. self.endive = None
  514. def get_consensus(self):
  515. """Download a fresh consensus (and ENDIVE if using Walking
  516. Onions) from a random dirauth."""
  517. a = random.choice(self.dirauthaddrs)
  518. c = network.thenetwork.connect(self, a, self.perfstats)
  519. if network.thenetwork.womode == network.WOMode.VANILLA:
  520. if self.consensus is not None and \
  521. len(self.consensus.consdict['relays']) > 0:
  522. self.consensus = c.getconsensusdiff()
  523. else:
  524. self.consensus = c.getconsensus()
  525. self.relaypicker = dirauth.Consensus.verify(self.consensus,
  526. network.thenetwork.dirauthkeys(), self.perfstats)
  527. else:
  528. self.consensus = c.getconsensus()
  529. if self.endive is not None and \
  530. len(self.endive.enddict['snips']) > 0:
  531. self.endive = c.getendivediff()
  532. else:
  533. self.endive = c.getendive()
  534. self.relaypicker = dirauth.ENDIVE.verify(self.endive,
  535. self.consensus, network.thenetwork.dirauthkeys(),
  536. self.perfstats)
  537. c.close()
  538. def received_msg(self, msg, peeraddr, channel):
  539. """Callback when a NetMsg not specific to a circuit is
  540. received."""
  541. print("RelayChannelManager: Node %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  542. if isinstance(msg, RelayRandomHopMsg):
  543. if msg.ttl > 0:
  544. # Pick a random next hop from the consensus
  545. nexthop = self.relaypicker.pick_weighted_relay()
  546. if network.thenetwork.womode == network.WOMode.VANILLA:
  547. nextaddr = nexthop.descdict["addr"]
  548. else:
  549. nextaddr = nexthop.snipdict["addr"]
  550. self.send_msg(RelayRandomHopMsg(msg.ttl-1), nextaddr)
  551. elif isinstance(msg, RelayGetConsensusMsg):
  552. self.send_msg(RelayConsensusMsg(self.consensus), peeraddr)
  553. elif isinstance(msg, RelayGetConsensusDiffMsg):
  554. self.send_msg(RelayConsensusDiffMsg(self.consensus), peeraddr)
  555. elif isinstance(msg, VanillaCreateCircuitMsg):
  556. # A new circuit has arrived
  557. circhandler = channel.new_circuit_with_circid(msg.circid)
  558. # Create the ntor reply
  559. reply, secret = NTor.reply(self.onionkey, self.idpubkey,
  560. msg.ntor_request, self.perfstats)
  561. # Set up the circuit to use the shared secret
  562. enckey = nacl.hash.sha256(secret + b'downstream')
  563. deckey = nacl.hash.sha256(secret + b'upstream')
  564. circhandler.add_crypt_layer(enckey, deckey)
  565. # Add a handler for if an Extend Cell arrives (there should
  566. # be at most one on this circuit).
  567. circhandler.replace_celltype_handler(
  568. VanillaExtendCircuitCell, VanillaExtendCircuitHandler())
  569. # Send the ntor reply
  570. self.send_msg(CircuitCellMsg(msg.circid,
  571. VanillaCreatedCircuitCell(reply)), peeraddr)
  572. elif isinstance(msg, TelescopingCreateCircuitMsg):
  573. print("LOG: Received TelescopingCreateCircuitMsg circuit message, handling.")
  574. # A new circuit has arrived
  575. circhandler = channel.new_circuit_with_circid(msg.circid)
  576. # Create the ntor reply
  577. reply, secret = NTor.reply(self.onionkey, self.idpubkey,
  578. msg.ntor_request, self.perfstats)
  579. # Set up the circuit to use the shared secret
  580. enckey = nacl.hash.sha256(secret + b'downstream')
  581. deckey = nacl.hash.sha256(secret + b'upstream')
  582. circhandler.add_crypt_layer(enckey, deckey)
  583. # Add a handler for if an Extend Cell arrives (there should
  584. # be at most one on this circuit).
  585. circhandler.replace_celltype_handler(
  586. TelescopingExtendCircuitCell,
  587. TelescopingExtendCircuitHandler(self.relaypicker))
  588. print("LOG: Sending TelescopingCreatedCircuitMsg circuit message")
  589. # Send the ntor reply
  590. self.send_msg(CircuitCellMsg(msg.circid,
  591. TelescopingCreatedCircuitCell(reply)), peeraddr)
  592. else:
  593. return super().received_msg(msg, peeraddr, channel)
  594. def received_cell(self, circid, cell, peeraddr, channel):
  595. """Callback with a circuit-specific cell is received."""
  596. print("RelayChannelManager: Node %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  597. return super().received_cell(circid, cell, peeraddr, channel)
  598. class Relay(network.Server):
  599. """The class representing an onion relay."""
  600. def __init__(self, dirauthaddrs, bw, flags):
  601. # Gather performance statistics
  602. self.perfstats = network.PerfStats(network.EntType.RELAY)
  603. self.perfstats.is_bootstrapping = True
  604. # Create the identity and onion keys
  605. self.idkey = nacl.signing.SigningKey.generate()
  606. self.onionkey = nacl.public.PrivateKey.generate()
  607. self.perfstats.keygens += 2
  608. self.name = self.idkey.verify_key.encode(encoder=nacl.encoding.HexEncoder).decode("ascii")
  609. # Bind to the network to get a network address
  610. self.netaddr = network.thenetwork.bind(self)
  611. self.perfstats.name = "Relay at %s" % self.netaddr
  612. # Our bandwidth and flags
  613. self.bw = bw
  614. self.flags = flags
  615. # Register for epoch change notification
  616. network.thenetwork.wantepochticks(self, True, end=True)
  617. network.thenetwork.wantepochticks(self, True)
  618. # Create the RelayChannelManager connection manager
  619. self.channelmgr = RelayChannelManager(self.netaddr, dirauthaddrs,
  620. self.onionkey, self.idkey.verify_key, self.perfstats)
  621. # Initially, we're not a fallback relay
  622. self.is_fallbackrelay = False
  623. self.uploaddesc()
  624. def terminate(self):
  625. """Stop this relay."""
  626. if self.is_fallbackrelay:
  627. # Fallback relays must not (for now) terminate
  628. raise RelayFallbackTerminationError(self)
  629. # Stop listening for epoch ticks
  630. network.thenetwork.wantepochticks(self, False, end=True)
  631. network.thenetwork.wantepochticks(self, False)
  632. # Tell the dirauths we're going away
  633. self.uploaddesc(False)
  634. # Close connections to other relays
  635. self.channelmgr.terminate()
  636. # Stop listening to our own bound port
  637. self.close()
  638. def set_is_fallbackrelay(self, isfallback = True):
  639. """Set this relay to be a fallback relay (or unset if passed
  640. False)."""
  641. self.is_fallbackrelay = isfallback
  642. def epoch_ending(self, epoch):
  643. # Download the new consensus, which will have been created
  644. # already since the dirauths' epoch_ending callbacks happened
  645. # before the relays'.
  646. self.channelmgr.get_consensus()
  647. def newepoch(self, epoch):
  648. self.uploaddesc()
  649. def uploaddesc(self, upload=True):
  650. # Upload the descriptor for the epoch to come, or delete a
  651. # previous upload if upload=False
  652. descdict = dict();
  653. descdict["epoch"] = network.thenetwork.getepoch() + 1
  654. descdict["idkey"] = self.idkey.verify_key
  655. descdict["onionkey"] = self.onionkey.public_key
  656. descdict["addr"] = self.netaddr
  657. descdict["bw"] = self.bw
  658. descdict["flags"] = self.flags
  659. desc = dirauth.RelayDescriptor(descdict)
  660. desc.sign(self.idkey, self.perfstats)
  661. dirauth.RelayDescriptor.verify(desc, self.perfstats)
  662. if upload:
  663. descmsg = dirauth.DirAuthUploadDescMsg(desc)
  664. else:
  665. # Note that this relies on signatures being deterministic;
  666. # otherwise we'd need to save the descriptor we uploaded
  667. # before so we could tell the airauths to delete the exact
  668. # one
  669. descmsg = dirauth.DirAuthDelDescMsg(desc)
  670. # Upload them
  671. for a in self.channelmgr.dirauthaddrs:
  672. c = network.thenetwork.connect(self, a, self.perfstats)
  673. c.sendmsg(descmsg)
  674. c.close()
  675. def connected(self, peer):
  676. """Callback invoked when someone (client or relay) connects to
  677. us. Create a pair of linked Channels and return the peer half
  678. to the peer."""
  679. # Create the linked pair
  680. if peer is self.netaddr:
  681. # A self-loop? We'll allow it.
  682. peerchannel = Channel()
  683. peerchannel.peer = peerchannel
  684. peerchannel.next_circid = 2
  685. return peerchannel
  686. peerchannel = Channel()
  687. ourchannel = Channel()
  688. peerchannel.peer = ourchannel
  689. peerchannel.next_circid = 2
  690. ourchannel.peer = peerchannel
  691. ourchannel.next_circid = 1
  692. # Add our channel to the RelayChannelManager
  693. self.channelmgr.add_channel(ourchannel, peer)
  694. return peerchannel
  695. if __name__ == '__main__':
  696. perfstats = network.PerfStats(network.EntType.NONE)
  697. network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
  698. network.SNIPAuthMode.THRESHSIG)
  699. # Start some dirauths
  700. numdirauths = 9
  701. dirauthaddrs = []
  702. for i in range(numdirauths):
  703. dira = dirauth.DirAuth(i, numdirauths)
  704. dirauthaddrs.append(dira.netaddr)
  705. # Start some relays
  706. numrelays = 10
  707. relays = []
  708. for i in range(numrelays):
  709. # Relay bandwidths (at least the ones fast enough to get used)
  710. # in the live Tor network (as of Dec 2019) are well approximated
  711. # by (200000-(200000-25000)/3*log10(x)) where x is a
  712. # uniform integer in [1,2500]
  713. x = random.randint(1,2500)
  714. bw = int(200000-(200000-25000)/3*math.log10(x))
  715. relays.append(Relay(dirauthaddrs, bw, 0))
  716. # The fallback relays are a hardcoded list of about 5% of the
  717. # relays, used by clients for bootstrapping
  718. numfallbackrelays = int(numrelays * 0.05) + 1
  719. fallbackrelays = random.sample(relays, numfallbackrelays)
  720. for r in fallbackrelays:
  721. r.set_is_fallbackrelay()
  722. network.thenetwork.setfallbackrelays(fallbackrelays)
  723. # Tick the epoch
  724. network.thenetwork.nextepoch()
  725. print(dirauth.DirAuth.consensus)
  726. print(dirauth.DirAuth.endive)
  727. if network.thenetwork.womode == network.WOMode.VANILLA:
  728. relaypicker = dirauth.Consensus.verify(dirauth.DirAuth.consensus,
  729. network.thenetwork.dirauthkeys(), perfstats)
  730. else:
  731. relaypicker = dirauth.ENDIVE.verify(dirauth.DirAuth.endive,
  732. dirauth.DirAuth.consensus,
  733. network.thenetwork.dirauthkeys(), perfstats)
  734. for s in dirauth.DirAuth.endive.enddict['snips']:
  735. dirauth.SNIP.verify(s, dirauth.DirAuth.consensus,
  736. network.thenetwork.dirauthkeys()[0], perfstats)
  737. print('ticked; epoch=', network.thenetwork.getepoch())
  738. relays[3].channelmgr.send_msg(RelayRandomHopMsg(30), relays[5].netaddr)
  739. # See what channels exist and do a consistency check
  740. for r in relays:
  741. print("%s: %s" % (r.netaddr, [ str(k) for k in r.channelmgr.channels.keys()]))
  742. raddr = r.netaddr
  743. for ad, ch in r.channelmgr.channels.items():
  744. if ch.peer.channelmgr.myaddr != ad:
  745. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  746. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  747. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  748. # Stop some relays
  749. relays[3].terminate()
  750. del relays[3]
  751. relays[5].terminate()
  752. del relays[5]
  753. relays[7].terminate()
  754. del relays[7]
  755. # Tick the epoch
  756. network.thenetwork.nextepoch()
  757. print(dirauth.DirAuth.consensus)
  758. print(dirauth.DirAuth.endive)
  759. # See what channels exist and do a consistency check
  760. for r in relays:
  761. print("%s: %s" % (r.netaddr, [ str(k) for k in r.channelmgr.channels.keys()]))
  762. raddr = r.netaddr
  763. for ad, ch in r.channelmgr.channels.items():
  764. if ch.peer.channelmgr.myaddr != ad:
  765. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  766. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  767. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  768. channel = relays[3].channelmgr.get_channel_to(relays[5].netaddr)
  769. circid, circhandler = channel.new_circuit()
  770. peerchannel = relays[5].channelmgr.get_channel_to(relays[3].netaddr)
  771. peerchannel.new_circuit_with_circid(circid)
  772. relays[3].channelmgr.send_cell(circid, StringCell("test"), relays[5].netaddr)
  773. idpubkey = relays[1].idkey.verify_key
  774. onionpubkey = relays[1].onionkey.public_key
  775. nt = NTor(perfstats)
  776. req = nt.request()
  777. R, S = NTor.reply(relays[1].onionkey, idpubkey, req, perfstats)
  778. S2 = nt.verify(R, onionpubkey, idpubkey)
  779. print(S == S2)