]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - contrib/kh2reg.py
Merge branch 'pre-0.64'
[PuTTY.git] / contrib / kh2reg.py
1 #! /usr/bin/env python
2
3 # Convert OpenSSH known_hosts and known_hosts2 files to "new format" PuTTY
4 # host keys.
5 #   usage:
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.
12
13 import fileinput
14 import base64
15 import struct
16 import string
17 import re
18 import sys
19 import getopt
20
21 def winmungestr(s):
22     "Duplicate of PuTTY's mungestr() in winstore.c:1.10 for Registry keys"
23     candot = 0
24     r = ""
25     for c in s:
26         if c in ' \*?%~' or ord(c)<ord(' ') or (c == '.' and not candot):
27             r = r + ("%%%02X" % ord(c))
28         else:
29             r = r + c
30         candot = 1
31     return r
32
33 def strtolong(s):
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)
37
38 def longtohex(n):
39     """Convert long int to lower-case hex.
40
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."""
45
46     plain=string.lower(re.match(r"0x([0-9A-Fa-f]*)l?$", hex(n), re.I).group(1))
47     return "0x" + plain
48
49 output_type = 'windows'
50
51 try:
52     optlist, args = getopt.getopt(sys.argv[1:], '', [ 'win', 'unix' ])
53     if filter(lambda x: x[0] == '--unix', optlist):
54         output_type = 'unix'
55 except getopt.error, e:
56     sys.stderr.write(str(e) + "\n")
57     sys.exit(1)
58
59 if output_type == 'windows':
60     # Output REG file header.
61     sys.stdout.write("""REGEDIT4
62
63 [HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys]
64 """)
65
66 # Now process all known_hosts input.
67 for line in fileinput.input(args):
68
69     try:
70         # Remove leading/trailing whitespace (should zap CR and LF)
71         line = string.strip (line)
72
73         # Skip blanks and comments
74         if line == '' or line[0] == '#':
75             raise "Skipping input line"
76
77         # Split line on spaces.
78         fields = string.split (line, ' ')
79
80         # Common fields
81         hostpat = fields[0]
82         magicnumbers = []   # placeholder
83         keytype = ""        # placeholder
84
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]):
88
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])
93             keytype = "rsa"
94
95         else:
96
97             # Treat as SSH-2-type host key.
98             # Format: hostpat keytype keyblob64 comment...
99             sshkeytype, blob = fields[1], base64.decodestring (fields[2])
100
101             # 'blob' consists of a number of
102             #   uint32    N (big-endian)
103             #   uint8[N]  field_data
104             subfields = []
105             while blob:
106                 sizefmt = ">L"
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 : ]
112
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:])
117
118             # Translate key type into something PuTTY can use.
119             if   sshkeytype == "ssh-rsa":   keytype = "rsa2"
120             elif sshkeytype == "ssh-dss":   keytype = "dss"
121             else:
122                 raise "Unknown SSH key type", sshkeytype
123
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"
128                                  % host)
129                 continue
130             elif re.match (r"\|", host):
131                 sys.stderr.write("Skipping hashed hostname '%s'\n" % host)
132                 continue
133             else:
134                 m = re.match (r"\[([^]]*)\]:(\d*)$", host)
135                 if m:
136                     (host, port) = m.group(1,2)
137                     port = int(port)
138                 else:
139                     port = 22
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':
145                     # Unix format.
146                     sys.stdout.write('%s %s\n' % (key, value))
147                 else:
148                     # Windows format.
149                     # XXX: worry about double quotes?
150                     sys.stdout.write("\"%s\"=\"%s\"\n"
151                                      % (winmungestr(key), value))
152
153     except "Unknown SSH key type", k:
154         sys.stderr.write("Unknown SSH key type '%s', skipping\n" % k)
155     except "Skipping input line":
156         pass