]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winstore.c
Fix `puttygen-unix-perms': f_open(), PuTTY's wrapper on fopen, now
[PuTTY.git] / windows / winstore.c
1 /*
2  * winstore.c: Windows-specific implementation of the interface
3  * defined in storage.h.
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <limits.h>
9 #include "putty.h"
10 #include "storage.h"
11
12 #include <shlobj.h>
13 #ifndef CSIDL_APPDATA
14 #define CSIDL_APPDATA 0x001a
15 #endif
16 #ifndef CSIDL_LOCAL_APPDATA
17 #define CSIDL_LOCAL_APPDATA 0x001c
18 #endif
19
20 static const char *const puttystr = PUTTY_REG_POS "\\Sessions";
21
22 static const char hex[16] = "0123456789ABCDEF";
23
24 static int tried_shgetfolderpath = FALSE;
25 static HMODULE shell32_module = NULL;
26 typedef HRESULT (WINAPI *p_SHGetFolderPath_t)
27     (HWND, int, HANDLE, DWORD, LPTSTR);
28 static p_SHGetFolderPath_t p_SHGetFolderPath = NULL;
29
30 static void mungestr(const char *in, char *out)
31 {
32     int candot = 0;
33
34     while (*in) {
35         if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' ||
36             *in == '%' || *in < ' ' || *in > '~' || (*in == '.'
37                                                      && !candot)) {
38             *out++ = '%';
39             *out++ = hex[((unsigned char) *in) >> 4];
40             *out++ = hex[((unsigned char) *in) & 15];
41         } else
42             *out++ = *in;
43         in++;
44         candot = 1;
45     }
46     *out = '\0';
47     return;
48 }
49
50 static void unmungestr(const char *in, char *out, int outlen)
51 {
52     while (*in) {
53         if (*in == '%' && in[1] && in[2]) {
54             int i, j;
55
56             i = in[1] - '0';
57             i -= (i > 9 ? 7 : 0);
58             j = in[2] - '0';
59             j -= (j > 9 ? 7 : 0);
60
61             *out++ = (i << 4) + j;
62             if (!--outlen)
63                 return;
64             in += 3;
65         } else {
66             *out++ = *in++;
67             if (!--outlen)
68                 return;
69         }
70     }
71     *out = '\0';
72     return;
73 }
74
75 void *open_settings_w(const char *sessionname, char **errmsg)
76 {
77     HKEY subkey1, sesskey;
78     int ret;
79     char *p;
80
81     *errmsg = NULL;
82
83     if (!sessionname || !*sessionname)
84         sessionname = "Default Settings";
85
86     p = snewn(3 * strlen(sessionname) + 1, char);
87     mungestr(sessionname, p);
88
89     ret = RegCreateKey(HKEY_CURRENT_USER, puttystr, &subkey1);
90     if (ret != ERROR_SUCCESS) {
91         sfree(p);
92         *errmsg = dupprintf("Unable to create registry key\n"
93                             "HKEY_CURRENT_USER\\%s", puttystr);
94         return NULL;
95     }
96     ret = RegCreateKey(subkey1, p, &sesskey);
97     RegCloseKey(subkey1);
98     if (ret != ERROR_SUCCESS) {
99         *errmsg = dupprintf("Unable to create registry key\n"
100                             "HKEY_CURRENT_USER\\%s\\%s", puttystr, p);
101         sfree(p);
102         return NULL;
103     }
104     sfree(p);
105     return (void *) sesskey;
106 }
107
108 void write_setting_s(void *handle, const char *key, const char *value)
109 {
110     if (handle)
111         RegSetValueEx((HKEY) handle, key, 0, REG_SZ, value,
112                       1 + strlen(value));
113 }
114
115 void write_setting_i(void *handle, const char *key, int value)
116 {
117     if (handle)
118         RegSetValueEx((HKEY) handle, key, 0, REG_DWORD,
119                       (CONST BYTE *) &value, sizeof(value));
120 }
121
122 void close_settings_w(void *handle)
123 {
124     RegCloseKey((HKEY) handle);
125 }
126
127 void *open_settings_r(const char *sessionname)
128 {
129     HKEY subkey1, sesskey;
130     char *p;
131
132     if (!sessionname || !*sessionname)
133         sessionname = "Default Settings";
134
135     p = snewn(3 * strlen(sessionname) + 1, char);
136     mungestr(sessionname, p);
137
138     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) {
139         sesskey = NULL;
140     } else {
141         if (RegOpenKey(subkey1, p, &sesskey) != ERROR_SUCCESS) {
142             sesskey = NULL;
143         }
144         RegCloseKey(subkey1);
145     }
146
147     sfree(p);
148
149     return (void *) sesskey;
150 }
151
152 char *read_setting_s(void *handle, const char *key, char *buffer, int buflen)
153 {
154     DWORD type, size;
155     size = buflen;
156
157     if (!handle ||
158         RegQueryValueEx((HKEY) handle, key, 0,
159                         &type, buffer, &size) != ERROR_SUCCESS ||
160         type != REG_SZ) return NULL;
161     else
162         return buffer;
163 }
164
165 int read_setting_i(void *handle, const char *key, int defvalue)
166 {
167     DWORD type, val, size;
168     size = sizeof(val);
169
170     if (!handle ||
171         RegQueryValueEx((HKEY) handle, key, 0, &type,
172                         (BYTE *) &val, &size) != ERROR_SUCCESS ||
173         size != sizeof(val) || type != REG_DWORD)
174         return defvalue;
175     else
176         return val;
177 }
178
179 int read_setting_fontspec(void *handle, const char *name, FontSpec *result)
180 {
181     char *settingname;
182     FontSpec ret;
183
184     if (!read_setting_s(handle, name, ret.name, sizeof(ret.name)))
185         return 0;
186     settingname = dupcat(name, "IsBold", NULL);
187     ret.isbold = read_setting_i(handle, settingname, -1);
188     sfree(settingname);
189     if (ret.isbold == -1) return 0;
190     settingname = dupcat(name, "CharSet", NULL);
191     ret.charset = read_setting_i(handle, settingname, -1);
192     sfree(settingname);
193     if (ret.charset == -1) return 0;
194     settingname = dupcat(name, "Height", NULL);
195     ret.height = read_setting_i(handle, settingname, INT_MIN);
196     sfree(settingname);
197     if (ret.height == INT_MIN) return 0;
198     *result = ret;
199     return 1;
200 }
201
202 void write_setting_fontspec(void *handle, const char *name, FontSpec font)
203 {
204     char *settingname;
205
206     write_setting_s(handle, name, font.name);
207     settingname = dupcat(name, "IsBold", NULL);
208     write_setting_i(handle, settingname, font.isbold);
209     sfree(settingname);
210     settingname = dupcat(name, "CharSet", NULL);
211     write_setting_i(handle, settingname, font.charset);
212     sfree(settingname);
213     settingname = dupcat(name, "Height", NULL);
214     write_setting_i(handle, settingname, font.height);
215     sfree(settingname);
216 }
217
218 int read_setting_filename(void *handle, const char *name, Filename *result)
219 {
220     return !!read_setting_s(handle, name, result->path, sizeof(result->path));
221 }
222
223 void write_setting_filename(void *handle, const char *name, Filename result)
224 {
225     write_setting_s(handle, name, result.path);
226 }
227
228 void close_settings_r(void *handle)
229 {
230     RegCloseKey((HKEY) handle);
231 }
232
233 void del_settings(const char *sessionname)
234 {
235     HKEY subkey1;
236     char *p;
237
238     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS)
239         return;
240
241     p = snewn(3 * strlen(sessionname) + 1, char);
242     mungestr(sessionname, p);
243     RegDeleteKey(subkey1, p);
244     sfree(p);
245
246     RegCloseKey(subkey1);
247 }
248
249 struct enumsettings {
250     HKEY key;
251     int i;
252 };
253
254 void *enum_settings_start(void)
255 {
256     struct enumsettings *ret;
257     HKEY key;
258
259     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &key) != ERROR_SUCCESS)
260         return NULL;
261
262     ret = snew(struct enumsettings);
263     if (ret) {
264         ret->key = key;
265         ret->i = 0;
266     }
267
268     return ret;
269 }
270
271 char *enum_settings_next(void *handle, char *buffer, int buflen)
272 {
273     struct enumsettings *e = (struct enumsettings *) handle;
274     char *otherbuf;
275     otherbuf = snewn(3 * buflen, char);
276     if (RegEnumKey(e->key, e->i++, otherbuf, 3 * buflen) == ERROR_SUCCESS) {
277         unmungestr(otherbuf, buffer, buflen);
278         sfree(otherbuf);
279         return buffer;
280     } else {
281         sfree(otherbuf);
282         return NULL;
283     }
284 }
285
286 void enum_settings_finish(void *handle)
287 {
288     struct enumsettings *e = (struct enumsettings *) handle;
289     RegCloseKey(e->key);
290     sfree(e);
291 }
292
293 static void hostkey_regname(char *buffer, const char *hostname,
294                             int port, const char *keytype)
295 {
296     int len;
297     strcpy(buffer, keytype);
298     strcat(buffer, "@");
299     len = strlen(buffer);
300     len += sprintf(buffer + len, "%d:", port);
301     mungestr(hostname, buffer + strlen(buffer));
302 }
303
304 int verify_host_key(const char *hostname, int port,
305                     const char *keytype, const char *key)
306 {
307     char *otherstr, *regname;
308     int len;
309     HKEY rkey;
310     DWORD readlen;
311     DWORD type;
312     int ret, compare;
313
314     len = 1 + strlen(key);
315
316     /*
317      * Now read a saved key in from the registry and see what it
318      * says.
319      */
320     otherstr = snewn(len, char);
321     regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
322
323     hostkey_regname(regname, hostname, port, keytype);
324
325     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
326                    &rkey) != ERROR_SUCCESS)
327         return 1;                      /* key does not exist in registry */
328
329     readlen = len;
330     ret = RegQueryValueEx(rkey, regname, NULL, &type, otherstr, &readlen);
331
332     if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA &&
333         !strcmp(keytype, "rsa")) {
334         /*
335          * Key didn't exist. If the key type is RSA, we'll try
336          * another trick, which is to look up the _old_ key format
337          * under just the hostname and translate that.
338          */
339         char *justhost = regname + 1 + strcspn(regname, ":");
340         char *oldstyle = snewn(len + 10, char); /* safety margin */
341         readlen = len;
342         ret = RegQueryValueEx(rkey, justhost, NULL, &type,
343                               oldstyle, &readlen);
344
345         if (ret == ERROR_SUCCESS && type == REG_SZ) {
346             /*
347              * The old format is two old-style bignums separated by
348              * a slash. An old-style bignum is made of groups of
349              * four hex digits: digits are ordered in sensible
350              * (most to least significant) order within each group,
351              * but groups are ordered in silly (least to most)
352              * order within the bignum. The new format is two
353              * ordinary C-format hex numbers (0xABCDEFG...XYZ, with
354              * A nonzero except in the special case 0x0, which
355              * doesn't appear anyway in RSA keys) separated by a
356              * comma. All hex digits are lowercase in both formats.
357              */
358             char *p = otherstr;
359             char *q = oldstyle;
360             int i, j;
361
362             for (i = 0; i < 2; i++) {
363                 int ndigits, nwords;
364                 *p++ = '0';
365                 *p++ = 'x';
366                 ndigits = strcspn(q, "/");      /* find / or end of string */
367                 nwords = ndigits / 4;
368                 /* now trim ndigits to remove leading zeros */
369                 while (q[(ndigits - 1) ^ 3] == '0' && ndigits > 1)
370                     ndigits--;
371                 /* now move digits over to new string */
372                 for (j = 0; j < ndigits; j++)
373                     p[ndigits - 1 - j] = q[j ^ 3];
374                 p += ndigits;
375                 q += nwords * 4;
376                 if (*q) {
377                     q++;               /* eat the slash */
378                     *p++ = ',';        /* add a comma */
379                 }
380                 *p = '\0';             /* terminate the string */
381             }
382
383             /*
384              * Now _if_ this key matches, we'll enter it in the new
385              * format. If not, we'll assume something odd went
386              * wrong, and hyper-cautiously do nothing.
387              */
388             if (!strcmp(otherstr, key))
389                 RegSetValueEx(rkey, regname, 0, REG_SZ, otherstr,
390                               strlen(otherstr) + 1);
391         }
392     }
393
394     RegCloseKey(rkey);
395
396     compare = strcmp(otherstr, key);
397
398     sfree(otherstr);
399     sfree(regname);
400
401     if (ret == ERROR_MORE_DATA ||
402         (ret == ERROR_SUCCESS && type == REG_SZ && compare))
403         return 2;                      /* key is different in registry */
404     else if (ret != ERROR_SUCCESS || type != REG_SZ)
405         return 1;                      /* key does not exist in registry */
406     else
407         return 0;                      /* key matched OK in registry */
408 }
409
410 void store_host_key(const char *hostname, int port,
411                     const char *keytype, const char *key)
412 {
413     char *regname;
414     HKEY rkey;
415
416     regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
417
418     hostkey_regname(regname, hostname, port, keytype);
419
420     if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
421                      &rkey) == ERROR_SUCCESS) {
422         RegSetValueEx(rkey, regname, 0, REG_SZ, key, strlen(key) + 1);
423         RegCloseKey(rkey);
424     } /* else key does not exist in registry */
425
426     sfree(regname);
427 }
428
429 /*
430  * Open (or delete) the random seed file.
431  */
432 enum { DEL, OPEN_R, OPEN_W };
433 static int try_random_seed(char const *path, int action, HANDLE *ret)
434 {
435     if (action == DEL) {
436         remove(path);
437         *ret = INVALID_HANDLE_VALUE;
438         return FALSE;                  /* so we'll do the next ones too */
439     }
440
441     *ret = CreateFile(path,
442                       action == OPEN_W ? GENERIC_WRITE : GENERIC_READ,
443                       action == OPEN_W ? 0 : (FILE_SHARE_READ |
444                                               FILE_SHARE_WRITE),
445                       NULL,
446                       action == OPEN_W ? CREATE_ALWAYS : OPEN_EXISTING,
447                       action == OPEN_W ? FILE_ATTRIBUTE_NORMAL : 0,
448                       NULL);
449
450     return (*ret != INVALID_HANDLE_VALUE);
451 }
452
453 static HANDLE access_random_seed(int action)
454 {
455     HKEY rkey;
456     DWORD type, size;
457     HANDLE rethandle;
458     char seedpath[2 * MAX_PATH + 10] = "\0";
459
460     /*
461      * Iterate over a selection of possible random seed paths until
462      * we find one that works.
463      * 
464      * We do this iteration separately for reading and writing,
465      * meaning that we will automatically migrate random seed files
466      * if a better location becomes available (by reading from the
467      * best location in which we actually find one, and then
468      * writing to the best location in which we can _create_ one).
469      */
470
471     /*
472      * First, try the location specified by the user in the
473      * Registry, if any.
474      */
475     size = sizeof(seedpath);
476     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey) ==
477         ERROR_SUCCESS) {
478         int ret = RegQueryValueEx(rkey, "RandSeedFile",
479                                   0, &type, seedpath, &size);
480         if (ret != ERROR_SUCCESS || type != REG_SZ)
481             seedpath[0] = '\0';
482         RegCloseKey(rkey);
483
484         if (*seedpath && try_random_seed(seedpath, action, &rethandle))
485             return rethandle;
486     }
487
488     /*
489      * Next, try the user's local Application Data directory,
490      * followed by their non-local one. This is found using the
491      * SHGetFolderPath function, which won't be present on all
492      * versions of Windows.
493      */
494     if (!tried_shgetfolderpath) {
495         shell32_module = LoadLibrary("SHELL32.DLL");
496         if (shell32_module) {
497             p_SHGetFolderPath = (p_SHGetFolderPath_t)
498                 GetProcAddress(shell32_module, "SHGetFolderPathA");
499         }
500     }
501     if (p_SHGetFolderPath) {
502         if (SUCCEEDED(p_SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA,
503                                         NULL, SHGFP_TYPE_CURRENT, seedpath))) {
504             strcat(seedpath, "\\PUTTY.RND");
505             if (try_random_seed(seedpath, action, &rethandle))
506                 return rethandle;
507         }
508
509         if (SUCCEEDED(p_SHGetFolderPath(NULL, CSIDL_APPDATA,
510                                         NULL, SHGFP_TYPE_CURRENT, seedpath))) {
511             strcat(seedpath, "\\PUTTY.RND");
512             if (try_random_seed(seedpath, action, &rethandle))
513                 return rethandle;
514         }
515     }
516
517     /*
518      * Failing that, try %HOMEDRIVE%%HOMEPATH% as a guess at the
519      * user's home directory.
520      */
521     {
522         int len, ret;
523
524         len =
525             GetEnvironmentVariable("HOMEDRIVE", seedpath,
526                                    sizeof(seedpath));
527         ret =
528             GetEnvironmentVariable("HOMEPATH", seedpath + len,
529                                    sizeof(seedpath) - len);
530         if (ret != 0) {
531             strcat(seedpath, "\\PUTTY.RND");
532             if (try_random_seed(seedpath, action, &rethandle))
533                 return rethandle;
534         }
535     }
536
537     /*
538      * And finally, fall back to C:\WINDOWS.
539      */
540     GetWindowsDirectory(seedpath, sizeof(seedpath));
541     strcat(seedpath, "\\PUTTY.RND");
542     if (try_random_seed(seedpath, action, &rethandle))
543         return rethandle;
544
545     /*
546      * If even that failed, give up.
547      */
548     return INVALID_HANDLE_VALUE;
549 }
550
551 void read_random_seed(noise_consumer_t consumer)
552 {
553     HANDLE seedf = access_random_seed(OPEN_R);
554
555     if (seedf != INVALID_HANDLE_VALUE) {
556         while (1) {
557             char buf[1024];
558             DWORD len;
559
560             if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
561                 consumer(buf, len);
562             else
563                 break;
564         }
565         CloseHandle(seedf);
566     }
567 }
568
569 void write_random_seed(void *data, int len)
570 {
571     HANDLE seedf = access_random_seed(OPEN_W);
572
573     if (seedf != INVALID_HANDLE_VALUE) {
574         DWORD lenwritten;
575
576         WriteFile(seedf, data, len, &lenwritten, NULL);
577         CloseHandle(seedf);
578     }
579 }
580
581 /*
582  * Recursively delete a registry key and everything under it.
583  */
584 static void registry_recursive_remove(HKEY key)
585 {
586     DWORD i;
587     char name[MAX_PATH + 1];
588     HKEY subkey;
589
590     i = 0;
591     while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
592         if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
593             registry_recursive_remove(subkey);
594             RegCloseKey(subkey);
595         }
596         RegDeleteKey(key, name);
597     }
598 }
599
600 void cleanup_all(void)
601 {
602     HKEY key;
603     int ret;
604     char name[MAX_PATH + 1];
605
606     /* ------------------------------------------------------------
607      * Wipe out the random seed file, in all of its possible
608      * locations.
609      */
610     access_random_seed(DEL);
611
612     /* ------------------------------------------------------------
613      * Destroy all registry information associated with PuTTY.
614      */
615
616     /*
617      * Open the main PuTTY registry key and remove everything in it.
618      */
619     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) ==
620         ERROR_SUCCESS) {
621         registry_recursive_remove(key);
622         RegCloseKey(key);
623     }
624     /*
625      * Now open the parent key and remove the PuTTY main key. Once
626      * we've done that, see if the parent key has any other
627      * children.
628      */
629     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_PARENT,
630                    &key) == ERROR_SUCCESS) {
631         RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
632         ret = RegEnumKey(key, 0, name, sizeof(name));
633         RegCloseKey(key);
634         /*
635          * If the parent key had no other children, we must delete
636          * it in its turn. That means opening the _grandparent_
637          * key.
638          */
639         if (ret != ERROR_SUCCESS) {
640             if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
641                            &key) == ERROR_SUCCESS) {
642                 RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);
643                 RegCloseKey(key);
644             }
645         }
646     }
647     /*
648      * Now we're done.
649      */
650 }