relay.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 network
  8. import dirauth
  9. class RelayNetMsg(network.NetMsg):
  10. """The subclass of NetMsg for messages between relays and either
  11. relays or clients."""
  12. class RelayGetConsensusMsg(RelayNetMsg):
  13. """The subclass of RelayNetMsg for fetching the consensus."""
  14. class RelayConsensusMsg(RelayNetMsg):
  15. """The subclass of RelayNetMsg for returning the consensus."""
  16. def __init__(self, consensus):
  17. self.consensus = consensus
  18. class RelayRandomHopMsg(RelayNetMsg):
  19. """A message used for testing, that hops from relay to relay
  20. randomly until its TTL expires."""
  21. def __init__(self, ttl):
  22. self.ttl = ttl
  23. def __str__(self):
  24. return "RandomHop TTL=%d" % self.ttl
  25. class CircuitCellMsg(RelayNetMsg):
  26. """Send a message tagged with a circuit id."""
  27. def __init__(self, circuitid, cell):
  28. self.circid = circuitid
  29. self.cell = cell
  30. def __str__(self):
  31. return "C%d:%s" % (self.circid, self.cell)
  32. class RelayFallbackTerminationError(Exception):
  33. """An exception raised when someone tries to terminate a fallback
  34. relay."""
  35. class CircuitHandler:
  36. """A class for managing sending and receiving encrypted cells on a
  37. particular circuit."""
  38. def __init__(self, channel, circid):
  39. self.channel = channel
  40. self.circid = circid
  41. self.send_cell = self.channel_send_cell
  42. self.received_cell = self.channel_received_cell
  43. def channel_send_cell(self, cell):
  44. """Send a cell on this circuit."""
  45. self.channel.send_msg(CircuitCellMsg(self.circid, cell))
  46. def channel_received_cell(self, cell, peeraddr, peer):
  47. """A cell has been received on this circuit. Forward it to the
  48. channel's received_cell callback."""
  49. self.channel.cellhandler.received_cell(self.circid, cell, peeraddr, peer)
  50. class Channel(network.Connection):
  51. """A class representing a channel between a relay and either a
  52. client or a relay, transporting cells from various circuits."""
  53. def __init__(self):
  54. super().__init__()
  55. # The CellRelay managing this Channel
  56. self.cellhandler = None
  57. # The Channel at the other end
  58. self.peer = None
  59. # The function to call when the connection closes
  60. self.closer = lambda: 0
  61. # The next circuit id to use on this channel. The party that
  62. # opened the channel uses even numbers; the receiving party uses
  63. # odd numbers.
  64. self.next_circid = None
  65. # A map for CircuitHandlers to use for each open circuit on the
  66. # channel
  67. self.circuithandlers = dict()
  68. def closed(self):
  69. self.closer()
  70. self.peer = None
  71. def close(self):
  72. if self.peer is not None and self.peer is not self:
  73. self.peer.closed()
  74. self.closed()
  75. def new_circuit(self):
  76. """Allocate a new circuit on this channel, returning the new
  77. circuit's id."""
  78. circid = self.next_circid
  79. self.next_circid += 2
  80. self.circuithandlers[circid] = CircuitHandler(self, circid)
  81. return circid
  82. def new_circuit_with_circid(self, circid):
  83. """Allocate a new circuit on this channel, with the circuit id
  84. received from our peer."""
  85. self.circuithandlers[circid] = CircuitHandler(self, circid)
  86. def send_cell(self, circid, cell):
  87. """Send the given message on the given circuit, encrypting or
  88. decrypting as needed."""
  89. self.circuithandlers[circid].send_cell(cell)
  90. def send_raw_cell(self, circid, cell):
  91. """Send the given message, tagged for the given circuit id. No
  92. encryption or decryption is done."""
  93. self.send_msg(CircuitCellMsg(self.circid, self.cell))
  94. def send_msg(self, msg):
  95. """Send the given NetMsg on the channel."""
  96. self.peer.received(self.cellhandler.myaddr, msg)
  97. def received(self, peeraddr, msg):
  98. """Callback when a message is received from the network."""
  99. if isinstance(msg, CircuitCellMsg):
  100. circid, cell = msg.circid, msg.cell
  101. self.circuithandlers[circid].received_cell(cell, peeraddr, self.peer)
  102. else:
  103. self.cellhandler.received_msg(msg, peeraddr, self.peer)
  104. class CellHandler:
  105. """The class that manages the channels to other relays and clients.
  106. Relays and clients both use subclasses of this class to both create
  107. on-demand channels to relays, to gracefully handle the closing of
  108. channels, and to handle commands received over the channels."""
  109. def __init__(self, myaddr, dirauthaddrs):
  110. # A dictionary of Channels to other hosts, indexed by NetAddr
  111. self.channels = dict()
  112. self.myaddr = myaddr
  113. self.dirauthaddrs = dirauthaddrs
  114. self.consensus = None
  115. def terminate(self):
  116. """Close all connections we're managing."""
  117. while self.channels:
  118. channelitems = iter(self.channels.items())
  119. addr, channel = next(channelitems)
  120. print('closing channel', addr, channel)
  121. channel.close()
  122. def add_channel(self, channel, peeraddr):
  123. """Add the given channel to the list of channels we are
  124. managing. If we are already managing a channel to the same
  125. peer, close it first."""
  126. if peeraddr in self.channels:
  127. self.channels[peeraddr].close()
  128. channel.cellhandler = self
  129. self.channels[peeraddr] = channel
  130. channel.closer = lambda: self.channels.pop(peeraddr)
  131. def get_channel_to(self, addr):
  132. """Get the Channel connected to the given NetAddr, creating one
  133. if none exists right now."""
  134. if addr in self.channels:
  135. return self.channels[addr]
  136. # Create the new channel
  137. newchannel = network.thenetwork.connect(self.myaddr, addr)
  138. self.channels[addr] = newchannel
  139. newchannel.closer = lambda: self.channels.pop(addr)
  140. newchannel.cellhandler = self
  141. return newchannel
  142. def received_msg(self, msg, peeraddr, peer):
  143. """Callback when a NetMsg not specific to a circuit is
  144. received."""
  145. print("CellHandler: Node %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  146. def received_cell(self, circid, cell, peeraddr, peer):
  147. """Callback with a circuit-specific cell is received."""
  148. print("CellHandler: Node %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  149. def send_msg(self, msg, peeraddr):
  150. """Send a message to the peer with the given address."""
  151. channel = self.get_channel_to(peeraddr)
  152. channel.send_msg(msg)
  153. def send_cell(self, circid, cell, peeraddr):
  154. """Send a cell on the given circuit to the peer with the given
  155. address."""
  156. channel = self.get_channel_to(peeraddr)
  157. channel.send_cell(circid, cell)
  158. class CellRelay(CellHandler):
  159. """The subclass of CellHandler for relays."""
  160. def __init__(self, myaddr, dirauthaddrs):
  161. super().__init__(myaddr, dirauthaddrs)
  162. def get_consensus(self):
  163. """Download a fresh consensus from a random dirauth."""
  164. a = random.choice(self.dirauthaddrs)
  165. c = network.thenetwork.connect(self, a)
  166. self.consensus = c.getconsensus()
  167. dirauth.Consensus.verify(self.consensus, network.thenetwork.dirauthkeys())
  168. c.close()
  169. def received_msg(self, msg, peeraddr, peer):
  170. """Callback when a NetMsg not specific to a circuit is
  171. received."""
  172. print("CellRelay: Node %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  173. if isinstance(msg, RelayRandomHopMsg):
  174. if msg.ttl > 0:
  175. # Pick a random next hop from the consensus
  176. nexthop = random.choice(self.consensus.consdict['relays'])
  177. nextaddr = nexthop.descdict['addr']
  178. self.send_msg(RelayRandomHopMsg(msg.ttl-1), nextaddr)
  179. elif isinstance(msg, RelayGetConsensusMsg):
  180. self.send_msg(RelayConsensusMsg(self.consensus), peeraddr)
  181. else:
  182. return super().received_msg(msg, peeraddr, peer)
  183. def received_cell(self, circid, cell, peeraddr, peer):
  184. """Callback with a circuit-specific cell is received."""
  185. print("CellRelay: Node %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  186. return super().received_cell(circid, cell, peeraddr, peer)
  187. class Relay(network.Server):
  188. """The class representing an onion relay."""
  189. def __init__(self, dirauthaddrs, bw, flags):
  190. # Create the identity and onion keys
  191. self.idkey = nacl.signing.SigningKey.generate()
  192. self.onionkey = nacl.public.PrivateKey.generate()
  193. self.name = self.idkey.verify_key.encode(encoder=nacl.encoding.HexEncoder).decode("ascii")
  194. # Bind to the network to get a network address
  195. self.netaddr = network.thenetwork.bind(self)
  196. # Our bandwidth and flags
  197. self.bw = bw
  198. self.flags = flags
  199. # Register for epoch change notification
  200. network.thenetwork.wantepochticks(self, True, end=True)
  201. network.thenetwork.wantepochticks(self, True)
  202. # Create the CellRelay connection manager
  203. self.cellhandler = CellRelay(self.netaddr, dirauthaddrs)
  204. # Initially, we're not a fallback relay
  205. self.is_fallbackrelay = False
  206. self.uploaddesc()
  207. def terminate(self):
  208. """Stop this relay."""
  209. if self.is_fallbackrelay:
  210. # Fallback relays must not (for now) terminate
  211. raise RelayFallbackTerminationError(self)
  212. # Stop listening for epoch ticks
  213. network.thenetwork.wantepochticks(self, False, end=True)
  214. network.thenetwork.wantepochticks(self, False)
  215. # Tell the dirauths we're going away
  216. self.uploaddesc(False)
  217. # Close connections to other relays
  218. self.cellhandler.terminate()
  219. # Stop listening to our own bound port
  220. self.close()
  221. def set_is_fallbackrelay(self, isfallback = True):
  222. """Set this relay to be a fallback relay (or unset if passed
  223. False)."""
  224. self.is_fallbackrelay = isfallback
  225. def epoch_ending(self, epoch):
  226. # Download the new consensus, which will have been created
  227. # already since the dirauths' epoch_ending callbacks happened
  228. # before the relays'.
  229. self.cellhandler.get_consensus()
  230. def newepoch(self, epoch):
  231. self.uploaddesc()
  232. def uploaddesc(self, upload=True):
  233. # Upload the descriptor for the epoch to come, or delete a
  234. # previous upload if upload=False
  235. descdict = dict();
  236. descdict["epoch"] = network.thenetwork.getepoch() + 1
  237. descdict["idkey"] = self.idkey.verify_key
  238. descdict["onionkey"] = self.onionkey.public_key
  239. descdict["addr"] = self.netaddr
  240. descdict["bw"] = self.bw
  241. descdict["flags"] = self.flags
  242. desc = dirauth.RelayDescriptor(descdict)
  243. desc.sign(self.idkey)
  244. dirauth.RelayDescriptor.verify(desc)
  245. if upload:
  246. descmsg = dirauth.DirAuthUploadDescMsg(desc)
  247. else:
  248. # Note that this relies on signatures being deterministic;
  249. # otherwise we'd need to save the descriptor we uploaded
  250. # before so we could tell the airauths to delete the exact
  251. # one
  252. descmsg = dirauth.DirAuthDelDescMsg(desc)
  253. # Upload them
  254. for a in self.cellhandler.dirauthaddrs:
  255. c = network.thenetwork.connect(self, a)
  256. c.sendmsg(descmsg)
  257. c.close()
  258. def connected(self, peer):
  259. """Callback invoked when someone (client or relay) connects to
  260. us. Create a pair of linked Channels and return the peer half
  261. to the peer."""
  262. # Create the linked pair
  263. if peer is self.netaddr:
  264. # A self-loop? We'll allow it.
  265. peerchannel = Channel()
  266. peerchannel.peer = peerchannel
  267. peerchannel.next_circid = 2
  268. return peerchannel
  269. peerchannel = Channel()
  270. ourchannel = Channel()
  271. peerchannel.peer = ourchannel
  272. peerchannel.next_circid = 2
  273. ourchannel.peer = peerchannel
  274. ourchannel.next_circid = 1
  275. # Add our channel to the CellRelay
  276. self.cellhandler.add_channel(ourchannel, peer)
  277. return peerchannel
  278. if __name__ == '__main__':
  279. # Start some dirauths
  280. numdirauths = 9
  281. dirauthaddrs = []
  282. for i in range(numdirauths):
  283. dira = dirauth.DirAuth(i, numdirauths)
  284. dirauthaddrs.append(network.thenetwork.bind(dira))
  285. # Start some relays
  286. numrelays = 10
  287. relays = []
  288. for i in range(numrelays):
  289. # Relay bandwidths (at least the ones fast enough to get used)
  290. # in the live Tor network (as of Dec 2019) are well approximated
  291. # by (200000-(200000-25000)/3*log10(x)) where x is a
  292. # uniform integer in [1,2500]
  293. x = random.randint(1,2500)
  294. bw = int(200000-(200000-25000)/3*math.log10(x))
  295. relays.append(Relay(dirauthaddrs, bw, 0))
  296. # The fallback relays are a hardcoded list of about 5% of the
  297. # relays, used by clients for bootstrapping
  298. numfallbackrelays = int(numrelays * 0.05) + 1
  299. fallbackrelays = random.sample(relays, numfallbackrelays)
  300. for r in fallbackrelays:
  301. r.set_is_fallbackrelay()
  302. network.thenetwork.setfallbackrelays(fallbackrelays)
  303. # Tick the epoch
  304. network.thenetwork.nextepoch()
  305. dirauth.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys())
  306. print('ticked; epoch=', network.thenetwork.getepoch())
  307. relays[3].cellhandler.send_msg(RelayRandomHopMsg(30), relays[5].netaddr)
  308. # See what channels exist and do a consistency check
  309. for r in relays:
  310. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()]))
  311. raddr = r.netaddr
  312. for ad, ch in r.cellhandler.channels.items():
  313. if ch.peer.cellhandler.myaddr != ad:
  314. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  315. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  316. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  317. # Stop some relays
  318. relays[3].terminate()
  319. del relays[3]
  320. relays[5].terminate()
  321. del relays[5]
  322. relays[7].terminate()
  323. del relays[7]
  324. # Tick the epoch
  325. network.thenetwork.nextepoch()
  326. print(dirauth.DirAuth.consensus)
  327. # See what channels exist and do a consistency check
  328. for r in relays:
  329. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()]))
  330. raddr = r.netaddr
  331. for ad, ch in r.cellhandler.channels.items():
  332. if ch.peer.cellhandler.myaddr != ad:
  333. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  334. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  335. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  336. channel = relays[3].cellhandler.get_channel_to(relays[5].netaddr)
  337. circid = channel.new_circuit()
  338. peerchannel = relays[5].cellhandler.get_channel_to(relays[3].netaddr)
  339. peerchannel.new_circuit_with_circid(circid)
  340. relays[3].cellhandler.send_cell(circid, network.StringNetMsg("test"), relays[5].netaddr)