3 # Convert OpenSSH known_hosts and known_hosts2 files to "new format" PuTTY
6 # kh2reg.py [ --win ] known_hosts1 2 3 4 ... > hosts.reg
7 # Creates a Windows .REG file (double-click to install).
8 # kh2reg.py --unix known_hosts1 2 3 4 ... > sshhostkeys
9 # Creates data suitable for storing in ~/.putty/sshhostkeys (Unix).
10 # Line endings are someone else's problem as is traditional.
11 # Developed for Python 1.5.2.
22 "Duplicate of PuTTY's mungestr() in winstore.c:1.10 for Registry keys"
26 if c in ' \*?%~' or ord(c)<ord(' ') or (c == '.' and not candot):
27 r = r + ("%%%02X" % ord(c))
34 "Convert arbitrary-length big-endian binary data to a Python long"
35 bytes = struct.unpack(">%luB" % len(s), s)
36 return reduce ((lambda a, b: (long(a) << 8) + long(b)), bytes)
39 """Convert long int to lower-case hex.
41 Ick, Python (at least in 1.5.2) doesn't appear to have a way to
42 turn a long int into an unadorned hex string -- % gets upset if the
43 number is too big, and raw hex() uses uppercase (sometimes), and
44 adds unwanted "0x...L" around it."""
46 plain=string.lower(re.match(r"0x([0-9A-Fa-f]*)l?$", hex(n), re.I).group(1))
49 output_type = 'windows'
52 optlist, args = getopt.getopt(sys.argv[1:], '', [ 'win', 'unix' ])
53 if filter(lambda x: x[0] == '--unix', optlist):
55 except getopt.error, e:
56 sys.stderr.write(str(e) + "\n")
59 if output_type == 'windows':
60 # Output REG file header.
61 sys.stdout.write("""REGEDIT4
63 [HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys]
66 # Now process all known_hosts input.
67 for line in fileinput.input(args):
70 # Remove leading/trailing whitespace (should zap CR and LF)
71 line = string.strip (line)
73 # Skip blanks and comments
74 if line == '' or line[0] == '#':
75 raise "Skipping input line"
77 # Split line on spaces.
78 fields = string.split (line, ' ')
82 magicnumbers = [] # placeholder
83 keytype = "" # placeholder
85 # Grotty heuristic to distinguish known_hosts from known_hosts2:
86 # is second field entirely decimal digits?
87 if re.match (r"\d*$", fields[1]):
89 # Treat as SSH-1-type host key.
90 # Format: hostpat bits10 exp10 mod10 comment...
91 # (PuTTY doesn't store the number of bits.)
92 magicnumbers = map (long, fields[2:4])
97 # Treat as SSH-2-type host key.
98 # Format: hostpat keytype keyblob64 comment...
99 sshkeytype, blob = fields[1], base64.decodestring (fields[2])
101 # 'blob' consists of a number of
102 # uint32 N (big-endian)
103 # uint8[N] field_data
107 (size,) = struct.unpack (sizefmt, blob[0:4])
108 size = int(size) # req'd for slicage
109 (data,) = struct.unpack (">%lus" % size, blob[4:size+4])
110 subfields.append(data)
111 blob = blob [struct.calcsize(sizefmt) + size : ]
113 # The first field is keytype again, and the rest we can treat as
114 # an opaque list of bignums (same numbers and order as stored
115 # by PuTTY). (currently embedded keytype is ignored entirely)
116 magicnumbers = map (strtolong, subfields[1:])
118 # Translate key type into something PuTTY can use.
119 if sshkeytype == "ssh-rsa": keytype = "rsa2"
120 elif sshkeytype == "ssh-dss": keytype = "dss"
122 raise "Unknown SSH key type", sshkeytype
124 # Now print out one line per host pattern, discarding wildcards.
125 for host in string.split (hostpat, ','):
126 if re.search (r"[*?!]", host):
127 sys.stderr.write("Skipping wildcard host pattern '%s'\n"
130 elif re.match (r"\|", host):
131 sys.stderr.write("Skipping hashed hostname '%s'\n" % host)
134 m = re.match (r"\[([^]]*)\]:(\d*)$", host)
136 (host, port) = m.group(1,2)
140 # Slightly bizarre output key format: 'type@port:hostname'
141 # XXX: does PuTTY do anything useful with literal IP[v4]s?
142 key = keytype + ("@%d:%s" % (port, host))
143 value = string.join (map (longtohex, magicnumbers), ',')
144 if output_type == 'unix':
146 sys.stdout.write('%s %s\n' % (key, value))
149 # XXX: worry about double quotes?
150 sys.stdout.write("\"%s\"=\"%s\"\n"
151 % (winmungestr(key), value))
153 except "Unknown SSH key type", k:
154 sys.stderr.write("Unknown SSH key type '%s', skipping\n" % k)
155 except "Skipping input line":