relay.py 31 KB

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