asn1.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. # -*- coding: ascii -*-
  2. #
  3. # Util/asn1.py : Minimal support for ASN.1 DER binary encoding.
  4. #
  5. # ===================================================================
  6. # The contents of this file are dedicated to the public domain. To
  7. # the extent that dedication to the public domain is not available,
  8. # everyone is granted a worldwide, perpetual, royalty-free,
  9. # non-exclusive license to exercise all rights associated with the
  10. # contents of this file for any purpose whatsoever.
  11. # No rights are reserved.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  17. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  18. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. # ===================================================================
  22. from Crypto.Util.number import long_to_bytes, bytes_to_long
  23. import sys
  24. from Crypto.Util.py3compat import *
  25. __all__ = [ 'DerObject', 'DerInteger', 'DerOctetString', 'DerNull', 'DerSequence', 'DerObjectId' ]
  26. class DerObject:
  27. """Base class for defining a single DER object.
  28. Instantiate this class ONLY when you have to decode a DER element.
  29. """
  30. # Known TAG types
  31. typeTags = { 'SEQUENCE': 0x30, 'BIT STRING': 0x03, 'INTEGER': 0x02,
  32. 'OCTET STRING': 0x04, 'NULL': 0x05, 'OBJECT IDENTIFIER': 0x06 }
  33. def __init__(self, ASN1Type=None, payload=b('')):
  34. """Initialize the DER object according to a specific type.
  35. The ASN.1 type is either specified as the ASN.1 string (e.g.
  36. 'SEQUENCE'), directly with its numerical tag or with no tag
  37. at all (None)."""
  38. if isInt(ASN1Type) or ASN1Type is None:
  39. self.typeTag = ASN1Type
  40. else:
  41. if len(ASN1Type)==1:
  42. self.typeTag = ord(ASN1Type)
  43. else:
  44. self.typeTag = self.typeTags.get(ASN1Type)
  45. self.payload = payload
  46. def isType(self, ASN1Type):
  47. return self.typeTags[ASN1Type]==self.typeTag
  48. def _lengthOctets(self, payloadLen):
  49. """Return a byte string that encodes the given payload length (in
  50. bytes) in a format suitable for a DER length tag (L).
  51. """
  52. if payloadLen>127:
  53. encoding = long_to_bytes(payloadLen)
  54. return bchr(len(encoding)+128) + encoding
  55. return bchr(payloadLen)
  56. def encode(self):
  57. """Return a complete DER element, fully encoded as a TLV."""
  58. return bchr(self.typeTag) + self._lengthOctets(len(self.payload)) + self.payload
  59. def _decodeLen(self, idx, der):
  60. """Given a (part of a) DER element, and an index to the first byte of
  61. a DER length tag (L), return a tuple with the payload size,
  62. and the index of the first byte of the such payload (V).
  63. Raises a ValueError exception if the DER length is invalid.
  64. Raises an IndexError exception if the DER element is too short.
  65. """
  66. length = bord(der[idx])
  67. if length<=127:
  68. return (length,idx+1)
  69. payloadLength = bytes_to_long(der[idx+1:idx+1+(length & 0x7F)])
  70. if payloadLength<=127:
  71. raise ValueError("Not a DER length tag.")
  72. return (payloadLength, idx+1+(length & 0x7F))
  73. def decode(self, derEle, noLeftOvers=0):
  74. """Decode a complete DER element, and re-initializes this
  75. object with it.
  76. @param derEle A complete DER element. It must start with a DER T
  77. tag.
  78. @param noLeftOvers Indicate whether it is acceptable to complete the
  79. parsing of the DER element and find that not all
  80. bytes in derEle have been used.
  81. @return Index of the first unused byte in the given DER element.
  82. Raises a ValueError exception in case of parsing errors.
  83. Raises an IndexError exception if the DER element is too short.
  84. """
  85. try:
  86. self.typeTag = bord(derEle[0])
  87. if (self.typeTag & 0x1F)==0x1F:
  88. raise ValueError("Unsupported DER tag")
  89. (length,idx) = self._decodeLen(1, derEle)
  90. if noLeftOvers and len(derEle) != (idx+length):
  91. raise ValueError("Not a DER structure")
  92. self.payload = derEle[idx:idx+length]
  93. except IndexError:
  94. raise ValueError("Not a valid DER SEQUENCE.")
  95. return idx+length
  96. class DerInteger(DerObject):
  97. def __init__(self, value = 0):
  98. """Class to model an INTEGER DER element.
  99. Limitation: only non-negative values are supported.
  100. """
  101. DerObject.__init__(self, 'INTEGER')
  102. self.value = value
  103. def encode(self):
  104. """Return a complete INTEGER DER element, fully encoded as a TLV."""
  105. self.payload = long_to_bytes(self.value)
  106. if bord(self.payload[0])>127:
  107. self.payload = bchr(0x00) + self.payload
  108. return DerObject.encode(self)
  109. def decode(self, derEle, noLeftOvers=0):
  110. """Decode a complete INTEGER DER element, and re-initializes this
  111. object with it.
  112. @param derEle A complete INTEGER DER element. It must start with a DER
  113. INTEGER tag.
  114. @param noLeftOvers Indicate whether it is acceptable to complete the
  115. parsing of the DER element and find that not all
  116. bytes in derEle have been used.
  117. @return Index of the first unused byte in the given DER element.
  118. Raises a ValueError exception if the DER element is not a
  119. valid non-negative INTEGER.
  120. Raises an IndexError exception if the DER element is too short.
  121. """
  122. tlvLength = DerObject.decode(self, derEle, noLeftOvers)
  123. if self.typeTag!=self.typeTags['INTEGER']:
  124. raise ValueError ("Not a DER INTEGER.")
  125. if bord(self.payload[0])>127:
  126. raise ValueError ("Negative INTEGER.")
  127. self.value = bytes_to_long(self.payload)
  128. return tlvLength
  129. class DerSequence(DerObject):
  130. """Class to model a SEQUENCE DER element.
  131. This object behave like a dynamic Python sequence.
  132. Sub-elements that are INTEGERs, look like Python integers.
  133. Any other sub-element is a binary string encoded as the complete DER
  134. sub-element (TLV).
  135. """
  136. def __init__(self, startSeq=None):
  137. """Initialize the SEQUENCE DER object. Always empty
  138. initially."""
  139. DerObject.__init__(self, 'SEQUENCE')
  140. if startSeq==None:
  141. self._seq = []
  142. else:
  143. self._seq = startSeq
  144. ## A few methods to make it behave like a python sequence
  145. def __delitem__(self, n):
  146. del self._seq[n]
  147. def __getitem__(self, n):
  148. return self._seq[n]
  149. def __setitem__(self, key, value):
  150. self._seq[key] = value
  151. def __setslice__(self,i,j,sequence):
  152. self._seq[i:j] = sequence
  153. def __delslice__(self,i,j):
  154. del self._seq[i:j]
  155. def __getslice__(self, i, j):
  156. return self._seq[max(0, i):max(0, j)]
  157. def __len__(self):
  158. return len(self._seq)
  159. def append(self, item):
  160. return self._seq.append(item)
  161. def hasInts(self):
  162. """Return the number of items in this sequence that are numbers."""
  163. return len(filter(isInt, self._seq))
  164. def hasOnlyInts(self):
  165. """Return True if all items in this sequence are numbers."""
  166. return self._seq and self.hasInts()==len(self._seq)
  167. def encode(self):
  168. """Return the DER encoding for the ASN.1 SEQUENCE, containing
  169. the non-negative integers and longs added to this object.
  170. Limitation: Raises a ValueError exception if it some elements
  171. in the sequence are neither Python integers nor complete DER INTEGERs.
  172. """
  173. self.payload = b('')
  174. for item in self._seq:
  175. try:
  176. self.payload += item
  177. except:
  178. try:
  179. self.payload += DerInteger(item).encode()
  180. except:
  181. raise ValueError("Trying to DER encode an unknown object")
  182. return DerObject.encode(self)
  183. def decode(self, derEle, noLeftOvers=0):
  184. """Decode a complete SEQUENCE DER element, and re-initializes this
  185. object with it.
  186. @param derEle A complete SEQUENCE DER element. It must start with a DER
  187. SEQUENCE tag.
  188. @param noLeftOvers Indicate whether it is acceptable to complete the
  189. parsing of the DER element and find that not all
  190. bytes in derEle have been used.
  191. @return Index of the first unused byte in the given DER element.
  192. DER INTEGERs are decoded into Python integers. Any other DER
  193. element is not decoded. Its validity is not checked.
  194. Raises a ValueError exception if the DER element is not a
  195. valid DER SEQUENCE.
  196. Raises an IndexError exception if the DER element is too short.
  197. """
  198. self._seq = []
  199. try:
  200. tlvLength = DerObject.decode(self, derEle, noLeftOvers)
  201. if self.typeTag!=self.typeTags['SEQUENCE']:
  202. raise ValueError("Not a DER SEQUENCE.")
  203. # Scan one TLV at once
  204. idx = 0
  205. while idx<len(self.payload):
  206. typeTag = bord(self.payload[idx])
  207. if typeTag==self.typeTags['INTEGER']:
  208. newInteger = DerInteger()
  209. idx += newInteger.decode(self.payload[idx:])
  210. self._seq.append(newInteger.value)
  211. else:
  212. itemLen,itemIdx = self._decodeLen(idx+1,self.payload)
  213. self._seq.append(self.payload[idx:itemIdx+itemLen])
  214. idx = itemIdx + itemLen
  215. except IndexError:
  216. raise ValueError("Not a valid DER SEQUENCE.")
  217. return tlvLength
  218. class DerOctetString(DerObject):
  219. def __init__(self, value = b('')):
  220. DerObject.__init__(self, 'OCTET STRING')
  221. self.payload = value
  222. def decode(self, derEle, noLeftOvers=0):
  223. p = DerObject.decode(derEle, noLeftOvers)
  224. if not self.isType("OCTET STRING"):
  225. raise ValueError("Not a valid OCTET STRING.")
  226. return p
  227. class DerNull(DerObject):
  228. def __init__(self):
  229. DerObject.__init__(self, 'NULL')
  230. class DerObjectId(DerObject):
  231. def __init__(self):
  232. DerObject.__init__(self, 'OBJECT IDENTIFIER')
  233. def decode(self, derEle, noLeftOvers=0):
  234. p = DerObject.decode(derEle, noLeftOvers)
  235. if not self.isType("OBJECT IDENTIFIER"):
  236. raise ValueError("Not a valid OBJECT IDENTIFIER.")
  237. return p
  238. def isInt(x):
  239. test = 0
  240. try:
  241. test += x
  242. except TypeError:
  243. return 0
  244. return 1