kh2reg.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. #!/usr/bin/env python3
  2. # Convert OpenSSH known_hosts and known_hosts2 files to "new format" PuTTY
  3. # host keys.
  4. # usage:
  5. # kh2reg.py [ --win ] known_hosts1 2 3 4 ... > hosts.reg
  6. # Creates a Windows .REG file (double-click to install).
  7. # kh2reg.py --unix known_hosts1 2 3 4 ... > sshhostkeys
  8. # Creates data suitable for storing in ~/.putty/sshhostkeys (Unix).
  9. # Line endings are someone else's problem as is traditional.
  10. # Should run under either Python 2 or 3.
  11. import fileinput
  12. import base64
  13. import struct
  14. import string
  15. import re
  16. import sys
  17. import argparse
  18. import itertools
  19. import collections
  20. import hashlib
  21. from functools import reduce
  22. def winmungestr(s):
  23. "Duplicate of PuTTY's mungestr() in winstore.c:1.10 for Registry keys"
  24. candot = 0
  25. r = ""
  26. for c in s:
  27. if c in r' \*?%~' or ord(c)<ord(' ') or (c == '.' and not candot):
  28. r = r + ("%%%02X" % ord(c))
  29. else:
  30. r = r + c
  31. candot = 1
  32. return r
  33. def strtoint(s):
  34. "Convert arbitrary-length big-endian binary data to a Python int"
  35. bytes = struct.unpack(">{:d}B".format(len(s)), s)
  36. return reduce ((lambda a, b: (int(a) << 8) + int(b)), bytes)
  37. def strtoint_le(s):
  38. "Convert arbitrary-length little-endian binary data to a Python int"
  39. bytes = reversed(struct.unpack(">{:d}B".format(len(s)), s))
  40. return reduce ((lambda a, b: (int(a) << 8) + int(b)), bytes)
  41. def inttohex(n):
  42. "Convert int to lower-case hex."
  43. return "0x{:x}".format(n)
  44. def warn(s):
  45. "Warning with file/line number"
  46. sys.stderr.write("%s:%d: %s\n"
  47. % (fileinput.filename(), fileinput.filelineno(), s))
  48. class HMAC(object):
  49. def __init__(self, hashclass, blocksize):
  50. self.hashclass = hashclass
  51. self.blocksize = blocksize
  52. self.struct = struct.Struct(">{:d}B".format(self.blocksize))
  53. def pad_key(self, key):
  54. return key + b'\0' * (self.blocksize - len(key))
  55. def xor_key(self, key, xor):
  56. return self.struct.pack(*[b ^ xor for b in self.struct.unpack(key)])
  57. def keyed_hash(self, key, padbyte, string):
  58. return self.hashclass(self.xor_key(key, padbyte) + string).digest()
  59. def compute(self, key, string):
  60. if len(key) > self.blocksize:
  61. key = self.hashclass(key).digest()
  62. key = self.pad_key(key)
  63. return self.keyed_hash(key, 0x5C, self.keyed_hash(key, 0x36, string))
  64. def openssh_hashed_host_match(hashed_host, try_host):
  65. if hashed_host.startswith(b'|1|'):
  66. salt, expected = hashed_host[3:].split(b'|')
  67. salt = base64.decodebytes(salt)
  68. expected = base64.decodebytes(expected)
  69. mac = HMAC(hashlib.sha1, 64)
  70. else:
  71. return False # unrecognised magic number prefix
  72. return mac.compute(salt, try_host) == expected
  73. def invert(n, p):
  74. """Compute inverse mod p."""
  75. if n % p == 0:
  76. raise ZeroDivisionError()
  77. a = n, 1, 0
  78. b = p, 0, 1
  79. while b[0]:
  80. q = a[0] // b[0]
  81. a = a[0] - q*b[0], a[1] - q*b[1], a[2] - q*b[2]
  82. b, a = a, b
  83. assert abs(a[0]) == 1
  84. return a[1]*a[0]
  85. def jacobi(n,m):
  86. """Compute the Jacobi symbol.
  87. The special case of this when m is prime is the Legendre symbol,
  88. which is 0 if n is congruent to 0 mod m; 1 if n is congruent to a
  89. non-zero square number mod m; -1 if n is not congruent to any
  90. square mod m.
  91. """
  92. assert m & 1
  93. acc = 1
  94. while True:
  95. n %= m
  96. if n == 0:
  97. return 0
  98. while not (n & 1):
  99. n >>= 1
  100. if (m & 7) not in {1,7}:
  101. acc *= -1
  102. if n == 1:
  103. return acc
  104. if (n & 3) == 3 and (m & 3) == 3:
  105. acc *= -1
  106. n, m = m, n
  107. class SqrtModP(object):
  108. """Class for finding square roots of numbers mod p.
  109. p must be an odd prime (but its primality is not checked)."""
  110. def __init__(self, p):
  111. p = abs(p)
  112. assert p & 1
  113. self.p = p
  114. # Decompose p as 2^e k + 1 for odd k.
  115. self.k = p-1
  116. self.e = 0
  117. while not (self.k & 1):
  118. self.k >>= 1
  119. self.e += 1
  120. # Find a non-square mod p.
  121. for self.z in itertools.count(1):
  122. if jacobi(self.z, self.p) == -1:
  123. break
  124. self.zinv = invert(self.z, self.p)
  125. def sqrt_recurse(self, a):
  126. ak = pow(a, self.k, self.p)
  127. for i in range(self.e, -1, -1):
  128. if ak == 1:
  129. break
  130. ak = ak*ak % self.p
  131. assert i > 0
  132. if i == self.e:
  133. return pow(a, (self.k+1) // 2, self.p)
  134. r_prime = self.sqrt_recurse(a * pow(self.z, 2**i, self.p))
  135. return r_prime * pow(self.zinv, 2**(i-1), self.p) % self.p
  136. def sqrt(self, a):
  137. j = jacobi(a, self.p)
  138. if j == 0:
  139. return 0
  140. if j < 0:
  141. raise ValueError("{} has no square root mod {}".format(a, self.p))
  142. a %= self.p
  143. r = self.sqrt_recurse(a)
  144. assert r*r % self.p == a
  145. # Normalise to the smaller (or 'positive') one of the two roots.
  146. return min(r, self.p - r)
  147. def __str__(self):
  148. return "{}({})".format(type(self).__name__, self.p)
  149. def __repr__(self):
  150. return self.__str__()
  151. instances = {}
  152. @classmethod
  153. def make(cls, p):
  154. if p not in cls.instances:
  155. cls.instances[p] = cls(p)
  156. return cls.instances[p]
  157. @classmethod
  158. def root(cls, n, p):
  159. return cls.make(p).sqrt(n)
  160. NistCurve = collections.namedtuple("NistCurve", "p a b")
  161. nist_curves = {
  162. "ecdsa-sha2-nistp256": NistCurve(0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff, 0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc, 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b),
  163. "ecdsa-sha2-nistp384": NistCurve(0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff, 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc, 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef),
  164. "ecdsa-sha2-nistp521": NistCurve(0x01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, 0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc, 0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00),
  165. }
  166. class BlankInputLine(Exception):
  167. pass
  168. class UnknownKeyType(Exception):
  169. def __init__(self, keytype):
  170. self.keytype = keytype
  171. class KeyFormatError(Exception):
  172. def __init__(self, msg):
  173. self.msg = msg
  174. def handle_line(line, output_formatter, try_hosts):
  175. try:
  176. # Remove leading/trailing whitespace (should zap CR and LF)
  177. line = line.strip()
  178. # Skip blanks and comments
  179. if line == '' or line[0] == '#':
  180. raise BlankInputLine
  181. # Split line on spaces.
  182. fields = line.split(' ')
  183. # Common fields
  184. hostpat = fields[0]
  185. keyparams = [] # placeholder
  186. keytype = "" # placeholder
  187. # Grotty heuristic to distinguish known_hosts from known_hosts2:
  188. # is second field entirely decimal digits?
  189. if re.match (r"\d*$", fields[1]):
  190. # Treat as SSH-1-type host key.
  191. # Format: hostpat bits10 exp10 mod10 comment...
  192. # (PuTTY doesn't store the number of bits.)
  193. keyparams = list(map(int, fields[2:4]))
  194. keytype = "rsa"
  195. else:
  196. # Treat as SSH-2-type host key.
  197. # Format: hostpat keytype keyblob64 comment...
  198. sshkeytype, blob = fields[1], base64.decodebytes(
  199. fields[2].encode("ASCII"))
  200. # 'blob' consists of a number of
  201. # uint32 N (big-endian)
  202. # uint8[N] field_data
  203. subfields = []
  204. while blob:
  205. sizefmt = ">L"
  206. (size,) = struct.unpack (sizefmt, blob[0:4])
  207. size = int(size) # req'd for slicage
  208. (data,) = struct.unpack (">%lus" % size, blob[4:size+4])
  209. subfields.append(data)
  210. blob = blob [struct.calcsize(sizefmt) + size : ]
  211. # The first field is keytype again.
  212. if subfields[0].decode("ASCII") != sshkeytype:
  213. raise KeyFormatError("""
  214. outer and embedded key types do not match: '%s', '%s'
  215. """ % (sshkeytype, subfields[1]))
  216. # Translate key type string into something PuTTY can use, and
  217. # munge the rest of the data.
  218. if sshkeytype == "ssh-rsa":
  219. keytype = "rsa2"
  220. # The rest of the subfields we can treat as an opaque list
  221. # of bignums (same numbers and order as stored by PuTTY).
  222. keyparams = list(map(strtoint, subfields[1:]))
  223. elif sshkeytype == "ssh-dss":
  224. keytype = "dss"
  225. # Same again.
  226. keyparams = list(map(strtoint, subfields[1:]))
  227. elif sshkeytype in nist_curves:
  228. keytype = sshkeytype
  229. # Have to parse this a bit.
  230. if len(subfields) > 3:
  231. raise KeyFormatError("too many subfields in blob")
  232. (curvename, Q) = subfields[1:]
  233. # First is yet another copy of the key name.
  234. if not re.match("ecdsa-sha2-" + re.escape(
  235. curvename.decode("ASCII")), sshkeytype):
  236. raise KeyFormatError("key type mismatch ('%s' vs '%s')"
  237. % (sshkeytype, curvename))
  238. # Second contains key material X and Y (hopefully).
  239. # First a magic octet indicating point compression.
  240. point_type = struct.unpack_from("B", Q, 0)[0]
  241. Qrest = Q[1:]
  242. if point_type == 4:
  243. # Then two equal-length bignums (X and Y).
  244. bnlen = len(Qrest)
  245. if (bnlen % 1) != 0:
  246. raise KeyFormatError("odd-length X+Y")
  247. bnlen = bnlen // 2
  248. x = strtoint(Qrest[:bnlen])
  249. y = strtoint(Qrest[bnlen:])
  250. elif 2 <= point_type <= 3:
  251. # A compressed point just specifies X, and leaves
  252. # Y implicit except for parity, so we have to
  253. # recover it from the curve equation.
  254. curve = nist_curves[sshkeytype]
  255. x = strtoint(Qrest)
  256. yy = (x*x*x + curve.a*x + curve.b) % curve.p
  257. y = SqrtModP.root(yy, curve.p)
  258. if y % 2 != point_type % 2:
  259. y = curve.p - y
  260. keyparams = [curvename, x, y]
  261. elif sshkeytype in { "ssh-ed25519", "ssh-ed448" }:
  262. keytype = sshkeytype
  263. if len(subfields) != 2:
  264. raise KeyFormatError("wrong number of subfields in blob")
  265. # Key material y, with the top bit being repurposed as
  266. # the expected parity of the associated x (point
  267. # compression).
  268. y = strtoint_le(subfields[1])
  269. x_parity = y >> 255
  270. y &= ~(1 << 255)
  271. # Curve parameters.
  272. p, d, a = {
  273. "ssh-ed25519": (2**255 - 19, 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3, -1),
  274. "ssh-ed448": (2**448-2**224-1, -39081, +1),
  275. }[sshkeytype]
  276. # Recover x^2 = (y^2 - 1) / (d y^2 - a).
  277. xx = (y*y - 1) * invert(d*y*y - a, p) % p
  278. # Take the square root.
  279. x = SqrtModP.root(xx, p)
  280. # Pick the square root of the correct parity.
  281. if (x % 2) != x_parity:
  282. x = p - x
  283. keyparams = [x, y]
  284. else:
  285. raise UnknownKeyType(sshkeytype)
  286. # Now print out one line per host pattern, discarding wildcards.
  287. for host in hostpat.split(','):
  288. if re.search (r"[*?!]", host):
  289. warn("skipping wildcard host pattern '%s'" % host)
  290. continue
  291. if re.match (r"\|", host):
  292. for try_host in try_hosts:
  293. if openssh_hashed_host_match(host.encode('ASCII'),
  294. try_host.encode('UTF-8')):
  295. host = try_host
  296. break
  297. else:
  298. warn("unable to match hashed hostname '%s'" % host)
  299. continue
  300. m = re.match (r"\[([^]]*)\]:(\d*)$", host)
  301. if m:
  302. (host, port) = m.group(1,2)
  303. port = int(port)
  304. else:
  305. port = 22
  306. # Slightly bizarre output key format: 'type@port:hostname'
  307. # XXX: does PuTTY do anything useful with literal IP[v4]s?
  308. key = keytype + ("@%d:%s" % (port, host))
  309. # Most of these are numbers, but there's the occasional
  310. # string that needs passing through
  311. value = ",".join(map(
  312. lambda x: x if isinstance(x, str)
  313. else x.decode('ASCII') if isinstance(x, bytes)
  314. else inttohex(x), keyparams))
  315. output_formatter.key(key, value)
  316. except UnknownKeyType as k:
  317. warn("unknown SSH key type '%s', skipping" % k.keytype)
  318. except KeyFormatError as k:
  319. warn("trouble parsing key (%s), skipping" % k.msg)
  320. except BlankInputLine:
  321. pass
  322. class OutputFormatter(object):
  323. def __init__(self, fh):
  324. self.fh = fh
  325. def header(self):
  326. pass
  327. def trailer(self):
  328. pass
  329. class WindowsOutputFormatter(OutputFormatter):
  330. def header(self):
  331. # Output REG file header.
  332. self.fh.write(r"""REGEDIT4
  333. [HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys]
  334. """)
  335. def key(self, key, value):
  336. # XXX: worry about double quotes?
  337. self.fh.write("\"%s\"=\"%s\"\n" % (winmungestr(key), value))
  338. def trailer(self):
  339. # The spec at http://support.microsoft.com/kb/310516 says we need
  340. # a blank line at the end of the reg file:
  341. #
  342. # Note the registry file should contain a blank line at the
  343. # bottom of the file.
  344. #
  345. self.fh.write("\n")
  346. class UnixOutputFormatter(OutputFormatter):
  347. def key(self, key, value):
  348. self.fh.write('%s %s\n' % (key, value))
  349. def main():
  350. parser = argparse.ArgumentParser(
  351. description="Convert OpenSSH known hosts files to PuTTY's format.")
  352. group = parser.add_mutually_exclusive_group()
  353. group.add_argument(
  354. "--windows", "--win", action='store_const',
  355. dest="output_formatter_class", const=WindowsOutputFormatter,
  356. help="Produce Windows .reg file output that regedit.exe can import"
  357. " (default).")
  358. group.add_argument(
  359. "--unix", action='store_const',
  360. dest="output_formatter_class", const=UnixOutputFormatter,
  361. help="Produce a file suitable for use as ~/.putty/sshhostkeys.")
  362. parser.add_argument("-o", "--output", type=argparse.FileType("w"),
  363. default=argparse.FileType("w")("-"),
  364. help="Output file to write to (default stdout).")
  365. parser.add_argument("--hostname", action="append",
  366. help="Host name(s) to try matching against hashed "
  367. "host entries in input.")
  368. parser.add_argument("infile", nargs="*",
  369. help="Input file(s) to read from (default stdin).")
  370. parser.set_defaults(output_formatter_class=WindowsOutputFormatter,
  371. hostname=[])
  372. args = parser.parse_args()
  373. output_formatter = args.output_formatter_class(args.output)
  374. output_formatter.header()
  375. for line in fileinput.input(args.infile):
  376. handle_line(line, output_formatter, args.hostname)
  377. output_formatter.trailer()
  378. if __name__ == "__main__":
  379. main()