]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - winstore.c
Make memory management uniform: _everything_ now goes through the
[PuTTY.git] / winstore.c
1 /*
2  * winstore.c: Windows-specific implementation of the interface
3  * defined in storage.h.
4  */
5
6 #include <windows.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include "putty.h"
10 #include "storage.h"
11
12 static const char *const puttystr = PUTTY_REG_POS "\\Sessions";
13
14 static char seedpath[2*MAX_PATH+10] = "\0";
15
16 static char hex[16] = "0123456789ABCDEF";
17
18 static void mungestr(char *in, char *out) {
19     int candot = 0;
20
21     while (*in) {
22         if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' ||
23             *in == '%' || *in < ' ' || *in > '~' || (*in == '.' && !candot)) {
24             *out++ = '%';
25             *out++ = hex[((unsigned char)*in) >> 4];
26             *out++ = hex[((unsigned char)*in) & 15];
27         } else
28             *out++ = *in;
29         in++;
30         candot = 1;
31     }
32     *out = '\0';
33     return;
34 }
35
36 static void unmungestr(char *in, char *out, int outlen) {
37     while (*in) {
38         if (*in == '%' && in[1] && in[2]) {
39             int i, j;
40
41             i = in[1] - '0'; i -= (i > 9 ? 7 : 0);
42             j = in[2] - '0'; j -= (j > 9 ? 7 : 0);
43
44             *out++ = (i<<4) + j;
45             if (!--outlen) return;
46             in += 3;
47         } else {
48             *out++ = *in++;
49             if (!--outlen) return;
50         }
51     }
52     *out = '\0';
53     return;
54 }
55
56 void *open_settings_w(char *sessionname) {
57     HKEY subkey1, sesskey;
58     int ret;
59     char *p;
60
61     p = smalloc(3*strlen(sessionname)+1);
62     mungestr(sessionname, p);
63     
64     ret = RegCreateKey(HKEY_CURRENT_USER, puttystr, &subkey1);
65     if (ret != ERROR_SUCCESS) {
66         sfree(p);
67         return NULL;
68     }
69     ret = RegCreateKey(subkey1, p, &sesskey);
70     sfree(p);
71     RegCloseKey(subkey1);
72     if (ret != ERROR_SUCCESS)
73         return NULL;
74     return (void *)sesskey;
75 }
76
77 void write_setting_s(void *handle, char *key, char *value) {
78     if (handle)
79         RegSetValueEx((HKEY)handle, key, 0, REG_SZ, value, 1+strlen(value));
80 }
81
82 void write_setting_i(void *handle, char *key, int value) {
83     if (handle)
84         RegSetValueEx((HKEY)handle, key, 0, REG_DWORD,
85                       (CONST BYTE *)&value, sizeof(value));
86 }
87
88 void close_settings_w(void *handle) {
89     RegCloseKey((HKEY)handle);
90 }
91
92 void *open_settings_r(char *sessionname) {
93     HKEY subkey1, sesskey;
94     char *p;
95
96     p = smalloc(3*strlen(sessionname)+1);
97     mungestr(sessionname, p);
98
99     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) {
100         sesskey = NULL;
101     } else {
102         if (RegOpenKey(subkey1, p, &sesskey) != ERROR_SUCCESS) {
103             sesskey = NULL;
104         }
105         RegCloseKey(subkey1);
106     }
107
108     sfree(p);
109
110     return (void *)sesskey;
111 }
112
113 char *read_setting_s(void *handle, char *key, char *buffer, int buflen) {
114     DWORD type, size;
115     size = buflen;
116
117     if (!handle ||
118         RegQueryValueEx((HKEY)handle, key, 0,
119                         &type, buffer, &size) != ERROR_SUCCESS ||
120         type != REG_SZ)
121         return NULL;
122     else
123         return buffer;
124 }
125
126 int read_setting_i(void *handle, char *key, int defvalue) {
127     DWORD type, val, size;
128     size = sizeof(val);
129
130     if (!handle ||
131         RegQueryValueEx((HKEY)handle, key, 0, &type,
132                         (BYTE *)&val, &size) != ERROR_SUCCESS ||
133         size != sizeof(val) || type != REG_DWORD)
134         return defvalue;
135     else
136         return val;
137 }
138
139 void close_settings_r(void *handle) {
140     RegCloseKey((HKEY)handle);
141 }
142
143 void del_settings (char *sessionname) {
144     HKEY subkey1;
145     char *p;
146
147     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS)
148         return;
149
150     p = smalloc(3*strlen(sessionname)+1);
151     mungestr(sessionname, p);
152     RegDeleteKey(subkey1, p);
153     sfree(p);
154
155     RegCloseKey(subkey1);
156 }
157
158 struct enumsettings {
159     HKEY key;
160     int i;
161 };
162
163 void *enum_settings_start(void) {
164     struct enumsettings *ret;
165     HKEY key;
166
167     if (RegCreateKey(HKEY_CURRENT_USER, puttystr, &key) != ERROR_SUCCESS)
168         return NULL;
169
170     ret = smalloc(sizeof(*ret));
171     if (ret) {
172         ret->key = key;
173         ret->i = 0;
174     }
175
176     return ret;
177 }
178
179 char *enum_settings_next(void *handle, char *buffer, int buflen) {
180     struct enumsettings *e = (struct enumsettings *)handle;
181     char *otherbuf;
182     otherbuf = smalloc(3*buflen);
183     if (otherbuf && RegEnumKey(e->key, e->i++, otherbuf,
184                                3*buflen) == ERROR_SUCCESS) {
185         unmungestr(otherbuf, buffer, buflen);
186         sfree(otherbuf);
187         return buffer;
188     } else
189         return NULL;
190
191 }
192
193 void enum_settings_finish(void *handle) {
194     struct enumsettings *e = (struct enumsettings *)handle;
195     RegCloseKey(e->key);
196     sfree(e);
197 }
198
199 static void hostkey_regname(char *buffer, char *hostname,
200                             int port, char *keytype) {
201     int len;
202     strcpy(buffer, keytype);
203     strcat(buffer, "@");
204     len = strlen(buffer);
205     len += sprintf(buffer+len, "%d:", port);
206     mungestr(hostname, buffer + strlen(buffer));
207 }
208
209 int verify_host_key(char *hostname, int port, char *keytype, char *key) {
210     char *otherstr, *regname;
211     int len;
212     HKEY rkey;
213     DWORD readlen;
214     DWORD type;
215     int ret, compare;
216
217     len = 1 + strlen(key);
218
219     /*
220      * Now read a saved key in from the registry and see what it
221      * says.
222      */
223     otherstr = smalloc(len);
224     regname = smalloc(3*(strlen(hostname)+strlen(keytype))+15);
225
226     hostkey_regname(regname, hostname, port, keytype);
227
228     if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
229                      &rkey) != ERROR_SUCCESS)
230         return 1;                      /* key does not exist in registry */
231
232     readlen = len;
233     ret = RegQueryValueEx(rkey, regname, NULL, &type, otherstr, &readlen);
234
235     if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA &&
236         !strcmp(keytype, "rsa")) {
237         /*
238          * Key didn't exist. If the key type is RSA, we'll try
239          * another trick, which is to look up the _old_ key format
240          * under just the hostname and translate that.
241          */
242         char *justhost = regname + 1 + strcspn(regname, ":");
243         char *oldstyle = smalloc(len + 10);   /* safety margin */
244         readlen = len;
245         ret = RegQueryValueEx(rkey, justhost, NULL, &type,
246                               oldstyle, &readlen);
247         
248         if (ret == ERROR_SUCCESS && type == REG_SZ) {
249             /*
250              * The old format is two old-style bignums separated by
251              * a slash. An old-style bignum is made of groups of
252              * four hex digits: digits are ordered in sensible
253              * (most to least significant) order within each group,
254              * but groups are ordered in silly (least to most)
255              * order within the bignum. The new format is two
256              * ordinary C-format hex numbers (0xABCDEFG...XYZ, with
257              * A nonzero except in the special case 0x0, which
258              * doesn't appear anyway in RSA keys) separated by a
259              * comma. All hex digits are lowercase in both formats.
260              */
261             char *p = otherstr;
262             char *q = oldstyle;
263             int i, j;
264
265             for (i = 0; i < 2; i++) {
266                 int ndigits, nwords;
267                 *p++ = '0'; *p++ = 'x';
268                 ndigits = strcspn(q, "/");   /* find / or end of string */
269                 nwords = ndigits / 4;
270                 /* now trim ndigits to remove leading zeros */
271                 while (q[ (ndigits-1) ^ 3 ] == '0' && ndigits > 1)
272                     ndigits--;
273                 /* now move digits over to new string */
274                 for (j = 0; j < ndigits; j++)
275                     p[ndigits-1-j] = q[j^3];
276                 p += ndigits;
277                 q += nwords*4;
278                 if (*q) {
279                     q++;               /* eat the slash */
280                     *p++ = ',';        /* add a comma */
281                 }
282                 *p = '\0';             /* terminate the string */
283             }
284
285             /*
286              * Now _if_ this key matches, we'll enter it in the new
287              * format. If not, we'll assume something odd went
288              * wrong, and hyper-cautiously do nothing.
289              */
290             if (!strcmp(otherstr, key))
291                 RegSetValueEx(rkey, regname, 0, REG_SZ, otherstr,
292                               strlen(otherstr)+1);
293         }
294     }
295
296     RegCloseKey(rkey);
297
298     compare = strcmp(otherstr, key);
299
300     sfree(otherstr);
301     sfree(regname);
302
303     if (ret == ERROR_MORE_DATA ||
304         (ret == ERROR_SUCCESS && type == REG_SZ && compare))
305         return 2;                      /* key is different in registry */
306     else if (ret != ERROR_SUCCESS || type != REG_SZ)
307         return 1;                      /* key does not exist in registry */
308     else
309         return 0;                      /* key matched OK in registry */
310 }
311
312 void store_host_key(char *hostname, int port, char *keytype, char *key) {
313     char *regname;
314     HKEY rkey;
315
316     regname = smalloc(3*(strlen(hostname)+strlen(keytype))+15);
317
318     hostkey_regname(regname, hostname, port, keytype);
319
320     if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
321                      &rkey) != ERROR_SUCCESS)
322         return;                        /* key does not exist in registry */
323     RegSetValueEx(rkey, regname, 0, REG_SZ, key,
324                   strlen(key)+1);
325     RegCloseKey(rkey);
326 }
327
328 /*
329  * Find the random seed file path and store it in `seedpath'.
330  */
331 static void get_seedpath(void) {
332     HKEY rkey;
333     DWORD type, size;
334
335     size = sizeof(seedpath);
336
337     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey)==ERROR_SUCCESS) {
338         int ret = RegQueryValueEx(rkey, "RandSeedFile",
339                                   0, &type, seedpath, &size);
340         if (ret != ERROR_SUCCESS || type != REG_SZ)
341             seedpath[0] = '\0';
342         RegCloseKey(rkey);
343     } else
344         seedpath[0] = '\0';
345
346     if (!seedpath[0]) {
347         int len, ret;
348
349         len = GetEnvironmentVariable("HOMEDRIVE", seedpath, sizeof(seedpath));
350         ret = GetEnvironmentVariable("HOMEPATH", seedpath+len,
351                                       sizeof(seedpath)-len);
352         if (ret == 0) {                /* probably win95; store in \WINDOWS */
353             GetWindowsDirectory(seedpath, sizeof(seedpath));
354             len = strlen(seedpath);
355         } else
356             len += ret;
357         strcpy(seedpath+len, "\\PUTTY.RND");
358     }
359 }
360
361 void read_random_seed(noise_consumer_t consumer) {
362     HANDLE seedf;
363
364     if (!seedpath[0])
365         get_seedpath();
366
367     seedf = CreateFile(seedpath, GENERIC_READ,
368                        FILE_SHARE_READ | FILE_SHARE_WRITE,
369                        NULL, OPEN_EXISTING, 0, NULL);
370
371     if (seedf != INVALID_HANDLE_VALUE) {
372         while (1) {
373             char buf[1024];
374             DWORD len;
375
376             if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
377                 consumer(buf, len);
378             else
379                 break;
380         }
381         CloseHandle(seedf);
382     }
383 }
384
385 void write_random_seed(void *data, int len) {
386     HANDLE seedf;
387
388     if (!seedpath[0])
389         get_seedpath();
390
391     seedf = CreateFile(seedpath, GENERIC_WRITE, 0,
392                        NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
393
394     if (seedf != INVALID_HANDLE_VALUE) {
395         DWORD lenwritten;
396
397         WriteFile(seedf, data, len, &lenwritten, NULL);
398         CloseHandle(seedf);
399     }
400 }
401
402 /*
403  * Recursively delete a registry key and everything under it.
404  */
405 static void registry_recursive_remove(HKEY key) {
406     DWORD i;
407     char name[MAX_PATH+1];
408     HKEY subkey;
409
410     i = 0;
411     while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
412         if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
413             registry_recursive_remove(subkey);
414             RegCloseKey(subkey);
415         }
416         RegDeleteKey(key, name);
417     }
418 }
419
420 void cleanup_all(void) {
421     HKEY key;
422     int ret;
423     char name[MAX_PATH+1];
424
425     /* ------------------------------------------------------------
426      * Wipe out the random seed file.
427      */
428     if (!seedpath[0])
429         get_seedpath();
430     remove(seedpath);
431
432     /* ------------------------------------------------------------
433      * Destroy all registry information associated with PuTTY.
434      */
435
436     /*
437      * Open the main PuTTY registry key and remove everything in it.
438      */
439     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) == ERROR_SUCCESS) {
440         registry_recursive_remove(key);
441         RegCloseKey(key);
442     }
443     /*
444      * Now open the parent key and remove the PuTTY main key. Once
445      * we've done that, see if the parent key has any other
446      * children.
447      */
448     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_PARENT,
449                    &key) == ERROR_SUCCESS) {
450         RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
451         ret = RegEnumKey(key, 0, name, sizeof(name));
452         RegCloseKey(key);
453         /*
454          * If the parent key had no other children, we must delete
455          * it in its turn. That means opening the _grandparent_
456          * key.
457          */
458         if (ret != ERROR_SUCCESS) {
459             if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
460                            &key) == ERROR_SUCCESS) {
461                 RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);
462                 RegCloseKey(key);
463             }
464         }
465     }
466     /*
467      * Now we're done.
468      */
469 }