relay.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 Channel(network.Connection):
  36. """A class representing a channel between a relay and either a
  37. client or a relay, transporting cells from various circuits."""
  38. def __init__(self):
  39. super().__init__()
  40. # The CellRelay managing this Channel
  41. self.cellrelay = None
  42. # The Channel at the other end
  43. self.peer = None
  44. # The function to call when the connection closes
  45. self.closer = lambda: 0
  46. def closed(self):
  47. self.closer()
  48. self.peer = None
  49. def close(self):
  50. if self.peer is not None and self.peer is not self:
  51. self.peer.closed()
  52. self.closed()
  53. def send_cell(self, circid, cell):
  54. """Send the given message, tagged for the given circuit id."""
  55. msg = CircuitCellMsg(circid, cell)
  56. self.send_msg(msg)
  57. def send_msg(self, msg):
  58. """Send the given NetMsg on the channel."""
  59. self.peer.received(self.cellrelay.myaddr, msg)
  60. def received(self, peeraddr, msg):
  61. """Callback when a message is received from the network."""
  62. if isinstance(msg, CircuitCellMsg):
  63. circid, cell = msg.circid, msg.cell
  64. self.cellrelay.received_cell(circid, cell, peeraddr, self.peer)
  65. else:
  66. self.cellrelay.received_msg(msg, peeraddr, self.peer)
  67. class CellRelay:
  68. """The class that manages the channels to other relays and clients.
  69. Relays and clients both use this class to both create on-demand
  70. channels to relays, to gracefully handle the closing of channels,
  71. and to handle commands received over the channels."""
  72. def __init__(self, myaddr, dirauthaddrs):
  73. # A dictionary of Channels to other hosts, indexed by NetAddr
  74. self.channels = dict()
  75. self.myaddr = myaddr
  76. self.dirauthaddrs = dirauthaddrs
  77. self.consensus = None
  78. def terminate(self):
  79. """Close all connections we're managing."""
  80. while self.channels:
  81. channelitems = iter(self.channels.items())
  82. addr, channel = next(channelitems)
  83. print('closing channel', addr, channel)
  84. channel.close()
  85. def get_consensus(self):
  86. """Download a fresh consensus from a random dirauth."""
  87. a = random.choice(self.dirauthaddrs)
  88. c = network.thenetwork.connect(self, a)
  89. self.consensus = c.getconsensus()
  90. print('consensus downloaded:', self.consensus)
  91. c.close()
  92. def add_channel(self, channel, peeraddr):
  93. """Add the given channel to the list of channels we are
  94. managing. If we are already managing a channel to the same
  95. peer, close it first."""
  96. if peeraddr in self.channels:
  97. self.channels[peeraddr].close()
  98. channel.cellrelay = self
  99. self.channels[peeraddr] = channel
  100. channel.closer = lambda: self.channels.pop(peeraddr)
  101. def get_channel_to(self, addr):
  102. """Get the Channel connected to the given NetAddr, creating one
  103. if none exists right now."""
  104. if addr in self.channels:
  105. return self.channels[addr]
  106. # Create the new connection
  107. newconn = network.thenetwork.connect(self.myaddr, addr)
  108. self.channels[addr] = newconn
  109. newconn.closer = lambda: self.channels.pop(addr)
  110. newconn.cellrelay = self
  111. return newconn
  112. def received_msg(self, msg, peeraddr, peer):
  113. """Callback when a NetMsg not specific to a circuit is
  114. received."""
  115. print("Node %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  116. if isinstance(msg, RelayRandomHopMsg):
  117. if msg.ttl > 0:
  118. # Pick a random next hop from the consensus
  119. nexthop = random.choice(self.consensus.consdict['relays'])
  120. nextaddr = nexthop.descdict['addr']
  121. self.send_msg(RelayRandomHopMsg(msg.ttl-1), nextaddr)
  122. def received_cell(self, circid, cell, peeraddr, peer):
  123. """Callback with a circuit-specific cell is received."""
  124. print("Node %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  125. def send_msg(self, msg, peeraddr):
  126. """Send a message to the peer with the given address."""
  127. conn = self.get_channel_to(peeraddr)
  128. conn.send_msg(msg)
  129. def send_cell(self, circid, cell, peeraddr):
  130. """Send a cell on the given circuit to the peer with the given
  131. address."""
  132. conn = self.get_channel_to(peeraddr)
  133. conn.send_cell(circid, cell)
  134. class Relay(network.Server):
  135. """The class representing an onion relay."""
  136. def __init__(self, dirauthaddrs, bw, flags):
  137. # Create the identity and onion keys
  138. self.idkey = nacl.signing.SigningKey.generate()
  139. self.onionkey = nacl.public.PrivateKey.generate()
  140. self.name = self.idkey.verify_key.encode(encoder=nacl.encoding.HexEncoder).decode("ascii")
  141. # Bind to the network to get a network address
  142. self.netaddr = network.thenetwork.bind(self)
  143. # Our bandwidth and flags
  144. self.bw = bw
  145. self.flags = flags
  146. # Register for epoch change notification
  147. network.thenetwork.wantepochticks(self, True, end=True)
  148. network.thenetwork.wantepochticks(self, True)
  149. # Create the CellRelay connection manager
  150. self.cellrelay = CellRelay(self.netaddr, dirauthaddrs)
  151. # Initially, we're not a fallback relay
  152. self.is_fallbackrelay = False
  153. self.uploaddesc()
  154. def terminate(self):
  155. """Stop this relay."""
  156. if self.is_fallbackrelay:
  157. # Fallback relays must not (for now) terminate
  158. raise RelayFallbackTerminationError(self)
  159. # Stop listening for epoch ticks
  160. network.thenetwork.wantepochticks(self, False, end=True)
  161. network.thenetwork.wantepochticks(self, False)
  162. # Tell the dirauths we're going away
  163. self.uploaddesc(False)
  164. # Close connections to other relays
  165. self.cellrelay.terminate()
  166. # Stop listening to our own bound port
  167. self.close()
  168. def set_is_fallbackrelay(self, isfallback = True):
  169. """Set this relay to be a fallback relay (or unset if passed
  170. False)."""
  171. self.is_fallbackrelay = isfallback
  172. def epoch_ending(self, epoch):
  173. # Download the new consensus, which will have been created
  174. # already since the dirauths' epoch_ending callbacks happened
  175. # before the relays'.
  176. self.cellrelay.get_consensus()
  177. def newepoch(self, epoch):
  178. self.uploaddesc()
  179. def uploaddesc(self, upload=True):
  180. # Upload the descriptor for the epoch to come, or delete a
  181. # previous upload if upload=False
  182. descdict = dict();
  183. descdict["epoch"] = network.thenetwork.getepoch() + 1
  184. descdict["idkey"] = self.idkey.verify_key
  185. descdict["onionkey"] = self.onionkey.public_key
  186. descdict["addr"] = self.netaddr
  187. descdict["bw"] = self.bw
  188. descdict["flags"] = self.flags
  189. desc = dirauth.RelayDescriptor(descdict)
  190. desc.sign(self.idkey)
  191. desc.verify()
  192. if upload:
  193. descmsg = dirauth.DirAuthUploadDescMsg(desc)
  194. else:
  195. # Note that this relies on signatures being deterministic;
  196. # otherwise we'd need to save the descriptor we uploaded
  197. # before so we could tell the airauths to delete the exact
  198. # one
  199. descmsg = dirauth.DirAuthDelDescMsg(desc)
  200. # Upload them
  201. for a in self.cellrelay.dirauthaddrs:
  202. c = network.thenetwork.connect(self, a)
  203. c.sendmsg(descmsg)
  204. c.close()
  205. def connected(self, peer):
  206. """Callback invoked when someone (client or relay) connects to
  207. us. Create a pair of linked Channels and return the peer half
  208. to the peer."""
  209. # Create the linked pair
  210. if peer is self.netaddr:
  211. # A self-loop? We'll allow it.
  212. peerchannel = Channel()
  213. peerchannel.peer = peerchannel
  214. return peerchannel
  215. peerchannel = Channel()
  216. ourchannel = Channel()
  217. peerchannel.peer = ourchannel
  218. ourchannel.peer = peerchannel
  219. # Add our channel to the CellRelay
  220. self.cellrelay.add_channel(ourchannel, peer)
  221. return peerchannel
  222. if __name__ == '__main__':
  223. # Start some dirauths
  224. numdirauths = 9
  225. dirauthaddrs = []
  226. for i in range(numdirauths):
  227. dira = dirauth.DirAuth(i, numdirauths)
  228. dirauthaddrs.append(network.thenetwork.bind(dira))
  229. # Start some relays
  230. numrelays = 10
  231. relays = []
  232. for i in range(numrelays):
  233. # Relay bandwidths (at least the ones fast enough to get used)
  234. # in the live Tor network (as of Dec 2019) are well approximated
  235. # by (200000-(200000-25000)/3*log10(x)) where x is a
  236. # uniform integer in [1,2500]
  237. x = random.randint(1,2500)
  238. bw = int(200000-(200000-25000)/3*math.log10(x))
  239. relays.append(Relay(dirauthaddrs, bw, 0))
  240. # The fallback relays are a hardcoded list of about 5% of the
  241. # relays, used by clients for bootstrapping
  242. numfallbackrelays = int(numrelays * 0.05) + 1
  243. fallbackrelays = random.sample(relays, numfallbackrelays)
  244. for r in fallbackrelays:
  245. r.set_is_fallbackrelay()
  246. network.thenetwork.setfallbackrelays(fallbackrelays)
  247. # Tick the epoch
  248. network.thenetwork.nextepoch()
  249. dirauth.DirAuth.consensus.verify(network.thenetwork.dirauthkeys())
  250. print('ticked; epoch=', network.thenetwork.getepoch())
  251. relays[3].cellrelay.send_msg(RelayRandomHopMsg(30), relays[5].netaddr)
  252. # See what channels exist and do a consistency check
  253. for r in relays:
  254. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellrelay.channels.keys()]))
  255. raddr = r.netaddr
  256. for ad, ch in r.cellrelay.channels.items():
  257. if ch.peer.cellrelay.myaddr != ad:
  258. print('address mismatch:', raddr, ad, ch.peer.cellrelay.myaddr)
  259. if ch.peer.cellrelay.channels[raddr].peer is not ch:
  260. print('asymmetry:', raddr, ad, ch, ch.peer.cellrelay.channels[raddr].peer)
  261. # Stop some relays
  262. relays[3].terminate()
  263. relays.remove(relays[3])
  264. relays[5].terminate()
  265. relays.remove(relays[5])
  266. relays[7].terminate()
  267. relays.remove(relays[7])
  268. # Tick the epoch
  269. network.thenetwork.nextepoch()
  270. print(dirauth.DirAuth.consensus)
  271. # See what channels exist and do a consistency check
  272. for r in relays:
  273. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellrelay.channels.keys()]))
  274. raddr = r.netaddr
  275. for ad, ch in r.cellrelay.channels.items():
  276. if ch.peer.cellrelay.myaddr != ad:
  277. print('address mismatch:', raddr, ad, ch.peer.cellrelay.myaddr)
  278. if ch.peer.cellrelay.channels[raddr].peer is not ch:
  279. print('asymmetry:', raddr, ad, ch, ch.peer.cellrelay.channels[raddr].peer)
  280. #relays[3].cellrelay.send_cell(1, network.StringNetMsg("test"), relays[3].consensus.consdict['relays'][5].descdict['addr'])
  281. #relays[3].cellrelay.send_cell(2, network.StringNetMsg("cell"), relays[3].consensus.consdict['relays'][6].descdict['addr'])
  282. #relays[3].cellrelay.send_cell(2, network.StringNetMsg("again"), relays[3].consensus.consdict['relays'][1].descdict['addr'])
  283. #relays[3].cellrelay.send_cell(2, network.StringNetMsg("and again"), relays[3].consensus.consdict['relays'][5].descdict['addr'])