relay.py 33 KB

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