dirauth.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import bisect
  4. import nacl.encoding
  5. import nacl.signing
  6. import network
  7. # A relay descriptor is a dict containing:
  8. # epoch: epoch id
  9. # idkey: a public identity key
  10. # onionkey: a public onion key
  11. # addr: a network address
  12. # bw: bandwidth
  13. # flags: relay flags
  14. # vrfkey: a VRF public key (Single-Pass Walking Onions only)
  15. # sig: a signature over the above by the idkey
  16. class RelayDescriptor:
  17. def __init__(self, descdict):
  18. self.descdict = descdict
  19. def __str__(self, withsig = True):
  20. res = "RelayDesc [\n"
  21. for k in ["epoch", "idkey", "onionkey", "addr", "bw", "flags",
  22. "vrfkey", "sig"]:
  23. if k in self.descdict:
  24. if k == "idkey" or k == "onionkey":
  25. res += " " + k + ": " + self.descdict[k].encode(encoder=nacl.encoding.HexEncoder).decode("ascii") + "\n"
  26. elif k == "sig":
  27. if withsig:
  28. res += " " + k + ": " + nacl.encoding.HexEncoder.encode(self.descdict[k]).decode("ascii") + "\n"
  29. else:
  30. res += " " + k + ": " + str(self.descdict[k]) + "\n"
  31. res += "]\n"
  32. return res
  33. def sign(self, signingkey, perfstats):
  34. serialized = self.__str__(False)
  35. signed = signingkey.sign(serialized.encode("ascii"))
  36. perfstats.sigs += 1
  37. self.descdict["sig"] = signed.signature
  38. @staticmethod
  39. def verify(desc, perfstats):
  40. assert(type(desc) is RelayDescriptor)
  41. serialized = desc.__str__(False)
  42. perfstats.verifs += 1
  43. desc.descdict["idkey"].verify(serialized.encode("ascii"), desc.descdict["sig"])
  44. # A consensus is a dict containing:
  45. # epoch: epoch id
  46. # numrelays: total number of relays
  47. # totbw: total bandwidth of relays
  48. # relays: list of relay descriptors (Vanilla Onion Routing only)
  49. # sigs: list of signatures from the dirauths
  50. class Consensus:
  51. def __init__(self, epoch, relays):
  52. relays = [ d for d in relays if d.descdict['epoch'] == epoch ]
  53. self.consdict = dict()
  54. self.consdict['epoch'] = epoch
  55. self.consdict['numrelays'] = len(relays)
  56. self.consdict['totbw'] = sum([ d.descdict['bw'] for d in relays ])
  57. self.consdict['relays'] = relays
  58. def __str__(self, withsigs = True):
  59. res = "Consensus [\n"
  60. for k in ["epoch", "numrelays", "totbw"]:
  61. if k in self.consdict:
  62. res += " " + k + ": " + str(self.consdict[k]) + "\n"
  63. for r in self.consdict['relays']:
  64. res += str(r)
  65. if withsigs and ('sigs' in self.consdict):
  66. for s in self.consdict['sigs']:
  67. res += " sig: " + nacl.encoding.HexEncoder.encode(s).decode("ascii") + "\n"
  68. res += "]\n"
  69. return res
  70. def sign(self, signingkey, index, perfstats):
  71. """Use the given signing key to sign the consensus, storing the
  72. result in the sigs list at the given index."""
  73. serialized = self.__str__(False)
  74. signed = signingkey.sign(serialized.encode("ascii"))
  75. perfstats.sigs += 1
  76. if 'sigs' not in self.consdict:
  77. self.consdict['sigs'] = []
  78. if index >= len(self.consdict['sigs']):
  79. self.consdict['sigs'].extend([None] * (index+1-len(self.consdict['sigs'])))
  80. self.consdict['sigs'][index] = signed.signature
  81. def bw_cdf(self):
  82. """Create the array of cumulative bandwidth values from a consensus.
  83. The array (cdf) will have the same length as the number of relays
  84. in the consensus. cdf[0] = 0, and cdf[i] = cdf[i-1] + relay[i-1].bw."""
  85. cdf = [0]
  86. for r in self.consdict['relays']:
  87. cdf.append(cdf[-1]+r.descdict['bw'])
  88. # Remove the last item, which should be the sum of all the bws
  89. cdf.pop()
  90. print('cdf=', cdf)
  91. return cdf
  92. def select_weighted_relay(self, cdf):
  93. """Use the cdf generated by bw_cdf to select a relay with
  94. probability proportional to its bw weight."""
  95. totbw = self.consdict['totbw']
  96. if totbw < 1:
  97. raise ValueError("No relays to choose from")
  98. val = random.randint(0, totbw-1)
  99. # Find the rightmost entry less than or equal to val
  100. idx = bisect.bisect_right(cdf, val)
  101. return self.consdict['relays'][idx-1]
  102. @staticmethod
  103. def verify(consensus, verifkeylist, perfstats):
  104. """Use the given list of verification keys to check the
  105. signatures on the consensus."""
  106. assert(type(consensus) is Consensus)
  107. serialized = consensus.__str__(False)
  108. for i, vk in enumerate(verifkeylist):
  109. perfstats.verifs += 1
  110. vk.verify(serialized.encode("ascii"), consensus.consdict['sigs'][i])
  111. class DirAuthNetMsg(network.NetMsg):
  112. """The subclass of NetMsg for messages to and from directory
  113. authorities."""
  114. class DirAuthUploadDescMsg(DirAuthNetMsg):
  115. """The subclass of DirAuthNetMsg for uploading a relay
  116. descriptor."""
  117. def __init__(self, desc):
  118. self.desc = desc
  119. class DirAuthDelDescMsg(DirAuthNetMsg):
  120. """The subclass of DirAuthNetMsg for deleting a relay
  121. descriptor."""
  122. def __init__(self, desc):
  123. self.desc = desc
  124. class DirAuthGetConsensusMsg(DirAuthNetMsg):
  125. """The subclass of DirAuthNetMsg for fetching the consensus."""
  126. class DirAuthConsensusMsg(DirAuthNetMsg):
  127. """The subclass of DirAuthNetMsg for returning the consensus."""
  128. def __init__(self, consensus):
  129. self.consensus = consensus
  130. class DirAuthGetENDIVEMsg(DirAuthNetMsg):
  131. """The subclass of DirAuthNetMsg for fetching the ENDIVE."""
  132. class DirAuthENDIVEMsg(DirAuthNetMsg):
  133. """The subclass of DirAuthNetMsg for returning the ENDIVE."""
  134. def __init__(self, endive):
  135. self.endive = endive
  136. class DirAuthConnection(network.ClientConnection):
  137. """The subclass of Connection for connections to directory
  138. authorities."""
  139. def __init__(self, peer):
  140. super().__init__(peer)
  141. def uploaddesc(self, desc):
  142. """Upload our RelayDescriptor to the DirAuth."""
  143. self.sendmsg(DirAuthUploadDescMeg(desc))
  144. def getconsensus(self):
  145. self.consensus = None
  146. self.sendmsg(DirAuthGetConsensusMsg())
  147. return self.consensus
  148. def getENDIVE(self):
  149. self.endive = None
  150. self.sendmsg(DirAuthGetENDIVEMsg())
  151. return self.endive
  152. def receivedfromserver(self, msg):
  153. if isinstance(msg, DirAuthConsensusMsg):
  154. self.consensus = msg.consensus
  155. elif isinstance(msg, DirAuthENDIVEMsg):
  156. self.endive = msg.endive
  157. else:
  158. raise TypeError('Not a server-originating DirAuthNetMsg', msg)
  159. class DirAuth(network.Server):
  160. """The class representing directory authorities."""
  161. # We simulate the act of computing the consensus by keeping a
  162. # class-static dict that's accessible to all of the dirauths
  163. # This dict is indexed by epoch, and the value is itself a dict
  164. # indexed by the stringified descriptor, with value a pair of (the
  165. # number of dirauths that saw that descriptor, the descriptor
  166. # itself).
  167. uploadeddescs = dict()
  168. consensus = None
  169. endive = None
  170. def __init__(self, me, tot):
  171. """Create a new directory authority. me is the index of which
  172. dirauth this one is (starting from 0), and tot is the total
  173. number of dirauths."""
  174. self.me = me
  175. self.tot = tot
  176. self.name = "Dirauth %d of %d" % (me+1, tot)
  177. self.perfstats = network.PerfStats(network.EntType.DIRAUTH)
  178. self.perfstats.is_bootstrapping = True
  179. # Create the dirauth signature keypair
  180. self.sigkey = nacl.signing.SigningKey.generate()
  181. self.perfstats.keygens += 1
  182. self.netaddr = network.thenetwork.bind(self)
  183. self.perfstats.name = "DirAuth at %s" % self.netaddr
  184. network.thenetwork.setdirauthkey(me, self.sigkey.verify_key)
  185. network.thenetwork.wantepochticks(self, True, True)
  186. def connected(self, client):
  187. """Callback invoked when a client connects to us. This callback
  188. creates the DirAuthConnection that will be passed to the
  189. client."""
  190. # We don't actually need to keep per-connection state at
  191. # dirauths, even in long-lived connections, so this is
  192. # particularly simple.
  193. return DirAuthConnection(self)
  194. def generate_consensus(self, epoch):
  195. """Generate the consensus (and ENDIVE, if using Walking Onions)
  196. for the given epoch, which should be the one after the one
  197. that's currently about to end."""
  198. threshold = int(self.tot/2)+1
  199. consensusdescs = []
  200. for numseen, desc in DirAuth.uploadeddescs[epoch].values():
  201. if numseen >= threshold:
  202. consensusdescs.append(desc)
  203. DirAuth.consensus = Consensus(epoch, consensusdescs)
  204. def epoch_ending(self, epoch):
  205. # Only dirauth 0 actually needs to generate the consensus
  206. # because of the shared class-static state, but everyone has to
  207. # sign it. Note that this code relies on dirauth 0's
  208. # epoch_ending callback being called before any of the other
  209. # dirauths'.
  210. if (epoch+1) not in DirAuth.uploadeddescs:
  211. DirAuth.uploadeddescs[epoch+1] = dict()
  212. if self.me == 0:
  213. self.generate_consensus(epoch+1)
  214. del DirAuth.uploadeddescs[epoch+1]
  215. DirAuth.consensus.sign(self.sigkey, self.me, self.perfstats)
  216. def received(self, client, msg):
  217. self.perfstats.bytes_received += msg.size()
  218. if isinstance(msg, DirAuthUploadDescMsg):
  219. # Check the uploaded descriptor for sanity
  220. epoch = msg.desc.descdict['epoch']
  221. if epoch != network.thenetwork.getepoch() + 1:
  222. return
  223. # Store it in the class-static dict
  224. if epoch not in DirAuth.uploadeddescs:
  225. DirAuth.uploadeddescs[epoch] = dict()
  226. descstr = str(msg.desc)
  227. if descstr not in DirAuth.uploadeddescs[epoch]:
  228. DirAuth.uploadeddescs[epoch][descstr] = (1, msg.desc)
  229. else:
  230. DirAuth.uploadeddescs[epoch][descstr] = \
  231. (DirAuth.uploadeddescs[epoch][descstr][0]+1,
  232. DirAuth.uploadeddescs[epoch][descstr][1])
  233. elif isinstance(msg, DirAuthDelDescMsg):
  234. # Check the uploaded descriptor for sanity
  235. epoch = msg.desc.descdict['epoch']
  236. if epoch != network.thenetwork.getepoch() + 1:
  237. return
  238. # Remove it from the class-static dict
  239. if epoch not in DirAuth.uploadeddescs:
  240. return
  241. descstr = str(msg.desc)
  242. if descstr not in DirAuth.uploadeddescs[epoch]:
  243. return
  244. elif DirAuth.uploadeddescs[epoch][descstr][0] == 1:
  245. del DirAuth.uploadeddescs[epoch][descstr]
  246. else:
  247. DirAuth.uploadeddescs[epoch][descstr] = \
  248. (DirAuth.uploadeddescs[epoch][descstr][0]-1,
  249. DirAuth.uploadeddescs[epoch][descstr][1])
  250. elif isinstance(msg, DirAuthGetConsensusMsg):
  251. replymsg = DirAuthConsensusMsg(DirAuth.consensus)
  252. msgsize = replymsg.size()
  253. self.perfstats.bytes_sent += msgsize
  254. client.reply(replymsg)
  255. elif isinstance(msg, DirAuthGetENDIVEMsg):
  256. replymsg = DirAuthENDIVEMsg(DirAuth.endive)
  257. msgsize = replymsg.size()
  258. self.perfstats.bytes_sent += msgsize
  259. client.reply(replymsg)
  260. else:
  261. raise TypeError('Not a client-originating DirAuthNetMsg', msg)
  262. def closed(self):
  263. pass
  264. if __name__ == '__main__':
  265. # Start some dirauths
  266. numdirauths = 9
  267. dirauthaddrs = []
  268. for i in range(numdirauths):
  269. dirauth = DirAuth(i, numdirauths)
  270. dirauthaddrs.append(dirauth.netaddr)
  271. for a in dirauthaddrs:
  272. print(a,end=' ')
  273. print()
  274. network.thenetwork.nextepoch()