/gdata/Crypto/Protocol/Chaffing.py

http://radioappz.googlecode.com/ · Python · 229 lines · 170 code · 14 blank · 45 comment · 18 complexity · cc1704d6003575b07376264cfc5d8966 MD5 · raw file

  1. """This file implements the chaffing algorithm.
  2. Winnowing and chaffing is a technique for enhancing privacy without requiring
  3. strong encryption. In short, the technique takes a set of authenticated
  4. message blocks (the wheat) and adds a number of chaff blocks which have
  5. randomly chosen data and MAC fields. This means that to an adversary, the
  6. chaff blocks look as valid as the wheat blocks, and so the authentication
  7. would have to be performed on every block. By tailoring the number of chaff
  8. blocks added to the message, the sender can make breaking the message
  9. computationally infeasible. There are many other interesting properties of
  10. the winnow/chaff technique.
  11. For example, say Alice is sending a message to Bob. She packetizes the
  12. message and performs an all-or-nothing transformation on the packets. Then
  13. she authenticates each packet with a message authentication code (MAC). The
  14. MAC is a hash of the data packet, and there is a secret key which she must
  15. share with Bob (key distribution is an exercise left to the reader). She then
  16. adds a serial number to each packet, and sends the packets to Bob.
  17. Bob receives the packets, and using the shared secret authentication key,
  18. authenticates the MACs for each packet. Those packets that have bad MACs are
  19. simply discarded. The remainder are sorted by serial number, and passed
  20. through the reverse all-or-nothing transform. The transform means that an
  21. eavesdropper (say Eve) must acquire all the packets before any of the data can
  22. be read. If even one packet is missing, the data is useless.
  23. There's one twist: by adding chaff packets, Alice and Bob can make Eve's job
  24. much harder, since Eve now has to break the shared secret key, or try every
  25. combination of wheat and chaff packet to read any of the message. The cool
  26. thing is that Bob doesn't need to add any additional code; the chaff packets
  27. are already filtered out because their MACs don't match (in all likelihood --
  28. since the data and MACs for the chaff packets are randomly chosen it is
  29. possible, but very unlikely that a chaff MAC will match the chaff data). And
  30. Alice need not even be the party adding the chaff! She could be completely
  31. unaware that a third party, say Charles, is adding chaff packets to her
  32. messages as they are transmitted.
  33. For more information on winnowing and chaffing see this paper:
  34. Ronald L. Rivest, "Chaffing and Winnowing: Confidentiality without Encryption"
  35. http://theory.lcs.mit.edu/~rivest/chaffing.txt
  36. """
  37. __revision__ = "$Id: Chaffing.py,v 1.7 2003/02/28 15:23:21 akuchling Exp $"
  38. from Crypto.Util.number import bytes_to_long
  39. class Chaff:
  40. """Class implementing the chaff adding algorithm.
  41. Methods for subclasses:
  42. _randnum(size):
  43. Returns a randomly generated number with a byte-length equal
  44. to size. Subclasses can use this to implement better random
  45. data and MAC generating algorithms. The default algorithm is
  46. probably not very cryptographically secure. It is most
  47. important that the chaff data does not contain any patterns
  48. that can be used to discern it from wheat data without running
  49. the MAC.
  50. """
  51. def __init__(self, factor=1.0, blocksper=1):
  52. """Chaff(factor:float, blocksper:int)
  53. factor is the number of message blocks to add chaff to,
  54. expressed as a percentage between 0.0 and 1.0. blocksper is
  55. the number of chaff blocks to include for each block being
  56. chaffed. Thus the defaults add one chaff block to every
  57. message block. By changing the defaults, you can adjust how
  58. computationally difficult it could be for an adversary to
  59. brute-force crack the message. The difficulty is expressed
  60. as:
  61. pow(blocksper, int(factor * number-of-blocks))
  62. For ease of implementation, when factor < 1.0, only the first
  63. int(factor*number-of-blocks) message blocks are chaffed.
  64. """
  65. if not (0.0<=factor<=1.0):
  66. raise ValueError, "'factor' must be between 0.0 and 1.0"
  67. if blocksper < 0:
  68. raise ValueError, "'blocksper' must be zero or more"
  69. self.__factor = factor
  70. self.__blocksper = blocksper
  71. def chaff(self, blocks):
  72. """chaff( [(serial-number:int, data:string, MAC:string)] )
  73. : [(int, string, string)]
  74. Add chaff to message blocks. blocks is a list of 3-tuples of the
  75. form (serial-number, data, MAC).
  76. Chaff is created by choosing a random number of the same
  77. byte-length as data, and another random number of the same
  78. byte-length as MAC. The message block's serial number is
  79. placed on the chaff block and all the packet's chaff blocks
  80. are randomly interspersed with the single wheat block. This
  81. method then returns a list of 3-tuples of the same form.
  82. Chaffed blocks will contain multiple instances of 3-tuples
  83. with the same serial number, but the only way to figure out
  84. which blocks are wheat and which are chaff is to perform the
  85. MAC hash and compare values.
  86. """
  87. chaffedblocks = []
  88. # count is the number of blocks to add chaff to. blocksper is the
  89. # number of chaff blocks to add per message block that is being
  90. # chaffed.
  91. count = len(blocks) * self.__factor
  92. blocksper = range(self.__blocksper)
  93. for i, wheat in map(None, range(len(blocks)), blocks):
  94. # it shouldn't matter which of the n blocks we add chaff to, so for
  95. # ease of implementation, we'll just add them to the first count
  96. # blocks
  97. if i < count:
  98. serial, data, mac = wheat
  99. datasize = len(data)
  100. macsize = len(mac)
  101. addwheat = 1
  102. # add chaff to this block
  103. for j in blocksper:
  104. import sys
  105. chaffdata = self._randnum(datasize)
  106. chaffmac = self._randnum(macsize)
  107. chaff = (serial, chaffdata, chaffmac)
  108. # mix up the order, if the 5th bit is on then put the
  109. # wheat on the list
  110. if addwheat and bytes_to_long(self._randnum(16)) & 0x40:
  111. chaffedblocks.append(wheat)
  112. addwheat = 0
  113. chaffedblocks.append(chaff)
  114. if addwheat:
  115. chaffedblocks.append(wheat)
  116. else:
  117. # just add the wheat
  118. chaffedblocks.append(wheat)
  119. return chaffedblocks
  120. def _randnum(self, size):
  121. # TBD: Not a very secure algorithm.
  122. # TBD: size * 2 to work around possible bug in RandomPool
  123. from Crypto.Util import randpool
  124. import time
  125. pool = randpool.RandomPool(size * 2)
  126. while size > pool.entropy:
  127. pass
  128. # we now have enough entropy in the pool to get size bytes of random
  129. # data... well, probably
  130. return pool.get_bytes(size)
  131. if __name__ == '__main__':
  132. text = """\
  133. We hold these truths to be self-evident, that all men are created equal, that
  134. they are endowed by their Creator with certain unalienable Rights, that among
  135. these are Life, Liberty, and the pursuit of Happiness. That to secure these
  136. rights, Governments are instituted among Men, deriving their just powers from
  137. the consent of the governed. That whenever any Form of Government becomes
  138. destructive of these ends, it is the Right of the People to alter or to
  139. abolish it, and to institute new Government, laying its foundation on such
  140. principles and organizing its powers in such form, as to them shall seem most
  141. likely to effect their Safety and Happiness.
  142. """
  143. print 'Original text:\n=========='
  144. print text
  145. print '=========='
  146. # first transform the text into packets
  147. blocks = [] ; size = 40
  148. for i in range(0, len(text), size):
  149. blocks.append( text[i:i+size] )
  150. # now get MACs for all the text blocks. The key is obvious...
  151. print 'Calculating MACs...'
  152. from Crypto.Hash import HMAC, SHA
  153. key = 'Jefferson'
  154. macs = [HMAC.new(key, block, digestmod=SHA).digest()
  155. for block in blocks]
  156. assert len(blocks) == len(macs)
  157. # put these into a form acceptable as input to the chaffing procedure
  158. source = []
  159. m = map(None, range(len(blocks)), blocks, macs)
  160. print m
  161. for i, data, mac in m:
  162. source.append((i, data, mac))
  163. # now chaff these
  164. print 'Adding chaff...'
  165. c = Chaff(factor=0.5, blocksper=2)
  166. chaffed = c.chaff(source)
  167. from base64 import encodestring
  168. # print the chaffed message blocks. meanwhile, separate the wheat from
  169. # the chaff
  170. wheat = []
  171. print 'chaffed message blocks:'
  172. for i, data, mac in chaffed:
  173. # do the authentication
  174. h = HMAC.new(key, data, digestmod=SHA)
  175. pmac = h.digest()
  176. if pmac == mac:
  177. tag = '-->'
  178. wheat.append(data)
  179. else:
  180. tag = ' '
  181. # base64 adds a trailing newline
  182. print tag, '%3d' % i, \
  183. repr(data), encodestring(mac)[:-1]
  184. # now decode the message packets and check it against the original text
  185. print 'Undigesting wheat...'
  186. newtext = "".join(wheat)
  187. if newtext == text:
  188. print 'They match!'
  189. else:
  190. print 'They differ!'