relay.py 28 KB

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