relay.py 36 KB

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