ber.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  2. #
  3. # This file is part of paramiko.
  4. #
  5. # Paramiko is free software; you can redistribute it and/or modify it under the
  6. # terms of the GNU Lesser General Public License as published by the Free
  7. # Software Foundation; either version 2.1 of the License, or (at your option)
  8. # any later version.
  9. #
  10. # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
  11. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  13. # details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  17. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. from paramiko.common import max_byte, zero_byte
  19. from paramiko.py3compat import b, byte_ord, byte_chr, long
  20. import paramiko.util as util
  21. class BERException(Exception):
  22. pass
  23. class BER(object):
  24. """
  25. Robey's tiny little attempt at a BER decoder.
  26. """
  27. def __init__(self, content=bytes()):
  28. self.content = b(content)
  29. self.idx = 0
  30. def asbytes(self):
  31. return self.content
  32. def __str__(self):
  33. return self.asbytes()
  34. def __repr__(self):
  35. return "BER('" + repr(self.content) + "')"
  36. def decode(self):
  37. return self.decode_next()
  38. def decode_next(self):
  39. if self.idx >= len(self.content):
  40. return None
  41. ident = byte_ord(self.content[self.idx])
  42. self.idx += 1
  43. if (ident & 31) == 31:
  44. # identifier > 30
  45. ident = 0
  46. while self.idx < len(self.content):
  47. t = byte_ord(self.content[self.idx])
  48. self.idx += 1
  49. ident = (ident << 7) | (t & 0x7f)
  50. if not (t & 0x80):
  51. break
  52. if self.idx >= len(self.content):
  53. return None
  54. # now fetch length
  55. size = byte_ord(self.content[self.idx])
  56. self.idx += 1
  57. if size & 0x80:
  58. # more complimicated...
  59. # FIXME: theoretically should handle indefinite-length (0x80)
  60. t = size & 0x7f
  61. if self.idx + t > len(self.content):
  62. return None
  63. size = util.inflate_long(
  64. self.content[self.idx : self.idx + t], True
  65. )
  66. self.idx += t
  67. if self.idx + size > len(self.content):
  68. # can't fit
  69. return None
  70. data = self.content[self.idx : self.idx + size]
  71. self.idx += size
  72. # now switch on id
  73. if ident == 0x30:
  74. # sequence
  75. return self.decode_sequence(data)
  76. elif ident == 2:
  77. # int
  78. return util.inflate_long(data)
  79. else:
  80. # 1: boolean (00 false, otherwise true)
  81. msg = "Unknown ber encoding type {:d} (robey is lazy)"
  82. raise BERException(msg.format(ident))
  83. @staticmethod
  84. def decode_sequence(data):
  85. out = []
  86. ber = BER(data)
  87. while True:
  88. x = ber.decode_next()
  89. if x is None:
  90. break
  91. out.append(x)
  92. return out
  93. def encode_tlv(self, ident, val):
  94. # no need to support ident > 31 here
  95. self.content += byte_chr(ident)
  96. if len(val) > 0x7f:
  97. lenstr = util.deflate_long(len(val))
  98. self.content += byte_chr(0x80 + len(lenstr)) + lenstr
  99. else:
  100. self.content += byte_chr(len(val))
  101. self.content += val
  102. def encode(self, x):
  103. if type(x) is bool:
  104. if x:
  105. self.encode_tlv(1, max_byte)
  106. else:
  107. self.encode_tlv(1, zero_byte)
  108. elif (type(x) is int) or (type(x) is long):
  109. self.encode_tlv(2, util.deflate_long(x))
  110. elif type(x) is str:
  111. self.encode_tlv(4, x)
  112. elif (type(x) is list) or (type(x) is tuple):
  113. self.encode_tlv(0x30, self.encode_sequence(x))
  114. else:
  115. raise BERException(
  116. "Unknown type for encoding: {!r}".format(type(x))
  117. )
  118. @staticmethod
  119. def encode_sequence(data):
  120. ber = BER()
  121. for item in data:
  122. ber.encode(item)
  123. return ber.asbytes()