You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

293 lines
10 KiB

7 years ago
  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 distrubuted 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. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
  18. """
  19. ECDSA keys
  20. """
  21. from cryptography.exceptions import InvalidSignature
  22. from cryptography.hazmat.backends import default_backend
  23. from cryptography.hazmat.primitives import hashes, serialization
  24. from cryptography.hazmat.primitives.asymmetric import ec
  25. from cryptography.hazmat.primitives.asymmetric.utils import (
  26. decode_dss_signature, encode_dss_signature
  27. )
  28. from paramiko.common import four_byte
  29. from paramiko.message import Message
  30. from paramiko.pkey import PKey
  31. from paramiko.ssh_exception import SSHException
  32. from paramiko.util import deflate_long
  33. class _ECDSACurve(object):
  34. """
  35. Represents a specific ECDSA Curve (nistp256, nistp384, etc).
  36. Handles the generation of the key format identifier and the selection of
  37. the proper hash function. Also grabs the proper curve from the 'ecdsa'
  38. package.
  39. """
  40. def __init__(self, curve_class, nist_name):
  41. self.nist_name = nist_name
  42. self.key_length = curve_class.key_size
  43. # Defined in RFC 5656 6.2
  44. self.key_format_identifier = "ecdsa-sha2-" + self.nist_name
  45. # Defined in RFC 5656 6.2.1
  46. if self.key_length <= 256:
  47. self.hash_object = hashes.SHA256
  48. elif self.key_length <= 384:
  49. self.hash_object = hashes.SHA384
  50. else:
  51. self.hash_object = hashes.SHA512
  52. self.curve_class = curve_class
  53. class _ECDSACurveSet(object):
  54. """
  55. A collection to hold the ECDSA curves. Allows querying by oid and by key
  56. format identifier. The two ways in which ECDSAKey needs to be able to look
  57. up curves.
  58. """
  59. def __init__(self, ecdsa_curves):
  60. self.ecdsa_curves = ecdsa_curves
  61. def get_key_format_identifier_list(self):
  62. return [curve.key_format_identifier for curve in self.ecdsa_curves]
  63. def get_by_curve_class(self, curve_class):
  64. for curve in self.ecdsa_curves:
  65. if curve.curve_class == curve_class:
  66. return curve
  67. def get_by_key_format_identifier(self, key_format_identifier):
  68. for curve in self.ecdsa_curves:
  69. if curve.key_format_identifier == key_format_identifier:
  70. return curve
  71. def get_by_key_length(self, key_length):
  72. for curve in self.ecdsa_curves:
  73. if curve.key_length == key_length:
  74. return curve
  75. class ECDSAKey(PKey):
  76. """
  77. Representation of an ECDSA key which can be used to sign and verify SSH2
  78. data.
  79. """
  80. _ECDSA_CURVES = _ECDSACurveSet([
  81. _ECDSACurve(ec.SECP256R1, 'nistp256'),
  82. _ECDSACurve(ec.SECP384R1, 'nistp384'),
  83. _ECDSACurve(ec.SECP521R1, 'nistp521'),
  84. ])
  85. def __init__(self, msg=None, data=None, filename=None, password=None,
  86. vals=None, file_obj=None, validate_point=True):
  87. self.verifying_key = None
  88. self.signing_key = None
  89. self.public_blob = None
  90. if file_obj is not None:
  91. self._from_private_key(file_obj, password)
  92. return
  93. if filename is not None:
  94. self._from_private_key_file(filename, password)
  95. return
  96. if (msg is None) and (data is not None):
  97. msg = Message(data)
  98. if vals is not None:
  99. self.signing_key, self.verifying_key = vals
  100. c_class = self.signing_key.curve.__class__
  101. self.ecdsa_curve = self._ECDSA_CURVES.get_by_curve_class(c_class)
  102. else:
  103. # Must set ecdsa_curve first; subroutines called herein may need to
  104. # spit out our get_name(), which relies on this.
  105. key_type = msg.get_text()
  106. # But this also means we need to hand it a real key/curve
  107. # identifier, so strip out any cert business. (NOTE: could push
  108. # that into _ECDSACurveSet.get_by_key_format_identifier(), but it
  109. # feels more correct to do it here?)
  110. suffix = '-cert-v01@openssh.com'
  111. if key_type.endswith(suffix):
  112. key_type = key_type[:-len(suffix)]
  113. self.ecdsa_curve = self._ECDSA_CURVES.get_by_key_format_identifier(
  114. key_type
  115. )
  116. key_types = self._ECDSA_CURVES.get_key_format_identifier_list()
  117. cert_types = [
  118. '{}-cert-v01@openssh.com'.format(x)
  119. for x in key_types
  120. ]
  121. self._check_type_and_load_cert(
  122. msg=msg,
  123. key_type=key_types,
  124. cert_type=cert_types,
  125. )
  126. curvename = msg.get_text()
  127. if curvename != self.ecdsa_curve.nist_name:
  128. raise SSHException(
  129. "Can't handle curve of type {}".format(curvename)
  130. )
  131. pointinfo = msg.get_binary()
  132. try:
  133. numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(
  134. self.ecdsa_curve.curve_class(), pointinfo
  135. )
  136. except ValueError:
  137. raise SSHException("Invalid public key")
  138. self.verifying_key = numbers.public_key(backend=default_backend())
  139. @classmethod
  140. def supported_key_format_identifiers(cls):
  141. return cls._ECDSA_CURVES.get_key_format_identifier_list()
  142. def asbytes(self):
  143. key = self.verifying_key
  144. m = Message()
  145. m.add_string(self.ecdsa_curve.key_format_identifier)
  146. m.add_string(self.ecdsa_curve.nist_name)
  147. numbers = key.public_numbers()
  148. key_size_bytes = (key.curve.key_size + 7) // 8
  149. x_bytes = deflate_long(numbers.x, add_sign_padding=False)
  150. x_bytes = b'\x00' * (key_size_bytes - len(x_bytes)) + x_bytes
  151. y_bytes = deflate_long(numbers.y, add_sign_padding=False)
  152. y_bytes = b'\x00' * (key_size_bytes - len(y_bytes)) + y_bytes
  153. point_str = four_byte + x_bytes + y_bytes
  154. m.add_string(point_str)
  155. return m.asbytes()
  156. def __str__(self):
  157. return self.asbytes()
  158. def __hash__(self):
  159. return hash((self.get_name(), self.verifying_key.public_numbers().x,
  160. self.verifying_key.public_numbers().y))
  161. def get_name(self):
  162. return self.ecdsa_curve.key_format_identifier
  163. def get_bits(self):
  164. return self.ecdsa_curve.key_length
  165. def can_sign(self):
  166. return self.signing_key is not None
  167. def sign_ssh_data(self, data):
  168. ecdsa = ec.ECDSA(self.ecdsa_curve.hash_object())
  169. sig = self.signing_key.sign(data, ecdsa)
  170. r, s = decode_dss_signature(sig)
  171. m = Message()
  172. m.add_string(self.ecdsa_curve.key_format_identifier)
  173. m.add_string(self._sigencode(r, s))
  174. return m
  175. def verify_ssh_sig(self, data, msg):
  176. if msg.get_text() != self.ecdsa_curve.key_format_identifier:
  177. return False
  178. sig = msg.get_binary()
  179. sigR, sigS = self._sigdecode(sig)
  180. signature = encode_dss_signature(sigR, sigS)
  181. try:
  182. self.verifying_key.verify(
  183. signature, data, ec.ECDSA(self.ecdsa_curve.hash_object())
  184. )
  185. except InvalidSignature:
  186. return False
  187. else:
  188. return True
  189. def write_private_key_file(self, filename, password=None):
  190. self._write_private_key_file(
  191. filename,
  192. self.signing_key,
  193. serialization.PrivateFormat.TraditionalOpenSSL,
  194. password=password
  195. )
  196. def write_private_key(self, file_obj, password=None):
  197. self._write_private_key(
  198. file_obj,
  199. self.signing_key,
  200. serialization.PrivateFormat.TraditionalOpenSSL,
  201. password=password
  202. )
  203. @classmethod
  204. def generate(cls, curve=ec.SECP256R1(), progress_func=None, bits=None):
  205. """
  206. Generate a new private ECDSA key. This factory function can be used to
  207. generate a new host key or authentication key.
  208. :param progress_func: Not used for this type of key.
  209. :returns: A new private key (`.ECDSAKey`) object
  210. """
  211. if bits is not None:
  212. curve = cls._ECDSA_CURVES.get_by_key_length(bits)
  213. if curve is None:
  214. raise ValueError("Unsupported key length: {:d}".format(bits))
  215. curve = curve.curve_class()
  216. private_key = ec.generate_private_key(curve, backend=default_backend())
  217. return ECDSAKey(vals=(private_key, private_key.public_key()))
  218. # ...internals...
  219. def _from_private_key_file(self, filename, password):
  220. data = self._read_private_key_file('EC', filename, password)
  221. self._decode_key(data)
  222. def _from_private_key(self, file_obj, password):
  223. data = self._read_private_key('EC', file_obj, password)
  224. self._decode_key(data)
  225. def _decode_key(self, data):
  226. try:
  227. key = serialization.load_der_private_key(
  228. data, password=None, backend=default_backend()
  229. )
  230. except (ValueError, AssertionError) as e:
  231. raise SSHException(str(e))
  232. self.signing_key = key
  233. self.verifying_key = key.public_key()
  234. curve_class = key.curve.__class__
  235. self.ecdsa_curve = self._ECDSA_CURVES.get_by_curve_class(curve_class)
  236. def _sigencode(self, r, s):
  237. msg = Message()
  238. msg.add_mpint(r)
  239. msg.add_mpint(s)
  240. return msg.asbytes()
  241. def _sigdecode(self, sig):
  242. msg = Message(sig)
  243. r = msg.get_mpint()
  244. s = msg.get_mpint()
  245. return r, s

Powered by TurnKey Linux.